-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathParser.php
2301 lines (2021 loc) · 65.5 KB
/
Parser.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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Mf2;
use DOMDocument;
use DOMElement;
use DOMXPath;
use DOMNode;
use DOMNodeList;
use Exception;
use SplObjectStorage;
use stdClass;
/**
* Parse Microformats2
*
* Functional shortcut for the commonest cases of parsing microformats2 from HTML.
*
* Example usage:
*
* use Mf2;
* $output = Mf2\parse('<span class="h-card">Barnaby Walters</span>');
* echo json_encode($output, JSON_PRETTY_PRINT);
*
* Produces:
*
* {
* "items": [
* {
* "type": ["h-card"],
* "properties": {
* "name": ["Barnaby Walters"]
* }
* }
* ],
* "rels": {}
* }
*
* @param string|DOMDocument $input The HTML string or DOMDocument object to parse
* @param string $url The URL the input document was found at, for relative URL resolution
* @param bool $convertClassic whether or not to convert classic microformats
* @return array Canonical MF2 array structure
*/
function parse($input, $url = null, $convertClassic = true) {
$parser = new Parser($input, $url);
return $parser->parse($convertClassic);
}
/**
* Fetch microformats2
*
* Given a URL, fetches it (following up to 5 redirects) and, if the content-type appears to be HTML, returns the parsed
* microformats2 array structure.
*
* Not that even if the response code was a 4XX or 5XX error, if the content-type is HTML-like then it will be parsed
* all the same, as there are legitimate cases where error pages might contain useful microformats (for example a deleted
* h-entry resulting in a 410 Gone page with a stub h-entry explaining the reason for deletion). Look in $curlInfo['http_code']
* for the actual value.
*
* @param string $url The URL to fetch
* @param bool $convertClassic (optional, default true) whether or not to convert classic microformats
* @param &array $curlInfo (optional) the results of curl_getinfo will be placed in this variable for debugging
* @return array|null canonical microformats2 array structure on success, null on failure
*/
function fetch($url, $convertClassic = true, &$curlInfo=null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: text/html'
));
$html = curl_exec($ch);
$info = $curlInfo = curl_getinfo($ch);
curl_close($ch);
if (strpos(strtolower($info['content_type']), 'html') === false) {
// The content was not delivered as HTML, do not attempt to parse it.
return null;
}
# ensure the final URL is used to resolve relative URLs
$url = $info['url'];
return parse($html, $url, $convertClassic);
}
/**
* Unicode to HTML Entities
* @param string $input String containing characters to convert into HTML entities
* @return string
*/
function unicodeToHtmlEntities($input) {
return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
}
/**
* Collapse Whitespace
*
* Collapses any sequences of whitespace within a string into a single space
* character.
*
* @deprecated since v0.2.3
* @param string $str
* @return string
*/
function collapseWhitespace($str) {
return preg_replace('/[\s|\n]+/', ' ', $str);
}
function unicodeTrim($str) {
// this is cheating. TODO: find a better way if this causes any problems
$str = str_replace(mb_convert_encoding(' ', 'UTF-8', 'HTML-ENTITIES'), ' ', $str);
$str = preg_replace('/^\s+/', '', $str);
return preg_replace('/\s+$/', '', $str);
}
/**
* Microformat Name From Class string
*
* Given the value of @class, get the relevant mf classnames (e.g. h-card,
* p-name).
*
* @param string $class A space delimited list of classnames
* @param string $prefix The prefix to look for
* @return string|array The prefixed name of the first microfomats class found or false
*/
function mfNamesFromClass($class, $prefix='h-') {
$class = str_replace(array(' ', ' ', "\n"), ' ', $class);
$classes = explode(' ', $class);
$classes = preg_grep('#^(h|p|u|dt|e)-([a-z0-9]+-)?[a-z]+(-[a-z]+)*$#', $classes);
$matches = array();
foreach ($classes as $classname) {
$compare_classname = ' ' . $classname;
$compare_prefix = ' ' . $prefix;
if (strstr($compare_classname, $compare_prefix) !== false && ($compare_classname != $compare_prefix)) {
$matches[] = ($prefix === 'h-') ? $classname : substr($classname, strlen($prefix));
}
}
return $matches;
}
/**
* Get Nested µf Property Name From Class
*
* Returns all the p-, u-, dt- or e- prefixed classnames it finds in a
* space-separated string.
*
* @param string $class
* @return array
*/
function nestedMfPropertyNamesFromClass($class) {
$prefixes = array('p-', 'u-', 'dt-', 'e-');
$propertyNames = array();
$class = str_replace(array(' ', ' ', "\n"), ' ', $class);
foreach (explode(' ', $class) as $classname) {
foreach ($prefixes as $prefix) {
// Check if $classname is a valid property classname for $prefix.
if (mb_substr($classname, 0, mb_strlen($prefix)) == $prefix && $classname != $prefix) {
$propertyName = mb_substr($classname, mb_strlen($prefix));
$propertyNames[$propertyName][] = $prefix;
}
}
}
foreach ($propertyNames as $property => $prefixes) {
$propertyNames[$property] = array_unique($prefixes);
}
return $propertyNames;
}
/**
* Wraps mfNamesFromClass to handle an element as input (common)
*
* @param DOMElement $e The element to get the classname for
* @param string $prefix The prefix to look for
* @return mixed See return value of mf2\Parser::mfNameFromClass()
*/
function mfNamesFromElement(\DOMElement $e, $prefix = 'h-') {
$class = $e->getAttribute('class');
return mfNamesFromClass($class, $prefix);
}
/**
* Wraps nestedMfPropertyNamesFromClass to handle an element as input
*/
function nestedMfPropertyNamesFromElement(\DOMElement $e) {
$class = $e->getAttribute('class');
return nestedMfPropertyNamesFromClass($class);
}
/**
* Converts various time formats to HH:MM
* @param string $time The time to convert
* @return string
*/
function convertTimeFormat($time) {
$hh = $mm = $ss = '';
preg_match('/(\d{1,2}):?(\d{2})?:?(\d{2})?(a\.?m\.?|p\.?m\.?)?/i', $time, $matches);
// If no am/pm is specified:
if (empty($matches[4])) {
return $time;
} else {
// Otherwise, am/pm is specified.
$meridiem = strtolower(str_replace('.', '', $matches[4]));
// Hours.
$hh = $matches[1];
// Add 12 to hours if pm applies.
if ($meridiem == 'pm' && ($hh < 12)) {
$hh += 12;
}
$hh = str_pad($hh, 2, '0', STR_PAD_LEFT);
// Minutes.
$mm = (empty($matches[2]) ) ? '00' : $matches[2];
// Seconds, only if supplied.
if (!empty($matches[3])) {
$ss = $matches[3];
}
if (empty($ss)) {
return sprintf('%s:%s', $hh, $mm);
}
else {
return sprintf('%s:%s:%s', $hh, $mm, $ss);
}
}
}
/**
* If a date value has a timezone offset, normalize it.
* @param string $dtValue
* @return string isolated, normalized TZ offset for implied TZ for other dt- properties
*/
function normalizeTimezoneOffset(&$dtValue) {
preg_match('/Z|[+-]\d{1,2}:?(\d{2})?$/i', $dtValue, $matches);
if (empty($matches)) {
return null;
}
$timezoneOffset = null;
if ( $matches[0] != 'Z' ) {
$timezoneString = str_replace(':', '', $matches[0]);
$plus_minus = substr($timezoneString, 0, 1);
$timezoneOffset = substr($timezoneString, 1);
if ( strlen($timezoneOffset) <= 2 ) {
$timezoneOffset .= '00';
}
$timezoneOffset = str_pad($timezoneOffset, 4, 0, STR_PAD_LEFT);
$timezoneOffset = $plus_minus . $timezoneOffset;
$dtValue = preg_replace('/Z?[+-]\d{1,2}:?(\d{2})?$/i', $timezoneOffset, $dtValue);
}
return $timezoneOffset;
}
function applySrcsetUrlTransformation($srcset, $transformation) {
return implode(', ', array_filter(array_map(function ($srcsetPart) use ($transformation) {
$parts = explode(" \t\n\r\0\x0B", trim($srcsetPart), 2);
$parts[0] = rtrim($parts[0]);
if (empty($parts[0])) { return false; }
$parts[0] = call_user_func($transformation, $parts[0]);
return $parts[0] . (empty($parts[1]) ? '' : ' ' . $parts[1]);
}, explode(',', trim($srcset)))));
}
/**
* Microformats2 Parser
*
* A class which holds state for parsing microformats2 from HTML.
*
* Example usage:
*
* use Mf2;
* $parser = new Mf2\Parser('<p class="h-card">Barnaby Walters</p>');
* $output = $parser->parse();
*/
class Parser {
/** @var string The baseurl (if any) to use for this parse */
public $baseurl;
/** @var DOMXPath object which can be used to query over any fragment*/
public $xpath;
/** @var DOMDocument */
public $doc;
/** @var SplObjectStorage */
protected $parsed;
/**
* @var bool
*/
public $jsonMode;
/** @var boolean Whether to include experimental language parsing in the result */
public $lang = false;
/** @var bool Whether to include alternates object (dropped from spec in favor of rel-urls) */
public $enableAlternates = false;
/**
* Elements upgraded to mf2 during backcompat
* @var SplObjectStorage
*/
protected $upgraded;
/**
* Whether to convert classic microformats
* @var bool
*/
public $convertClassic;
/**
* Constructor
*
* @param DOMDocument|string $input The data to parse. A string of HTML or a DOMDocument
* @param string $url The URL of the parsed document, for relative URL resolution
* @param boolean $jsonMode Whether or not to use a stdClass instance for an empty `rels` dictionary. This breaks PHP looping over rels, but allows the output to be correctly serialized as JSON.
*/
public function __construct($input, $url = null, $jsonMode = false) {
libxml_use_internal_errors(true);
if (is_string($input)) {
if (class_exists('Masterminds\\HTML5')) {
$doc = new \Masterminds\HTML5(array('disable_html_ns' => true));
$doc = $doc->loadHTML($input);
} else {
$doc = new DOMDocument();
@$doc->loadHTML(unicodeToHtmlEntities($input));
}
} elseif (is_a($input, 'DOMDocument')) {
$doc = clone $input;
} else {
$doc = new DOMDocument();
@$doc->loadHTML('');
}
$this->xpath = new DOMXPath($doc);
$baseurl = $url;
foreach ($this->xpath->query('//base[@href]') as $base) {
$baseElementUrl = $base->getAttribute('href');
if (parse_url($baseElementUrl, PHP_URL_SCHEME) === null) {
/* The base element URL is relative to the document URL.
*
* :/
*
* Perhaps the author was high? */
$baseurl = resolveUrl($url, $baseElementUrl);
} else {
$baseurl = $baseElementUrl;
}
break;
}
// Ignore <template> elements as per the HTML5 spec
foreach ($this->xpath->query('//template') as $templateEl) {
$templateEl->parentNode->removeChild($templateEl);
}
$this->baseurl = $baseurl;
$this->doc = $doc;
$this->parsed = new SplObjectStorage();
$this->upgraded = new SplObjectStorage();
$this->jsonMode = $jsonMode;
}
private function elementPrefixParsed(\DOMElement $e, $prefix) {
if (!$this->parsed->contains($e))
$this->parsed->attach($e, array());
$prefixes = $this->parsed[$e];
$prefixes[] = $prefix;
$this->parsed[$e] = $prefixes;
}
/**
* Determine if the element has already been parsed
* @param DOMElement $e
* @param string $prefix
* @return bool
*/
private function isElementParsed(\DOMElement $e, $prefix) {
if (!$this->parsed->contains($e)) {
return false;
}
$prefixes = $this->parsed[$e];
if (!in_array($prefix, $prefixes)) {
return false;
}
return true;
}
/**
* Determine if the element's specified property has already been upgraded during backcompat
* @param DOMElement $el
* @param string $property
* @return bool
*/
private function isElementUpgraded(\DOMElement $el, $property) {
if ( $this->upgraded->contains($el) ) {
if ( in_array($property, $this->upgraded[$el]) ) {
return true;
}
}
return false;
}
private function resolveChildUrls(DOMElement $el) {
$hyperlinkChildren = $this->xpath->query('.//*[@src or @href or @data]', $el);
foreach ($hyperlinkChildren as $child) {
if ($child->hasAttribute('href'))
$child->setAttribute('href', $this->resolveUrl($child->getAttribute('href')));
if ($child->hasAttribute('src'))
$child->setAttribute('src', $this->resolveUrl($child->getAttribute('src')));
if ($child->hasAttribute('srcset'))
$child->setAttribute('srcset', applySrcsetUrlTransformation($child->getAttribute('href'), array($this, 'resolveUrl')));
if ($child->hasAttribute('data'))
$child->setAttribute('data', $this->resolveUrl($child->getAttribute('data')));
}
}
/**
* The following two methods implements plain text parsing.
* @see https://wiki.zegnat.net/media/textparsing.html
**/
public function textContent(DOMElement $element)
{
return preg_replace(
'/(^[\t\n\f\r ]+| +(?=\n)|(?<=\n) +| +(?= )|[\t\n\f\r ]+$)/',
'',
$this->elementToString($element)
);
}
private function elementToString(DOMElement $input)
{
$output = '';
foreach ($input->childNodes as $child) {
if ($child->nodeType === XML_TEXT_NODE) {
$output .= str_replace(array("\t", "\n", "\r") , ' ', $child->textContent);
} else if ($child->nodeType === XML_ELEMENT_NODE) {
$tagName = strtoupper($child->tagName);
if (in_array($tagName, array('SCRIPT', 'STYLE'))) {
continue;
} else if ($tagName === 'IMG') {
if ($child->hasAttribute('alt')) {
$output .= ' ' . trim($child->getAttribute('alt'), "\t\n\f\r ") . ' ';
} else if ($child->hasAttribute('src')) {
$output .= ' ' . $this->resolveUrl(trim($child->getAttribute('src'), "\t\n\f\r ")) . ' ';
}
} else if ($tagName === 'BR') {
$output .= "\n";
} else if ($tagName === 'P') {
$output .= "\n" . $this->elementToString($child);
} else {
$output .= $this->elementToString($child);
}
}
}
return $output;
}
/**
* This method parses the language of an element
* @param DOMElement $el
* @access public
* @return string
*/
public function language(DOMElement $el)
{
// element has a lang attribute; use it
if ($el->hasAttribute('lang')) {
return unicodeTrim($el->getAttribute('lang'));
}
if ($el->tagName == 'html') {
// we're at the <html> element and no lang; check <meta> http-equiv Content-Language
foreach ( $this->xpath->query('.//meta[@http-equiv]') as $node )
{
if ($node->hasAttribute('http-equiv') && $node->hasAttribute('content') && strtolower($node->getAttribute('http-equiv')) == 'content-language') {
return unicodeTrim($node->getAttribute('content'));
}
}
} elseif ($el->parentNode instanceof DOMElement) {
// check the parent node
return $this->language($el->parentNode);
}
return '';
} # end method language()
// TODO: figure out if this has problems with sms: and geo: URLs
public function resolveUrl($url) {
// If the URL is seriously malformed it’s probably beyond the scope of this
// parser to try to do anything with it.
if (parse_url($url) === false) {
return $url;
}
// per issue #40 valid URLs could have a space on either side
$url = trim($url);
$scheme = parse_url($url, PHP_URL_SCHEME);
if (empty($scheme) and !empty($this->baseurl)) {
return resolveUrl($this->baseurl, $url);
} else {
return $url;
}
}
// Parsing Functions
/**
* Parse value-class/value-title on an element, joining with $separator if
* there are multiple.
*
* @param \DOMElement $e
* @param string $separator = '' if multiple value-title elements, join with this string
* @return string|null the parsed value or null if value-class or -title aren’t in use
*/
public function parseValueClassTitle(\DOMElement $e, $separator = '') {
$valueClassElements = $this->xpath->query('./*[contains(concat(" ", @class, " "), " value ")]', $e);
if ($valueClassElements->length !== 0) {
// Process value-class stuff
$val = '';
foreach ($valueClassElements as $el) {
$val .= $this->textContent($el);
}
return unicodeTrim($val);
}
$valueTitleElements = $this->xpath->query('./*[contains(concat(" ", @class, " "), " value-title ")]', $e);
if ($valueTitleElements->length !== 0) {
// Process value-title stuff
$val = '';
foreach ($valueTitleElements as $el) {
$val .= $el->getAttribute('title');
}
return unicodeTrim($val);
}
// No value-title or -class in this element
return null;
}
/**
* Given an element with class="p-*", get its value
*
* @param DOMElement $p The element to parse
* @return string The plaintext value of $p, dependant on type
* @todo Make this adhere to value-class
*/
public function parseP(\DOMElement $p) {
$classTitle = $this->parseValueClassTitle($p, ' ');
if ($classTitle !== null) {
return $classTitle;
}
$this->resolveChildUrls($p);
if ($p->tagName == 'img' and $p->hasAttribute('alt')) {
$pValue = $p->getAttribute('alt');
} elseif ($p->tagName == 'area' and $p->hasAttribute('alt')) {
$pValue = $p->getAttribute('alt');
} elseif (($p->tagName == 'abbr' or $p->tagName == 'link') and $p->hasAttribute('title')) {
$pValue = $p->getAttribute('title');
} elseif (in_array($p->tagName, array('data', 'input')) and $p->hasAttribute('value')) {
$pValue = $p->getAttribute('value');
} else {
$pValue = $this->textContent($p);
}
return $pValue;
}
/**
* Given an element with class="u-*", get the value of the URL
*
* @param DOMElement $u The element to parse
* @return string The plaintext value of $u, dependant on type
* @todo make this adhere to value-class
*/
public function parseU(\DOMElement $u) {
if (($u->tagName == 'a' or $u->tagName == 'area' or $u->tagName == 'link') and $u->hasAttribute('href')) {
$uValue = $u->getAttribute('href');
} elseif (in_array($u->tagName, array('img', 'audio', 'video', 'source')) and $u->hasAttribute('src')) {
$uValue = $u->getAttribute('src');
} elseif ($u->tagName == 'video' and !$u->hasAttribute('src') and $u->hasAttribute('poster')) {
$uValue = $u->getAttribute('poster');
} elseif ($u->tagName == 'object' and $u->hasAttribute('data')) {
$uValue = $u->getAttribute('data');
} elseif (($classTitle = $this->parseValueClassTitle($u)) !== null) {
$uValue = $classTitle;
} elseif (($u->tagName == 'abbr' or $u->tagName == 'link') and $u->hasAttribute('title')) {
$uValue = $u->getAttribute('title');
} elseif (in_array($u->tagName, array('data', 'input')) and $u->hasAttribute('value')) {
$uValue = $u->getAttribute('value');
} else {
$uValue = $this->textContent($u);
}
return $this->resolveUrl($uValue);
}
/**
* Given an element with class="dt-*", get the value of the datetime as a php date object
*
* @param DOMElement $dt The element to parse
* @param array $dates Array of dates processed so far
* @param string $impliedTimezone
* @return string The datetime string found
*/
public function parseDT(\DOMElement $dt, &$dates = array(), &$impliedTimezone = null) {
// Check for value-class pattern
$valueClassChildren = $this->xpath->query('./*[contains(concat(" ", @class, " "), " value ") or contains(concat(" ", @class, " "), " value-title ")]', $dt);
$dtValue = false;
if ($valueClassChildren->length > 0) {
// They’re using value-class
$dateParts = array();
foreach ($valueClassChildren as $e) {
if (strstr(' ' . $e->getAttribute('class') . ' ', ' value-title ')) {
$title = $e->getAttribute('title');
if (!empty($title)) {
$dateParts[] = $title;
}
}
elseif ($e->tagName == 'img' or $e->tagName == 'area') {
// Use @alt
$alt = $e->getAttribute('alt');
if (!empty($alt)) {
$dateParts[] = $alt;
}
}
elseif ($e->tagName == 'data') {
// Use @value, otherwise innertext
$value = $e->hasAttribute('value') ? $e->getAttribute('value') : unicodeTrim($e->nodeValue);
if (!empty($value)) {
$dateParts[] = $value;
}
}
elseif ($e->tagName == 'abbr') {
// Use @title, otherwise innertext
$title = $e->hasAttribute('title') ? $e->getAttribute('title') : unicodeTrim($e->nodeValue);
if (!empty($title)) {
$dateParts[] = $title;
}
}
elseif ($e->tagName == 'del' or $e->tagName == 'ins' or $e->tagName == 'time') {
// Use @datetime if available, otherwise innertext
$dtAttr = ($e->hasAttribute('datetime')) ? $e->getAttribute('datetime') : unicodeTrim($e->nodeValue);
if (!empty($dtAttr)) {
$dateParts[] = $dtAttr;
}
}
else {
if (!empty($e->nodeValue)) {
$dateParts[] = unicodeTrim($e->nodeValue);
}
}
}
// Look through dateParts
$datePart = '';
$timePart = '';
$timezonePart = '';
foreach ($dateParts as $part) {
// Is this part a full ISO8601 datetime?
if (preg_match('/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?(Z|[+-]\d{2}:?\d{2})?$/', $part)) {
// Break completely, we’ve got our value.
$dtValue = $part;
break;
} else {
// Is the current part a valid time(+TZ?) AND no other time representation has been found?
if ((preg_match('/^\d{1,2}:\d{2}(:\d{2})?(Z|[+-]\d{1,2}:?\d{2})?$/', $part) or preg_match('/^\d{1,2}(:\d{2})?(:\d{2})?[ap]\.?m\.?$/i', $part)) and empty($timePart)) {
$timePart = $part;
$timezoneOffset = normalizeTimezoneOffset($timePart);
if (!$impliedTimezone && $timezoneOffset) {
$impliedTimezone = $timezoneOffset;
}
// Is the current part a valid date AND no other date representation has been found?
} elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $part) and empty($datePart)) {
$datePart = $part;
// Is the current part a valid timezone offset AND no other timezone part has been found?
} elseif (preg_match('/^(Z|[+-]\d{1,2}:?(\d{2})?)$/', $part) and empty($timezonePart)) {
$timezonePart = $part;
$timezoneOffset = normalizeTimezoneOffset($timezonePart);
if (!$impliedTimezone && $timezoneOffset) {
$impliedTimezone = $timezoneOffset;
}
// Current part already represented by other VCP parts; do nothing with it
} else {
continue;
}
if ( !empty($datePart) && !in_array($datePart, $dates) ) {
$dates[] = $datePart;
}
if (!empty($timezonePart) && !empty($timePart)) {
$timePart .= $timezonePart;
}
$dtValue = '';
if ( empty($datePart) && !empty($timePart) ) {
$timePart = convertTimeFormat($timePart);
$dtValue = unicodeTrim($timePart);
}
else if ( !empty($datePart) && empty($timePart) ) {
$dtValue = rtrim($datePart, 'T');
}
else {
$timePart = convertTimeFormat($timePart);
$dtValue = rtrim($datePart, 'T') . ' ' . unicodeTrim($timePart);
}
}
}
} else {
// Not using value-class (phew).
if ($dt->tagName == 'img' or $dt->tagName == 'area') {
// Use @alt
// Is it an entire dt?
$alt = $dt->getAttribute('alt');
if (!empty($alt)) {
$dtValue = $alt;
}
} elseif (in_array($dt->tagName, array('data'))) {
// Use @value, otherwise innertext
// Is it an entire dt?
$value = $dt->getAttribute('value');
if (!empty($value)) {
$dtValue = $value;
}
else {
$dtValue = $this->textContent($dt);
}
} elseif ($dt->tagName == 'abbr') {
// Use @title, otherwise innertext
// Is it an entire dt?
$title = $dt->getAttribute('title');
if (!empty($title)) {
$dtValue = $title;
}
else {
$dtValue = $this->textContent($dt);
}
} elseif ($dt->tagName == 'del' or $dt->tagName == 'ins' or $dt->tagName == 'time') {
// Use @datetime if available, otherwise innertext
// Is it an entire dt?
$dtAttr = $dt->getAttribute('datetime');
if (!empty($dtAttr)) {
$dtValue = $dtAttr;
}
else {
$dtValue = $this->textContent($dt);
}
} else {
$dtValue = $this->textContent($dt);
}
// if the dtValue is not just YYYY-MM-DD
if (!preg_match('/^(\d{4}-\d{2}-\d{2})$/', $dtValue)) {
// no implied timezone set and dtValue has a TZ offset, use un-normalized TZ offset
preg_match('/Z|[+-]\d{1,2}:?(\d{2})?$/i', $dtValue, $matches);
if (!$impliedTimezone && !empty($matches[0])) {
$impliedTimezone = $matches[0];
}
}
$dtValue = unicodeTrim($dtValue);
// Store the date part so that we can use it when assembling the final timestamp if the next one is missing a date part
if (preg_match('/(\d{4}-\d{2}-\d{2})/', $dtValue, $matches)) {
$dates[] = $matches[0];
}
}
/**
* if $dtValue is only a time and there are recently parsed dates,
* form the full date-time using the most recently parsed dt- value
*/
if ((preg_match('/^\d{1,2}:\d{2}(:\d{2})?(Z|[+-]\d{2}:?\d{2}?)?$/', $dtValue) or preg_match('/^\d{1,2}(:\d{2})?(:\d{2})?[ap]\.?m\.?$/i', $dtValue)) && !empty($dates)) {
$timezoneOffset = normalizeTimezoneOffset($dtValue);
if (!$impliedTimezone && $timezoneOffset) {
$impliedTimezone = $timezoneOffset;
}
$dtValue = convertTimeFormat($dtValue);
$dtValue = end($dates) . ' ' . unicodeTrim($dtValue);
}
return $dtValue;
}
/**
* Given the root element of some embedded markup, return a string representing that markup
*
* @param DOMElement $e The element to parse
* @return string $e’s innerHTML
*
* @todo need to mark this element as e- parsed so it doesn’t get parsed as it’s parent’s e-* too
*/
public function parseE(\DOMElement $e) {
$classTitle = $this->parseValueClassTitle($e);
if ($classTitle !== null)
return $classTitle;
// Expand relative URLs within children of this element
// TODO: as it is this is not relative to only children, make this .// and rerun tests
$this->resolveChildUrls($e);
// Temporarily move all descendants into a separate DocumentFragment.
// This way we can DOMDocument::saveHTML on the entire collection at once.
// Running DOMDocument::saveHTML per node may add whitespace that isn't in source.
// See https://stackoverflow.com/q/38317903
$innerNodes = $e->ownerDocument->createDocumentFragment();
while ($e->hasChildNodes()) {
$innerNodes->appendChild($e->firstChild);
}
$html = $e->ownerDocument->saveHtml($innerNodes);
// Put the nodes back in place.
if($innerNodes->hasChildNodes()) {
$e->appendChild($innerNodes);
}
$return = array(
'html' => unicodeTrim($html),
'value' => $this->textContent($e),
);
if($this->lang) {
// Language
if ( $html_lang = $this->language($e) ) {
$return['lang'] = $html_lang;
}
}
return $return;
}
private function removeTags(\DOMElement &$e, $tagName) {
while(($r = $e->getElementsByTagName($tagName)) && $r->length) {
$r->item(0)->parentNode->removeChild($r->item(0));
}
}
/**
* Recursively parse microformats
*
* @param DOMElement $e The element to parse
* @param bool $is_backcompat Whether using backcompat parsing or not
* @param bool $has_nested_mf Whether this microformat has a nested microformat
* @return array A representation of the values contained within microformat $e
*/
public function parseH(\DOMElement $e, $is_backcompat = false, $has_nested_mf = false) {
// If it’s already been parsed (e.g. is a child mf), skip
if ($this->parsed->contains($e)) {
return null;
}
// Get current µf name
$mfTypes = mfNamesFromElement($e, 'h-');
if (!$mfTypes) {
return null;
}
// Initalise var to store the representation in
$return = array();
$children = array();
$dates = array();
$prefixes = array();
$impliedTimezone = null;
if($e->tagName == 'area') {
$coords = $e->getAttribute('coords');
$shape = $e->getAttribute('shape');
}
// Handle p-*
foreach ($this->xpath->query('.//*[contains(concat(" ", @class) ," p-")]', $e) as $p) {
// element is already parsed
if ($this->isElementParsed($p, 'p')) {
continue;
// backcompat parsing and element was not upgraded; skip it
} else if ( $is_backcompat && empty($this->upgraded[$p]) ) {
$this->elementPrefixParsed($p, 'p');
continue;
}
$prefixes[] = 'p-';
$pValue = $this->parseP($p);
// Add the value to the array for it’s p- properties
foreach (mfNamesFromElement($p, 'p-') as $propName) {
if (!empty($propName)) {
$return[$propName][] = $pValue;
}
}
// Make sure this sub-mf won’t get parsed as a top level mf
$this->elementPrefixParsed($p, 'p');
}
// Handle u-*
foreach ($this->xpath->query('.//*[contains(concat(" ", @class)," u-")]', $e) as $u) {
// element is already parsed
if ($this->isElementParsed($u, 'u')) {
continue;
// backcompat parsing and element was not upgraded; skip it
} else if ( $is_backcompat && empty($this->upgraded[$u]) ) {
$this->elementPrefixParsed($u, 'u');
continue;
}
$prefixes[] = 'u-';
$uValue = $this->parseU($u);
// Add the value to the array for it’s property types
foreach (mfNamesFromElement($u, 'u-') as $propName) {
$return[$propName][] = $uValue;
}
// Make sure this sub-mf won’t get parsed as a top level mf
$this->elementPrefixParsed($u, 'u');
}
$temp_dates = array();
// Handle dt-*
foreach ($this->xpath->query('.//*[contains(concat(" ", @class), " dt-")]', $e) as $dt) {
// element is already parsed
if ($this->isElementParsed($dt, 'dt')) {
continue;
// backcompat parsing and element was not upgraded; skip it
} else if ( $is_backcompat && empty($this->upgraded[$dt]) ) {
$this->elementPrefixParsed($dt, 'dt');
continue;
}
$prefixes[] = 'dt-';
$dtValue = $this->parseDT($dt, $dates, $impliedTimezone);
if ($dtValue) {
// Add the value to the array for dt- properties
foreach (mfNamesFromElement($dt, 'dt-') as $propName) {
$temp_dates[$propName][] = $dtValue;
}
}
// Make sure this sub-mf won’t get parsed as a top level mf
$this->elementPrefixParsed($dt, 'dt');
}
foreach ($temp_dates as $propName => $data) {
foreach ( $data as $dtValue ) {
// var_dump(preg_match('/[+-]\d{2}(\d{2})?$/i', $dtValue));
if ( $impliedTimezone && preg_match('/(Z|[+-]\d{2}:?(\d{2})?)$/i', $dtValue, $matches) == 0 ) {
$dtValue .= $impliedTimezone;
}
$return[$propName][] = $dtValue;
}
}
// Handle e-*
foreach ($this->xpath->query('.//*[contains(concat(" ", @class)," e-")]', $e) as $em) {