-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExtension.php
More file actions
639 lines (553 loc) · 19.7 KB
/
Extension.php
File metadata and controls
639 lines (553 loc) · 19.7 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
<?php
/**
* ToC Extension/Plugin for Parsedown.
*
* It creates a list of contents table in various format from the headings in Markdown text.
*
* @package keinos/ParsedownToC
* @author KEINOS (https://github.com/KEINOS/)
* @author Contributors (https://github.com/KEINOS/parsedown-extension_table-of-contents/graphs/contributors)
* @php >=5.3.0 <8.4 (Currently fails on PHP 8.4)
* @see https://github.com/KEINOS/parsedown-extension_table-of-contents/ ReadMe & Usage
* @see https://keinos.github.io/parsedown-extension_table-of-contents/ PHPDoc
* @example https://github.com/KEINOS/parsedown-extension_table-of-contents/tree/master/examples
* @license https://github.com/KEINOS/parsedown-extension_table-of-contents/LICENSE MIT License
* @copyright 2018-2025 KEINOS and the contributors
*/
// Make it compatible with ParsedownExtra
// - Feature Implementation from Issue #13 by @qwertygc
// https://github.com/KEINOS/parsedown-extension_table-of-contents/issues/13
if (class_exists('ParsedownExtra')) {
class DynamicParent extends \ParsedownExtra
{
public function __construct()
{
parent::__construct();
}
}
} else {
// Extended class for Parsedown
class DynamicParent extends \Parsedown
{
public function __construct()
{
//
}
}
}
class ParsedownToC extends DynamicParent
{
/**
* ========================================================================
* Constants / Properties
* ========================================================================
*/
// phpcs:disable PSR12.Properties.ConstantVisibility -- for backward compatibility
/** Version of this extension */
const VERSION = '1.4.0';
/** Version of Parsedown required */
const VERSION_PARSEDOWN_REQUIRED = '1.7.4';
/** Version of ParsedownExtra required */
const VERSION_PARSEDOWN_EXTRA_REQUIRED = '0.8.0';
/** Default ToC tag */
const TAG_TOC_DEFAULT = '[toc]';
/** Default ID attribute for ToC (only for ParsedownExtra) */
const ID_ATTRIBUTE_DEFAULT = 'toc';
// phpcs:enable
/** @var array It holds the heading blocks of the content in array form. */
protected $contentsListArray = array();
/** @var string It holds the headings in markdown format string. */
protected $contentsListString = '';
/** @var int It holds the initial heading level of the content. */
protected $firstHeadLevel = 0;
/** @var string It holds the user defined ToC ID attribute. */
protected $id_toc = '';
/** @var string It holds the user defined ToC tag. */
protected $tag_toc = '';
/**
* ========================================================================
* Constructor
* ========================================================================
*/
/**
* Version requirement check and parent constructor call.
*
* @throws Exception
* @return void
*/
public function __construct()
{
$msg_error = $this->checkRequirements();
if (! empty($msg_error)) {
throw new Exception($msg_error);
}
parent::__construct();
}
/**
* ========================================================================
* Methods (in ABC order)
* ========================================================================
*/
/**
* Check the requirements of the extension.
*
* @return string
*/
protected function checkRequirements()
{
$msg_error = "";
if (! class_exists('\Parsedown')) {
$msg_error .= 'Requirement Error:' . PHP_EOL;
$msg_error .= ' Parsedown class is not found. Make sure Parsedown is installed and loaded.' . PHP_EOL;
return $msg_error;
}
if (version_compare(\Parsedown::version, self::VERSION_PARSEDOWN_REQUIRED) < 0) {
$msg_error .= 'Version Error:' . PHP_EOL;
$msg_error .= ' Parsedown ToC Extension requires a later version of Parsedown.' . PHP_EOL;
$msg_error .= ' - Current Parsedown Version : ' . \Parsedown::version . PHP_EOL;
$msg_error .= ' - Required Parsedown Version: ' . self::VERSION_PARSEDOWN_REQUIRED . PHP_EOL;
return $msg_error;
}
// Check ParsedownExtra if the class exists
if (class_exists('\ParsedownExtra')) {
if (version_compare(\ParsedownExtra::version, self::VERSION_PARSEDOWN_EXTRA_REQUIRED) < 0) {
$msg_error .= 'Version Error:' . PHP_EOL;
$msg_error .= ' Parsedown ToC Extension requires a later version of ParsedownExtra.' . PHP_EOL;
$msg_error .= ' - Current ParsedownExtra Version : ' . \ParsedownExtra::version . PHP_EOL;
$msg_error .= ' - Required ParsedownExtra Version: ' . self::VERSION_PARSEDOWN_EXTRA_REQUIRED . PHP_EOL;
return $msg_error;
}
}
return $msg_error;
}
/**
* Build hierarchical ToC from a flat toc array.
*
* @param array $flatToc Flat list of toc entries.
* @return array Hierarchical toc as nested array.
*/
protected function buildNestedToc(array $flatToc)
{
$hierarchy = [];
$stack = [];
foreach ($flatToc as $item) {
$level = (int) substr($item['level'], 1); // 'h1' -> 1, etc.
$entry = [
'text' => $item['text'],
'id' => $item['id'],
'level' => $item['level'], // keep the original level as reference
'children' => []
];
// If no parent exists, add as top-level entry
if (empty($stack)) {
$hierarchy[] = $entry;
$stack[] = ['level' => $level, 'ref' => &$hierarchy[count($hierarchy) - 1]];
continue;
}
// If deeper than last, add as child
if ($level > $stack[count($stack) - 1]['level']) {
$parent = &$stack[count($stack) - 1]['ref'];
$parent['children'][] = $entry;
$stack[] = ['level' => $level, 'ref' => &$parent['children'][count($parent['children']) - 1]];
continue;
}
// Pop until we find a shallower level
while (!empty($stack) && $stack[count($stack) - 1]['level'] >= $level) {
array_pop($stack);
}
// If stack empty, add as top-level entry
if (empty($stack)) {
$hierarchy[] = $entry;
$stack[] = ['level' => $level, 'ref' => &$hierarchy[count($hierarchy) - 1]];
continue;
}
// Else, add as sibling child
$parent = &$stack[count($stack) - 1]['ref'];
$parent['children'][] = $entry;
$stack[] = ['level' => $level, 'ref' => &$parent['children'][count($parent['children']) - 1]];
}
return $hierarchy;
}
/**
* Heading process. It retruns the heading block element if the given $Line
* is a heading element.
*
* It extends the parent method: \Parsedown::blockHeader() and creates a
* ToC list from the heading blocks and stores them. Use "contentsList()"
* to retrieve the ToC list.
*
* @param array $Line Array that Parsedown detected as a block type element.
* @return void|array Array of Heading Block.
* @see contentsList()
*/
#[\Override]
protected function blockHeader($Line)
{
// Use parent blockHeader method to process the $Line to $Block
/**
* @var void|array{
* element: array{
* id: string,
* name: string,
* text: string,
* handler: array{
* function: string,
* argument: string,
* destination: string
* },
* attributes: array{
* id: string,
* name: string
* }
* }
* } $Block
*/
$Block = (array) DynamicParent::blockHeader($Line);
if (empty($Block)) {
return;
}
// Get the text of the heading
$text = '';
if (isset($Block['element']['handler']['argument'])) {
// Compatibility with old Parsedown version
$text = "{$Block['element']['handler']['argument']}";
}
if (isset($Block['element']['text'])) {
// Current Parsedown
$text = "{$Block['element']['text']}";
}
// Get the heading level. Levels are h1, h2, ..., h6
$level = "{$Block['element']['name']}";
// Get the anchor of the heading to link from the ToC list
$id = isset($Block['element']['attributes']['id']) ?
$Block['element']['attributes']['id'] : $this->createAnchorID($text);
// Set/re-set attributes to head tags
$Block['element']['attributes']['id'] = $id;
$Block['element']['attributes']['name'] = $id;
// Add/store the heading element info to the ToC list
$this->setContentsList(array(
'text' => $text,
'id' => $id,
'level' => $level
));
return $Block;
}
/**
* Parses the given markdown string to an HTML string but it leaves the ToC
* tag as is. It's an alias of the parent method "\DynamicParent::text()".
*
* @param string $text Markdown string to be parsed.
* @param bool $omit_toc_tag (Optional) If true, the ToC tag will be excluded from the result. Default is false.
* @return string Parsed HTML string.
*/
public function body($text, $omit_toc_tag = false)
{
// Exclude the ToC tag from parsing
if ($omit_toc_tag) {
$tag_origin = $this->getTagToC();
// replace the ToC tag to empty string
$text = str_replace($tag_origin, '', $text);
// Parses the markdown text
return (string) DynamicParent::text($text);
}
$text = $this->encodeTagToHash($text); // Escapes ToC tag temporary
$html = (string) DynamicParent::text($text); // Parses the markdown text
$html = $this->decodeTagFromHash("{$html}"); // Unescape the ToC tag
return $html;
}
/**
* Returns the parsed ToC in various formats.
*
* If the arg is empty or "html" then it returns the ToC in HTML string.
*
* @param string $type_return Type of the return format. Available types: "markdown", "html", "json", "flatarray" and "nestedarray". Default: "html". Aliases: "string" = "html", "md" = "markdown".
*
* @return false|string|array ToC in HTML/JSON/Markdown format string or PHP array.
*/
public function contentsList($type_return = 'html')
{
$type_return = strtolower($type_return);
if ('markdown' === $type_return || 'md' === $type_return) {
$result = '';
if (! empty($this->contentsListString)) {
$result = $this->contentsListString;
}
return rtrim($result);
}
if ('html' === $type_return || 'string' === $type_return) {
$result = '';
if (! empty($this->contentsListString)) {
// Parses the markdown ToC list to HTML
$result = $this->body($this->contentsListString);
}
return $result;
}
if ('json' === $type_return) {
return json_encode($this->contentsListArray);
}
if ('flatarray' === $type_return) {
return $this->contentsListArray;
}
if ('nestedarray' === $type_return) {
return $this->buildNestedToc($this->contentsListArray);
}
// Log the error and forces to return ToC as "string"
error_log(
'Unknown return type given while parsing ToC.'
. ' At: ' . __FUNCTION__ . '() '
. ' in Line:' . __LINE__ . ' (Using default type)'
);
return $this->contentsList('html');
}
/**
* Generates an anchor text that are link-able even the heading is not in
* ASCII.
*
* @param string $text
* @return string
*/
protected function createAnchorID($text)
{
return urlencode($this->getTextOnly($text));
}
/**
* Decodes the hashed ToC tag to an original tag and replaces.
*
* This is used to avoid parsing user defined ToC tag which includes "_" in
* their tag such as "[[_toc_]]". Unless it will be parsed as:
* "<p>[[<em>TOC</em>]]</p>"
*
* @param string $text
* @return string
*/
protected function decodeTagFromHash($text)
{
$salt = $this->getSalt();
$tag_origin = $this->getTagToC();
$tag_hashed = hash('sha256', $salt . $tag_origin);
if (strpos($text, "$tag_hashed") === false) {
return $text;
}
return str_replace("$tag_hashed", $tag_origin, $text);
}
/**
* Encodes the ToC tag to a hashed tag and replace.
*
* This is used to avoid parsing user defined ToC tag which includes "_" in
* their tag such as "[[_toc_]]". Unless it will be parsed as:
* "<p>[[<em>TOC</em>]]</p>"
*
* @param string $text
* @return string
*/
protected function encodeTagToHash($text)
{
$salt = $this->getSalt();
$tag_origin = $this->getTagToC();
if (strpos($text, $tag_origin) === false) {
return $text;
}
$tag_hashed = hash('sha256', $salt . $tag_origin);
return str_replace($tag_origin, "$tag_hashed", $text);
}
/**
* [Deprecated] Superseded by "getTextOnly()".
*
* Get only the text from a markdown string. It parses to HTML once then
* trims the tags to get the text. It's been replaced by "getTextOnly()".
*
* @deprecated It will be removed in the near future. Currently it is
* an alias of "getTextOnly()".
* @see getTextOnly()
* @param string $text Markdown text.
* @return string
*/
protected function fetchText($text)
{
return $this->getTextOnly($text);
}
/**
* ------------------------------------------------------------------------
* Getters
* ------------------------------------------------------------------------
*/
/**
* Gets the ID attribute of the ToC for HTML tags.
*
* @return string
*/
protected function getIdAttributeToC()
{
if (! empty($this->id_toc)) {
return (string) $this->id_toc;
}
return self::ID_ATTRIBUTE_DEFAULT;
}
/**
* Unique string to use as a salt value.
*
* @return string
*/
protected function getSalt()
{
static $salt;
if (isset($salt) && ! empty($salt)) {
return "$salt";
}
$salt = hash('md5', time());
return "$salt";
}
/**
* Gets the markdown tag for ToC.
*
* It returns the current tag to search for the ToC tag, '[toc]' for example, in the markdown text.
*
* @return string
*/
protected function getTagToC()
{
if (! empty($this->tag_toc)) {
return $this->tag_toc;
}
return self::TAG_TOC_DEFAULT;
}
/**
* Get only the text from a markdown string.
*
* It parses to HTML once then trims the tags to get the text.
*
* @param string $text Markdown text.
* @return string
*/
protected function getTextOnly($text)
{
return trim(strip_tags("{$this->line($text)}"));
}
/**
* ------------------------------------------------------------------------
* Setters
* ------------------------------------------------------------------------
*/
/**
* Set/stores the heading block to ToC list in a string and array format.
*
* @param array $Content Heading info such as "level","id" and "text".
* @return void
*/
protected function setContentsList(array $Content)
{
// Stores as an array
$this->setContentsListAsArray($Content);
// Stores as string in markdown list format.
$this->setContentsListAsString($Content);
}
/**
* Sets/stores the heading block info as an array.
*
* @param array $Content
* @return void
*/
protected function setContentsListAsArray(array $Content)
{
$this->contentsListArray[] = $Content;
}
/**
* Sets/stores the heading block info as a list in markdown format.
*
* @param array $Content Heading info such as "level","id" and "text".
* @return void
*/
protected function setContentsListAsString(array $Content)
{
$text = $this->getTextOnly("{$Content['text']}");
$id = "{$Content['id']}";
$link = "[{$text}](#{$id})";
$level = (int) trim("{$Content['level']}", 'h');
if ($this->firstHeadLevel === 0) {
$this->firstHeadLevel = $level;
}
$cutIndent = $this->firstHeadLevel - 1;
if ($cutIndent > $level) {
$level = 1;
} else {
$level = $level - $cutIndent;
}
$indent = str_repeat(' ', $level-1);
// Stores in markdown list format as below:
// - [Header1](#Header1)
// - [Header2-1](#Header2-1)
// - [Header3](#Header3)
// - [Header2-2](#Header2-2)
// ...
$this->contentsListString .= "{$indent}- {$link}" . PHP_EOL;
}
/**
* Sets the user defined ID attribute of HTML DIV tag for ToC.
*
* Special characters are not allowed in the ID attribute.
*
* @param string $id Alphanumeric string as ID attribute.
* @return void
*/
public function setIdAttributeToC($id)
{
$id = trim($id);
if (self::escape($id) === $id) {
// Set ToC ID attribute if it's safe
$this->id_toc = $id;
return;
}
// Do nothing but log
error_log(
'Malformed ToC user ID attribute given.'
. ' At: ' . __FUNCTION__ . '() '
. ' in Line:' . __LINE__ . ' (Using default ToC ID attribute)'
);
}
/**
* Sets the user defined ToC markdown tag.
*
* @param string $tag
* @return void
*/
public function setTagToc($tag)
{
$tag = trim($tag);
if (self::escape($tag) === $tag) {
// Set ToC tag if it's safe
$this->tag_toc = $tag;
return;
}
// Do nothing but log
error_log(
'Malformed ToC user tag given.'
. ' At: ' . __FUNCTION__ . '() '
. ' in Line:' . __LINE__ . ' (Using default ToC tag)'
);
}
/**
* Parses markdown string to HTML and also the "[toc]" tag as well.
* It overrides the parent method: \Parsedown::text().
*
* @param string $text
*
* @return string
*/
#[\Override]
public function text($text)
{
// Parses the markdown text except the ToC tag. This also searches
// the list of contents and available to get from "contentsList()"
// method.
$html = $this->body($text);
$tag_origin = $this->getTagToC();
if (strpos($text, $tag_origin) === false) {
return $html;
}
$toc_data = $this->contentsList();
$toc_id = $this->getIdAttributeToC();
$needle = '<p>' . $tag_origin . '</p>';
$replace = "<div id=\"{$toc_id}\">{$toc_data}</div>";
return str_replace($needle, $replace, $html);
}
}