File size: 18,872 Bytes
7731906
 
 
 
 
 
 
1790e5d
 
 
 
 
 
7731906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8607af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d476260
8607af0
 
 
d476260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7731906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1790e5d
722f273
 
7731906
 
 
1790e5d
722f273
 
 
 
 
7731906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722f273
 
 
 
 
 
7731906
 
 
 
1790e5d
7731906
 
 
 
 
 
 
 
 
 
1790e5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7731906
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
namespace App\Controllers;

use App\Models\Book;

class BookController {
    public function index() {
        // Serve covers through /cover so the browser never hits i.ibb.co directly
        // (imgbb answers 503 for hotlinked requests).
        $books = array_map(function ($book) {
            $book['imageURL'] = bookCoverUrl($book);
            return $book;
        }, Book::getAll());

        $dharmaCategories = array_values(array_unique(array_filter(array_map(fn($b) => $b['ໝວດຟາຍ'] ?? '', $books))));
        sort($dharmaCategories);

        $jsonLd = [
            '@context' => 'https://schema.org',
            '@type' => 'CollectionPage',
            'name' => 'ປື້ມ - ຄຳສອນພຸດທະ',
            'description' => 'ລວມປື້ມທັມມະ ແລະ ຄຳສອນຂອງພຣະພຸດທະເຈົ້າ',
            'url' => canonicalUrl(),
            'inLanguage' => 'lo',
        ];

        return view('pages.book.index', [
            'books' => $books,
            'dharmaCategories' => $dharmaCategories,
            'seo' => [
                'title' => 'ປື້ມ - ຄຳສອນພຸດທະ',
                'description' => 'ລວມປື້ມທັມມະ ແລະ ຄຳສອນຂອງພຣະພຸດທະເຈົ້າ',
                'keywords' => 'ປື້ມ, ທັມມະ, ຄຳສອນພຸດທະ, ພຸດທະສາສະໜາ',
                'json_ld' => $jsonLd,
            ]
        ]);
    }

    // The 12 links in clock order (hour 12 = ອະວິຊາ), with their round (ວັດຕະ: ກິເລສ/ກຳ/ວິບາກ),
    // Pali formula and the period (ກາລະ) each belongs to.
    public static function paticca() {
        return [
            ['hour' => 12, 'vatta' => 'ກິເລສ', 'pali' => 'ອະວິຊຊາ ປັດຈະຍາ ສັງຂາຣາ', 'name' => 'ອະວິຊາ', 'mean' => 'ຄວາມບໍ່ຮູ້ຕາມເປັນຈິງ', 'detail' => 'ບໍ່ຮູ້ອະລິຍະສັດ 4: ທຸກ, ເຫດຂອງທຸກ, ຄວາມດັບທຸກ ແລະ ຂໍ້ປະຕິບັດເຖິງຄວາມດັບທຸກ.', 'kala' => 'past'],
            ['hour' => 1, 'vatta' => 'ກຳ', 'pali' => 'ສັງຂາຣະ ປັດຈະຍາ ວິນຍານັງ', 'name' => 'ສັງຂານ', 'mean' => 'ການປຸງແຕ່ງ (ກຳ)', 'detail' => 'ການປຸງແຕ່ງ 3 ທາງ: ກາຍ, ວາຈາ ແລະ ໃຈ.', 'kala' => 'past'],
            ['hour' => 2, 'vatta' => 'ວິບາກ', 'pali' => 'ວິນຍານະ ປັດຈະຍາ ນາມະຣູປັງ', 'name' => 'ວິນຍານ', 'mean' => 'ທາດຮູ້ແຈ້ງອາລົມ', 'detail' => 'ວິນຍານ 6: ທາງຕາ, ຫູ, ດັງ, ລີ້ນ, ກາຍ ແລະ ໃຈ.', 'kala' => 'present-result'],
            ['hour' => 3, 'vatta' => 'ວິບາກ', 'pali' => 'ນາມະຣູປະ ປັດຈະຍາ ສະລາຍະຕະນັງ', 'name' => 'ນາມຮູບ', 'mean' => 'ຈິດໃຈ ແລະ ຮ່າງກາຍ', 'detail' => 'ນາມ: ເວທະນາ, ສັນຍາ, ສັງຂານ — ຮູບ: ດິນ, ນ້ຳ, ໄຟ, ລົມ.', 'kala' => 'present-result'],
            ['hour' => 4, 'vatta' => 'ວິບາກ', 'pali' => 'ສະລາຍະຕະນະ ປັດຈະຍາ ຜັສໂສ', 'name' => 'ສະລາຍະຕະນະ', 'mean' => 'ຊ່ອງທາງຮັບຮູ້ 6', 'detail' => 'ຕາ, ຫູ, ດັງ, ລີ້ນ, ກາຍ, ໃຈ — ປະຕູທີ່ວິນຍານໄປຮັບຮູ້.', 'kala' => 'present-result'],
            ['hour' => 5, 'vatta' => 'ວິບາກ', 'pali' => 'ຜັສສະ ປັດຈະຍາ ເວທະນາ', 'name' => 'ຜັດສະ', 'mean' => 'ການກະທົບອາລົມ', 'detail' => 'ຜັດສະ = ອາຍະຕະນະໃນ + ອາລົມ + ວິນຍານ ມາປະຈວບກັນ.', 'kala' => 'present-result'],
            ['hour' => 6, 'vatta' => 'ວິບາກ', 'pali' => 'ເວທະນາ ປັດຈະຍາ ຕັນຫາ', 'name' => 'ເວທະນາ', 'mean' => 'ການສະເຫວີຍອາລົມ', 'detail' => 'ຮູ້ສຶກ ສຸກ, ທຸກ ຫຼື ເສີຍໆ ຫຼັງຈາກການກະທົບ.', 'kala' => 'present-result'],
            ['hour' => 7, 'vatta' => 'ກິເລສ', 'pali' => 'ຕັນຫາ ປັດຈະຍາ ອຸປາທານັງ', 'name' => 'ຕັນຫາ', 'mean' => 'ຄວາມທະຍານຢາກ', 'detail' => 'ຄວາມຢາກໃນເວທະນາ: ກາມຕັນຫາ, ພະວະຕັນຫາ, ວິພະວະຕັນຫາ.', 'kala' => 'present-cause'],
            ['hour' => 8, 'vatta' => 'ກິເລສ', 'pali' => 'ອຸປາທານະ ປັດຈະຍາ ພະໂວ', 'name' => 'ອຸປາທານ', 'mean' => 'ຄວາມຍຶດຕິດ', 'detail' => 'ຄວາມຍຶດໝັ້ນຖືໝັ້ນ — ລວມທັງການຍຶດວ່າ “ນີ້ແມ່ນຕົວເຮົາ”.', 'kala' => 'present-cause'],
            ['hour' => 9, 'vatta' => 'ກຳ', 'pali' => 'ພະວະ ປັດຈະຍາ ຊາຕິ', 'name' => 'ພົບ', 'mean' => 'ພາວະຊີວິດເປັນຢູ່', 'detail' => 'ຄວາມເປັນ: ກຳມະພົບ (ກຳ) ແລະ ອຸປັດຕິພົບ (ຜົນຂອງກຳ).', 'kala' => 'present-cause'],
            ['hour' => 10, 'vatta' => 'ວິບາກ', 'pali' => 'ຊາຕິ ປັດຈະຍາ ຊະຣາມະຣະນັງ', 'name' => 'ຊາດ', 'mean' => 'ຄວາມເກີດ', 'detail' => 'ຄວາມປາກົດຂຶ້ນຂອງຂັນທ໌ 5 — ການເກີດຂອງ “ຕົວເຮົາ” ໃໝ່.', 'kala' => 'future'],
            ['hour' => 11, 'vatta' => 'ວິບາກ', 'pali' => 'ໂສກະ ປະລິເທວະ ທຸກຂະ ໂທມະນັດສຸປາຍາສາ ສຳພະວັນຕິ', 'name' => 'ຊະລາມໍລະນະ', 'mean' => 'ຄວາມແກ່ ແລະ ຄວາມຕາຍ', 'detail' => 'ທຸກ: ໂສກະ, ປະລິເທວະ, ທຸກຂະ, ໂທມະນັດ, ອຸປາຍາສະ — ແລ້ວວົນກັບໄປຫາອະວິຊາ.', 'kala' => 'future'],
        ];
    }

    // Full-screen slide deck (no site layout), opened from the cover card at the start of the book list.
    public function slides() {
        $paticca = self::paticca();
        $seo = [
            'title' => 'ວົງລໍ້ ກິເລສ · ກຳ · ວິບາກ - ຄຳສອນພຸດທະ',
            'description' => 'ປະຕິຈຈະສະມຸບບາດ · ອາການ 20 — ເວລາກັບຈິດ, ແສງຈາກດວງດາວ ແລະ ວົງລໍ້ ກິເລສ · ກຳ · ວິບາກ',
            'image' => absoluteUrl('assets/images/paticca-wheel-cover.png'),
            'canonical' => canonicalUrl(),
        ];
        $narration = self::slidesNarration();
        require __DIR__ . '/../../views/pages/book/slides.php';
    }

    // [lang][slide] => [['t' => sentence, 'a' => pre-generated mp3 URL or null], ...].
    // A missing file (sentence edited, script not re-run) falls back to /api/tts/synthesize in the browser.
    public static function slidesNarration() {
        require_once __DIR__ . '/../Data/slides_audio.php';
        $out = [];
        foreach (require __DIR__ . '/../Data/slides_narration.php' as $lang => $slides) {
            foreach ($slides as $s => $lines) {
                foreach ($lines as $text) {
                    $file = slidesAudioFile($lang, $text);
                    $out[$lang][$s][] = ['t' => $text, 'a' => is_file(SLIDES_AUDIO_DIR . '/' . $file) ? url('assets/audio/slides/' . $file) : null];
                }
            }
        }
        return $out;
    }

    public function show($id) {
        $books = Book::getAll();
        $book = null;
        foreach ($books as $item) {
            if ($item['ID'] == $id) {
                $book = $item;
                break;
            }
        }

        if (!$book) {
            header("HTTP/1.0 404 Not Found");
            echo "Book not found";
            return;
        }

        $linkBook = $book['link'] ?? '';
        $pdfEmbedLink = str_replace('/view?usp=sharing', '/preview', $linkBook);
        $pdfDownloadUrl = '';
        $pdfViewUrl = '';
        $isDirectLink = false;

        if (preg_match('/\/d\/([a-zA-Z0-9_-]+)/', $linkBook, $matches)) {
            $fileId = $matches[1];
            $pdfDownloadUrl = "https://drive.google.com/uc?export=download&id={$fileId}";
            $pdfViewUrl = url('/book/pdf/' . $id);
        } elseif (!empty($linkBook)) {
            // Non-Google Drive link - use it directly
            $isDirectLink = true;
            $pdfEmbedLink = $linkBook;
            $pdfDownloadUrl = $linkBook;
        }
 
        $canonicalUrl = canonicalUrl();
        $bookTitle = $book['ຊື່'] ?? 'ປື້ມ';

        $jsonLd = [
            '@context' => 'https://schema.org',
            '@type' => 'Book',
            'name' => $bookTitle,
            'url' => $canonicalUrl,
            'inLanguage' => 'lo',
            'isPartOf' => [
                '@type' => 'Collection',
                'name' => 'ຄຳສອນພຸດທະ', 
            ],
            'breadcrumb' => [
                '@type' => 'BreadcrumbList',
                'itemListElement' => [
                    ['@type' => 'ListItem', 'position' => 1, 'name' => 'ໜ້າຫຼັກ', 'item' => absoluteUrl('')],
                    ['@type' => 'ListItem', 'position' => 2, 'name' => 'ປື້ມ', 'item' => absoluteUrl('/book')],
                    ['@type' => 'ListItem', 'position' => 3, 'name' => $bookTitle],
                ],
            ],
        ];

        if (!empty($book['imageURL'])) {
            $jsonLd['image'] = $book['imageURL'];
        }

        $bookDescription = strip_tags($book['description'] ?? $book['detail'] ?? '');
        $bookDescription = !empty($bookDescription)
            ? (mb_strlen($bookDescription) > 160 ? mb_substr($bookDescription, 0, 157) . '...' : $bookDescription)
            : 'ປຶ້ມ: ' . $bookTitle;

        // If it's a direct link (non-Google Drive), redirect to it
        if ($isDirectLink) {
            header("Location: " . $linkBook);
            exit;
        }

        return view('pages.book.show', [
            'book' => $book,
            'pdfEmbedLink' => $pdfEmbedLink,
            'pdfDownloadUrl' => $pdfDownloadUrl,
            'pdfViewUrl' => $pdfViewUrl,
            'seo' => [
                'title' => $bookTitle . ' - ຄຳສອນພຸດທະ',
                'description' => $bookDescription,
                'keywords' => ($book['ໝວດທັມ'] ?? '') . ', ປື້ມ, ທັມມະ, ຄຳສອນພຸດທະ',
                'image' => $book['imageURL'] ?? absoluteUrl('assets/images/logo_shared.png'),
                'json_ld' => $jsonLd,
                'og_type' => 'book',
            ]
        ]);
    }

    // Same-origin proxy for Google Drive PDFs so the full-screen viewer can use pdf.js.
    public function pdf($id) {
        $book = null;
        foreach (Book::getAll() as $item) {
            if (($item['ID'] ?? '') == $id) { $book = $item; break; }
        }

        $fileId = '';
        if ($book && preg_match('/\/d\/([a-zA-Z0-9_-]+)/', $book['link'] ?? '', $m)) {
            $fileId = $m[1];
        }
        if (!$fileId) {
            http_response_code(404);
            header('Content-Type: text/plain; charset=utf-8');
            echo 'PDF not found';
            return;
        }

        $dir = __DIR__ . '/../../storage/cache/pdf';
        if (!is_dir($dir) && !@mkdir($dir, 0777, true)) {
            $dir = rtrim(sys_get_temp_dir(), '/\\') . '/buddhaword-pdf';
            @mkdir($dir, 0777, true);
        }
        if (!is_writable($dir)) {
            $dir = rtrim(sys_get_temp_dir(), '/\\') . '/buddhaword-pdf';
            @mkdir($dir, 0777, true);
        }

        $cacheFile = $dir . '/' . $fileId . '.pdf';
        $stale = !is_file($cacheFile) || filesize($cacheFile) < 5 || (time() - (int) @filemtime($cacheFile) > 604800);
        if ($stale) {
            $lock = @fopen($cacheFile . '.lock', 'c');
            if ($lock) flock($lock, LOCK_EX);
            if (!is_file($cacheFile) || filesize($cacheFile) < 5) {
                $tmp = $cacheFile . '.' . getmypid() . '.' . bin2hex(random_bytes(4)) . '.tmp';
                $urls = [
                    'https://drive.usercontent.google.com/download?id=' . rawurlencode($fileId) . '&export=download&confirm=t',
                    'https://drive.google.com/uc?export=download&id=' . rawurlencode($fileId) . '&confirm=t',
                ];

                $saved = false;
                foreach ($urls as $url) {
                    for ($attempt = 0; $attempt < 2 && !$saved; $attempt++) {
                        self::fetchPdfFile($url, $tmp);
                        if (self::isPdfFile($tmp)) {
                            $saved = true;
                            break;
                        }
                        // Large files answer with a virus-scan form; resend its confirm/uuid token.
                        $confirmUrl = self::driveConfirmUrl($fileId, $tmp);
                        if ($confirmUrl !== null) {
                            self::fetchPdfFile($confirmUrl, $tmp);
                            if (self::isPdfFile($tmp)) {
                                $saved = true;
                                break;
                            }
                        }
                        @unlink($tmp);
                        usleep(400000);
                    }
                    if ($saved) break;
                }

                if ($saved) {
                    @rename($tmp, $cacheFile);
                } else {
                    @unlink($tmp);
                    error_log('Book PDF download failed: ' . $fileId);
                }
            }
            if ($lock) {
                flock($lock, LOCK_UN);
                fclose($lock);
            }
        }

        if (!is_file($cacheFile) || filesize($cacheFile) < 5) {
            http_response_code(502);
            header('Content-Type: text/plain; charset=utf-8');
            echo 'Unable to download PDF';
            return;
        }

        self::servePdfFile($cacheFile);
    }

    private static function fetchPdfFile($url, $path) {
        $fp = @fopen($path, 'wb');
        if (!$fp) return false;

        $ok = false;
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_FILE => $fp,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_MAXREDIRS => 8,
                CURLOPT_CONNECTTIMEOUT => 20,
                CURLOPT_TIMEOUT => 300,
                CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',
                CURLOPT_HTTPHEADER => ['Accept: application/pdf,*/*'],
            ]);
            $ok = curl_exec($ch) !== false && (int) curl_getinfo($ch, CURLINFO_HTTP_CODE) < 400;
            curl_close($ch);
        }

        // Some hosts run PHP without curl; retry with the stream wrapper.
        if (!$ok) {
            ftruncate($fp, 0);
            rewind($fp);
            $ctx = stream_context_create([
                'http' => [
                    'follow_location' => 1,
                    'max_redirects' => 8,
                    'timeout' => 300,
                    'user_agent' => 'Mozilla/5.0',
                    'header' => "Accept: application/pdf,*/*\r\n",
                ],
            ]);
            $in = @fopen($url, 'rb', false, $ctx);
            if ($in) {
                $ok = stream_copy_to_stream($in, $fp) > 0;
                fclose($in);
            }
        }

        fclose($fp);
        return $ok;
    }

    private static function isPdfFile($path) {
        $head = @file_get_contents($path, false, null, 0, 2048);
        return $head !== false && strpos($head, '%PDF-') !== false;
    }

    private static function driveConfirmUrl($fileId, $path) {
        $html = @file_get_contents($path);
        if ($html === false || stripos($html, 'confirm') === false) return null;

        $confirm = 't';
        if (preg_match('/name="confirm"\s+value="([^"]+)"/i', $html, $m)) {
            $confirm = $m[1];
        }
        $url = 'https://drive.usercontent.google.com/download?id=' . rawurlencode($fileId)
            . '&export=download&confirm=' . rawurlencode($confirm);
        if (preg_match('/name="uuid"\s+value="([^"]+)"/i', $html, $m)) {
            $url .= '&uuid=' . rawurlencode($m[1]);
        }
        return $url;
    }

    private static function servePdfFile($file) {
        $size = filesize($file);
        $start = 0;
        $end = $size - 1;
        $partial = false;

        if (isset($_SERVER['HTTP_RANGE']) && preg_match('/bytes=(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $m)) {
            if ($m[1] !== '') $start = (int) $m[1];
            if ($m[2] !== '') $end = (int) $m[2];
            if ($m[1] === '' && $m[2] !== '') {
                $start = max(0, $size - (int) $m[2]);
                $end = $size - 1;
            }
            if ($start > $end || $start >= $size) {
                http_response_code(416);
                header('Content-Range: bytes */' . $size);
                return;
            }
            $end = min($end, $size - 1);
            $partial = true;
        }

        $length = $end - $start + 1;
        if ($partial) {
            http_response_code(206);
            header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
        }
        header('Content-Type: application/pdf');
        header('Content-Length: ' . $length);
        header('Accept-Ranges: bytes');
        header('Content-Disposition: inline');
        header('Cache-Control: public, max-age=86400');

        $fp = fopen($file, 'rb');
        if (!$fp) return;
        fseek($fp, $start);
        while ($length > 0 && !feof($fp)) {
            $chunk = fread($fp, min(8192, $length));
            if ($chunk === false || $chunk === '') break;
            echo $chunk;
            $length -= strlen($chunk);
        }
        fclose($fp);
    }
}