-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
ParsedownToc.php
608 lines (513 loc) · 17.3 KB
/
ParsedownToc.php
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
<?php
/**
*
* This code checks if the class 'ParsedownExtra' exists. If it does, it creates an alias for it called 'ParsedownTocParentAlias'.
* If 'ParsedownExtra' does not exist, it creates an alias for 'Parsedown' called 'ParsedownTocParentAlias'.
*/
if (class_exists('ParsedownExtra')) {
class_alias('ParsedownExtra', 'ParsedownTocParentAlias');
} else {
class_alias('Parsedown', 'ParsedownTocParentAlias');
}
class ParsedownToc extends ParsedownTocParentAlias
{
const VERSION = '1.5';
const VERSION_PARSEDOWN_REQUIRED = '1.7.4';
protected $options = [];
protected $defaultOptions = array(
'selectors' => ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
'delimiter' => '-',
'limit' => null,
'lowercase' => true,
'replacements' => null,
'transliterate' => true,
'urlencode' => false,
'blacklist' => [],
'url' => '',
'toc_tag' => '[toc]',
'toc_id' => 'toc',
);
public function __construct()
{
if (version_compare(\Parsedown::version, self::VERSION_PARSEDOWN_REQUIRED) < 0) {
$msg_error = 'Version Error.' . PHP_EOL;
$msg_error .= ' ParsedownToc requires a later version of Parsedown.' . PHP_EOL;
$msg_error .= ' - Current version : ' . \Parsedown::version . PHP_EOL;
$msg_error .= ' - Required version: ' . self::VERSION_PARSEDOWN_REQUIRED .' and later'. PHP_EOL;
throw new Exception($msg_error);
}
parent::__construct();
// Initialize default options
$this->options = $this->defaultOptions;
}
/**
* Set options for the ParsedownToc parser.
*
* @param array $options The options to set.
* @return void
*/
public function setOptions(array $options) : void
{
$this->options = array_merge($this->options, $options);
}
/**
* Set the selectors option.
*
* @param array $selectors The selectors to set.
* @return void
*/
public function setTocSelectors(array $selectors) : void
{
$this->options['selectors'] = $selectors;
}
/**
* Set the delimiter option.
*
* @param string $delimiter The delimiter to set.
* @return void
*/
public function setTocDelimiter(string $delimiter) : void
{
$this->options['delimiter'] = $delimiter;
}
/**
* Set the limit option.
*
* @param int|null $limit The limit to set.
* @return void
*/
public function setTocLimit(?int $limit) : void
{
$this->options['limit'] = $limit;
}
/**
* Set the lowercase option.
*
* @param bool $lowercase The lowercase option to set.
* @return void
*/
public function setTocLowercase(bool $lowercase) : void
{
$this->options['lowercase'] = $lowercase;
}
/**
* Set the replacements option.
*
* @param array|null $replacements The replacements to set.
* @return void
*/
public function setTocReplacements(?array $replacements) : void
{
$this->options['replacements'] = $replacements;
}
/**
* Set the transliterate option.
*
* @param bool $transliterate The transliterate option to set.
* @return void
*/
public function setTocTransliterate(bool $transliterate) : void
{
$this->options['transliterate'] = $transliterate;
}
/**
* Set the urlencode option.
*
* @param bool $urlencode The urlencode option to set.
* @return void
*/
public function setTocUrlencode(bool $urlencode) : void
{
$this->options['urlencode'] = $urlencode;
}
/**
* Set the blacklist option.
*
* @param array $blacklist The blacklist to set.
* @return void
*/
public function setTocBlacklist(array $blacklist) : void
{
$this->options['blacklist'] = $blacklist;
}
/**
* Set the url option.
*
* @param string $url The url to set.
* @return void
*/
public function setTocUrl(string $url) : void
{
$this->options['url'] = $url;
}
/**
* Set the toc_tag option.
*
* @param string $toc_tag The toc_tag to set.
* @return void
*/
public function setTocTag(string $toc_tag) : void
{
$this->options['toc_tag'] = $toc_tag;
}
/**
* Set the toc_id option.
*
* @param string $toc_id The toc_id to set.
* @return void
*/
public function setTocId(string $toc_id) : void
{
$this->options['toc_id'] = $toc_id;
}
/**
* Heading process.
* Creates heading block element and stores to the ToC list. It overrides
* the parent method: \Parsedown::blockHeader() and returns $Block array if
* the $Line is a heading element.
*
* @param array $Line Array that Parsedown detected as a block type element.
* @return void|array Array of Heading Block.
*/
protected function blockHeader($Line)
{
// Use parent blockHeader method to process the $Line to $Block
$Block = ParsedownTocParentAlias::blockHeader($Line);
if (!empty($Block)) {
// Get the text of the heading
if (isset($Block['element']['text'])) {
$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 attributes to head tags
$Block['element']['attributes']['id'] = $id;
// Check if level are defined as a selector
if (in_array($level, $this->options['selectors'])) {
// Add/stores the heading element info to the ToC list
$this->setContentsList(array(
'text' => $text,
'id' => $id,
'level' => $level
));
}
return $Block;
}
}
/**
* Heading process.
* Creates heading block element and stores to the ToC list. It overrides
* the parent method: \Parsedown::blockSetextHeader() and returns $Block array if
* the $Line is a heading element.
*
* @param array $Line Array that Parsedown detected as a block type element.
* @return void|array Array of Heading Block.
*/
protected function blockSetextHeader($Line, array $Block = null)
{
// Use parent blockHeader method to process the $Line to $Block
$Block = ParsedownTocParentAlias::blockSetextHeader($Line, $Block);
if (!empty($Block)) {
// Get the text of the heading
if (isset($Block['element']['text'])) {
$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 attributes to head tags
$Block['element']['attributes']['id'] = $id;
// Check if level are defined as a selector
if (in_array($level, $this->options['selectors'])) {
// Add/stores 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 "\ParsedownTocParentAlias::text()".
*
* @param string $text Markdown string to be parsed.
* @return string Parsed HTML string.
*/
public function body($text) : string
{
$text = $this->encodeTagToHash($text); // Escapes ToC tag temporary
$html = ParsedownTocParentAlias::text($text); // Parses the markdown text
$html = $this->decodeTagFromHash($html); // Unescape the ToC tag
return $html;
}
/**
* Returns the parsed ToC.
*
* @param string $type_return Type of the return format. "html", "json", or "array".
* @return string|array HTML/JSON string, or array of ToC.
*/
public function contentsList($type_return = 'html')
{
if ('html' === strtolower($type_return)) {
$result = '';
if (! empty($this->contentsListString)) {
// Parses the ToC list in markdown to HTML
$result = $this->body($this->contentsListString);
}
return $result;
}
if ('json' === strtolower($type_return)) {
return json_encode($this->contentsListArray);
}
if ('array' === strtolower($type_return)) {
return $this->contentsListArray;
}
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($str) : string
{
// Make sure string is in UTF-8 and strip invalid UTF-8 characters
$str = mb_convert_encoding((string)$str, 'UTF-8', mb_list_encodings());
if($this->options['urlencode']) {
// Check AnchorID is unique
$str = $this->incrementAnchorId($str);
return urlencode($str);
}
// Make custom replacements
if(!empty($this->options['replacements'])) {
$str = preg_replace(array_keys($this->options['replacements']), $this->options['replacements'], $str);
}
// Transliterate characters to ASCII
if ($this->options['transliterate']) {
$str = iconv('UTF-8', 'ASCII//IGNORE', $str);
}
// Replace non-alphanumeric characters with our delimiter
$str = preg_replace('/[^\p{L}\p{Nd}]+/u', $this->options['delimiter'], $str);
// Remove duplicate delimiters
$str = preg_replace('/(' . preg_quote($this->options['delimiter'], '/') . '){2,}/', '$1', $str);
// Truncate slug to max. characters
$str = mb_substr($str, 0, ($this->options['limit'] ? $this->options['limit'] : mb_strlen($str, 'UTF-8')), 'UTF-8');
// Remove delimiter from ends
$str = trim($str, $this->options['delimiter']);
$str = $this->options['lowercase'] ? mb_strtolower($str, 'UTF-8') : $str;
$str = $this->incrementAnchorId($str);
return $str;
}
/**
* 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 "[[_]]". Unless it will be parsed as:
* "<p>[[<em>TOC</em>]]</p>"
*
* @param string $text
* @return string
*/
protected function decodeTagFromHash(string $text) : string
{
$salt = $this->getSalt();
$tag_origin = $this->getTocTag();
$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 "[[_]]". Unless it will be parsed as:
* "<p>[[<em>TOC</em>]]</p>"
*
* @param string $text
* @return string
*/
protected function encodeTagToHash(string $text) : string
{
$salt = $this->getSalt();
$tag_origin = $this->getTocTag();
if (strpos($text, $tag_origin) === false) {
return $text;
}
$tag_hashed = hash('sha256', $salt . $tag_origin);
return str_replace($tag_origin, $tag_hashed, $text);
}
/**
* 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 fetchText(string $text) : string
{
return trim(strip_tags($this->line($text)));
}
/**
* Gets the ID attribute of the ToC for HTML tags.
*
* @return string
*/
protected function getTocIdAttribute() : string
{
return $this->options['toc_id'];
}
/**
* Unique string to use as a salt value.
*
* @return string
*/
protected function getSalt() : string
{
static $salt;
if (isset($salt)) {
return $salt;
}
$salt = hash('md5', time());
return $salt;
}
/**
* Gets the markdown tag for ToC.
*
* @return string
*/
protected function getTocTag() : string
{
return $this->options['toc_tag'];
}
/**
* 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) : void
{
// 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) : void
{
$this->contentsListArray[] = $Content;
}
protected $contentsListArray = array();
/**
* 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) : void
{
$text = $this->fetchText($Content['text']);
$id = $Content['id'];
$level = (integer) trim($Content['level'], 'h');
$link = "[{$text}]({$this->options['url']}#{$id})";
if ($this->firstHeadLevel === 0) {
$this->firstHeadLevel = $level;
}
$cutIndent = $this->firstHeadLevel - 1;
if ($cutIndent > $level) {
$level = 1;
} else {
$level = $level - $cutIndent;
}
$indent = str_repeat(' ', $level);
// 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;
}
protected $contentsListString = '';
protected $firstHeadLevel = 0;
/**
* Parses markdown string to HTML and also the "[toc]" tag as well.
* It overrides the parent method: \Parsedown::text().
*
* @param string $text
* @return string
*/
public function text($text) : string
{
// 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->getTocTag();
if (strpos($text, $tag_origin) === false) {
return $html;
}
$data = $this->contentsList();
$toc_id = $this->getTocIdAttribute();
$needle = '<p>' . $tag_origin . '</p>';
$replace = "<div id=\"{$toc_id}\">{$data}</div>";
return str_replace($needle, $replace, $html);
}
protected $isBlacklistInitialized = false;
protected $anchorDuplicates = [];
/**
* Add blacklisted ids to anchor list
*/
protected function initBlacklist() : void
{
if ($this->isBlacklistInitialized) return;
if (!empty($this->options['blacklist']) && is_array($this->options['blacklist'])) {
foreach ($this->options['blacklist'] as $v) {
if (is_string($v)) $this->anchorDuplicates[$v] = 0;
}
}
$this->isBlacklistInitialized = true;
}
/**
* Collect and count anchors in use to prevent duplicated ids. Return string
* with incremental, numeric suffix. Also init optional blacklist of ids.
*
* @param string $str
* @return string
*/
protected function incrementAnchorId(string $str) : string
{
// add blacklist to list of used anchors
if (!$this->isBlacklistInitialized) $this->initBlacklist();
$this->anchorDuplicates[$str] = !isset($this->anchorDuplicates[$str]) ? 0 : ++$this->anchorDuplicates[$str];
$newStr = $str;
if ($count = $this->anchorDuplicates[$str]) {
$newStr .= "-{$count}";
// increment until conversion doesn't produce new duplicates anymore
if (isset($this->anchorDuplicates[$newStr])) {
$newStr = $this->incrementAnchorId($str);
}
else {
$this->anchorDuplicates[$newStr] = 0;
}
}
return $newStr;
}
}