-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnanodown.php
632 lines (552 loc) · 15.5 KB
/
nanodown.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
<?php
/**
* Nanodown - Small, Performant, and Memory Efficient Markdown Library for PHP
* Written by: Celestina Dragoni
* GitHub: https://github.com/CelestinaDragoni
*/
class Nanodown
{
/** In HTML/Raw Flag **/
private $_inRaw = false;
/** In Code Block Flag **/
private $_inPre = false;
/** In Table Block Flag **/
private $_inTable = false;
/** In List Block Flag **/
private $_inList = false;
/** In Quote Block Flag **/
private $_inQuote = false;
/** Edge Case Surrounding Tables and Blockquotes **/
private $_inQuoteTable = false;
/** HTML Buffer **/
private $_html = '';
/** Escape Characters for Markdown and HTML **/
private $_escape = [
'sanitize' => [
'<' => '<',
'>' => '>',
'"' => '"',
'\'' => ''',
"\n" => '',
"\r" => '',
"\0" => '',
'\*' => '*',
'\_' => '_',
'\`' => '`',
'\{' => '{',
'\}' => '}',
'\[' => '[',
'\]' => ']',
'\(' => '(',
'\)' => ')',
'\#' => '#',
'\~' => '~',
'\|' => '|',
'\=' => '=',
'\^' => '^',
'\-' => '-',
'\+' => '+',
'\:' => ':',
],
'code' => [
'*' => '*',
'_' => '_',
'`' => '`',
'{' => '{',
'}' => '}',
'[' => '[',
']' => ']',
'(' => '(',
')' => ')',
'#' => '#',
'~' => '~',
'|' => '|',
'=' => '=',
'^' => '^',
'-' => '-',
'+' => '+',
':' => ':',
],
];
/** Generic Regexes **/
private $_regex = [
'tokens' => [
'/^##### (.*?)$/',
'/^#### (.*?)$/',
'/^### (.*?)$/',
'/^## (.*?)$/',
'/^# (.*?)$/',
'/^---/',
'/^\: (.*?)$/',
'/[*_]{3}(.*?)[*_]{3}/',
'/[*_]{2}(.*?)[*_]{2}/',
'/[*_]{1}(.*?)[*_]{1}/',
'/\~\~(.*?)\~\~/',
'/\^(.*?)\^/',
'/\~(.*?)\~/',
'/\=\=(.*?)\=\=/',
],
'replace' => [
'<h5>$1</h5>',
'<h4>$1</h4>',
'<h3>$1</h3>',
'<h2>$1</h2>',
'<h1>$1</h1>',
'<hr/>',
'<span>$1</span>',
'<em><strong>$1</strong></em>',
'<strong>$1</strong>',
'<em>$1</em>',
'<s>$1</s>',
'<sup>$1</sup>',
'<sub>$1</sub>',
'<mark>$1</mark>',
],
];
/** Specific Regex Strings for Links and Images **/
private $_regexLinks = [
'/(\!)\[(.*?)\]\((.*?)\)/',
'/\[(.*?)\]\((.*?)\)/',
'/(<)(http|https|ftp|sftp|gemini|gopher|git|tel|email)\:(\/?\/?)(.*?)>/',
'/(^|\s)(http|https|ftp|sftp|gemini|gopher|git|tel|email)\:(\/?\/?)(.*?)($|\s)/',
];
/**
* Singleton Constructor
* @return Nanodown
*/
public static function getInstance() : \Nanodown
{
static $instance = false;
return $instance ? $instance : $instance = new \Nanodown();
}
/**
* Converts markdown string to an HTML string.
* @param String $markdown Markdown Input
* @return String HTML Output
*/
public function convertFromString(String $markdown) : String
{
$this->_reset();
// String stream saves memory consumption.
if ($stream = fopen('php://memory','r+')) {
fwrite($stream, $markdown);
rewind($stream);
while(!feof($stream)) {
$line = fgets($stream);
$this->_parse($line);
$this->_html .= "$line\n";
}
fclose($stream);
}
return $this->_dealloc();
}
/**
* Converts markdown from file to an HTML string.
* @param String $filename Markdown File Location
* @return String HTML Output
*/
public function convertFromFile(String $filename) : String
{
$this->_reset();
if (!file_exists($filename) && !is_readable($filename)) {
return '';
}
if ($file = fopen($filename, "r")) {
while(!feof($file)) {
$line = fgets($file);
$this->_parse($line);
$this->_html .= "$line\n";
}
fclose($file);
}
return $this->_dealloc();
}
/**
* Writes to local string and returns. Deallocs HTML variable from class. (PHP Optimization)
* @return String
*/
private function _dealloc() : String
{
$html = $this->_html;
$this->_html = '';
return $html;
}
/**
* Reset class variables on new conversion process.
* @return Void
*/
private function _reset() : Void
{
$this->_html = '';
$this->_inRaw = false;
$this->_inPre = false;
$this->_inTable = false;
$this->_inList = false;
$this->_inQuote = false;
$this->_inQuoteTable = false;
}
/**
* Parse markdown line and convert into HTML
* @param String $line
* @return Void
*/
private function _parse(String &$line) : Void
{
$this->_raw($line);
if ($this->_inRaw) {
return;
}
$this->_sanitize($line);
$this->_quote($line);
$this->_pre($line);
$this->_code($line);
$this->_links($line);
$this->_table($line);
$this->_list($line);
$this->_regex($line);
$this->_endline($line);
}
/**
* Sanitize markdown line from HTML injections and breakage. (Best we can here).
* @param String $line Markdown Line
* @return Void
*/
private function _sanitize(String &$line) : Void
{
$line = strtr($line, $this->_escape['sanitize']);
}
/**
* Regular Expression Handler for Generic Inline Markdown Tags
* @param String $line Markdown Line
* @return Void
*/
private function _regex(String &$line) : Void
{
if ($this->_inPre) {
return;
}
// Run Regular Expressions
$line = preg_replace(
$this->_regex['tokens'],
$this->_regex['replace'],
$line
);
}
/**
* Generates and Escapes Links and Images
* @param String $line
* @return Void
*/
private function _links(String &$line) : Void
{
if ($this->_inPre) {
return;
}
$line = preg_replace_callback(
$this->_regexLinks,
function ($matches) {
$url = '';
$label = '';
$space = '';
$length = count($matches);
if ($length === 6) {
$url = $matches[2] . ':' . $matches[3] . $matches[4];
$label = $url;
$space = ' ';
} else if ($length === 5) {
$url = $matches[2] . ':' . $matches[3] . $matches[4];
$label = $url;
$space = ' ';
} else if ($length === 4) {
$url = $matches[3];
$label = $matches[2];
} else if ($length === 3) {
$url = $matches[2];
$label = $matches[1];
}
$url = strtr($url, $this->_escape['code']);
$label = strtr($label, $this->_escape['code']);
if ($length === 4) {
return "$space<img src=\"$url\" alt=\"$label\"/>$space";
}
return "$space<a href=\"$url\">$label</a>$space";
},
$line
);
}
/**
* Renders Raw Content like HTML
* @param String $line
* @return void
*/
private function _raw(String &$line) : Void
{
if (strpos($line, '^^^^^') !== 0) {
return;
}
$line = '';
$this->_inRaw = !$this->_inRaw;
}
/**
* Renders Quote Blocks
* @param String $line
* @return Void
*/
private function _quote(String &$line) : Void
{
$isQuote = (strpos($line, '>') === 0);
// Nope
if (!$this->_inQuote && !$isQuote) {
return;
}
// Exiting Quote Block
if ($this->_inQuote && !$isQuote) {
if ($this->_inTable) {
$this->_inQuoteTable = true;
} else {
$this->_html .= "</blockquote>\n";
}
$this->_inQuote = false;
return;
}
// Entering Quote Block
if (!$this->_inQuote && $isQuote) {
$this->_html .= "<blockquote>\n";
$this->_inQuote = true;
}
// Truncate Quote Syntax From Line
$line = substr($line, 5);
}
/**
* Renders Pre-Formatted Code Blocks
* @param String $line Markdown Line
* @return Void
*/
private function _pre(String &$line) : Void
{
if (strpos($line, '```') !== 0) {
return;
}
if ($this->_inPre) {
$this->_inPre = false;
$line = '</pre>';
} else {
$this->_inPre = true;
$line = '<pre>';
}
}
/**
* Renders Inline Code Blocks
* @param String $line
* @return Void
*/
private function _code(String &$line) : Void
{
$line = preg_replace_callback(
'/\`(.*?)\`/',
function ($matches) {
$matches[1] = strtr($matches[1], $this->_escape['code']);
return "<code>{$matches[1]}</code>";
},
$line
);
}
/**
* Renders Table
* @param String $line
* @return Void
*/
private function _table(String &$line) : Void
{
// Static Column Count
static $length = -1;
// Don't Run Table Logic When...
if ($this->_inPre) {
return;
}
$isTable = strpos($line, '|') === 0;
$isDiv = strpos($line, '|-') === 0;
// Not a Table
if (!$this->_inTable && !$isTable) {
return;
}
// Exiting Exising Table
if ($this->_inTable && !$isTable) {
$length = -1;
$this->_html .= $this->_inQuoteTable ? "</table></blockquote>\n" : "</table>\n";
$this->_inTable = false;
$this->_inQuoteTable = false;
return;
}
// Check for Table Split/Alignment (Unsupported Syntax)
if ($isTable && $isDiv) {
$line = '';
return;
}
// Get Column Data
$data = [];
if ($isTable) {
$data = explode(
'|',
ltrim(rtrim($line, '|'), '|'),
);
if ($length === -1) {
$length = count($data);
}
}
// Default Column Tag Type
$tag = 'td';
// Entering Table
if (!$this->_inTable) {
$this->_html .= "<table>\n";
$this->_inTable = true;
$tag = 'th';
}
// Build Columns
$cols = '';
for ($i = 0; $i < $length; $i++) {
if (isset($data[$i])) {
$cols .= "<$tag>{$data[$i]}</$tag>";
} else {
$cols .= "<$tag> </$tag>";
}
}
// Write Line
$line = "<tr>$cols</tr>";
}
/**
* Renders Lists and Nested Lists Using Flattened Recursion
* Note: I hate all of this, but...
* @param String $line
* @return Void
*/
private function _list(String &$line) : Void
{
static $nested = [];
static $indent = -1;
// Don't Run Table Logic When...
if ($this->_inPre || $this->_inTable) {
return;
}
// Line Buffer
$buffer = '';
// Line Item w/o Indent
$item = ltrim($line);
// Indent Autodetect
$tab = strlen($line) - strlen($item);
// Invalid List Format
if (!$this->_inList && $tab > 0) {
return;
}
// Check For List
$isOL = preg_match('/^[0-9]{1,}\. /', $item);
$isUL = preg_match('/^[\+\*\-]{1} /', $item);
$isLI = $isOL || $isUL;
// Exit
if (!$isLI && !$this->_inList) {
return;
}
// Close List
if (!$isLI && $this->_inList) {
// Close Remaining Tags
foreach (array_reverse($nested) as &$nest) {
$key = $nest[0];
$buffer .= "</li></$key>";
}
// Write To Line Before
$this->_html .= "$buffer\n";
// Reset
$indent = -1;
$nested = [];
$this->_inList = false;
return;
}
// Start List
if ($isLI && !$this->_inList) {
$indent = -1;
$nested = [];
$this->_inList = true;
}
// Set Tab Length
if ($indent === -1 && $tab > 0) {
$indent = $tab;
}
// Determine Depth
$depth = intval(floor($tab / $indent));
// Get Maximum Depth
$imax = count($nested) - 1;
// Check Valid Depth
if (!isset($nested[$depth])) {
if ($depth > count($nested)) {
$depth = $imax;
}
// Write Nested
if (!isset($nested[$depth])) {
$nested[] = [
(($isOL) ? 'ol' : 'ul'),
0
];
}
}
// Close Existing Tags and Pop Off
if ($depth < $imax) {
foreach (array_reverse($nested) as &$nest) {
$imax = count($nested) - 1;
if ($imax === $depth) {
break;
}
$key = $nest[0];
$buffer .= "</li></$key>";
array_pop($nested);
}
}
// List Logic
if ($nested[$depth][1] === 0) {
$buffer .= "<{$nested[$depth][0]}>";
} else {
$buffer .= "</li>";
}
// Write Item
if ($isOL) {
$buffer .= preg_replace('/^[0-9]{1,}\. (.*?)$/', '<li>$1', $item);
} else {
$buffer .= preg_replace('/^[\+\*\-]{1} (.*?)$/', '<li>$1', $item);
}
// Increase Line Count
$nested[$depth][1]++;
// Write Line
$line = $buffer;
}
/**
* Determine If Content Is Paragraph Worthy
* @param String $line
* @return Void
*/
private function _endline(String &$line) : Void
{
// These set, ignore
if (
$this->_inPre ||
$this->_inTable ||
$this->_inList ||
$this->_inRaw
) {
return;
}
// Blank line, Ignore
if (trim($line) === '') {
return;
}
// Done as a memory saving method of detection.
if (
(strpos($line, '<h') === 0) ||
(strpos($line, '<div') === 0) ||
(strpos($line, '<pre') === 0) ||
(strpos($line, '</pre') === 0)
) {
return;
}
// Wrap in paragraph.
$line = "<p>$line</p>";
}
}