-
Notifications
You must be signed in to change notification settings - Fork 0
/
Textify.php
828 lines (623 loc) · 19.5 KB
/
Textify.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
<?php
/**
* Textify
*
* Render HTML markup using Markdown-style plain text
*
* @copyright Copyright (c) 2011 Ingenesis Limited
* @author Jonathan Davis <[email protected]>
* @package Textify
* @license GPLv2
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
class Textify {
private $markup = false;
private $DOM = false;
function __construct ($markup) {
$this->markup = $markup;
$DOM = new DOMDocument();
$DOM->loadHTML($markup);
$DOM->normalizeDocument();
$this->DOM = $DOM;
}
function render () {
$node = $this->DOM->documentElement;
$HTML = new TextifyTag($node);
return $HTML->render();
}
}
/**
* TextifyTag
*
* Foundational Textify rendering behavior
*
* @author Jonathan Davis
* @since 1.2
* @package textify
**/
class TextifyTag {
const NEWLINE = "\n";
const STRPAD = " ";
const CLASSPREFIX = 'Textify';
const DEBUG = true;
static $_marks = array( // Default text decoration marks registry
'inline' => '',
'padding' => array('top'=>' ','right'=>' ','bottom' =>' ','left'=>' '),
'margins' => array('top'=>' ','right'=>' ','bottom' =>' ','left'=>' '),
'borders' => array('top'=>'-','right'=>'|','bottom' =>'-','left'=>'|'),
'corners' => array('top-left'=>'·','top-right' => '·','bottom-right' => '·','bottom-left' => '·','middle-middle'=> '·','top-middle'=>'·','middle-left'=>'·','middle-right'=>'·','bottom-middle'=>'·')
);
protected $node = false; // The DOM node for the tag
protected $renderer = false; // The Textify Renderer object for this node
protected $content = array(); // The rendered child/text content
protected $height = 0;
protected $width = array('max' => 0, 'min' => 0);
protected $tag = ''; // Name of the tag
protected $attrs = array(); // Name of the tag
protected $styles = array(); // Parsed styles
protected $textalign = 'left'; // Text alignment (left,center,right, justified)
protected $legend = ''; // Tag legend
protected $marks = array(); // Override-able text decoration marks registry
protected $borders = array('top'=>0,'right'=>0,'bottom'=>0,'left'=>0);
protected $margins = array('top'=>0,'right'=>0,'bottom'=>0,'left'=>0);
function __construct (&$tag) {
$this->node = $tag;
$this->tag = $tag->tagName;
$this->marks = array_merge(TextifyTag::$_marks,$this->marks);
// Style attribute parser
// if (isset($attrs['style'])) $this->style
}
/**
* Rendering engine
*
* Recursive processing of each node passed off to a renderer for
* text formatting and other rendering (borders, padding, markdown marks)
*
* @author Jonathan Davis
* @since 1.2
*
* @param DOMNode $node The DOMNode to render out
* @return string The rendered content
**/
function render ($node = false) {
if ( !$node ) {
$node = $this->node;
if (!$node) return false;
}
if ($node->hasAttributes()) {
foreach ($node->attributes as $name => $attr) {
if ('style' == $name) $this->styles($attr->value);
else $this->attrs[$name] = $attr->value;
}
}
// No child nodes, render it out to and send back the parent container
if ( ! $node->hasChildNodes() ) return $this->layout();
foreach ($node->childNodes as $index => $child) {
if ( XML_TEXT_NODE == $child->nodeType || XML_CDATA_SECTION_NODE == $child->nodeType ) {
$text = $child->nodeValue;
if (!empty($text)) $this->append( $this->format($text) );
} elseif ( XML_ELEMENT_NODE == $child->nodeType) {
$Renderer = $this->renderer($child);
$this->append( $Renderer->render(), isset($Renderer->block) );
}
}
// All done, render it out and send it all back to the parent container
return $this->layout();
}
/**
* Combines the assembled content
*
* @author Jonathan Davis
* @since 1.2
*
* @return string The final assembled content for the element
**/
function layout () {
// Follows box model standards
$this->prepend( $this->before() ); // Add before content
$this->append( $this->after() ); // Add after content
$this->padding(); // Add padding box
$this->dimensions(); // Calculate final dimensions
$this->borders(); // Add border decoration box
$this->margins(); // Add margins box
// Send the string back to the parent renderer
return join(TextifyTag::NEWLINE,$this->content);
}
function append ($content,$block=false) {
$lines = array_filter($this->lines($content));
if (empty($lines)) return;
if (!$block) {
// Stitch the content of the first new line to the last content in the line list
$firstline = array_shift($lines);
if (!is_null($firstline) && !empty($this->content)) {
$id = count($this->content)-1;
$this->content[ $id ] .= $firstline;
// Determine if max width has changed
$this->width['max'] = max($this->width['max'],strlen($this->content[$id]));
} else $this->content[] = $firstline;
}
$this->content = array_merge($this->content,$lines);
}
function prepend ($content) {
$lines = array_filter($this->lines($content));
if (empty($lines)) return;
// Stitch the content of the last new line to the first line of the current content line list
$lastline = array_pop($lines);
$this->content[0] = $lastline.$this->content[0];
$this->width['max'] = max($this->width['max'],strlen($this->content[0]));
$this->content[0] = TextifyTag::whitespace($this->content[0]);
$this->content = array_merge($lines,$this->content);
}
function lines ($content) {
if (is_array($content)) $content = join('',$content);
if (empty($content)) return array();
$linebreaks = TextifyTag::NEWLINE;
$wordbreaks = " \t";
$maxline = 0; $maxword = 0;
$lines = explode($linebreaks,$content);
foreach ((array)$lines as $line) {
$maxline = max($maxline,strlen($line));
$word = false;
$word = strtok($line,$wordbreaks);
while (false !== $word) {
$maxword = max($maxword,strlen($word));
$word = strtok($wordbreaks);
}
}
$this->width['min'] = max($this->width['min'],$maxword);
$this->width['max'] = max($this->width['max'],$maxline);
return $lines;
}
/**
* Calculate content min/max widths
*
* Maximum width is the longest contiguous (unbroken) line
* Minimum width is the longest word
*
* @author Jonathan Davis
* @since 1.2
*
* @param string $content The content to calculate
* @return void
**/
function dimensions () {
$this->lines(join(TextifyTag::NEWLINE,$this->content));
}
function before () {
// if (TextifyTag::DEBUG) return "<$this->tag>";
}
function format ($text) {
return TextifyTag::whitespace($text);
}
function after () {
// if (TextifyTag::DEBUG) return "</$this->tag>";
}
function padding () { /* placeholder */ }
function borders () { /* placeholder */ }
function margins () { /* placeholder */ }
/**
* Mark renderer
*
* @author Jonathan Davis
* @since 1.2
*
* @return string
**/
function marks ($repeat = 1) {
return str_repeat($this->marks['inline'],$repeat);
}
function linebreak () {
return self::NEWLINE;
}
/**
* Collapses whitespace into a single space
*
* @author Jonathan Davis
* @since 1.2
*
* @return void Description...
**/
static function whitespace ($text) {
return preg_replace('/\s+/', ' ', $text);
}
function renderer ($tag) {
if (isset($tag->Renderer)) {
$tag->Renderer->content = array();
return $tag->Renderer;
}
$Tagname = ucfirst($tag->tagName);
$Renderer = self::CLASSPREFIX.$Tagname;
if (!class_exists($Renderer)) $Renderer = __CLASS__;
$tag->Renderer = new $Renderer($tag);
return $tag->Renderer;
}
function parent () {
return $this->node->parentNode->Renderer;
}
function styles ($string) {
}
}
class TextifyInlineElement extends TextifyTag {
function before () { return $this->marks(); }
function after () { return $this->marks(); }
}
class TextifyA extends TextifyInlineElement {
function before () {
return '<';
}
function after () {
$string = '';
if (isset($this->attrs['href']) && !empty($this->attrs['href'])) {
$href = $this->attrs['href'];
if ('#' != $href{0}) $string .= ': '.$href;
}
return $string.'>';
}
}
class TextifyEm extends TextifyInlineElement {
var $marks = array('inline' => '_');
}
class TextifyStrong extends TextifyInlineElement {
var $marks = array('inline' => '**');
}
class TextifyCode extends TextifyInlineElement {
var $marks = array('inline' => '`');
}
class TextifyBr extends TextifyInlineElement {
function layout () {
$this->content = array(' ',' ');
return parent::layout();
}
}
class TextifyBlockElement extends TextifyTag {
protected $block = true;
protected $margins = array('top' => 0,'right' => 0,'bottom' => 0,'left' => 0);
protected $borders = array('top' => 0,'right' => 0,'bottom' => 0,'left' => 0);
protected $padding = array('top' => 0,'right' => 0,'bottom' => 0,'left' => 0);
function width () {
return $this->width['max'];
}
function box (&$lines,$type='margins') {
if (!isset($this->marks[$type])) return;
$size = 0;
$marks = array('top' => '','right' => '', 'bottom' => '', 'left' => '');
if (isset($this->marks[ $type ]) && !empty($this->marks[ $type ]))
$marks = array_merge($marks,$this->marks[ $type ]);
if ( isset($this->$type) ) $sizes = $this->$type;
$left = str_repeat($marks['left'],$sizes['left']);
$right = str_repeat($marks['right'],$sizes['right']);
$width = $this->width();
$boxwidth = $width;
foreach ($lines as &$line) {
if (empty($line)) $line = $left.str_repeat(TextifyTag::STRPAD,$width).$right;
else $line = $left.str_pad($line,$width,TextifyTag::STRPAD).$right;
$boxwidth = max($boxwidth,strlen($line));
}
if ( $sizes['top'] ) {
for ($i = 0; $i < $sizes['top']; $i++) {
$top = str_repeat($marks['top'],$boxwidth);
if ('borders' == $type) $this->legend($top);
array_unshift( $lines, $top );
}
}
if ( $sizes['bottom'] )
for ($i = 0; $i < $sizes['bottom']; $i++)
array_push( $lines, str_repeat($marks['bottom'],$boxwidth) );
}
function padding () {
$this->box($this->content,'padding');
}
function borders () {
$this->box($this->content,'borders');
}
function margins () {
$this->box($this->content,'margins');
}
function legend ($string) {
if (TextifyTag::DEBUG) $legend = $this->tag;
else $legend = $this->legend;
return substr($string,0,2).$legend.substr($string,(2+strlen($legend)));
}
}
class TextifyDiv extends TextifyBlockElement {
}
class TextifyHeader extends TextifyBlockElement {
var $level = 1;
var $marks = array('inline' => '#');
var $margins = array('top' => 1,'right' => 0,'bottom' => 1,'left' => 0);
function before () {
$text = parent::before();
$text .= $this->marks($this->level).' ';
return $text;
}
function after () {
$text = ' '.$this->marks($this->level);
$text .= parent::after();
return $text;
}
}
class TextifyH1 extends TextifyHeader {
var $marks = array('inline' => '=');
function before () {}
function format ($text) {
$marks = $this->marks(strlen($text));
return "$text\n$marks";
}
function after () {}
}
class TextifyH2 extends TextifyH1 {
var $level = 2;
var $marks = array('inline' => '-');
}
class TextifyH3 extends TextifyHeader {
var $level = 3;
}
class TextifyH4 extends TextifyHeader {
var $level = 4;
}
class TextifyH5 extends TextifyHeader {
var $level = 5;
}
class TextifyH6 extends TextifyHeader {
var $level = 6;
}
class TextifyP extends TextifyBlockElement {
var $margins = array('top' => 0,'right' => 0,'bottom' => 1,'left' => 0);
}
class TextifyBlockquote extends TextifyBlockElement {
function layout () {
$this->content = array_map(array($this,'quote'),$this->content);
return parent::layout();
}
function quote ($line) {
return "> $line";
}
}
class TextifyListContainer extends TextifyBlockElement {
var $margins = array('top' => 0,'right' => 0,'bottom' => 1,'left' => 4);
var $counter = 0;
function additem () {
return ++$this->counter;
}
}
class TextifyDl extends TextifyListContainer {
var $margins = array('top' => 0,'right' => 0,'bottom' => 1,'left' => 0);
}
class TextifyDt extends TextifyBlockElement {
}
class TextifyDd extends TextifyBlockElement {
var $margins = array('top' => 0,'right' => 0,'bottom' => 0,'left' => 4);
}
class TextifyUl extends TextifyListContainer {
var $margins = array('top' => 0,'right' => 0,'bottom' => 1,'left' => 4);
}
class TextifyOl extends TextifyListContainer {
var $margins = array('top' => 0,'right' => 0,'bottom' => 1,'left' => 4);
}
class TextifyLi extends TextifyBlockElement {
var $margins = array('top' => 0,'right' => 0,'bottom' => 0,'left' => 0);
var $num = false;
function __construct(&$tag) {
parent::__construct($tag);
$parent = $this->parent();
if ($parent && method_exists($parent,'additem'))
$this->num = $parent->additem();
}
function before () {
if ('TextifyOl' == get_class($this->parent())) return $this->num.'. ';
else return '* ';
}
}
class TextifyHr extends TextifyBlockElement {
var $margins = array('top' => 1,'right' => 0,'bottom' => 1,'left' => 0);
var $marks = array('inline' => '-');
function layout () {
$this->content = array($this->marks(75));
return parent::layout();
}
}
class TextifyTable extends TextifyBlockElement {
var $margins = array('top' => 0,'right' => 0,'bottom' => 1,'left' => 0);
private $rows = 0; // Total number of rows
private $colwidths = array();
/**
* Table layout engine
*
* Recursive processing of each node passed off to a renderer for
* text formatting and other rendering (borders, padding, markdown marks)
*
* @author Jonathan Davis
* @since 1.2
*
* @param DOMNode $node The DOMNode to render out
* @return string The rendered content
**/
function render ($node = false) {
if ( !$node ) {
$node = $this->node;
if (!$node) return false;
}
// No child nodes, render it out to and send back the parent container
if ( ! $node->hasChildNodes() ) return $this->layout();
// Step 1: Determine min/max dimensions from rendered content
foreach ($node->childNodes as $index => $child) {
if ( XML_TEXT_NODE == $child->nodeType || XML_CDATA_SECTION_NODE == $child->nodeType ) {
$text = trim($child->nodeValue,"\t\n\r\0\x0B");
if (!empty($text)) $this->append( $this->format($text) );
} elseif ( XML_ELEMENT_NODE == $child->nodeType) {
$Renderer = $this->renderer($child);
$this->append( $Renderer->render() );
}
}
// Step 2: Reflow content based on width constraints
$this->content = array();
foreach ($node->childNodes as $index => $child) {
if ( XML_TEXT_NODE == $child->nodeType || XML_CDATA_SECTION_NODE == $child->nodeType ) {
$text = trim($child->nodeValue,"\t\n\r\0\x0B");
if (!empty($text)) $this->append( $this->format($text) );
} elseif ( XML_ELEMENT_NODE == $child->nodeType) {
$Renderer = $this->renderer($child);
$this->append( $Renderer->render() );
}
}
// All done, render it out and send it all back to the parent container
return $this->layout();
}
function append ($content,$block=true) {
$lines = array_filter($this->lines($content));
if (empty($lines)) return;
// Stitch the content of the first new line to the last content in the line list
$firstline = $lines[0];
$lastline = false;
if ( ! empty($this->content) )
$lastline = $this->content[ count($this->content)-1 ];
if (!empty($lastline) && $lastline === $firstline) array_shift($lines);
$this->content = array_merge($this->content,$lines);
}
function borders () { /* disabled */ }
function addrow () {
$this->layout[$this->rows] = array();
return $this->rows++;
}
function addrowcolumn ($row = 0) {
$col = false;
if (isset($this->layout[$row])) {
$col = count($this->layout[$row]);
$this->layout[$row][$col] = array();
}
return $col;
}
function colwidth ($column,$width=false) {
if ( ! isset($this->colwidths[$column]) ) $this->colwidths[$column] = 0;
if (false !== $width)
$this->colwidths[$column] = max($this->colwidths[$column],$width);
return $this->colwidths[$column];
}
}
class TextifyTableTag extends TextifyBlockElement {
protected $table = false; // Parent table layout
function __construct ($tag) {
parent::__construct($tag);
$tablenode = $this->tablenode();
if (!$tablenode) return; // Bail, can't determine table layout
$this->table = $tablenode->Renderer;
}
/**
* Find the parent table node
*
* @author Jonathan Davis
* @since 1.2
*
* @return DOMNode
**/
function tablenode () {
$path = $this->node->getNodePath();
if (false === strpos($path,'table')) return false;
$parent = $this->node;
while ('table' != $parent->parentNode->tagName) {
$parent = $parent->parentNode;
}
return $parent->parentNode;
}
}
class TextifyTr extends TextifyTableTag {
private $row = 0;
private $cols = 0;
function __construct ($tag) {
parent::__construct($tag);
$this->row = $this->table->addrow();
}
function layout () {
$_ = array();
$lines = array();
foreach ($this->content as $cells) {
$segments = explode("\n",$cells);
$total = max(count($lines),count($segments));
for ($i = 0; $i < $total; $i++) {
if (!isset($segments[$i])) continue;
if (isset($lines[$i]) && !empty($lines[$i])) {
$eol = strlen($lines[$i])-1;
if (!empty($segments[$i]) && $lines[$i]{$eol} == $segments[$i]{0}) $lines[$i] .= substr($segments[$i],1);
else $lines[$i] .= $segments[$i];
} else {
if (!isset($lines[$i])) $lines[$i] = '';
$lines[$i] .= $segments[$i];
}
}
}
$_[] = join("\n",$lines);
return join('',$_);
}
function append ($content,$block=true) {
$this->content[] = $content;
}
function format ($text) { /* disabled */ }
function addcolumn ($column = 0) {
$id = $this->table->addrowcolumn($this->row);
$this->cols++;
return $id;
}
function tablerow () {
return $this->row;
}
function padding () { /* Disabled */ }
}
class TextifyTd extends TextifyTableTag {
var $row = false;
var $col = 0;
protected $padding = array('top' => 0,'right' => 1,'bottom' => 0,'left' => 1);
private $reported = false;
function __construct ($tag) {
parent::__construct($tag);
$row = $this->getrow();
$this->row = $row->tablerow();
$this->col = $row->addcolumn();
}
function margins () { /* disabled */ }
function dimensions () {
parent::dimensions();
if ($this->reported) return;
$this->table->colwidth($this->col,$this->width['max']);
$this->reported = true;
}
function width () {
return $this->table->colwidth($this->col);
}
function getrow () {
return $this->node->parentNode->Renderer;
}
}
class TextifyTh extends TextifyTd {
function before () { return '['; }
function after () { return ']'; }
}
class TextifyFieldset extends TextifyBlockElement {
}
class TextifyLegend extends TextifyBlockElement {
function format ($text) {
$this->legend = $text;
if (!$this->borders['top']) return '['.$text.']';
}
}
class TextifyAddress extends TextifyBlockElement {
// function append ($content,$block=false) {
// $lines = array_filter($this->lines($content));
// if (empty($lines)) return;
//
// $this->content = array_merge($this->content,$lines);
//
// }
}