This repository has been archived by the owner on Mar 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 205
/
document.parser.class.inc.php
5397 lines (4846 loc) · 215 KB
/
document.parser.class.inc.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
/**
* MODX Document Parser
* Function: This class contains the main document parsing functions
*
*/
if (!defined('E_DEPRECATED')) define('E_DEPRECATED', 8192);
if (!defined('E_USER_DEPRECATED')) define('E_USER_DEPRECATED', 16384);
class DocumentParser {
var $apiVersion;
var $db; // db object
var $event, $Event; // event object
var $pluginEvent;
var $config= null;
var $rs;
var $result;
var $sql;
var $table_prefix;
var $debug;
var $documentIdentifier;
var $documentMethod;
var $documentGenerated;
var $documentContent;
var $tstart;
var $mstart;
var $minParserPasses;
var $maxParserPasses;
var $documentObject;
var $templateObject;
var $snippetObjects;
var $stopOnNotice;
var $executedQueries;
var $queryTime;
var $currentSnippet;
var $documentName;
var $aliases;
var $visitor;
var $entrypage;
var $documentListing;
var $dumpSnippets;
var $snippetsCode;
var $snippetsCount=array();
var $snippetsTime=array();
var $chunkCache;
var $snippetCache;
var $contentTypes;
var $dumpSQL;
var $queryCode;
var $virtualDir;
var $placeholders;
var $sjscripts;
var $jscripts;
var $loadedjscripts;
var $documentMap;
var $forwards= 3;
var $error_reporting;
var $dumpPlugins;
var $pluginsCode;
var $pluginsTime=array();
var $pluginCache=array();
var $aliasListing;
var $lockedElements=null;
var $tmpCache = array();
private $version=array();
public $extensions = array();
public $cacheKey = null;
public $recentUpdate = 0;
public $useConditional = false;
protected $systemCacheKey = null;
var $snipLapCount;
var $messageQuitCount;
var $time;
/**
* Document constructor
*
* @return DocumentParser
*/
function __construct() {
$this->apiVersion = '1.0.0'; // This is New evolution
global $database_server;
if(substr(PHP_OS,0,3) === 'WIN' && $database_server==='localhost') $database_server = '127.0.0.1';
$this->loadExtension('DBAPI') or die('Could not load DBAPI class.'); // load DBAPI class
$this->dbConfig= & $this->db->config; // alias for backward compatibility
$this->jscripts= array ();
$this->sjscripts= array ();
$this->loadedjscripts= array ();
// events
$this->event= new SystemEvent();
$this->Event= & $this->event; //alias for backward compatibility
$this->pluginEvent= array ();
// set track_errors ini variable
@ ini_set("track_errors", "1"); // enable error tracking in $php_errormsg
$this->error_reporting = 1;
$this->debug = false;
$this->dumpSQL = false;
$this->dumpSnippets = false; // feed the parser the execution start time
$this->dumpPlugins = false;
$this->stopOnNotice = false;
$this->snipLapCount = 0;
$this->time = time(); // for having global timestamp
}
function __call($method_name,$arguments) {
include_once(MODX_MANAGER_PATH . 'includes/extenders/deprecated.functions.inc.php');
if(method_exists($this->old,$method_name)) $error_type=1;
else $error_type=3;
if(!isset($this->config['error_reporting'])||1<$this->config['error_reporting'])
{
if($error_type==1)
{
$title = 'Call deprecated method';
$msg = $this->htmlspecialchars("\$modx->{$method_name}() is deprecated function");
}
else
{
$title = 'Call undefined method';
$msg = $this->htmlspecialchars("\$modx->{$method_name}() is undefined function");
}
$info = debug_backtrace();
$m[] = $msg;
if(!empty($this->currentSnippet)) $m[] = 'Snippet - ' . $this->currentSnippet;
elseif(!empty($this->event->activePlugin)) $m[] = 'Plugin - ' . $this->event->activePlugin;
$m[] = $this->decoded_request_uri;
$m[] = str_replace('\\','/',$info[0]['file']) . '(line:' . $info[0]['line'] . ')';
$msg = implode('<br />', $m);
$this->logEvent(0, $error_type, $msg, $title);
}
if(method_exists($this->old,$method_name))
return call_user_func_array(array($this->old,$method_name),$arguments);
}
function checkSQLconnect($connector = 'db'){
$flag = false;
if(is_scalar($connector) && !empty($connector) && isset($this->{$connector}) && $this->{$connector} instanceof DBAPI){
$flag = (bool)$this->{$connector}->conn;
}
return $flag;
}
/**
* Loads an extension from the extenders folder.
* You can load any extension creating a boot file:
* MODX_MANAGER_PATH."includes/extenders/ex_{$extname}.inc.php"
* $extname - extension name in lowercase
*
* @return boolean
*/
function loadExtension($extname, $reload = true) {
$out = false;
$flag = ($reload || !in_array($extname, $this->extensions));
if($this->checkSQLconnect('db') && $flag){
$evtOut = $this->invokeEvent('OnBeforeLoadExtension', array('name' => $extname, 'reload' => $reload));
if (is_array($evtOut) && count($evtOut) > 0){
$out = array_pop($evtOut);
}
}
if( ! $out && $flag){
$extname = trim(str_replace(array('..','/','\\'),'',strtolower($extname)));
$filename = MODX_MANAGER_PATH."includes/extenders/ex_{$extname}.inc.php";
$out = is_file($filename) ? include $filename : false;
}
if($out && !in_array($extname, $this->extensions)){
$this->extensions[] = $extname;
}
return $out;
}
/**
* Returns the current micro time
*
* @return float
*/
function getMicroTime() {
list ($usec, $sec)= explode(' ', microtime());
return ((float) $usec + (float) $sec);
}
/**
* Redirect
*
* @global string $base_url
* @global string $site_url
* @param string $url
* @param int $count_attempts
* @param type $type
* @param type $responseCode
* @return boolean
*/
function sendRedirect($url, $count_attempts= 0, $type= '', $responseCode= '') {
if (empty ($url)) return false;
if ($count_attempts == 1) {
// append the redirect count string to the url
$currentNumberOfRedirects= isset ($_REQUEST['err']) ? $_REQUEST['err'] : 0;
if ($currentNumberOfRedirects > 3) {
$this->messageQuit('Redirection attempt failed - please ensure the document you\'re trying to redirect to exists. <p>Redirection URL: <i>' . $url . '</i></p>');
} else {
$currentNumberOfRedirects += 1;
if (strpos($url, "?") > 0) {
$url .= "&err=$currentNumberOfRedirects";
} else {
$url .= "?err=$currentNumberOfRedirects";
}
}
}
if ($type == 'REDIRECT_REFRESH') {
$header= 'Refresh: 0;URL=' . $url;
}
elseif ($type == 'REDIRECT_META') {
$header= '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=' . $url . '" />';
echo $header;
exit;
}
elseif ($type == 'REDIRECT_HEADER' || empty ($type)) {
// check if url has /$base_url
global $base_url, $site_url;
if (substr($url, 0, strlen($base_url)) == $base_url) {
// append $site_url to make it work with Location:
$url= $site_url . substr($url, strlen($base_url));
}
if (strpos($url, "\n") === false) {
$header= 'Location: ' . $url;
} else {
$this->messageQuit('No newline allowed in redirect url.');
}
}
if ($responseCode && (strpos($responseCode, '30') !== false)) {
header($responseCode);
}
header($header);
exit();
}
/**
* Forward to another page
*
* @param int $id
* @param string $responseCode
*/
function sendForward($id, $responseCode= '') {
if ($this->forwards > 0) {
$this->forwards= $this->forwards - 1;
$this->documentIdentifier= $id;
$this->documentMethod= 'id';
$this->documentObject= $this->getDocumentObject('id', $id);
if ($responseCode) {
header($responseCode);
}
$this->prepareResponse();
exit();
} else {
header('HTTP/1.0 500 Internal Server Error');
die('<h1>ERROR: Too many forward attempts!</h1><p>The request could not be completed due to too many unsuccessful forward attempts.</p>');
}
}
/**
* Redirect to the error page, by calling sendForward(). This is called for example when the page was not found.
*/
function sendErrorPage($noEvent = false) {
$this->systemCacheKey = 'notfound';
if(!$noEvent) {
// invoke OnPageNotFound event
$this->invokeEvent('OnPageNotFound');
}
$url = $this->config['error_page'] ? $this->config['error_page'] : $this->config['site_start'];
$this->sendForward($url, 'HTTP/1.0 404 Not Found');
exit();
}
function sendUnauthorizedPage($noEvent = false) {
// invoke OnPageUnauthorized event
$_REQUEST['refurl'] = $this->documentIdentifier;
$this->systemCacheKey = 'unauth';
if(!$noEvent) {
$this->invokeEvent('OnPageUnauthorized');
}
if ($this->config['unauthorized_page']) {
$unauthorizedPage= $this->config['unauthorized_page'];
} elseif ($this->config['error_page']) {
$unauthorizedPage= $this->config['error_page'];
} else {
$unauthorizedPage= $this->config['site_start'];
}
$this->sendForward($unauthorizedPage, 'HTTP/1.1 401 Unauthorized');
exit();
}
/**
* Get MODX settings including, but not limited to, the system_settings table
*/
function getSettings() {
$tbl_system_settings = $this->getFullTableName('system_settings');
$tbl_web_user_settings = $this->getFullTableName('web_user_settings');
$tbl_user_settings = $this->getFullTableName('user_settings');
if (!is_array($this->config) || empty ($this->config)) {
if ($included= file_exists(MODX_BASE_PATH . $this->getCacheFolder() . 'siteCache.idx.php')) {
$included= include_once (MODX_BASE_PATH . $this->getCacheFolder() . 'siteCache.idx.php');
}
if (!$included || !is_array($this->config) || empty ($this->config)) {
include_once(MODX_MANAGER_PATH . 'processors/cache_sync.class.processor.php');
$cache = new synccache();
$cache->setCachepath(MODX_BASE_PATH . $this->getCacheFolder());
$cache->setReport(false);
$rebuilt = $cache->buildCache($this);
$included = false;
if($rebuilt && $included= file_exists(MODX_BASE_PATH . $this->getCacheFolder() . 'siteCache.idx.php')) {
$included= include MODX_BASE_PATH . $this->getCacheFolder() . 'siteCache.idx.php';
}
if(!$included) {
$result= $this->db->select('setting_name, setting_value', $tbl_system_settings);
while ($row= $this->db->getRow($result)) {
$this->config[$row['setting_name']]= $row['setting_value'];
}
}
}
// added for backwards compatibility - garry FS#104
$this->config['etomite_charset'] = & $this->config['modx_charset'];
// store base_url and base_path inside config array
$this->config['base_url']= MODX_BASE_URL;
$this->config['base_path']= MODX_BASE_PATH;
$this->config['site_url']= MODX_SITE_URL;
$this->config['valid_hostnames']= MODX_SITE_HOSTNAMES;
$this->config['site_manager_url']=MODX_MANAGER_URL;
$this->config['site_manager_path']=MODX_MANAGER_PATH;
// load user setting if user is logged in
$usrSettings= array ();
if ($id= $this->getLoginUserID()) {
$usrType= $this->getLoginUserType();
if (isset ($usrType) && $usrType == 'manager')
$usrType= 'mgr';
if ($usrType == 'mgr' && $this->isBackend()) {
// invoke the OnBeforeManagerPageInit event, only if in backend
$this->invokeEvent("OnBeforeManagerPageInit");
}
if (isset ($_SESSION[$usrType . 'UsrConfigSet'])) {
$usrSettings= & $_SESSION[$usrType . 'UsrConfigSet'];
} else {
if ($usrType == 'web')
{
$from = $tbl_web_user_settings;
$where = "webuser='{$id}'";
}
else
{
$from = $tbl_user_settings;
$where = "user='{$id}'";
}
$result= $this->db->select('setting_name, setting_value', $from, $where);
while ($row= $this->db->getRow($result))
$usrSettings[$row['setting_name']]= $row['setting_value'];
if (isset ($usrType))
$_SESSION[$usrType . 'UsrConfigSet']= $usrSettings; // store user settings in session
}
}
if ($this->isFrontend() && $mgrid= $this->getLoginUserID('mgr')) {
$musrSettings= array ();
if (isset ($_SESSION['mgrUsrConfigSet'])) {
$musrSettings= & $_SESSION['mgrUsrConfigSet'];
} else {
if ($result= $this->db->select('setting_name, setting_value', $tbl_user_settings, "user='{$mgrid}'")) {
while ($row= $this->db->getRow($result)) {
$musrSettings[$row['setting_name']]= $row['setting_value'];
}
$_SESSION['mgrUsrConfigSet']= $musrSettings; // store user settings in session
}
}
if (!empty ($musrSettings)) {
$usrSettings= array_merge($musrSettings, $usrSettings);
}
}
$this->error_reporting = $this->config['error_reporting'];
$this->config= array_merge($this->config, $usrSettings);
$this->config['filemanager_path'] = str_replace('[(base_path)]',MODX_BASE_PATH,$this->config['filemanager_path']);
$this->config['rb_base_dir'] = str_replace('[(base_path)]',MODX_BASE_PATH,$this->config['rb_base_dir']);
$where = "plugincode LIKE '%phx.parser.class.inc.php%OnParseDocument();%' AND disabled != 1";
$count = $this->db->getRecordCount($this->db->select('id', '[+prefix+]site_plugins', $where));
if($count) $this->config['enable_filter'] = '0';
}
}
/**
* Get the method by which the current document/resource was requested
*
* @return string 'alias' (friendly url alias) or 'id'
*/
function getDocumentMethod() {
// function to test the query and find the retrieval method
if (!empty ($_REQUEST['q'])) { //LANG
return "alias";
}
elseif (isset ($_GET['id'])) {
return "id";
} else {
return "none";
}
}
/**
* Returns the document identifier of the current request
*
* @param string $method id and alias are allowed
* @return int
*/
function getDocumentIdentifier($method) {
// function to test the query and find the retrieval method
$docIdentifier= $this->config['site_start'];
switch ($method) {
case 'alias' :
$docIdentifier= $this->db->escape($_REQUEST['q']);
break;
case 'id' :
if (!is_numeric($_GET['id'])) {
$this->sendErrorPage();
} else {
$docIdentifier= intval($_GET['id']);
}
break;
default:
if(strpos($_SERVER['REQUEST_URI'],'index.php')!==false) {
list(,$_) = explode('index.php', $_SERVER['REQUEST_URI'], 2);
if(substr($_,0,1)==='/') $this->sendErrorPage();
}
}
return $docIdentifier;
}
/**
* Check for manager or webuser login session since v1.2
*
* @return boolean
*/
function isLoggedIn($context='mgr')
{
if(substr($context,0,1)=='m') $_ = 'mgrValidated';
else $_ = 'webValidated';
if(isset($_SESSION[$_]) && !empty($_SESSION[$_])) return true;
else return false;
}
/**
* Check for manager login session
*
* @return boolean
*/
function checkSession() {
return $this->isLoggedin();
}
/**
* Checks, if a the result is a preview
*
* @return boolean
*/
function checkPreview() {
if ($this->isLoggedIn() == true) {
if (isset ($_REQUEST['z']) && $_REQUEST['z'] == 'manprev') {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* check if site is offline
*
* @return boolean
*/
function checkSiteStatus() {
$siteStatus= $this->config['site_status'];
if ($siteStatus == 1) {
// site online
return true;
}
elseif ($siteStatus == 0 && $this->isLoggedIn()) {
// site offline but launched via the manager
return true;
} else {
// site is offline
return false;
}
}
/**
* Create a 'clean' document identifier with path information, friendly URL suffix and prefix.
*
* @param string $qOrig
* @return string
*/
function cleanDocumentIdentifier($qOrig) {
(!empty($qOrig)) or $qOrig = $this->config['site_start'];
$q= $qOrig;
/* First remove any / before or after */
$q = trim($q,'/');
/* Save path if any */
/* FS#476 and FS#308: only return virtualDir if friendly paths are enabled */
if ($this->config['use_alias_path'] == 1) {
$this->virtualDir= dirname($q);
$this->virtualDir= ($this->virtualDir == '.' ? '' : $this->virtualDir);
$q = preg_replace('/.*[\/\\\]/', '', $q);
} else {
$this->virtualDir= '';
}
$q= str_replace($this->config['friendly_url_prefix'], "", $q);
$q= str_replace($this->config['friendly_url_suffix'], "", $q);
if (is_numeric($q) && !isset($this->documentListing[$q])) { /* we got an ID returned, check to make sure it's not an alias */
/* FS#476 and FS#308: check that id is valid in terms of virtualDir structure */
if ($this->config['use_alias_path'] == 1) {
if ((($this->virtualDir != '' && !isset($this->documentListing[$this->virtualDir . '/' . $q])) || ($this->virtualDir == '' && !isset($this->documentListing[$q]))) && (($this->virtualDir != '' && isset($this->documentListing[$this->virtualDir]) && in_array($q, $this->getChildIds($this->documentListing[$this->virtualDir], 1))) || ($this->virtualDir == '' && in_array($q, $this->getChildIds(0, 1))))) {
$this->documentMethod= 'id';
return $q;
} else { /* not a valid id in terms of virtualDir, treat as alias */
$this->documentMethod= 'alias';
return $q;
}
} else {
$this->documentMethod= 'id';
return $q;
}
} else { /* we didn't get an ID back, so instead we assume it's an alias */
if ($this->config['friendly_alias_urls'] != 1) {
$q= $qOrig;
}
$this->documentMethod= 'alias';
return $q;
}
}
public function getCacheFolder(){
return "assets/cache/";
}
public function getHashFile($key){
return $this->getCacheFolder()."docid_" . $key . ".pageCache.php";
}
public function makePageCacheKey($id){
$hash = $id;
$tmp = null;
$params = array();
if(!empty($this->systemCacheKey)){
$hash = $this->systemCacheKey;
}else {
if (!empty($_GET)) {
// Sort GET parameters so that the order of parameters on the HTTP request don't affect the generated cache ID.
$params = $_GET;
ksort($params);
$hash .= '_'.md5(http_build_query($params));
}
}
$evtOut = $this->invokeEvent("OnMakePageCacheKey", array ("hash" => $hash, "id" => $id, 'params' => $params));
if (is_array($evtOut) && count($evtOut) > 0){
$tmp = array_pop($evtOut);
}
return empty($tmp) ? $hash : $tmp;
}
function checkCache($id, $loading = false) {
return $this->getDocumentObjectFromCache($id, $loading);
}
/**
* Check the cache for a specific document/resource
*
* @param int $id
* @param bool $loading
* @return string
*/
function getDocumentObjectFromCache($id, $loading = false) {
$key = ($this->config['cache_type'] == 2) ? $this->makePageCacheKey($id) : $id;
if($loading) $this->cacheKey = $key;
$cache_path = $this->getHashFile($key);
if (is_file($cache_path)) {
$content = file_get_contents($cache_path, false);
if(substr($content,0,5)==='<?php') $content = substr($content, strpos($content,'?>')+2); // remove php header
$a= explode('<!--__MODxCacheSpliter__-->', $content, 2);
if (count($a) == 1)
$result = $a[0]; // return only document content
else {
$docObj= unserialize($a[0]); // rebuild document object
// check page security
if ($docObj['privateweb'] && isset ($docObj['__MODxDocGroups__'])) {
$pass= false;
$usrGrps= $this->getUserDocGroups();
$docGrps= explode(',', $docObj['__MODxDocGroups__']);
// check is user has access to doc groups
if (is_array($usrGrps)) {
foreach ($usrGrps as $k => $v)
if (in_array($v, $docGrps)) {
$pass= true;
break;
}
}
// diplay error pages if user has no access to cached doc
if (!$pass) {
if ($this->config['unauthorized_page']) {
// check if file is not public
$rs= $this->db->select('count(id)', '[+prefix+]document_groups', "document='{$id}'", '', '1');
$total= $this->db->getValue($rs);
}
else $total = 0;
if ($total > 0) $this->sendUnauthorizedPage();
else $this->sendErrorPage();
exit; // stop here
}
}
// Grab the Scripts
if (isset($docObj['__MODxSJScripts__'])) $this->sjscripts = $docObj['__MODxSJScripts__'];
if (isset($docObj['__MODxJScripts__'])) $this->jscripts = $docObj['__MODxJScripts__'];
// Remove intermediate variables
unset($docObj['__MODxDocGroups__'], $docObj['__MODxSJScripts__'], $docObj['__MODxJScripts__']);
$this->documentObject= $docObj;
$result = $a[1]; // return document content
}
} else {
$this->documentGenerated= 1;
return '';
}
$this->documentGenerated= 0;
// invoke OnLoadWebPageCache event
$this->documentContent = $result;
$this->invokeEvent('OnLoadWebPageCache');
return $result;
}
/**
* Final processing and output of the document/resource.
*
* - runs uncached snippets
* - add javascript to <head>
* - removes unused placeholders
* - converts URL tags [~...~] to URLs
*
* @param boolean $noEvent Default: false
*/
function outputContent($noEvent= false) {
$this->documentOutput= $this->documentContent;
if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
if (!empty($this->sjscripts)) $this->documentObject['__MODxSJScripts__'] = $this->sjscripts;
if (!empty($this->jscripts)) $this->documentObject['__MODxJScripts__'] = $this->jscripts;
}
// check for non-cached snippet output
if (strpos($this->documentOutput, '[!') > -1) {
$this->recentUpdate = time() + $this->config['server_offset_time'];
$this->documentOutput= str_replace('[!', '[[', $this->documentOutput);
$this->documentOutput= str_replace('!]', ']]', $this->documentOutput);
// Parse document source
$this->documentOutput= $this->parseDocumentSource($this->documentOutput);
}
// Moved from prepareResponse() by sirlancelot
// Insert Startup jscripts & CSS scripts into template - template must have a <head> tag
if ($js= $this->getRegisteredClientStartupScripts()) {
// change to just before closing </head>
// $this->documentContent = preg_replace("/(<head[^>]*>)/i", "\\1\n".$js, $this->documentContent);
$this->documentOutput= preg_replace("/(<\/head>)/i", $js . "\n\\1", $this->documentOutput);
}
// Insert jscripts & html block into template - template must have a </body> tag
if ($js= $this->getRegisteredClientScripts()) {
$this->documentOutput= preg_replace("/(<\/body>)/i", $js . "\n\\1", $this->documentOutput);
}
// End fix by sirlancelot
$this->documentOutput = $this->cleanUpMODXTags($this->documentOutput);
// remove all unused placeholders
if (strpos($this->documentOutput, '[+')!==false) {
$matches= array ();
preg_match_all('~\[\+(.*?)\+\]~s', $this->documentOutput, $matches);
if ($matches[0])
$this->documentOutput= str_replace($matches[0], '', $this->documentOutput);
}
$this->documentOutput= $this->rewriteUrls($this->documentOutput);
// send out content-type and content-disposition headers
if (IN_PARSER_MODE == "true") {
$type= !empty ($this->contentTypes[$this->documentIdentifier]) ? $this->contentTypes[$this->documentIdentifier] : "text/html";
header('Content-Type: ' . $type . '; charset=' . $this->config['modx_charset']);
// if (($this->documentIdentifier == $this->config['error_page']) || $redirect_error)
// header('HTTP/1.0 404 Not Found');
if (!$this->checkPreview() && $this->documentObject['content_dispo'] == 1) {
if ($this->documentObject['alias'])
$name= $this->documentObject['alias'];
else {
// strip title of special characters
$name= $this->documentObject['pagetitle'];
$name= strip_tags($name);
$name= $this->cleanUpMODXTags($name);
$name= strtolower($name);
$name= preg_replace('/&.+?;/', '', $name); // kill entities
$name= preg_replace('/[^\.%a-z0-9 _-]/', '', $name);
$name= preg_replace('/\s+/', '-', $name);
$name= preg_replace('|-+|', '-', $name);
$name= trim($name, '-');
}
$header= 'Content-Disposition: attachment; filename=' . $name;
header($header);
}
}
$this->setConditional();
$stats = $this->getTimerStats($this->tstart);
$out =& $this->documentOutput;
$out= str_replace("[^q^]", $stats['queries'] , $out);
$out= str_replace("[^qt^]", $stats['queryTime'] , $out);
$out= str_replace("[^p^]", $stats['phpTime'] , $out);
$out= str_replace("[^t^]", $stats['totalTime'] , $out);
$out= str_replace("[^s^]", $stats['source'] , $out);
$out= str_replace("[^m^]", $stats['phpMemory'], $out);
//$this->documentOutput= $out;
// invoke OnWebPagePrerender event
if (!$noEvent) {
$evtOut = $this->invokeEvent('OnWebPagePrerender', array('documentOutput'=>$this->documentOutput));
if (is_array($evtOut) && count($evtOut) > 0){
$this->documentOutput = $evtOut['0'];
}
}
$this->documentOutput = $this->removeSanitizeSeed($this->documentOutput);
echo $this->documentOutput;
if ($this->dumpSQL) echo $this->queryCode;
if ($this->dumpSnippets) {
$sc = "";
$tt = 0;
foreach ($this->snippetsTime as $s=>$t) {
$sc .= "$s: ".$this->snippetsCount[$s]." (".sprintf("%2.2f ms", $t*1000).")<br>";
$tt += $t;
}
echo "<fieldset><legend><b>Snippets</b> (".count($this->snippetsTime)." / ".sprintf("%2.2f ms", $tt*1000).")</legend>{$sc}</fieldset><br />";
echo $this->snippetsCode;
}
if ($this->dumpPlugins) {
$ps = "";
$tc = 0;
foreach ($this->pluginsTime as $s=>$t) {
$ps .= "$s (".sprintf("%2.2f ms", $t*1000).")<br>";
$tt += $t;
}
echo "<fieldset><legend><b>Plugins</b> (".count($this->pluginsTime)." / ".sprintf("%2.2f ms", $tt*1000).")</legend>{$ps}</fieldset><br />";
echo $this->pluginsCode;
}
ob_end_flush();
}
function getTimerStats($tstart) {
$stats = array();
$stats['totalTime'] = ($this->getMicroTime() - $tstart);
$stats['queryTime'] = $this->queryTime;
$stats['phpTime'] = $stats['totalTime'] - $stats['queryTime'];
$stats['queryTime'] = sprintf("%2.4f s", $stats['queryTime']);
$stats['totalTime'] = sprintf("%2.4f s", $stats['totalTime']);
$stats['phpTime'] = sprintf("%2.4f s", $stats['phpTime']);
$stats['source'] = $this->documentGenerated == 1 ? "database" : "cache";
$stats['queries'] = isset ($this->executedQueries) ? $this->executedQueries : 0;
$stats['phpMemory'] = (memory_get_peak_usage(true) / 1024 / 1024) . " mb";
return $stats;
}
public function setConditional(){
if(!empty($_POST) || (defined('MODX_API_MODE') && MODX_API_MODE) || $this->getLoginUserID('mgr') || !$this->useConditional || empty($this->recentUpdate)) return;
$last_modified = gmdate('D, d M Y H:i:s T', $this->recentUpdate);
$etag = md5($last_modified);
$HTTP_IF_MODIFIED_SINCE = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
$HTTP_IF_NONE_MATCH = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false;
header('Pragma: no-cache');
if ($HTTP_IF_MODIFIED_SINCE == $last_modified || strpos($HTTP_IF_NONE_MATCH, $etag)!==false) {
header('HTTP/1.1 304 Not Modified');
header('Content-Length: 0');
exit;
} else {
header("Last-Modified: {$last_modified}");
header("ETag: '{$etag}'");
}
}
/**
* Checks the publish state of page
*/
function checkPublishStatus() {
$cacheRefreshTime= 0;
$recent_update = 0;
@include $this->config["base_path"] . $this->getCacheFolder() . "sitePublishing.idx.php";
$this->recentUpdate = $recent_update;
$timeNow = $_SERVER['REQUEST_TIME'] + $this->config['server_offset_time'];
if ($cacheRefreshTime <= $timeNow && $cacheRefreshTime != 0) {
// now, check for documents that need publishing
$this->db->update(
array(
'published' => 1,
'publishedon' => $timeNow,
), $this->getFullTableName('site_content'), "pub_date <= {$timeNow} AND pub_date!=0 AND published=0");
// now, check for documents that need un-publishing
$this->db->update(
array(
'published' => 0,
'publishedon' => 0,
), $this->getFullTableName('site_content'), "unpub_date <= {$timeNow} AND unpub_date!=0 AND published=1");
// clear the cache
$this->clearCache('full');
}
}
/**
* Final jobs.
*
* - cache page
*/
function postProcess() {
// if the current document was generated, cache it!
if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
// invoke OnBeforeSaveWebPageCache event
$this->invokeEvent("OnBeforeSaveWebPageCache");
if (!empty($this->cacheKey) && is_scalar($this->cacheKey) && $fp= @fopen(MODX_BASE_PATH.$this->getHashFile($this->cacheKey), "w")) {
// get and store document groups inside document object. Document groups will be used to check security on cache pages
$rs = $this->db->select('document_group', $this->getFullTableName("document_groups"), "document='{$this->documentIdentifier}'");
$docGroups= $this->db->getColumn("document_group", $rs);
// Attach Document Groups and Scripts
if (is_array($docGroups)) $this->documentObject['__MODxDocGroups__'] = implode(",", $docGroups);
$docObjSerial= serialize($this->documentObject);
$cacheContent= $docObjSerial . "<!--__MODxCacheSpliter__-->" . $this->documentContent;
fputs($fp, "<?php die('Unauthorized access.'); ?>$cacheContent");
fclose($fp);
}
}
// Useful for example to external page counters/stats packages
$this->invokeEvent('OnWebPageComplete');
// end post processing
}
function getTagsFromContent($content,$left='[+',$right='+]') {
$_ = $this->_getTagsFromContent($content,$left,$right);
if(empty($_)) return array();
foreach($_ as $v)
{
$tags[0][] = "{$left}{$v}{$right}";
$tags[1][] = $v;
}
return $tags;
}
function _getTagsFromContent($content, $left='[+',$right='+]') {
if(strpos($content,$left)===false) return array();
if(strpos($content,';}}')!==false) $content = str_replace(';}}', '',$content);
if(strpos($content,'{{}}')!==false) $content = str_replace('{{}}','',$content);
if(strpos($content,']]]]')!==false) $content = str_replace(']] ]]','',$content);
if(strpos($content,']]]')!==false) $content = str_replace('] ]]', '',$content);
$pos['<![CDATA['] = strpos($content,'<![CDATA[');
$pos[']]>'] = strpos($content,']]>');
if($pos['<![CDATA[']!==false && $pos[']]>']!==false) {
$content = substr($content,0,$pos['<![CDATA[']) . substr($content,$pos[']]>']+3);
}
$lp = explode($left,$content);
$piece = array();
foreach($lp as $lc=>$lv) {
if($lc!==0) $piece[] = $left;
if(strpos($lv,$right)===false) $piece[] = $lv;
else {
$rp = explode($right,$lv);
foreach($rp as $rc=>$rv) {
if($rc!==0) $piece[] = $right;
$piece[] = $rv;
}
}
}
$lc=0;
$rc=0;
$fetch = '';
foreach($piece as $v) {
if($v===$left) {
if(0<$lc) $fetch .= $left;
$lc++;
}
elseif($v===$right) {
if($lc===0) continue;
$rc++;
if($lc===$rc) {
if( !isset($tags) || !in_array($fetch, $tags)) { // Avoid double Matches
$tags[] = $fetch; // Fetch
};
$fetch = ''; // and reset
$lc=0;
$rc=0;
}
else $fetch .= $right;
} else {
if(0<$lc) $fetch .= $v;
else continue;
}
}
if(!$tags) return array();
foreach($tags as $tag) {
if(strpos($tag,$left)!==false) {
$innerTags = $this->_getTagsFromContent($tag,$left,$right);
$tags = array_merge($innerTags,$tags);
}
}
return $tags;
}
/**
* Merge content fields and TVs
*
* @param string $template
* @return string
*/
function mergeDocumentContent($content,$ph=false) {
if (strpos($content, '[*') === false)
return $content;
if(!isset($this->documentIdentifier)) return $content;
if(!isset($this->documentObject) || empty($this->documentObject)) return $content;
if(!$ph) $ph = $this->documentObject;
$matches = $this->getTagsFromContent($content,'[*','*]');
if(!$matches) return $content;
foreach($matches[1] as $i=>$key) {
if(substr($key, 0, 1) == '#') $key = substr($key, 1); // remove # for QuickEdit format
list($key,$modifiers) = $this->splitKeyAndFilter($key);
list($key,$context) = explode('@',$key,2);
if(!isset($ph[$key]) && !$context) {
$content= str_replace($matches[0][$i], '', $content);
continue;
}
elseif($context) $value = $this->_contextValue("{$key}@{$context}");
else $value = $ph[$key];
if (is_array($value)) {
include_once(MODX_MANAGER_PATH . 'includes/tmplvars.format.inc.php');
include_once(MODX_MANAGER_PATH . 'includes/tmplvars.commands.inc.php');
$value = getTVDisplayFormat($value[0], $value[1], $value[2], $value[3], $value[4]);
}
if($modifiers!==false) $value = $this->applyFilter($value,$modifiers,$key);
$content= str_replace($matches[0][$i], $value, $content);
}
return $content;
}
function _contextValue($key) {
list($key,$str) = explode('@',$key,2);
$context = strtolower($str);
if(substr($str,0,5)==='alias' && strpos($str,'(')!==false)
$context = 'alias';
elseif(substr($str,0,1)==='u' && strpos($str,'(')!==false)
$context = 'uparent';
switch($context) {
case 'site_start':
$docid = $this->config['site_start'];
break;
case 'parent':
case 'p':
$docid = $this->documentObject['parent'];
if($docid==0) $docid = $this->config['site_start'];
break;