-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathFileCompiler.php
More file actions
1205 lines (1040 loc) · 36.1 KB
/
Copy pathFileCompiler.php
File metadata and controls
1205 lines (1040 loc) · 36.1 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 namespace ProcessWire;
/**
* FileCompiler
*
* ProcessWire 3.x, Copyright 2023 by Ryan Cramer
* https://processwire.com
*
* @todo determine whether we should make storage in dedicated table rather than using wire('cache').
* @todo handle race conditions for multiple requests attempting to compile the same file(s).
*
* @method string compile($sourceFile)
* @method string compileData($data, $sourceFile)
*
*/
class FileCompiler extends Wire {
/**
* Compilation options for this FileCompiler instance
*
* @var array
*
*/
protected $options = array(
'includes' => true, // compile include()'d files too?
'namespace' => true, // compile to make compatible with PW namespace when necessary?
'modules' => false, // compile using installed FileCompiler modules
'skipIfNamespace' => false, // skip compiled file if original declares a namespace? (note: file still compiled, but not used)
);
/**
* Options for ALL FileCompiler instances
*
* Values shown below are for reference only as the get overwritten by $config->fileCompilerOptions at runtime.
*
* @var array
*
*/
protected $globalOptions = array(
'siteOnly' => false, // only allow compilation of files in /site/ directory
'showNotices' => true, // show notices about compiled files to superuser
'logNotices' => true, // log notices about compiled files and maintenance to file-compiler.txt log.
'chmodFile' => '', // mode to use for created files, i.e. "0644"
'chmodDir' => '', // mode to use for created directories, i.e. "0755"
'exclusions' => array(), // exclude files or paths that start with any of these (gets moved to $this->exclusions array)
'extensions' => array('php', 'module', 'inc'), // file extensions we compile (gets moved to $this->extensions array)
'cachePath' => '', // path where compiled files are stored (default is /site/assets/cache/FileCompiler/, moved to $this->cachePath)
);
/**
* Path to source files directory
*
* @var string
*
*/
protected $sourcePath;
/**
* Path to compiled files directory
*
* @var string
*
*/
protected $targetPath = null;
/**
* Path to root of compiled files directory (upon which targetPath is based)
*
* Set via the $config->fileCompilerOptions['cachePath'] setting.
*
* @var string
*
*/
protected $cachePath;
/**
* Files or directories that should be excluded from compilation
*
* @var array
*
*/
protected $exclusions = array();
/**
* File extensions that we compile and copy
*
* @var array
*
*/
protected $extensions = array(
'php',
'module',
'inc',
);
/**
* Detected file namespace (during compileData)
*
* @var string
*
*/
protected $ns = '';
/**
* String with raw PHP blocks only, and with any quoted values removed.
*
* @var string
*
*/
protected $rawPHP = '';
/**
* Same as raw PHP but with all quoted values converted to literal "string"
*
* @var string
*
*/
protected $rawDequotedPHP = '';
/**
* Construct
*
* @param string $sourcePath Path where source files are located
* @param array $options Indicate which compilations should be performed (default='includes' and 'namespace')
*
*/
public function __construct($sourcePath, array $options = array()) {
$this->options = array_merge($this->options, $options);
if(strpos($sourcePath, '..') !== false) $sourcePath = realpath($sourcePath);
if(DIRECTORY_SEPARATOR != '/') $sourcePath = str_replace(DIRECTORY_SEPARATOR, '/', $sourcePath);
$this->sourcePath = rtrim($sourcePath, '/') . '/';
parent::__construct();
}
/**
* Wired to instance
*
*/
public function wired() {
$config = $this->wire()->config;
$globalOptions = $config->fileCompilerOptions;
if(is_array($globalOptions)) {
$this->globalOptions = array_merge($this->globalOptions, $globalOptions);
}
if(!empty($this->globalOptions['extensions'])) {
$this->extensions = $this->globalOptions['extensions'];
}
if(empty($this->globalOptions['cachePath'])) {
$this->cachePath = $config->paths->cache . $this->className() . '/';
} else {
$this->cachePath = rtrim($this->globalOptions['cachePath'], '/') . '/';
}
if(!strlen(__NAMESPACE__)) {
// when PW compiled without namespace support
$this->options['skipIfNamespace'] = false;
$this->options['namespace'] = true;
}
parent::wired();
}
/**
* Initialize paths
*
* @throws WireException
*
*/
protected function init() {
if(!$this->isWired()) $this->wired();
static $preloaded = false;
$config = $this->wire()->config;
if(!$preloaded) {
$this->wire()->cache->preloadFor($this);
$preloaded = true;
}
if(!empty($this->globalOptions['exclusions'])) {
$this->exclusions = $this->globalOptions['exclusions'];
}
$this->addExclusion($config->paths->wire);
$this->addExclusion($config->paths->root . 'vendor/');
$rootPath = $config->paths->root;
$targetPath = $this->cachePath;
if(strpos($this->sourcePath, $targetPath) === 0) {
// sourcePath is inside the targetPath, correct this
$this->sourcePath = str_replace($targetPath, '', $this->sourcePath);
$this->sourcePath = $rootPath . $this->sourcePath;
}
$t = str_replace($rootPath, '', $this->sourcePath);
if(DIRECTORY_SEPARATOR != '/' && strpos($t, ':')) $t = str_replace(':', '', $t);
$this->targetPath = $targetPath . trim($t, '/') . '/';
$this->ns = '';
}
/**
* Make a directory with proper permissions
*
* @param string $path Path of directory to create
* @param bool $recursive Default is true
* @return bool
*
*/
protected function mkdir($path, $recursive = true) {
$chmod = $this->globalOptions['chmodDir'];
if(empty($chmod) || !is_string($chmod) || strlen($chmod) < 2) $chmod = null;
return $this->wire()->files->mkdir($path, $recursive, $chmod);
}
/**
* Change file to correct mode for FileCompiler
*
* @param string $filename
* @return bool
*
*/
protected function chmod($filename) {
$chmod = $this->globalOptions['chmodFile'];
if(empty($chmod) || !is_string($chmod) || strlen($chmod) < 2) $chmod = null;
return $this->wire()->files->chmod($filename, false, $chmod);
}
/**
* Initialize the target path, making sure that it exists and creating it if not
*
* @throws WireException
*
*/
protected function initTargetPath() {
if(!is_dir($this->targetPath)) {
if(!$this->mkdir($this->targetPath)) {
throw new WireException("Unable to create directory $this->targetPath");
}
}
}
/**
* Populate the $this->rawPHP data which contains only raw php without quoted values
*
* @param string $data
*
*/
protected function initRawPHP(&$data) {
$this->rawPHP = '';
$this->rawDequotedPHP = '';
$phpOpen = '<' . '?';
$phpClose = '?' . '>';
$phpBlocks = explode($phpOpen, $data);
foreach($phpBlocks as $phpBlock) {
$pos = strpos($phpBlock, $phpClose);
if($pos !== false) {
$closeBlock = substr($phpBlock, strlen($phpClose) + 2);
if(strrpos($closeBlock, '{') && strrpos($closeBlock, '}') && strrpos($closeBlock, '=')
&& strrpos($closeBlock, '(') && strrpos($closeBlock, ')')
&& preg_match('/\sif\s*\(/', $closeBlock)
&& preg_match('/\$[_a-zA-Z][_a-zA-Z0-9]+/', $closeBlock)) {
// closeBlock still looks a lot like PHP, leave $phpBlock as-is
// happens when for example a phpClose is within a PHP string
} else {
$phpBlock = substr($phpBlock, 0, $pos);
}
}
$this->rawPHP .= $phpOpen . $phpBlock . $phpClose . "\n";
}
// remove docblocks/comments
// $this->rawPHP = preg_replace('!/\*.+?\*/!s', '', $this->rawPHP);
// remove escaped quotes
$this->rawDequotedPHP = str_replace(array('\\"', "\\'"), '', $this->rawPHP);
// remove double quoted blocks
$this->rawDequotedPHP = preg_replace('/([\s(.=,])"[^"]*"/s', '$1"string"', $this->rawDequotedPHP);
// remove single quoted blocks
$this->rawDequotedPHP = preg_replace('/([\s(.=,])\'[^\']*\'/s', '$1\'string\'', $this->rawDequotedPHP);
}
/**
* Allow the given filename to be compiled?
*
* @param string $filename Full path and filename to compile (this property can be modified by the function).
* @param string $basename Just the basename (this property can be modified by the function).
* @return bool
*
*/
protected function allowCompile(&$filename, &$basename) {
if($this->globalOptions['siteOnly']) {
// only files in /site/ are allowed for compilation
if(strpos($filename, $this->wire()->config->paths->site) !== 0) {
// sourcePath is somewhere outside of the PW /site/, and not allowed
return false;
}
}
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array(strtolower($ext), $this->extensions)) {
if(!strlen($ext) && !is_file($filename)) {
foreach($this->extensions as $ext) {
if(is_file("$filename.$ext")) {
// assume PHP file extension if none given, for cases like wireIncludeFile
$filename .= ".$ext";
$basename .= ".$ext";
}
}
} else {
return false;
}
}
if(!is_file($filename)) {
return false;
}
$allow = true;
foreach($this->exclusions as $pathname) {
if(strpos($filename, $pathname) === 0) {
$allow = false;
break;
}
}
return $allow;
}
/**
* Compile given source file and return compiled destination file
*
* @param string $sourceFile Source file to compile (relative to sourcePath given in constructor)
* @return string Full path and filename of compiled file. Returns sourceFile is compilation is not necessary.
* @throws WireException if given invalid sourceFile
*
*/
public function ___compile($sourceFile) {
$this->init();
if(strpos($sourceFile, $this->sourcePath) === 0) {
$sourcePathname = $sourceFile;
$sourceFile = str_replace($this->sourcePath, '/', $sourceFile);
} else {
$sourcePathname = $this->sourcePath . ltrim($sourceFile, '/');
}
if(!$this->allowCompile($sourcePathname, $sourceFile)) return $sourcePathname;
$this->initTargetPath();
$cacheName = md5($sourcePathname);
$sourceHash = md5_file($sourcePathname);
$targetHash = '';
$targetPathname = $this->targetPath . ltrim($sourceFile, '/');
$compileNow = true;
if(is_file($targetPathname)) {
// target file already exists, check if it is up-to-date
// $targetData = file_get_contents($targetPathname);
$targetHash = md5_file($targetPathname);
$cache = $this->wire()->cache->getFor($this, $cacheName);
if($cache && is_array($cache)) {
if($cache['target']['hash'] == $targetHash && $cache['source']['hash'] == $sourceHash) {
// target file is up-to-date
$compileNow = false;
} else {
// target file changed somewhere else, needs to be re-compiled
$this->wire()->cache->deleteFor($this, $cacheName);
}
if(!$compileNow && isset($cache['source']['ns'])) {
$this->ns = $cache['source']['ns'];
}
}
}
if($compileNow) {
$sourcePath = dirname($sourcePathname);
$targetPath = dirname($targetPathname);
$targetData = file_get_contents($sourcePathname);
if(stripos($targetData, 'FileCompiler=0')) return $sourcePathname; // bypass if it contains this string
if(strpos($targetData, 'namespace') !== false) $this->ns = $this->wire()->files->getNamespace($targetData, true);
if(!$this->ns) $this->ns = "\\";
if(!__NAMESPACE__ && !$this->options['modules'] && $this->ns === "\\") return $sourcePathname;
set_time_limit(120);
$this->copyAllNewerFiles($sourcePath, $targetPath);
$targetDirname = dirname($targetPathname) . '/';
if(!is_dir($targetDirname)) $this->mkdir($targetDirname);
$targetData = $this->compileData($targetData, $sourcePathname);
if(false !== file_put_contents($targetPathname, $targetData, LOCK_EX)) {
$this->chmod($targetPathname);
$this->touch($targetPathname, filemtime($sourcePathname));
$targetHash = md5_file($targetPathname);
$cacheData = array(
'source' => array(
'file' => $sourcePathname,
'hash' => $sourceHash,
'size' => filesize($sourcePathname),
'time' => filemtime($sourcePathname),
'ns' => $this->ns,
),
'target' => array(
'file' => $targetPathname,
'hash' => $targetHash,
'size' => filesize($targetPathname),
'time' => filemtime($targetPathname),
)
);
$this->wire()->cache->saveFor($this, $cacheName, $cacheData, WireCache::expireNever);
}
}
// if source and target are identical, use the source file
if($targetHash && $sourceHash === $targetHash) {
return $sourcePathname;
}
// show notices about compiled files, when applicable
if($compileNow) {
$message = $this->_('Compiled file:') . ' ' . str_replace($this->wire()->config->paths->root, '/', $sourcePathname);
if($this->globalOptions['showNotices']) {
$u = $this->wire('user');
if($u && $u->isSuperuser()) $this->message($message);
}
if($this->globalOptions['logNotices']) {
$this->log($message);
}
}
// if source file declares a namespace and skipIfNamespace option in use, use source file
if($this->options['skipIfNamespace'] && $this->ns && $this->ns != "\\") return $sourcePathname;
return $targetPathname;
}
/**
* Compile the given string of data
*
* @param string $data
* @param string $sourceFile
* @return string
*
*/
protected function ___compileData($data, $sourceFile) {
if($this->options['skipIfNamespace'] && $this->ns && $this->ns !== "\\") {
// file already declares a namespace and options indicate we shouldn't compile
return $data;
}
$this->initRawPHP($data);
if($this->options['includes']) {
$dataHash = md5($data);
$this->compileIncludes($data, $sourceFile);
if(md5($data) != $dataHash) $this->initRawPHP($data);
}
if($this->options['namespace']) {
if(__NAMESPACE__) {
if($this->ns && $this->ns !== "\\") {
// namespace already present, no need for namespace compilation
} else {
$this->compileNamespace($data);
}
} else {
if($this->ns && $this->ns !== "\\") {
// namespace present in file
$this->compileNamespace($data);
}
}
}
if($this->options['modules']) {
// FileCompiler modules
$compilers = array();
foreach($this->wire()->modules->findByPrefix('FileCompiler', true) as $module) {
if(!$module instanceof FileCompilerModule) continue;
$runOrder = (int) $module->get('runOrder');
while(isset($compilers[$runOrder])) $runOrder++;
$compilers[$runOrder] = $module;
}
if(count($compilers)) {
ksort($compilers);
foreach($compilers as $module) {
/** @var FileCompilerModule $module */
$module->setSourceFile($sourceFile);
$data = $module->compile($data);
}
}
}
if(!strlen(__NAMESPACE__)) {
if(strpos($this->rawPHP, "ProcessWire\\")) {
$data = str_replace(array("\\ProcessWire\\", "ProcessWire\\"), "\\", $data);
}
}
if(stripos($data, "FileCompiler=?") !== false) {
// Allow for a token that gets replaced so a file can detect if it's compiled
$data = str_replace("FileCompiler=?", "FileCompiler=Yes", $data);
}
return $data;
}
/**
* Compile comments so that they can be easily identified by other compiler methods
*
* @todo this is a work in progress, not yet in use
*
* @param $data
*
*/
protected function compileComments(&$data) {
$inComment = false;
$inPHP = false;
$lines = explode("\n", $data);
$numChanges = 0;
$commentIdentifier = '!PWFC!';
foreach($lines as $key => $line) {
$_line = $line; // original
$phpOpen = strrpos($line, '<' . '?');
$phpClose = strrpos($line, '?' . '>');
if($inPHP) {
if($phpClose !== false && ($phpClose === 0 || $phpClose > (int) $phpOpen)) {
$inPHP = false;
}
} else {
if($phpOpen !== false && ($phpClose === false || $phpClose < $phpOpen)) {
$inPHP = true;
}
}
if(!$inPHP) continue;
$commentOpen = strpos($line, '/' . '*');
$commentClose = strpos($line, '*' . '/');
if($inComment) {
if($commentClose !== false && ($commentOpen === false || $commentOpen < $commentClose)) {
$inComment = false;
}
$line = $commentIdentifier . $line;
}
if($commentOpen !== false) {
// has an open comment
if($commentClose !== false) {
// has a close comment, skip this line
continue;
} else {
$inComment = true;
}
}
if($line !== $_line) {
$lines[$key] = $line;
$numChanges++;
}
}
if($numChanges) {
$data = implode("\n", $lines);
}
}
/**
* Compile include(), require() (and variations) to refer to compiled files where possible
*
* @param string $data
* @param string $sourceFile
*
*/
protected function compileIncludes(&$data, $sourceFile) {
// other related to includes
$rawPHP = $this->rawPHP;
if(strpos($rawPHP, '__DIR__') !== false) {
$data = str_replace('__DIR__', "'" . dirname($sourceFile) . "'", $data);
$rawPHP = str_replace('__DIR__', "'" . dirname($sourceFile) . "'", $rawPHP);
}
if(strpos($rawPHP, '__FILE__') !== false) {
$data = str_replace('__FILE__', "'" . $sourceFile . "'", $data);
$rawPHP = str_replace('__FILE__', "'" . $sourceFile . "'", $rawPHP);
}
$optionsStr = $this->optionsToString($this->options);
$funcs = array(
'include_once',
'include',
'require_once',
'require',
'wireIncludeFile',
'wireRenderFile',
'TemplateFile',
);
// main include regex
$re = '/^' .
'(.*?)' . // 1: open
'(' . implode('|', $funcs) . ')' . // 2:function
'([\( ]+)' . // 3: argOpen: open parenthesis and/or space
'(["\']?[^;\r\n]+)' . // 4:filename, and rest of the statement (file may be quoted or end with closing parens)
'([;\r\n])' . // 5:close, whatever the last character is on the line
'/im';
if(!preg_match_all($re, $rawPHP, $matches)) return;
foreach($matches[0] as $key => $fullMatch) {
// if the include statement looks like one of these below then skip compilation for included file
// include(/*NoCompile*/__DIR__ . '/file.php');
// include(__DIR__ . '/file.php'/*NoCompile*/);
if(strpos($fullMatch, 'NoCompile') !== false) continue;
$open = $matches[1][$key];
$funcMatch = $matches[2][$key];
$argOpen = trim($matches[3][$key]);
$fileMatch = $matches[4][$key];
$close = $matches[5][$key];
$argsMatch = '';
if(!$argOpen && strpos($funcMatch, 'include') !== 0 && strpos($funcMatch, 'require') !== 0) {
// only include, include_once, require, require_once can be used without opening parenthesis
continue;
}
$fileMatchType = $this->compileIncludesFileMatchType($fileMatch, $funcMatch);
if(!$fileMatchType) continue;
if(!$this->compileIncludesValidLineOpen($open)) continue;
if(strpos($fileMatch, '?' . '>')) {
// move closing PHP tag out of the fileMatch and into the close
list($fileMatch, $fileMatchExtra) = explode('?' . '>', $fileMatch);
$close = '?' . '>' . $fileMatchExtra . $close;
$fileMatch = trim($fileMatch);
}
if(substr($fileMatch, -1) == ')') {
// move the closing parenthesis out of fileMatch and into close
$fileMatch = substr($fileMatch, 0, -1);
$close = ")$close";
}
if(empty($fileMatch)) continue;
if(empty($argOpen)) {
// if there was no opening "(", compiler will be adding one, so we'll need an additional corresponding ")"
$close = ")$close";
}
$commaPos = strpos($fileMatch, ',');
if($commaPos) {
// fileMatch contains additional function arguments
$argsMatch = substr($fileMatch, $commaPos);
$fileMatch = substr($fileMatch, 0, $commaPos);
}
if(strpos($fileMatch, '"') === 0 || strpos($fileMatch, "'") === 0) {
// fileMatch is quoted string
if(strpos($fileMatch, './') === 1) {
// relative to current dir, convert to absolute
$fileMatch = $fileMatch[0] . dirname($sourceFile) . substr($fileMatch, 2);
} else if(strpos($fileMatch, '/') === false
&& strpos($fileMatch, '$') === false
&& strpos($fileMatch, '(') === false
&& strpos($fileMatch, '\\') === false) {
// i.e. include("file.php")
$fileMatch = $fileMatch[0] . dirname($sourceFile) . '/' . substr($fileMatch, 1);
}
}
$fileMatch = str_replace("\t", '', $fileMatch);
if(strlen($open)) $open .= ' ';
$ns = __NAMESPACE__ ? "\\ProcessWire" : "";
$open = rtrim($open) . ' ';
$newFullMatch = "$open$funcMatch($ns\\wire('files')->compile($fileMatch,$optionsStr)$argsMatch$close";
$data = str_replace($fullMatch, $newFullMatch, $data);
}
// replace absolute root path references with runtime generated versions
$rootPath = $this->wire()->config->paths->root;
if(strpos($data, $rootPath)) {
$ns = __NAMESPACE__ ? "\\ProcessWire" : "";
$data = preg_replace('%([\'"])' . preg_quote($rootPath) . '([^\'"\s\r\n]*[\'"])%',
$ns . '\\wire("config")->paths->root . $1$2',
$data);
}
}
/**
* Test the given line $open preceding an include statement for validity
*
* @param string $open
* @return bool Returns true if valid, false if not
*
*/
protected function compileIncludesValidLineOpen($open) {
if(!strlen($open)) return true;
$skipMatch = false;
$test = $open;
foreach(array('"', "'") as $quote) {
// skip when words like "require" are in a string
if(strpos($test, $quote) === false) continue;
$test = str_replace('\\' . $quote, '', $test); // ignore quotes that are escaped
if(strpos($test, $quote) === false) continue;
if(substr_count($test, $quote) % 2 > 0) {
// there are an uneven number of quotes, indicating that
// our $funcMatch is likely part of a quoted string
$skipMatch = true;
break;
}
if($quote == '"' && strpos($test, "'") !== false) {
// remove quoted apostrophes so they don't confuse the next iteration
$test = preg_replace('/"[^"\']*\'[^"]*"/', '', $test);
}
}
if(!$skipMatch && preg_match('/^[$_a-zA-Z0-9]+$/', substr($open, -1))) {
// skip things like: something_include(... and $include
$skipMatch = true;
}
return $skipMatch ? false : true;
}
/**
* Returns fileMatch type of 'var', 'file', 'func' or boolean false if not valid
*
* @param string $fileMatch The $fileMatch var from compileIncludes() method
* @param string $funcMatch include function name
* @return string|bool
*
*/
protected function compileIncludesFileMatchType($fileMatch, $funcMatch) {
$fileMatch = trim($fileMatch);
$isValid = false;
$phpVarSign = strpos($fileMatch, '$');
$doubleQuote1 = strpos($fileMatch, '"');
$doubleQuote2 = strrpos($fileMatch, '"');
$singleQuote1 = strpos($fileMatch, "'");
$singleQuote2 = strrpos($fileMatch, "'");
$parenthesis1 = strpos($fileMatch, '(');
$parenthesis2 = strrpos($fileMatch, ')');
$testFile = '';
if($phpVarSign === 0) {
// fileMatch starts with a var name, make sure it at least starts in PHP var format
if(preg_match('/^\$[_a-zA-Z]/', $fileMatch)) $isValid = 'var';
} else if($doubleQuote1 !== false && $doubleQuote2 > $doubleQuote1) {
// fileMatch has both open and close double quotes with possibly a filename, so validate extension
$testFile = substr($fileMatch, $doubleQuote1 + 1, $doubleQuote2 - $doubleQuote1 - 1);
} else if($singleQuote1 !== false && $singleQuote2 > $singleQuote1) {
// fileMatch has both open and close single quotes with possibly a filename, so validate extension
$testFile = substr($fileMatch, $singleQuote1 + 1, $singleQuote2 - $singleQuote1 - 1);
} else if($parenthesis1 > 0 && $parenthesis2 > $parenthesis1) {
// likely a function call, make sure open parenthesis is preceded by PHP name format
if(preg_match('/[_a-zA-Z][_a-zA-Z0-9]+\(/', $fileMatch)) $isValid = 'func';
} else {
// likely NOT a valid file match, as it doesn't have any of the expected characters
$isValid = false;
}
if($testFile) {
if(strrpos($testFile, '.')) {
// test contains a filename that needs extension validated
$parts = explode('.', $testFile);
$testExt = array_pop($parts);
if($testExt && in_array(strtolower($testExt), $this->extensions)) $isValid = 'file';
} else if($funcMatch == 'wireRenderFile' || $funcMatch == 'wireIncludeFile') {
// these methods don't require a file extension
$isValid = 'file';
}
}
return $isValid;
}
/**
* Compile global class/interface/function references to namespaced versions
*
* @param string $data
* @return bool Whether or not namespace changes were compiled
*
*/
protected function compileNamespace(&$data) {
/*
$pos = strpos($data, 'namespace');
if($pos !== false) {
if(preg_match('/(^.*)\s+namespace\s+[_a-zA-Z0-9\\\\]+\s*;/m', $data, $matches)) {
if(strpos($matches[1], '//') === false && strpos($matches[1], '/*') === false) {
// namespace already present, no need for namespace compilation
return false;
}
}
}
*/
$classes = get_declared_classes();
$classes = array_merge($classes, get_declared_interfaces());
// also add in all core classes, in case the have not yet been autoloaded
static $files = null;
if(is_null($files)) {
$files = array();
foreach(new \DirectoryIterator($this->wire()->config->paths->core) as $file) {
if($file->isDot() || $file->isDir()) continue;
$basename = $file->getBasename('.php');
if(strtoupper($basename[0]) == $basename[0]) {
$name = __NAMESPACE__ ? __NAMESPACE__ . "\\$basename" : $basename;
if(!in_array($name, $classes)) $files[] = $name;
}
}
}
// also add in all modules
foreach($this->wire()->modules as $module) {
$name = __NAMESPACE__ ? $module->className(true) : $module->className();
if(!in_array($name, $classes)) $classes[] = $name;
}
$classes = array_merge($classes, $files);
if(!__NAMESPACE__) $classes = array_merge($classes, array_keys($this->wire()->modules->getInstallable()));
$rawPHP = $this->rawPHP;
$rawDequotedPHP = $this->rawDequotedPHP;
// update classes and interfaces
foreach($classes as $class) {
if(__NAMESPACE__ && strpos($class, __NAMESPACE__ . '\\') !== 0) continue; // limit only to ProcessWire classes/interfaces
if(strpos($class, '\\') !== false) {
list($ns, $class) = explode('\\', $class, 2); // reduce to just class without namespace
} else {
$ns = '';
}
if($ns) {}
if(stripos($rawDequotedPHP, $class) === false) continue; // quick exit if class name not referenced in data
$patterns = array(
// 1=open 2=close
// all patterns match within 1 line only
"new" => '(new\s+)' . $class . '\s*(\(|;|\))', // 'new Page(' or 'new Page;' or 'new Page)'
"function" => '(function\s+[_a-zA-Z0-9]+\s*\([^\\\\)]*?)\b' . $class . '(\s+\$[_a-zA-Z0-9]+)', // 'function(Page $page' or 'function($a, Page $page'
"::" => '(^|[^_\\\\a-zA-Z0-9"\'])' . $class . '(::)', // constant ' Page::foo' or '(Page::foo' or '=Page::foo' or bitwise open
"extends" => '(\sextends\s+)' . $class . '(\s|\{|$)', // 'extends Page'
"implements" => '(\simplements[^{]*?[\s,]+)' . $class . '([^_a-zA-Z0-9]|$)', // 'implements Module' or 'implements Foo, Module'
"instanceof" => '(\sinstanceof\s+)' . $class . '([^_a-zA-Z0-9]|$)', // 'instanceof Page'
"$class " => '(\(\s*|,\s*)' . $class . '(\s+\$)', // type hinted '(Page $something' or '($foo, Page $something'
);
foreach($patterns as $check => $regex) {
if(stripos($rawDequotedPHP, $check) === false) continue;
if(!preg_match_all('/' . $regex . '/im', $rawDequotedPHP, $matches)) continue;
foreach($matches[0] as $key => $fullMatch) {
$open = $matches[1][$key];
$close = $matches[2][$key];
if(substr($open, -1) == '\\') continue; // if last character in open is '\' then skip the replacement
$className = __NAMESPACE__ ? '\\' . __NAMESPACE__ . '\\' . $class : '\\' . $class;
$repl = $open . $className . $close;
$data = str_replace($fullMatch, $repl, $data);
$rawPHP = str_replace($fullMatch, $repl, $rawPHP);
$rawDequotedPHP = str_replace($fullMatch, $repl, $rawDequotedPHP);
}
}
}
// update PW procedural function calls
$functions = get_defined_functions();
$hasFunctionExists = strpos($rawDequotedPHP, 'function_exists') !== false;
foreach($functions['user'] as $function) {
if(__NAMESPACE__) {
if(stripos($function, __NAMESPACE__ . '\\') !== 0) continue; // limit only to ProcessWire functions
list($ns, $function) = explode('\\', $function, 2); // reduce to just function name
$functionName = '\\' . __NAMESPACE__ . '\\' . $function;
} else {
if(stripos($function, '\\') !== 0) continue;
$functionName = '\\' . $function;
$ns = '';
}
if($ns) {}
if(stripos($rawDequotedPHP, $function) === false) continue; // if function name not mentioned in data, quick exit
$n = 0;
while(preg_match_all('/^(.*?[()!;,@\[=\s.])' . $function . '\s*\(/im', $rawPHP, $matches)) {
foreach($matches[0] as $key => $fullMatch) {
$open = $matches[1][$key];
if(strpos($open, 'function') !== false) continue; // skip function defined with same name
$repl = $open . $functionName . '(';
$data = str_replace($fullMatch, $repl, $data);
$rawPHP = str_replace($fullMatch, $repl, $rawPHP);
}
if(++$n > 5) break;
}
if($hasFunctionExists) {
$find = 'function_exists\s*\(\s*["\']' . $function . '["\']\s*\)';
$repl = "function_exists('$functionName')";
$data = preg_replace("/$find/i", $repl, $data);
}
}
// update other function calls
$ns = __NAMESPACE__ ? "\\ProcessWire" : "";
if(strpos($rawDequotedPHP, 'class_parents(') !== false) {
$data = preg_replace('/\bclass_parents\(/', $ns . '\\wireClassParents(', $data);
}
if(strpos($rawDequotedPHP, 'class_implements(') !== false) {
$data = preg_replace('/\bclass_implements\(/', $ns . '\\wireClassImplements(', $data);
}
return true;
}
/**
* Recursively copy all files from $source to $target, but only if $source file is $newer
*
* @param string $source
* @param string $target
* @param bool $recursive
* @return int Number of files copied
*
*/
protected function copyAllNewerFiles($source, $target, $recursive = true) {
$source = rtrim($source, '/') . '/';
$target = rtrim($target, '/') . '/';
// don't perform full copies of some directories
// @todo convert this to use the user definable exclusions list
$config = $this->wire()->config;
if($source === $config->paths->site) return 0;
if($source === $config->paths->siteModules) return 0;
if($source === $config->paths->templates) return 0;
if(!is_dir($target)) $this->wire()->files->mkdir($target, true);
$dir = new \DirectoryIterator($source);
$numCopied = 0;
foreach($dir as $file) {
if($file->isDot()) continue;
$sourceFile = $file->getPathname();
$targetFile = $target . $file->getBasename();
if($file->isDir()) {
if($recursive) {
$numCopied += $this->copyAllNewerFiles($sourceFile, $targetFile, $recursive);
}
continue;
}
$ext = strtolower($file->getExtension());
if(!in_array($ext, $this->extensions)) continue;
if(is_file($targetFile)) {
if(filemtime($targetFile) >= filemtime($sourceFile)) {
$numCopied++;
continue;
}
}
copy($sourceFile, $targetFile);
$this->chmod($targetFile);
$this->touch($targetFile, filemtime($sourceFile));
$numCopied++;
}
if(!$numCopied) {
$this->wire()->files->rmdir($target, true);
}