-
Notifications
You must be signed in to change notification settings - Fork 5
/
UpgradeSilverstripe.php
820 lines (730 loc) · 29.9 KB
/
UpgradeSilverstripe.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
<?php
require_once('ReplacementData.php');
/*
TODO:
Add colouring:
http://www.if-not-true-then-false.com/2010/php-class-for-coloring-php-command-line-cli-scripts-output-php-output-colorizing-using-bash-shell-colors/
**Test output on browser
*/
define("__FROM_COMMAND_LINE__", PHP_SAPI === 'cli');
class UpgradeSilverstripe
{
private $marker = "### @@@@ UPGRADE REQUIRED @@@@ ###";
private $endMarker = "### @@@@ ########### @@@@ ###";
private $output = "";
private $numberOfStraightReplacements = 0;
public function getNumberOfStraightReplacements()
{
return intval($this->numberOfStraightReplacements);
}
private $numberOfAllReplacements = 0;
public function getNumberOfAllReplacements()
{
return intval($this->numberOfAllReplacements);
}
private $checkReplacementIssues = false;
public function setCheckReplacementIssues($b)
{
$this->checkReplacementIssues = $b;
}
/**
*
* @param String $pathLocation - enter dot for anything in current directory.
* @param String $logFileLocation - where should the log file be saved. This file contains all the details about actual changes made.
* @param String $to - if you set this to, for example 3.0 then the code will be upgraded from 2.4 to 3.0.
* @param Boolean $doBasicReplacement - If set to false to show proposed changes on screen. If set to true, basic replacements (i.e. straight forward replace A with B scenarios will be made)
* @param Boolean $markStickingPoints - If set to false nothing happens, if set to true any code that need changing manually will be marked in the code itself.
* @param Array $ignoreFolderArray - a list of folders that should not be searched (and replaced) - folders that are automatically ignore are: CMS, SAPPHIRE, FRAMEWORK (all in lowercase)
* outputs to screen and/or to file
*/
public function run(
$pathLocation = ".",
$logFileLocation = "",
$to = "3.0",
$doBasicReplacement = false,
$markStickingPoints = false,
$ignoreFolderArray = array()
) {
if (!file_exists($pathLocation)) {
$this->addToOutput("\n\n");
user_error("ERROR: could not find specified path: ".$pathLocation);
$this->addToOutput("\n\n");
$this->addToOutput("---END ---\n");
}
if ($this->checkReplacementIssues) {
$this->checkReplacementIssues();
$this->addToOutput("---END ---\n");
}
//basic checks
if (!$doBasicReplacement && $markStickingPoints) {
user_error("You have to set doBasicReplacement = TRUE before you can set markStickingPoints = TRUE");
}
if (!is_array($ignoreFolderArray)) {
user_error("the ignoreFolderArray param should be an array");
}
$style = "BASIC";
if ($markStickingPoints) {
$style = "COMPLICATED";
}
if ($doBasicReplacement) {
$this->addToOutput("\n#################################### \n REAL $style REPLACEMENTS \n####################################\n ");
} else {
$this->addToOutput("\n#################################### \n TEST ALL REPLACEMENTS ONLY \n#################################### \n ");
$logFileLocation = null;
}
//get replacements
$replacementDataObject = new ReplacementData();
$previousTos = $replacementDataObject->getTos();
$previousMigrationsDone = true;
$migrationChecksDone = false;
$this->numberOfStraightReplacements = 0;
$this->numberOfAllReplacements = 0;
foreach ($previousTos as $previousTo) {
$totalForOneVersion = 0;
$this->addToOutput("\n------------------------------------\nUpgrade to Silverstripe: $previousTo \n------------------------------------");
if ($to == $previousTo) {
$migrationChecksDone = true;
if (!$previousMigrationsDone) {
echo $this->printItNow();
die("\nError: Your code is not ready to migrate to $to (see above)");
}
}
$numberToAdd = $this->numberOfReplacements($pathLocation, $previousTo, $ignoreFolderArray, true);
$totalForOneVersion += $numberToAdd;
$this->numberOfStraightReplacements += $numberToAdd;
if ($this->numberOfStraightReplacements == 0) {
$this->addToOutput("\n[BASIC: DONE] migration to $previousTo for basic replacements completed.");
} else {
$this->addToOutput("\n[BASIC: TO DO] migration to $previousTo for basic replacements NOT completed yet ($numberToAdd items to do).");
$previousMigrationsDone = false;
}
$numberToAdd = $this->numberOfReplacements($pathLocation, $previousTo, $ignoreFolderArray, false);
$totalForOneVersion += $numberToAdd;
$this->numberOfAllReplacements += $numberToAdd;
if ($this->numberOfAllReplacements == 0) {
$this->addToOutput("\n[COMPLEX: DONE] migration to $previousTo for complicated items completed.");
} else {
$this->addToOutput("\n[COMPLEX: UNSURE] migration to $previousTo for complicated items NOT completed yet ($numberToAdd items to do).");
}
$this->addToOutput("\n------------------------------------\n$totalForOneVersion items to do for $previousTo \n------------------------------------\n");
$totalForOneVersion = 0;
$this->addToOutput("\n\n");
if ($migrationChecksDone) {
break;
}
}
$textSearchMachine = new TextSearch();
//set basics
$textSearchMachine->addIgnoreFolderArray($ignoreFolderArray); //setting extensions to search files within
$textSearchMachine->setBasePath($pathLocation);
if ($logFileLocation) {
$textSearchMachine->setLogFileLocation($logFileLocation);
} else {
$textSearchMachine->setLogFileLocation($pathLocation."/ss_upgrade_log.txt");
}
$array = $replacementDataObject->getReplacementArrays($to);
foreach ($array as $extension => $extensionArray) {
$this->addToOutput("\n\n\n\n++++++++++++++++++++++++++++++++++++ \n CHECKING $extension FILES \n++++++++++++++++++++++++++++++++++++ \n\n\n\n");
$textSearchMachine->setExtensions(array($extension)); //setting extensions to search files within
foreach ($extensionArray as $replaceArray) {
$find = $replaceArray[0];
//$replace = $replaceArray[1]; unset($replaceArray[1]);
//$fullReplacement = (isset($replaceArray[2]) ? "/* ".$replaceArray[2]." */\n" : "").$replaceArray[1];
$fullReplacement = "";
$isStraightReplace = true;
if (isset($replaceArray[2])) {
// Has comment
$isStraightReplace = false;
$fullReplacement = "/*\n".$this->marker."\nFIND: ".$replaceArray[0]."\nNOTE: ".$replaceArray[2]." \n".$this->endMarker."\n*/".$replaceArray[1];
} else { // Straight replace
$fullReplacement = $replaceArray[1];
}
$comment = isset($replaceArray[2]) ? $replaceArray[2] : "";
$codeReplacement = $replaceArray[1];
if (!$find) {
user_error("no find is specified, replace is: $replace");
}
if (!$fullReplacement) {
user_error("no replace is specified, find is: $find");
}
if ($doBasicReplacement) {
if (!$markStickingPoints && !$isStraightReplace) {
continue;
}
$textSearchMachine->setSearchKey($find, 0, $isStraightReplace ? "BASIC" : "COMPLEX");
$textSearchMachine->setReplacementKey($fullReplacement);
$textSearchMachine->startSearching();//starting search
//output - only write to log for real replacements!
//$textSearchMachine->writeLogToFile($logFileLocation);
} else {
$textSearchMachine->setSearchKey($find, 0, $isStraightReplace ? "BASIC" : "COMPLEX");
$textSearchMachine->setFutureReplacementKey($codeReplacement);
$textSearchMachine->startSearching();//starting search
//output - only write to log for real replacements!
}
//$textSearchMachine->showLog();//showing log
}
$replacements = $textSearchMachine->showFormattedSearchTotals(false);
if ($replacements) {
$this->addToOutput($textSearchMachine->getOutput());
} else {
//flush output anyway!
$textSearchMachine->getOutput();
$this->addToOutput("\n No replacements for $extension \n------------------------------------\n");
}
}
return $this->printItNow();
}
/**
*
* @var Int
*/
private function numberOfReplacements(
$pathLocation = ".",
$to = "3.0",
$ignoreFolderArray = array(),
$simpleOnly = true
) {
//basic checks
$total = 0;
$textSearchMachine = new TextSearch();
//get replacements
$replacementData = new ReplacementData();
$array = $replacementData->getReplacementArrays($to);
//set basics
$textSearchMachine->addIgnoreFolderArray($ignoreFolderArray); //setting extensions to search files within
$textSearchMachine->setBasePath($pathLocation);
foreach ($array as $extension => $extensionArray) {
$textSearchMachine->setExtensions(array($extension)); //setting extensions to search files within
foreach ($extensionArray as $replaceArray) {
$find = $replaceArray[0];
$isStraightReplace = isset($replaceArray[2]) ? true : false;
if ($isStraightReplace && $simpleOnly) {
// Has comment
continue;
} elseif (!$isStraightReplace && !$simpleOnly) {
continue;
}
$textSearchMachine->setSearchKey($find, 0, $isStraightReplace ? "BASIC" : "COMPLEX");
$textSearchMachine->setFutureReplacementKey("TEST ONLY");
$textSearchMachine->startSearching();//starting search
}
//IMPORTANT!
$total += $textSearchMachine->showFormattedSearchTotals(true);
}
//flush output anyway!
$textSearchMachine->getOutput();
return $total;
}
/**
* 1. check that one find is not used twice:
* find can be found 2x
*
*/
private function checkReplacementIssues()
{
$r = new ReplacementData();
$arr = $r->getReplacementArrays(null);
$arrTos = array();
$arrLanguages = $r->getLanguages();
$fullFindArray = $r->getFlatFindArray();
$fullReplaceArray = $r->getFlatReplacedArray();
//1, check that one find may not stop another replacement.
foreach ($arrLanguages as $language) {
if (!isset($fullFindArray[$language])) {
continue;
}
unset($keyOuterDoneSoFar);
$keyOuterDoneSoFar = array();
foreach ($fullFindArray[$language] as $keyOuter => $findStringOuter) {
$keyOuterDoneSoFar[$keyOuter] = true;
foreach ($fullFindArray[$language] as $keyInner => $findStringInner) {
if (!isset($keyOuterDoneSoFar[$keyInner])) {
if ($keyOuter != $keyInner) {
$findStringOuterReplaced = str_replace($findStringInner, "...", $findStringOuter);
if ($findStringOuter == $findStringInner || $findStringOuterReplaced != $findStringOuter) {
$this->addToOutput("
ERROR in $language: \t\t we are trying to find the same thing twice (A and B)
---- A: ($keyOuter): \t\t $findStringOuter
---- B: ($keyInner): \t\t $findStringInner");
}
}
}
}
}
}
$this->addToOutput("\n");
//2. check that a replacement is not mentioned before the it is being replaced
foreach ($arrLanguages as $language) {
if (!isset($fullReplaceArray[$language])) {
continue;
}
unset($keyOuterDoneSoFar);
$keyOuterDoneSoFar = array();
foreach ($fullReplaceArray[$language] as $keyOuter => $findStringOuter) {
$keyOuterDoneSoFar[$keyOuter] = true;
foreach ($fullFindArray[$language] as $keyInner => $findStringInner) {
if (isset($keyOuterDoneSoFar[$keyInner])) {
if ($keyOuter != $keyInner) {
$findStringOuterReplaced = str_replace($findStringInner, "...", $findStringOuter);
if ($findStringOuter == $findStringInner || $findStringOuterReplaced != $findStringOuter) {
$this->addToOutput("
ERROR in $language: \t\t there is a replacement (A) that was earlier tried to be found (B).
---- A: ($keyOuter): \t\t $findStringOuter
---- B: ($keyInner): \t\t $findStringInner");
}
}
}
}
}
}
$this->addToOutput("\n");
}
private function addToOutput($text)
{
$this->output .= $text;
}
private function printItNow()
{
$text = $this->output;
$this->output = "";
if (__FROM_COMMAND_LINE__) {
echo $text."\n\n\n";
} else {
return "<pre>".$text."</pre>";
}
}
}
/**
* Class : TextSearch
*
* @author : MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
* Moderator, phpResource Group(http://groups.yahoo.com/group/phpresource/)
* URL: http://rupom.wordpress.com
*
* HEAVILY MODIFIED BY SUNNY SIDE UP
*
* @version : 1.0
* Date : 06/25/2006
* Purpose : Searching and replacing text within files of specified path
*/
class TextSearch
{
private $basePath = '.';
private $logFileLocation = '';
private $defaultIgnoreFolderArray = array("cms", "assets", "sapphire", "framework", "upgrade_silverstripe", ".svn", ".git");
private $ignoreFolderArray = array();
private $extensions = array("php", "ss", "yml", "yaml", "json", "js");
private $findAllExts = 0;
private $searchKey = '';
private $replacementKey = '';
private $futureReplacementKey = '';
private $isReplacingEnabled = 0;
private $replacementType = "";
private $caseSensitive = 0;
private $logString = ''; //details of one search
private $errorText = ''; //details of one search
private $totalFound = 0; //total matches in one search
private $output = ''; //buffer of output, until it is retrieved
private static $search_key_totals = array();
private static $folder_totals = array();
private static $total_total = 0;
public function __construct()
{
$this->ignoreFolderArray = $this->defaultIgnoreFolderArray;
}
//================================================
// Setters Before Run
//================================================
/**
* Sets folders to ignore
* @param Array ignoreFolderArray
* @return none
*/
public function setIgnoreFolderArray($ignoreFolderArray = array())
{
$this->ignoreFolderArray = $ignoreFolderArray;
$this->resetFileCache();
}
/**
* Sets folders to ignore
* @param Array ignoreFolderArray
* @return none
*/
public function addIgnoreFolderArray($ignoreFolderArray = array())
{
$this->ignoreFolderArray = $ignoreFolderArray;
$this->ignoreFolderArray = array_unique(array_merge($this->ignoreFolderArray, $this->defaultIgnoreFolderArray));
$this->resetFileCache();
}
/**
* remove a root folder that is avoided by default
* @param String $nameOfFolder
*/
public function unsetIgnoreFolderArray($nameOfFolder)
{
unset($this->ignoreFolderArray[$nameOfFolder]);
$this->resetFileCache();
}
/**
* Sets folders to ignore
* @param Array ignoreFolderArray
* @return none
*/
public function setBasePath($pathLocation)
{
$this->basePath = $pathLocation;
$this->resetFileCache();
}
/**
* Sets location for the log file
* logs are only written for real replacements
* @param String
* @return none
*/
public function setLogFileLocation($logFileLocation)
{
$this->logFileLocation = $logFileLocation;
}
/**
* Sets extensions to look
* @param Array extensions
*/
public function setExtensions($extensions = array())
{
$this->extensions = $extensions;
if (count($this->extensions)) {
$this->findAllExts = 0; //not all extensions
}
$this->resetFileCache();
}
//================================================
// Setters Before Every Search
//================================================
/**
* Sets search key and case sensitivity
* @param String $searchKey,
* @param Boolean $caseSensitivity
*/
public function setSearchKey($searchKey, $caseSensitive = 0, $replacementType)
{
$this->searchKey = $searchKey;
$this->caseSensitive = $caseSensitive;
$this->replacementType = $replacementType;
}
/**
* Sets key to replace searchKey with
* @param String $replacementKey
*/
public function setReplacementKey($replacementKey)
{
$this->replacementKey = $replacementKey;
$this->isReplacingEnabled = 1;
}
/**
* Sets key to replace searchKey with BUT only hypothetical
* (no replacement takes place!)
* @param String $replacementKey
*/
public function setFutureReplacementKey($replacementKey)
{
$this->futureReplacementKey = $replacementKey;
$this->isReplacingEnabled = 0;
}
//================================================
// Get FINAL output
//================================================
/**
* returns full output
* and clears it.
* @return string
*/
public function getOutput()
{
$output = $this->output;
$this->output = "";
return $output;
}
/**
* returns the TOTAL TOTAL number of
* found replacements
*/
public function getTotalTotalSearches()
{
return self::$total_total;
}
//================================================
// Write to log while doing the searches
//================================================
/**
* should be run at the end of an extension.
*/
public function showFormattedSearchTotals($returnTotalFoundOnly = false)
{
$totalSearches = 0;
foreach (self::$search_key_totals as $searchKey => $total) {
$totalSearches += $total;
}
if ($returnTotalFoundOnly) {
//do nothing
} else {
$flatArray = $this->getFlatFileArray();
$this->addToOutput("\n------------------------------------\nFiles Searched\n------------------------------------\n");
foreach ($flatArray as $file) {
$strippedFile = str_replace($this->basePath, "", $file);
$this->addToOutput($strippedFile."\n");
}
$folderSimpleTotals = array();
$realBase = realpath($this->basePath);
$this->addToOutput("\n------------------------------------\nSummary: by search key\n------------------------------------\n");
arsort(self::$search_key_totals);
foreach (self::$search_key_totals as $searchKey => $total) {
$this->addToOutput(sprintf("%d:\t %s\n", $total, $searchKey));
}
$this->addToOutput("\n------------------------------------\nSummary: by directory\n------------------------------------\n");
arsort(self::$folder_totals);
foreach (self::$folder_totals as $folder => $total) {
$path = str_replace($realBase, "", realpath($folder));
$pathArr = explode("/", $path);
if (isset($pathArr[1])) {
$folderName = $pathArr[1]."/";
if (!isset($folderSimpleTotals[$folderName])) {
$folderSimpleTotals[$folderName] = 0;
}
$folderSimpleTotals[$folderName] += $total;
$strippedFolder = str_replace($this->basePath, "", $folder);
$this->addToOutput(sprintf("%d:\t %s\n", $total, $strippedFolder));
}
}
$strippedRealBase = "/";
$this->addToOutput(sprintf("\n------------------------------------\nSummary: by root directory (%s)\n------------------------------------\n", $strippedRealBase));
arsort($folderSimpleTotals);
foreach ($folderSimpleTotals as $folder => $total) {
$strippedFolder = str_replace($this->basePath, "", $folder);
$this->addToOutput(sprintf("%d:\t %s\n", $total, $strippedFolder));
}
$this->addToOutput(sprintf("\n------------------------------------\nTotal replacements: %d\n------------------------------------\n", $totalSearches));
}
//add to total total
self::$total_total += $totalSearches;
//return total
return $totalSearches;
}
//================================================
// Doers
//================================================
/**
* Searches all the files and creates the logs
* @param $path to search
* @return none
*/
public function startSearching()
{
$flatArray = $this->getFlatFileArray();
foreach ($flatArray as $location) {
$this->searchFileData("$location");
}
if ($this->totalFound) {
$this->addToOutput("".$this->totalFound." matches (".$this->replacementType.") for: ".$this->logString);
}
if ($this->errorText!= '') {
$this->addToOutput("\t Error-----".$this->errorText);
}
$this->logString = "";
$this->errorText = "";
$this->totalFound = 0;
}
private function resetFileCache()
{
self::$file_array = null;
self::$file_array = array();
self::$flat_file_array = null;
self::$flat_file_array = array();
//cleanup other data
self::$search_key_totals = null;
self::$search_key_totals = array();
self::$folder_totals = null;
self::$folder_totals = array();
}
/**
* array of all the files we are searching
* @var array
*/
private static $file_array = array();
/**
* loads all the applicable files
* @param String $path (e.g. "." or "/var/www/mysite.co.nz")
* @param Boolean $innerLoop - is the method calling itself???
*
*
*/
private function getFileArray($path, $innerLoop = false)
{
$key = str_replace(array("/"), "__", $path);
if ($innerLoop || !count(self::$file_array)) {
$dir = opendir($path);
while ($file = readdir($dir)) {
if (($file == ".") || ($file == "..") || (__FILE__ == "$path/$file") || ($path == "." && basename(__FILE__) == $file)) {
continue;
}
//ignore hidden files and folders
if (substr($file, 0, 1) == ".") {
continue;
}
//ignore folders with _manifest_exclude in them!
if ($file == "_manifest_exclude") {
$this->ignoreFolderArray[] = $path;
unset(self::$file_array[$key]);
break;
}
if (filetype("$path/$file") == "dir") {
if (
(in_array($file, $this->ignoreFolderArray) && ($path == "."|| $path == $this->basePath)) ||
(in_array($path, $this->ignoreFolderArray))) {
continue;
}
$this->getFileArray("$path/$file", $innerLoop = true); //recursive traversing here
} elseif ($this->matchedExtension($file)) { //checks extension if we need to search this file
if (filesize("$path/$file")) {
self::$file_array[$key][] = "$path/$file"; //search file data
}
}
} //End of while
closedir($dir);
}
return self::$file_array;
}
/**
* Flattened array of files.
* @var Array
*/
private static $flat_file_array = array();
private function getFlatFileArray()
{
if (!count(self::$flat_file_array)) {
$array = $this->getFileArray($this->basePath, false);
$multiDimensionalArray = $this->getFileArray($this->basePath, false);
//flatten it!
self::$flat_file_array = new RecursiveIteratorIterator(new RecursiveArrayIterator($multiDimensionalArray));
}
return self::$flat_file_array;
}
/**
* Finds extension of a file
* @param filename
* @return file extension
*/
private function findExtension($file)
{
$fileArray = explode(".", $file);
return array_pop($fileArray);
}//End of function
/**
* Checks if a file extension is one of the extensions we are going to search
* @param String $filename
* @return Boolean
*/
private function matchedExtension($file)
{
if ($this->findAllExts) {
return true;
} elseif (sizeof(array_keys($this->extensions, $this->findExtension($file)))==1) {
return true;
}
return false;
}
/**
* THE KEY METHOD!
* Searches data, replaces (if enabled) with given key, prepares log
* @param String $file - e.g. /var/www/mysite.co.nz/mysite/code/Page.php
*/
private function searchFileData($file)
{
$searchKey = preg_quote($this->searchKey, '/');
if ($this->caseSensitive) {
$pattern = "/$searchKey/U";
} else {
$pattern = "/$searchKey/Ui";
}
$subject = file_get_contents($file);
$found = 0;
$found = preg_match_all($pattern, $subject, $matches, PREG_PATTERN_ORDER);
$this->totalFound +=$found;
if ($found) {
$foundStr = " x $found";
if ($this->isReplacingEnabled) {
if ($this->replacementKey) {
$outputStr = preg_replace($pattern, $this->replacementKey, $subject);
$foundStr = "-- Replaced in $found places";
$this->writeToFile($file, $outputStr);
$this->appendToLog($file, $foundStr, $this->replacementKey);
} else {
$this->errorText .= "********** ERROR: Replacement Text is not defined\n";
$this->appendToLog($file, "********** ERROR: Replacement Text is not defined", $this->replacementKey);
}
} else {
if ($this->futureReplacementKey) {
$this->appendToLog($file, $foundStr, $this->futureReplacementKey);
} else {
$this->errorText .= "********** ERROR: FUTURE Replacement Text is not defined\n";
$this->appendToLog($file, "********** ERROR: FUTURE Replacement Text is not defined");
}
}
if (!isset(self::$search_key_totals[$this->searchKey])) {
self::$search_key_totals[$this->searchKey] = 0;
}
self::$search_key_totals[$this->searchKey] += $found;
if (!isset(self::$folder_totals[dirname($file)])) {
self::$folder_totals[dirname($file)] = 0;
}
self::$folder_totals[dirname($file)] += $found;
} else {
//$this->appendToLog($file, "No matching Found", $this->replacementKey);
}
}
/**
* Writes new data (after the replacement) to file
* @param $file, $data
* @return none
*/
private function writeToFile($file, $data)
{
if (is_writable($file)) {
$fp = fopen($file, "w");
fwrite($fp, $data);
fclose($fp);
} else {
$this->errorText .= "********** ERROR: Can not replace text. File $file is not writable. \nPlease make it writable\n";
}
}
/**
* Appends log data to previous log data
* @param filename, match string, replacement key if any
* @return none
*/
private function appendToLog($file, $matchStr, $replacementKey = null)
{
if ($this->logString == '') {
$this->logString = "'".$this->searchKey."'\n";
}
$file = basename($file);
$this->logString .= " $matchStr IN $file\n";
}
/**
*
* @param String $text
*/
private function addToOutput($output)
{
if ($this->logFileLocation && $this->isReplacingEnabled) {
$handle = fopen($this->logFileLocation, "a");
if ($handle) {
fwrite($handle, $output);
fclose($handle);
} else {
die("\n\nLOG ERROR: Can not write to ".realpath(dirname($this->logFileLocation))." (".$this->logFileLocation.") .");
}
}
$this->output .= $output;
}
}