-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathqevix.php
More file actions
1968 lines (1650 loc) · 64.4 KB
/
qevix.php
File metadata and controls
1968 lines (1650 loc) · 64.4 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
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
class Qevix
{
const NIL = 0x0;
const PRINATABLE = 0x1;
const ALPHA = 0x2;
const NUMERIC = 0x4;
const PUNCTUATUON = 0x8;
const SPACE = 0x10;
const NL = 0x20;
const TAG_NAME = 0x40;
const TAG_PARAM_NAME = 0x80;
const TAG_QUOTE = 0x100;
const TEXT_QUOTE = 0x200;
const TEXT_BRACKET = 0x400;
const SPECIAL_CHAR = 0x800;
//const = 0x1000;
//const = 0x2000;
//const = 0x4000;
//const = 0x8000;
const NOPRINT = 0x10000;
public $tagsRules = array();
public $entities = array('"'=>'"', "'"=>''', '<'=>'<', '>'=>'>', '&'=>'&');
public $quotes = array(array('«', '»'), array('„', '“'));
public $bracketsALL = array('<'=>'>', '['=>']', '{'=>'}', '('=>')');
public $bracketsSPC = array('['=>']', '{'=>'}');
public $dash = "—";
public $nl = "\n";
protected $textBuf = array();
protected $textLen = 0;
protected $prevPos = -1;
protected $prevChar = null;
protected $prevCharOrd = 0;
protected $prevCharClass = self::NIL;
protected $curPos = -1;
protected $curChar = null;
protected $curCharOrd = 0;
protected $curCharClass = self::NIL;
protected $nextPos = -1;
protected $nextChar = null;
protected $nextCharOrd = 0;
protected $nextCharClass = self::NIL;
protected $curTag = null;
protected $statesStack = array();
protected $quotesOpened = 0;
protected $linkProtocolAllow = array('http','https','ftp');
protected $specialChars = array();
protected $isXHTMLMode = false;
protected $isAutoBrMode = true;
protected $isAutoLinkMode = true;
protected $isSpecialCharMode = false;
protected $typoMode = true;
protected $br = "<br>";
protected $errorsList = array();
/**
* Классификация тегов
*/
const TAG_ALLOWED = 1; // Тег допустим
const TAG_PARAM_ALLOWED = 2; // Параметр тега допустим
const TAG_PARAM_REQUIRED = 3; // Параметр тега является необходимым
const TAG_SHORT = 4; // Тег короткий
const TAG_CUT = 5; // Тег необходимо вырезать вместе с его контентом
const TAG_GLOBAL_ONLY = 6; // Тег может находиться только в "глобальной" области видимости (не быть дочерним к другим)
const TAG_PARENT_ONLY = 7; // Тег может содержать только другие теги
const TAG_CHILD_ONLY = 8; // Тег может находиться только внутри других тегов
const TAG_PARENT = 9; // Тег родитель относительно дочернего тега
const TAG_CHILD = 10; // Тег дочерний относительно родительского
const TAG_PREFORMATTED = 11; // Преформатированные теги
const TAG_PARAM_AUTO_ADD = 12; // Автодобавление параметров со значениями по умолчанию
const TAG_NO_TYPOGRAPHY = 13; // Тег с отключенным типографированием
const TAG_EMPTY = 14; // Пустой не короткий тег
const TAG_NO_AUTO_BR = 15; // Тег в котором не нужна авто-расстановка <br>
const TAG_BLOCK_TYPE = 16; // Тег после которого нужно удалять один перевод строки
const TAG_BUILD_CALLBACK = 17; // Тег обрабатывается и строится callback-функцией
const TAG_EVENT_CALLBACK = 18; // Тег обрабатывается callback-функцией для сбора информации
/**
* Классы символов из symbolclass.php
*/
protected $charClasses = array(0=>65536,1=>65536,2=>65536,3=>65536,4=>65536,5=>65536,6=>65536,7=>65536,8=>65536,9=>65552,10=>65568,
11=>65536,12=>65536,13=>65568,14=>65536,15=>65536,16=>65536,17=>65536,18=>65536,19=>65536,20=>65536,21=>65536,22=>65536,23=>65536,
24=>65536,25=>65536,26=>65536,27=>65536,28=>65536,29=>65536,30=>65536,31=>65536,32=>65552,97=>195,98=>195,99=>195,100=>195,101=>195,
102=>195,103=>195,104=>195,105=>195,106=>195,107=>195,108=>195,109=>195,110=>195,111=>195,112=>195,113=>195,114=>195,115=>195,116=>195,
117=>195,118=>195,119=>195,120=>195,121=>195,122=>195,65=>195,66=>195,67=>195,68=>195,69=>195,70=>195,71=>195,72=>195,73=>195,74=>195,
75=>195,76=>195,77=>195,78=>195,79=>195,80=>195,81=>195,82=>195,83=>195,84=>195,85=>195,86=>195,87=>195,88=>195,89=>195,90=>195,48=>197,
49=>197,50=>197,51=>197,52=>197,53=>197,54=>197,55=>197,56=>197,57=>197,45=>129,34=>769,39=>257,46=>9,44=>9,33=>9,63=>9,58=>9,59=>9,
60=>1025,62=>1025,91=>1025,93=>1025,123=>1025,125=>1025,40=>1025,41=>1025,64=>2049,35=>2049,36=>2049);
/**
* Установка конфигурации для одного или нескольких тегов
*
* @param array|string $tags тег(и)
* @param int $flag флаг конфигурации
* @param mixed $value значение флага
* @param boolean $createIfNoExists создать запить о теге, если он ещё не определён
*/
protected function _cfgSetTagsFlag($tags, $flag, $value, $createIfNoExists = true)
{
$tags = (is_array($tags)) ? $tags : array($tags);
foreach($tags as $tag)
{
if(!isset($this->tagsRules[$tag]) AND !$createIfNoExists) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$this->tagsRules[$tag][$flag] = $value;
}
}
/**
* КОНФИГУРАЦИЯ: Задает список разрешенных тегов
*
* @param array|string $tags тег(и)
*/
public function cfgAllowTags($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_ALLOWED, true);
}
/**
* КОНФИГУРАЦИЯ: Указывает, какие теги считать короткими (<br>, <img>)
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagShort($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_SHORT, true, false);
}
/**
* КОНФИГУРАЦИЯ: Указывает преформатированные теги, в которых нужно всё заменять на HTML сущности
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagPreformatted($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_PREFORMATTED, true, false);
}
/**
* КОНФИГУРАЦИЯ: Указывает теги в которых нужно отключить типографирование текста
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagNoTypography($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_NO_TYPOGRAPHY, true, false);
}
/**
* КОНФИГУРАЦИЯ: Указывает не короткие теги, которые могут быть пустыми и их не нужно из-за этого удалять
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagIsEmpty($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_EMPTY, true, false);
}
/**
* КОНФИГУРАЦИЯ: Указывает теги внутри которых не нужна авторасстановка тегов перевода на новую строку
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagNoAutoBr($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_NO_AUTO_BR, true, false);
}
/**
* КОНФИГУРАЦИЯ: Указывает теги, которые необходимо вырезать вместе с содержимым (style, script, iframe)
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagCutWithContent($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_CUT, true);
}
/**
* КОНФИГУРАЦИЯ: Указывает теги после которых не нужно добавлять дополнительный перевод строки, например, блочные теги
*
* @param array|string $tags тег(и)
*/
public function cfgSetTagBlockType($tags) {
$this->_cfgSetTagsFlag($tags, self::TAG_BLOCK_TYPE, true, false);
}
/**
* КОНФИГУРАЦИЯ: Добавляет разрешенные параметры для тегов
*
* @param string $tag тег
* @param string|array $params разрешённые параметры
*/
public function cfgAllowTagParams($tag, $params)
{
if(!isset($this->tagsRules[$tag])) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$params = (is_array($params)) ? $params : array($params);
foreach($params as $key => $value)
{
if(is_string($key)) {
$this->tagsRules[$tag][self::TAG_PARAM_ALLOWED][$key] = $value;
} else {
$this->tagsRules[$tag][self::TAG_PARAM_ALLOWED][$value] = '#text';
}
}
}
/**
* КОНФИГУРАЦИЯ: Добавляет обязательные параметры для тега
*
* @param string $tag тег
* @param string|array $params разрешённые параметры
*/
public function cfgSetTagParamsRequired($tag, $params)
{
if(!isset($this->tagsRules[$tag])) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$params = (is_array($params)) ? $params : array($params);
foreach($params as $param)
{
$this->tagsRules[$tag][self::TAG_PARAM_REQUIRED][$param] = true;
}
}
/**
* КОНФИГУРАЦИЯ: Указывает, какие теги являются контейнерами для других тегов
*
* @param string $tag тег
* @param string|array $childs разрешённые дочерние теги
* @param boolean $isParentOnly тег является только контейнером других тегов и не может содержать текст
* @param boolean $isChildOnly вложенные теги не могут присутствовать нигде кроме указанного тега
*/
public function cfgSetTagChilds($tag, $childs, $isParentOnly = false, $isChildOnly = false)
{
if(!isset($this->tagsRules[$tag])) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$childs = (is_array($childs)) ? $childs : array($childs);
if($isParentOnly) {
$this->tagsRules[$tag][self::TAG_PARENT_ONLY] = true;
}
foreach($childs as $child)
{
if(!isset($this->tagsRules[$child])) {
throw new Exception("Тег ".$child." отсутствует в списке разрешённых тегов");
}
$this->tagsRules[$tag][self::TAG_CHILD][$child] = true;
$this->tagsRules[$child][self::TAG_PARENT][$tag] = true;
if($isChildOnly) {
$this->tagsRules[$child][self::TAG_CHILD_ONLY] = true;
}
}
}
/**
* КОНФИГУРАЦИЯ: Указывает, какие теги не должны быть дочерними к другим тегам
*
* @param string|array $tag тег
*/
public function cfgSetTagGlobal($tags)
{
$this->_cfgSetTagsFlag($tags, self::TAG_GLOBAL_ONLY, true, false);
}
/**
* КОНФИГУРАЦИЯ: Указывает значения по умолчанию для параметров тега
*
* @param string $tag тег
* @param string $param атрибут
* @param sring $value значение
* @param boolean $isRewrite перезаписывать значение значением по умолчанию
*/
public function cfgSetTagParamDefault($tag, $param, $value, $isRewrite = false)
{
if(!isset($this->tagsRules[$tag])) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$this->tagsRules[$tag][self::TAG_PARAM_AUTO_ADD][$param] = array('value'=>$value, 'rewrite'=>$isRewrite);
}
/**
* КОНФИГУРАЦИЯ: Устанавливает на тег callback-функцию для построения тега
*
* @param string $tag тег
* @param mixed $callback функция
*/
public function cfgSetTagBuildCallback($tag, $callback)
{
if(!isset($this->tagsRules[$tag])) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$this->tagsRules[$tag][self::TAG_BUILD_CALLBACK] = $callback;
}
/**
* КОНФИГУРАЦИЯ: Устанавливает на тег callback-функцию для сбора информации
*
* @param string $tag тег
* @param mixed $callback функция
*/
public function cfgSetTagEventCallback($tag, $callback)
{
if(!isset($this->tagsRules[$tag])) {
throw new Exception("Тег ".$tag." отсутствует в списке разрешённых тегов");
}
$this->tagsRules[$tag][self::TAG_EVENT_CALLBACK] = $callback;
}
/**
* КОНФИГУРАЦИЯ: Устанавливает на строку предварённую спецсимволом callback-функцию
*
* @param string $char спецсимвол
* @param mixed $callback функция
*/
public function cfgSetSpecialCharCallback($char, $callback)
{
if(!is_string($char)) {
throw new Exception("Параметр \$char метода cfgSetSpecialCharCallback должен быть строкой из одного символа");
}
if(mb_strlen($char) != 1) {
throw new Exception("Параметр \$char метода cfgSetSpecialCharCallback должен быть строкой из одного символа");
}
$charClass = $this->getClassByOrd(static::ord($char));
if(($charClass & self::SPECIAL_CHAR) == self::NIL) {
throw new Exception("Параметр \$char метода cfgSetSpecialCharCallback отсутствует в списке разрешенных символов");
}
$this->isSpecialCharMode = true;
$this->specialChars[$char] = $callback;
}
/**
* КОНФИГУРАЦИЯ: Устанавливает список разрешенных протоколов для ссылок (https, http, ftp)
*
*
* @param array $protocols Список протоколов
*/
public function cfgSetLinkProtocolAllow($protocols)
{
$protocols = (is_array($protocols)) ? $protocols : array($protocols);
$this->linkProtocolAllow = $protocols;
}
/**
* КОНФИГУРАЦИЯ: Включает или выключает режим XHTML
*
* @param boolean $isXHTMLMode
*/
public function cfgSetXHTMLMode($isXHTMLMode)
{
$isXHTMLMode = (bool) $isXHTMLMode;
$this->br = ($isXHTMLMode) ? '<br/>' : '<br>';
$this->isXHTMLMode = $isXHTMLMode;
}
/**
* КОНФИГУРАЦИЯ: Включает или выключает режим автозамены символов переводов строк на тег <br>
*
* @param boolean $isAutoBrMode
*/
public function cfgSetAutoBrMode($isAutoBrMode) {
$this->isAutoBrMode = (bool) $isAutoBrMode;
}
/**
* КОНФИГУРАЦИЯ: Включает или выключает режим автоматического определения ссылок
*
* @param boolean $isAutoLinkMode
*/
public function cfgSetAutoLinkMode($isAutoLinkMode) {
$this->isAutoLinkMode = (bool) $isAutoLinkMode;
}
/**
* КОНФИГУРАЦИЯ: Задает символ/символы перевода строки в готовом тексте (\n или \r\n)
*
* @param string $nl - "\n" или "\r\n"
*/
public function cfgSetEOL($nl) {
if(in_array($nl, array("\n", "\r\n"))) {
$this->nl = $nl;
}
}
/**
* Разбивает строку в массив посимвольно
*
* @param string $string текст
*/
protected function strToArray($str)
{
preg_match_all('#.#su', $str, $chars); // preg_split работает медленнее
return $chars[0];
}
/**
* Запускает парсер
*
* @param string $text текст
* @param array $errors сообщения об ошибках
* @return string
*/
public function parse($text, &$errors)
{
$this->prevPos = -1;
$this->prevChar = null;
$this->prevCharOrd = 0;
$this->prevCharClass = self::NIL;
$this->curPos = -1;
$this->curChar = null;
$this->curCharOrd = 0;
$this->curCharClass = self::NIL;
$this->nextPos = -1;
$this->nextChar = null;
$this->nextCharOrd = 0;
$this->nextCharClass = self::NIL;
$this->curTag = null;
$this->statesStack = array();
$this->quotesOpened = 0;
$text = str_replace("\r", "", $text);
$this->textBuf = $this->strToArray($text);
$this->textLen = count($this->textBuf);
$this->errorsList = array();
$this->movePos(0);
$content = $this->makeContent();
$content = ($this->nl != "\n") ? str_replace("\n", $this->nl, $content) : $content;
$content = trim($content);
$errors = $this->errorsList;
return $content;
}
/**
* Получение следующего символа из входной строки
*
* @return boolean
*/
protected function moveNextPos()
{
return $this->movePos($this->curPos+1);
}
/**
* Получение следующего символа из входной строки
*
* @return boolean
*/
protected function movePrevPos()
{
return $this->movePos($this->curPos-1);
}
/**
* Перемещает указатель на указанную позицию во входной строке и считывание символа
*
* @param int $position позиция в тексте
* @return boolean
*/
protected function movePos($position)
{
$prevPos = $position - 1;
$curPos = $position;
$nextPos = $position + 1;
$prevPosStatus = ($prevPos < $this->textLen && $prevPos >= 0) ? true : false;
$this->prevPos = $prevPos;
$this->prevChar = ($prevPosStatus) ? $this->textBuf[$prevPos] : null;
$this->prevCharOrd = ($prevPosStatus) ? static::ord($this->prevChar) : 0;
$this->prevCharClass = ($prevPosStatus) ? $this->getClassByOrd($this->prevCharOrd) : self::NIL;
$curPosStatus = ($curPos < $this->textLen && $curPos >= 0) ? true : false;
$this->curPos = $curPos;
$this->curChar = ($curPosStatus) ? $this->textBuf[$curPos] : null;
$this->curCharOrd = ($curPosStatus) ? static::ord($this->curChar) : 0;
$this->curCharClass = ($curPosStatus) ? $this->getClassByOrd($this->curCharOrd) : self::NIL;
$nextPosStatus = ($nextPos < $this->textLen && $nextPos >= 0) ? true : false;
$this->nextPos = $nextPos;
$this->nextChar = ($nextPosStatus) ? $this->textBuf[$nextPos] : null;
$this->nextCharOrd = ($nextPosStatus) ? static::ord($this->nextChar) : 0;
$this->nextCharClass = ($nextPosStatus) ? $this->getClassByOrd($this->nextCharOrd) : self::NIL;
return (!is_null($this->curChar)) ? true : false;
}
/**
* Сохраняет текущее состояние автомата
*
*/
protected function saveState()
{
$state = array();
$state['prevPos'] = $this->prevPos;
$state['prevChar'] = $this->prevChar;
$state['prevCharOrd'] = $this->prevCharOrd;
$state['prevCharClass'] = $this->prevCharClass;
$state['curPos'] = $this->curPos;
$state['curChar'] = $this->curChar;
$state['curCharOrd'] = $this->curCharOrd;
$state['curCharClass'] = $this->curCharClass;
$state['nextPos'] = $this->nextPos;
$state['nextChar'] = $this->nextChar;
$state['nextCharOrd'] = $this->nextCharOrd;
$state['nextCharClass'] = $this->nextCharClass;
$this->statesStack[] = $state;
}
/**
* Восстанавливает последнее сохраненное состояние автомата
*
*/
protected function restoreState()
{
$state = array_pop($this->statesStack);
$this->prevPos = $state['prevPos'];
$this->prevChar = $state['prevChar'];
$this->prevCharOrd = $state['prevCharOrd'];
$this->prevCharClass = $state['prevCharClass'];
$this->curPos = $state['curPos'];
$this->curChar = $state['curChar'];
$this->curCharOrd = $state['curCharOrd'];
$this->curCharClass = $state['curCharClass'];
$this->nextPos = $state['nextPos'];
$this->nextChar = $state['nextChar'];
$this->nextCharOrd = $state['nextCharOrd'];
$this->nextCharClass = $state['nextCharClass'];
}
/**
* Удаляет последнее сохраненное состояние
*
*/
protected function removeState()
{
$state = array_pop($this->statesStack);
}
/**
* Проверяет допустимость тега, классификатора тега и других параметров тега
*
*/
protected function tagsRules()
{
$args_list = func_get_args();
if(count($args_list) == 0) {
return false;
}
$tagsRules =& $this->tagsRules;
foreach($args_list as $value)
{
if(is_null($value) || !isset($tagsRules[$value])) {
return false;
}
$tagsRules =& $tagsRules[$value];
}
return true;
}
/**
* Проверяет точное вхождение символа в текущей позиции
*
* @param string $char символ
* @return boolean
*/
protected function matchChar($char)
{
return ($this->curChar == $char) ? true : false;
}
/**
* Проверяет вхождение символа указанного класса в текущей позиции
*
* @param int $charClass класс символа
* @return boolean
*/
protected function matchCharClass($charClass)
{
return ($this->curCharClass & $charClass) ? true : false;
}
/**
* Проверяет точное вхождение кода символа в текущей позиции
*
* @param int $charOrd код символа
* @return boolean
*/
protected function matchCharOrd($charOrd)
{
return ($this->curCharOrd == $charOrd) ? true : false;
}
/**
* Проверяет точное совпадение строки в текущей позиции
*
* @param string $str
* @return boolean
*/
protected function matchStr($str)
{
$this->saveState();
$lenght = mb_strlen($str, 'UTF-8');
$buffer = '';
while($lenght-- && $this->curCharClass)
{
$buffer .= $this->curChar;
$this->moveNextPos();
}
$this->restoreState();
return ($buffer == $str) ? true : false;
}
/**
* Пропускает текст до нахождения указанного символа
*
* @param string $char символ для поиска
* @return boolean
*/
protected function skipTextToChar($char)
{
while($this->curChar != $char && $this->curCharClass)
{
$this->moveNextPos();
}
return ($this->curCharClass) ? true : false;
}
/**
* Пропускает текст до нахождения указанной строки
*
* @param string $str строка или символ для поиска
* @return boolean
*/
protected function skipTextToStr($str)
{
$chars = $this->strToArray($str);
while($this->curCharClass)
{
if($this->curChar == $chars[0])
{
$this->saveState();
$state = true;
foreach($chars as $char)
{
if($this->curCharClass == self::NIL) {
$this->removeState();
return false;
}
if($this->curChar != $char) {
$state = false;
break;
}
$this->moveNextPos();
}
$this->restoreState();
if($state) {
return true;
}
}
$this->moveNextPos();
}
return false;
}
/**
* Пропускает строку если она начинается с текущей позиции
*
* $this->skipTextToStr('-->') && $this->skipStr('-->');
*
* @param string $str строка для пропуска
* @return boolean
*/
protected function skipStr($str)
{
$chars = $this->strToArray($str);
$this->saveState();
$state = true;
foreach($chars as $char)
{
if($this->curCharClass == self::NIL) {
$state = false; break;
}
if($this->curChar != $char) {
$state = false; break;
}
$this->moveNextPos();
}
if($state) $this->removeState();
else $this->restoreState();
return ($state) ? true : false;
}
/**
* Возвращает класс символа по его коду
*
* @param int $ord код символа
* @return int класс символа
*/
protected function getClassByOrd($ord)
{
return isset($this->charClasses[$ord]) ? $this->charClasses[$ord] : self::PRINATABLE;
}
/**
* Пропускает пробелы
*
* @return int количество пропусков
*/
protected function skipSpaces()
{
$count = 0;
while($this->curCharClass & self::SPACE)
{
$this->moveNextPos();
$count++;
}
return $count;
}
/**
* Пропускает символы перевода строк
*
* @param int $limit лимит пропусков символов перевода строк, при установке в 0 - не лимитируется
* @return boolean
*/
protected function skipNL($limit=0)
{
$count = 0;
while($this->curCharClass & self::NL)
{
if($limit > 0 && $count >= $limit) {
break;
}
$this->moveNextPos();
$this->skipSpaces();
$count++;
}
return $count;
}
/**
* Пропускает символы относящиеся к классу и возвращает кол-во пропущенных символов
*
* @param int $class класс для пропуска
* @return string
*/
protected function skipClass($class)
{
$count = 0;
while($this->curCharClass & $class)
{
$this->moveNextPos();
$count++;
}
return $count;
}
/**
* Захватывает все последующие символы относящиеся к классу и возвращает их
*
* @param int $class класс для захвата
* @return string
*/
protected function grabCharClass($class)
{
$result = "";
while($this->curCharClass & $class)
{
$result .= $this->curChar;
$this->moveNextPos();
}
return $result;
}
/**
* Захватывает все последующие символы НЕ относящиеся к классу и возвращает их
*
* @param int $class класс для остановки захвата
* @return string
*/
protected function grabNotCharClass($class)
{
$result = "";
while($this->curCharClass && ($this->curCharClass & $class) == self::NIL)
{
$result .= $this->curChar;
$this->moveNextPos();
}
return $result;
}
/**
* Готовит контент
*
* @param string|null $parentTag имя родительского тега
* @return string
*/
protected function makeContent($parentTag = null)
{
$content = "";
$this->skipSpaces();
$this->skipNL();
while($this->curCharClass)
{
$tagName = null;
$tagParams = array();
$tagContent = null;
$shortTag = false;
// Если текущий тег это тег без текста - пропускаем символы до "<"
if($this->tagsRules($this->curTag, self::TAG_PARENT_ONLY) && $this->curChar != '<')
{
$this->skipTextToChar('<');
}
$this->saveState();
// Тег в котором есть текст
if($this->curChar == '<' && $this->matchTag($tagName, $tagParams, $tagContent, $shortTag))
{
$tagBuilt = $this->makeTag($tagName, $tagParams, $tagContent, $shortTag, $parentTag);
$content .= $tagBuilt;
if(($this->tagsRules($tagName, self::TAG_BLOCK_TYPE) || $tagName == 'br') && $tagBuilt != "") {
$this->skipNL(1);
}
if($tagBuilt == "") {
$this->skipClass(self::SPACE | self::NL);
}
}
// Комментарий <!-- -->
else if($this->curChar == '<' && $this->matchStr('<!--'))
{
$this->skipTextToStr('-->') && $this->skipStr('-->');
$this->skipClass(self::SPACE | self::NL);
}
// Конец тега
else if($this->curChar == '<' && $this->matchTagClose($tagName))
{
if(!is_null($this->curTag))
{
$this->restoreState();
return $content;
}
else {
$this->setError('Не ожидалось закрывающего тега '.$tagName);
}
}
// Просто символ "<"
else if($this->curChar == '<')
{
if(!$this->tagsRules($this->curTag, self::TAG_PARENT_ONLY)) {
$content .= $this->entities['<'];
}
$this->moveNextPos();
}
// Наверно тут просто текст, формируем его
else
{
$content .= $this->makeText();
}
$this->removeState();
}
return $content;
}
/**
* Обработка тега полностью
*
* @param string $tagName имя тега
* @param array $tagParams параметры тега
* @param string $tagContent контент тега
* @param boolean $shortTag короткий ли тег
* @return boolean
*/
protected function matchTag(&$tagName, &$tagParams, &$tagContent, &$shortTag)
{
$tagName = null;
$tagParams = array();
$tagContent = '';
$shortTag = false;
$closeTag = null;
if(!$this->matchTagOpen($tagName, $tagParams, $shortTag)) {
return false;
}
if($shortTag) {
return true;
}
$curTag = $this->curTag;
$typoMode = $this->typoMode;
if($this->tagsRules($tagName, self::TAG_NO_TYPOGRAPHY)) {
$this->typoMode = false;
}
$this->curTag = $tagName;
if($this->tagsRules($tagName, self::TAG_PREFORMATTED))
{
$tagContent = $this->makePreformatted($tagName);
}
else {
$tagContent = $this->makeContent($tagName);
}
if($this->matchTagClose($closeTag) && ($tagName != $closeTag))
{
$this->setError("Неверный закрывающийся тег ".$closeTag.". Ожидалось закрытие ".$tagName."");
}
$this->curTag = $curTag;
$this->typoMode = $typoMode;
return true;
}
/**