-
Notifications
You must be signed in to change notification settings - Fork 2
/
ProcessJumplinks.module.php
2105 lines (1823 loc) · 76.4 KB
/
ProcessJumplinks.module.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
/**
* Jumplinks for ProcessWire
* Manage permanent and temporary redirects. Uses named wildcards and mapping collections.
*
* Process module for ProcessWire 2.6.1+
*
* @author Mike Rockett
* @copyright (c) 2015-19, Mike Rockett. All Rights Reserved.
* @license ISC
*
* @see Documentation: https://jumplinks.rockett.pw
* @see Modules Directory: https://mods.pw/92
* @see Forum Thred: https://processwire.com/talk/topic/8697-jumplinks/
* @see Donate: https://rockett.pw/donate
*/
class ProcessJumplinks extends Process
{
/** Schema version for current release */
const SCHEMA_VERSION = 6;
/** NULL Date **/
const NULL_DATE = '0000-00-00 00:00:00';
/**
* Determine if the text/plain header is set
* @var boolean
*/
protected $headerSet = false;
/**
* Object (Array) that holds SQL statements
* @var stClass
*/
protected $sql;
/**
* Hold module information
* @var array
*/
protected $moduleInfo;
/**
* The base table name
* @rfc Should we make this constant?
* @var string
*/
protected $tableName = 'process_jumplinks';
/**
* The base table name for ProcessRedirects
* @var string
*/
protected $redirectsTableName = 'ProcessRedirects'; // This is the default, and will be checked for case
/**
* Paths to forms
* @var string
*/
protected $entityFormPath = 'entity/';
/**
* @var string
*/
protected $mappingCollectionFormPath = 'mappingcollection/';
/**
* @var string
*/
protected $importPath = 'import/';
/**
* @var string
*/
protected $clearNotFoundLogPath = 'clearnotfoundlog/';
/**
* Lowest date - for use when working with timestamps
* @var string
*/
protected $lowestDate = '1974-10-10';
/**
* Set the wildcard types.
* A wildcard type is the second fragment of a wildcard/
* Ex: {name:type}
* @var array
*/
protected $wildcards = [
'all' => '.*',
'alpha' => '[a-z]+',
'alphanum' => '\w+',
'any' => '[\w.-_%\=\s]+',
'ext' => 'aspx|asp|cfm|cgi|fcgi|dll|html|htm|shtml|shtm|jhtml|phtml|xhtm|xhtml|rbml|jspx|jsp|phps|php4|php',
'num' => '\d+',
'segment' => '[\w_-]+',
'segments' => '[\w/_-]+',
];
/**
* Set smart wildcards.
* These are like shortcuts for declaring wildcards.
* See the docs for more info.
* @var array
*/
protected $smartWildcards = [
'all' => 'all',
'ext' => 'ext',
'name|title|page|post|user|model|entry|segment' => 'segment',
'path|segments' => 'segments',
'year|month|day|id|num' => 'num',
];
/**
* Inject assets (used as assets are automatically inserted when
* using the same name as the module, but the get thrown in before
* JS dependencies. WireTabs also gets thrown in.)
* @return void
*/
protected function injectAssets()
{
// Inject script and style
$moduleAssetPath = "{$this->config->urls->ProcessJumplinks}Assets";
$this->config->scripts->add("{$moduleAssetPath}/ProcessJumplinks.min.js");
$this->config->styles->add("{$moduleAssetPath}/ProcessJumplinks.css");
// Include WireTabs
$this->modules->get('JqueryWireTabs');
}
/**
* Class constructor
* Init moduleInfo, sql
* @return void
*/
public function __construct()
{
// Set the lowest allowable date
$this->lowestDate = strtotime($this->lowestDate);
// Get the module info
$this->moduleInfo = wire('modules')->getModuleInfo($this, ['verbose' => true]);
// Get the correct table name for ProcessRedirects
$redirectsTableNameQuery = $this->database->prepare('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = :db_name AND TABLE_NAME LIKE :table_name');
$redirectsTableNameQuery->execute([
'db_name' => $this->config->dbName,
'table_name' => $this->redirectsTableName,
]);
if ($redirectsTableNameQuery->rowCount() > 0) {
$redirectsTableNameResult = $redirectsTableNameQuery->fetch(PDO::FETCH_OBJ)->TABLE_NAME;
if (
$this->redirectsTableName == $redirectsTableNameResult ||
strtolower($this->redirectsTableName) == $redirectsTableNameResult
) {
$this->redirectsTableName = $redirectsTableNameResult;
}
}
// Set the SQL statements for use elsewhere.
// These are kept in one place for ease of reference.
$this->sql = (object) [
'entity' => (object) [
'selectAll' => "SELECT * FROM {$this->tableName} ORDER BY `source`",
'selectOne' => "SELECT * FROM {$this->tableName} WHERE id = :id",
'dropOne' => "DELETE FROM {$this->tableName} WHERE id = :id",
'insert' => "INSERT INTO {$this->tableName} SET `source` = :source, destination = :destination, hits = :hits, date_start = :date_start, date_end = :date_end, user_created = :user_created, user_updated = :user_updated, created_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP ON DUPLICATE KEY UPDATE id = id",
'update' => "UPDATE {$this->tableName} SET `source` = :source, destination = :destination, date_start = :date_start, date_end = :date_end, user_updated = :user_updated, updated_at = CURRENT_TIMESTAMP WHERE id = :id",
'updateHits' => "UPDATE {$this->tableName} SET hits = :hits WHERE id = :id",
'updateLastHitDate' => "UPDATE {$this->tableName} SET last_hit = :last_hit WHERE id = :id",
],
'collection' => (object) [
'selectAll' => "SELECT * FROM {$this->tableName}_mc ORDER BY collection_name",
'selectOne' => "SELECT * FROM {$this->tableName}_mc WHERE id = :id",
'selectOneByName' => "SELECT * FROM {$this->tableName}_mc WHERE collection_name = :collection",
'dropOne' => "DELETE FROM {$this->tableName}_mc WHERE id = :id",
'insert' => "INSERT INTO {$this->tableName}_mc SET collection_name = :collection, collection_mappings = :mappings, user_created = :user_created, user_updated = :user_updated, created_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP ON DUPLICATE KEY UPDATE id = id",
'update' => "UPDATE {$this->tableName}_mc SET collection_name = :collection, collection_mappings = :mappings, user_updated = :user_updated WHERE id = :id",
],
'notFoundMonitor' => (object) [
'selectAll' => "SELECT * FROM {$this->tableName}_nf ORDER BY created_at DESC LIMIT 100",
'insert' => "INSERT INTO {$this->tableName}_nf SET request_uri = :request_uri, referrer = :referrer, user_agent = :user_agent, created_at = CURRENT_TIMESTAMP ON DUPLICATE KEY UPDATE id = id",
'deleteAll' => "TRUNCATE TABLE {$this->tableName}_nf",
],
];
}
/**
* Module initialisation
* @hook ProcessPageView::pageNotFound to scanAndRedirect
* @return void
*/
public function init()
{
parent::init();
// Make sure schemas are up to date.
// This process will be changed to ___upgrade() when the minimum PW version is 2.7.1.
if ($this->schemaVersion < self::SCHEMA_VERSION) {
$this->updateDatabaseSchema();
}
// Bail if we are running in the CLI (such as in a PW-bootstrapped script),
// or if we cannot safely resolve REQUEST_URI.
if (
php_sapi_name() === 'cli' ||
!isset($_SERVER['REQUEST_URI']) ||
in_array($_SERVER['REQUEST_URI'], [false, null], true)
) {
return;
}
// Get the current request
$this->request = ltrim($_SERVER['REQUEST_URI'], '/');
// Trim out index.php from the beginning of the URI if it is suffixed with a path.
// ProcessWire doesn't support these anyway.
$indexRequest = "~^index\.php(/.*)$~i";
if (preg_match($indexRequest, $this->request)) {
$this->session->redirect(preg_replace($indexRequest, '\\1', $this->request));
}
// Hook prior to the pageNotFound event ...
if ($this->moduleDisable == false) {
$this->addHookAfter('ProcessPageView::pageNotFound', $this, 'scanAndRedirect', [
'priority' => 1000
]);
}
}
/**
* Update database schema
* This method applies incremental updates until latest schema version is
* reached, while also keeping schemaVersion config setting up to date.
* @return void
*/
private function updateDatabaseSchema()
{
// Loop through each version, applying the applicable Blueprint for each one.
while ($this->_schemaVersion < self::SCHEMA_VERSION) {
++$this->_schemaVersion;
$memoryVersion = $this->_schemaVersion;
switch (true) {
case ($memoryVersion <= 6):
$statement = $this->blueprint("schema-update-v{$memoryVersion}");
break;
default:
throw new WireException("[Jumplinks] Unrecognized database schema version: {$memoryVersion}");
}
if ($statement && $this->database->exec($statement) !== false) {
// Now set the version name for later comparison.
$configData = $this->modules->getModuleConfigData($this);
$configData['_schemaVersion'] = $memoryVersion;
$this->modules->saveModuleConfigData($this, $configData);
$this->message($this->_('[Jumplinks] Schema updates applied.'));
} else {
throw new WireException("[Jumplinks] Couldn't update database schema to version {$memoryVersion}");
}
}
}
/**
* Generate help link (contextual)
* @param string $uri
* @return string
*/
protected function helpLinks($uri = '', $justTheLink = false, $title = null)
{
// Prepend a slash to the URI.
if (!empty($uri)) {
$uri = "/{$uri}";
}
// If only the link is required, then return it.
// Otherwise, format it along with all the other links.
if ($justTheLink) {
return $this->moduleInfo['href'] . $uri;
} else {
$supportDevelopment = $this->_('Support Jumplinks’ Development');
$needHelp = $this->_('Forum Support Thread');
$documentation = $this->_('Documentation');
if ($title !== null) {
$documentation = $this->_('Documentation on ') . $title;
}
return "<div class=\"pjHelpLink\"><a class=\"paypal\" target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://rockett.pw/donate\">{$supportDevelopment}</a><a target=\"_blank\" href=\"https://processwire.com/talk/topic/8697-jumplinks/\">{$needHelp}</a><a style=\"font-weight:700\" target=\"_blank\" href=\"{$this->moduleInfo['href']}{$uri}\">{$documentation}</a></div>";
}
}
/**
* Create a blueprint from file and give it some variables.
* @caller multiple
* @param string $name
* @param array $data
* @return string
*/
protected function blueprint($name, $data = [])
{
// Require the Blueprint parser
require_once __DIR__ . '/Classes/Blueprint.php';
$blueprint = new Blueprint($name);
// Set the data
$data = array_filter($data);
if (empty($data)) {
$data = ['table-name' => $this->tableName];
}
$blueprint->hydrate($data);
return (string) $blueprint->build();
}
/**
* Compile destination URL, keeping page refs, HTTPS, and subdirectories considered.
* @caller multiple
* @param string $destination
* @param bool $renderForOutput
* @param bool $http
* @return string
*/
protected function compileDestinationUrl($destination, $renderForOutput = false, $httpUrl = true)
{
$pageIdentifier = 'page:';
$usingPageIdentifier = substr($destination, 0, 5) === $pageIdentifier;
// Check if we're not using a page identifier or selector
if (!$usingPageIdentifier) {
// Check to see if we're working with an absolute URL
$isAbsolute = $this->destinationHasScheme($destination);
// If URL is absolute, then skip the prefix, otherwise build it
$prefix = ($isAbsolute) ? '' : $this->config->urls->root;
// If we're rendering for backend output, truncate and return the destination.
// Otherwise, return the full destination.
return ($renderForOutput)
? $this->truncate($destination)
: $prefix . $destination;
} else {
// If we're using a page identifier, fetch it
$pageId = str_replace($pageIdentifier, '', $destination);
$page = $this->pages->get((int) $pageId);
// If it's a valid page, then get its URL
if ($page->id) {
$destination = ($httpUrl ? $page->httpUrl : ltrim($page->path, '/'));
if (empty($destination)) {
$destination = '/';
}
if ($renderForOutput) {
$destination = "<abbr title=\"{$page->title} ({$page->httpUrl})\">{$destination}</abbr>";
}
}
return $destination;
}
}
/**
* Fetch the URI to the module's config page
* @caller multiple
* @return string
*/
protected function getModuleConfigUri()
{
return "{$this->config->urls->admin}module/edit?name={$this->moduleInfo['name']}";
// ^ Better way to get this URI?
}
/**
* Clean a passed wildcard value
* @caller scanAndRedirect
* @param string $input
* @param bool $noLower
* @return string
*/
public function cleanWildcard($input, $noLower = false)
{
if ($this->enhancedWildcardCleaning) {
// Courtesy @sln on StackOverflow
$input = preg_replace_callback("~([A-Z])([A-Z]+)(?=[A-Z]|\b)~", function ($captures) {
return $captures[1] . strtolower($captures[2]);
}, $input);
$input = preg_replace('~(?<=\\w)(?=[A-Z])~', '-\\1\\2', $input);
}
$input = preg_replace("~%u([a-f\d]{3,4})~i", '&#x\\1;', urldecode($input));
$input = preg_replace("~[^\\pL\d\/\?\&\=]+~u", '-', $input);
$input = iconv('utf-8', 'us-ascii//TRANSLIT', $input);
if ($this->enhancedWildcardCleaning) {
$input = preg_replace("~(\d)([a-z])~i", '\\1-\\2', preg_replace("~([a-z])(\d)~i", '\\1-\\2', $input));
}
$input = trim($input, '-');
$input = preg_replace('~[^\-\w\/\?\&\=]+~', '', $input);
if (!$noLower) {
$input = strtolower($input);
}
return (empty($input)) ? '' : $input;
}
/**
* Truncate string, and append ellipses with tooltip
* @caller multiple
* @param string $string
* @param int $length
* @return string
*/
protected function truncate($string, $length = 55)
{
if (strlen($string) > $length) {
return substr($string, 0, $length) . " <span class=\"ellipses\" title=\"{$string}\">...</span>";
} else {
return $string;
}
}
/**
* Given a fieldtype, create, populate, and return an Inputfield
* @param string $fieldNameId
* @param array $meta
* @return Inputfield
*/
protected function buildInputField($fieldNameId, $meta)
{
$field = $this->modules->get($fieldNameId);
foreach ($meta as $metaNames => $metaInfo) {
$metaNames = explode('+', $metaNames);
foreach ($metaNames as $metaName) {
$field->$metaName = $metaInfo;
}
}
return $field;
}
/**
* Given a an Inputfield, add props and return
* @param object $field
* @param array $meta
* @return Inputfield
*/
protected function populateInputField($field, $meta)
{
foreach ($meta as $metaNames => $metaInfo) {
$metaNames = explode('+', $metaNames);
foreach ($metaNames as $metaName) {
$field->$metaName = $metaInfo;
}
}
return $field;
}
/**
* Get response code of remote request
* @caller scanAndRedirect
* @param $request
* @return string
*/
protected function getResponseCode($request)
{
stream_context_set_default([
'http' => [
'method' => 'HEAD',
],
]);
$response = get_headers($request);
return substr($response[0], 9, 3);
}
/**
* Determine if the current user has debug rights.
* Must have relevant permission, and debug mode must be turned on.
* @return bool
*/
protected function userHasDebugRights()
{
return ($this->moduleDebug && $this->user->hasPermission('jumplinks-admin'));
}
/**
* Log something. Will set plain text header if not already set.
* @caller scanAndRedirect
* @param string $message
* @param bool $indent
* @param bool $break
* @param bool $die
*/
protected function log($message, $message2 = null, $extraLine = false)
{
if ($this->userHasDebugRights()) {
if (!$this->headerSet) {
header('Content-Type: text/plain');
$this->headerSet = true;
}
if (null === $message2) {
$output = $message;
} else {
$message = str_pad("- $message:", 30);
$output = $message . $message2;
}
if ($extraLine) {
$output .= "\n";
}
print "$output\n";
}
}
/**
* Log 404 to monitor
* @caller scanAndRedirect
* @param string $request
*/
protected function log404($request)
{
$canLog = true;
// MarkupSitemap[XML] exception
if (
($this->modules->isInstalled('MarkupSitemapXML') ||
$this->modules->isInstalled('MarkupSitemap')) &&
stripos($request, 'sitemap.xml') !== false
) {
$canLog = false;
}
// Log the 404 if it matches specific criteria
if ($canLog) {
$this->database->prepare($this->sql->notFoundMonitor->insert)->execute([
'request_uri' => substr($request, 0, 512),
'referrer' => @$_SERVER['HTTP_REFERER'],
'user_agent' => @$_SERVER['HTTP_USER_AGENT'],
]);
}
}
/**
* The fun part.
* @caller Hook: ProcessPageView::pageNotFound
* @return void
*/
protected function scanAndRedirect()
{
// Get the current request
$request = $this->request;
// Fetch all jumplinks
$jumplinks = $this->database->query($this->sql->entity->selectAll);
// If there aren't any, then log the hit and break out
if ($jumplinks->rowCount() === 0 && $this->enable404Monitor == true) {
$this->log404($request);
return false;
}
// Otherwise, start logging...
$this->log('404 Page Not Found');
// Get the home page URL - this is the same as the site root.
$siteRoot = rtrim($this->pages->get(1)->httpUrl, '/');
// Do some intro logging
$this->log(sprintf('Checked %s', date('r')));
$this->log("Request: {$siteRoot}/{$request}");
$this->log("ProcessWire Version: {$this->config->version}", null, true);
$this->log('Scanning for jumplinks...', null, true);
$rootUrl = $this->config->urls->root;
if ($rootUrl !== '/') {
$request = substr($request, strlen($rootUrl) - 1);
}
// Get the available wildcards, prepare for pattern match
$availableWildcards = '';
foreach ($this->wildcards as $wildcard => $expression) {
$availableWildcards .= "{$wildcard}|";
}
$availableWildcards = rtrim($availableWildcards, '|');
// Assign the wildcard pattern check
$pattern = '~\{!?([a-z]+):(' . $availableWildcards . ')\}~';
// Begin the loop
while ($jumplink = $jumplinks->fetchObject()) {
// If the jumplink source starts with a double-exclamation mark, then it is disabled
if (substr($jumplink->source, 0, 2) === '!!') {
continue;
}
$starts = (strtotime($jumplink->date_start) > $this->lowestDate) ? strtotime($jumplink->date_start) : false;
$ends = (strtotime($jumplink->date_end) > $this->lowestDate) ? strtotime($jumplink->date_end) : false;
$this->log("[Checking jumplink #{$jumplink->id}]");
// Timed Activation:
// If it ends, but doesn't start, then make it start now
if ($ends && !$starts) {
$starts = time();
}
// If it starts (which it will always do), but doesn't end,
// then set a dummy timestamp that is always in the future.
$dummyEnd = false;
$message = '';
if ($starts && !$ends) {
$ends = time() + (60 * 60);
$dummyEnd = true;
$message = '(has no ending, using dummy timestamp)';
}
// Log the activation periods for debugging
if ($starts || $ends) {
$this->log('Timed Activation (Starts)', date('r', $starts));
if (!$dummyEnd) {
$this->log('Timed Activation (Ends)', date('r', $ends));
}
}
$this->log('Original Source Path', $jumplink->source);
// Prepare the Source Path for matching:
// First, escape ? (and reverse /\?) & :
// Then, convert '[character]' to 'character?' for matching.
$source = preg_replace('~\[([a-z0-9\/])\]~i', '\\1?', str_replace(
['?', '/\?', '&', ':'],
['\?', '/?', '\&', '\:'],
$jumplink->source
));
// As a workaround for query strings attached to trailing slashes
// ensure that slashes are not made optional in the middle of the source.
// Refer: https://processwire.com/talk/topic/8697-jumplinks/?do=findComment&comment=126551
$source = preg_replace('~(.+)/\?(.+)~', '\\1/\?\\2', $source);
// Reverse ':' escaping for wildcards
$source = preg_replace("~\{([a-z]+)\\\:([a-z]+)\}~i", '{\\1:\\2}', $source);
if ($source !== $jumplink->source) {
$this->log('Escaped Source Path', $source);
}
// Compile the destination URL
$destination = $this->compileDestinationUrl($jumplink->destination);
// Setup capture prevention
$nonCaptureMatcher = '~<(.*?)>~';
if (preg_match($nonCaptureMatcher, $source)) {
$source = preg_replace($nonCaptureMatcher, '(?:\\1)', $source);
}
// Prepare Smart Wildcards - replace them with their equivalent standard ones.
$hasSmartWildcards = false;
foreach ($this->smartWildcards as $wildcard => $wildcardType) {
$smartWildcardMatcher = "~\{($wildcard)\}~i";
if (preg_match($smartWildcardMatcher, $source)) {
$source = preg_replace($smartWildcardMatcher, "{\\1:{$wildcardType}}", $source);
$hasSmartWildcards = true;
}
}
$computedReplacements = [];
// Convert wildcards into expressions for replacement
$computedWildcards = preg_replace_callback($pattern, function ($captures) use (&$computedReplacements) {
$computedReplacements[] = $captures[1];
return "({$this->wildcards[$captures[2]]})";
}, $source);
// Some more logging
if ($hasSmartWildcards) {
$this->log('After Smart Wildcards', $source);
}
$this->log('Compiled Source Path', $computedWildcards);
// If the request matches the source currently being checked:
if (preg_match("~^$computedWildcards$~i", $request)) {
// For the purposes of mapping, fetch all the collections and compile them
$collections = $this->database->query($this->sql->collection->selectAll);
$compiledCollections = new StdClass();
while ($collection = $collections->fetchObject()) {
$collectionData = explode("\n", $collection->collection_mappings);
$compiledCollectionData = [];
foreach ($collectionData as $mapping) {
$mapping = explode('=', $mapping);
$compiledCollectionData[$mapping[0]] = $mapping[1];
}
$compiledCollections->{$collection->collection_name} = $compiledCollectionData;
}
// Iterate through each source wildcard:
if ($computedWildcards == '(.*)') {
$computedWildcards = '(.+)';
};
$convertedWildcards = preg_replace_callback("~$computedWildcards~i", function ($captures) use ($destination, $computedReplacements) {
$result = $destination;
for ($c = 1, $n = count($captures); $c < $n; ++$c) {
$value = array_shift($computedReplacements);
// Check for destination wildcards that don't need to be cleaned
$paramSkipCleanCheck = "~\{!$value\}~i";
$uncleanedCapture = $captures[$c];
if (empty($uncleanedCapture)) {
continue;
}
if (!preg_match($paramSkipCleanCheck, $result)) {
$wildcardCleaning = $this->wildcardCleaning;
if ($wildcardCleaning === 'fullClean' || $wildcardCleaning === 'semiClean') {
$captures[$c] = $this->cleanWildcard($captures[$c], ($wildcardCleaning === 'fullClean') ? false : true);
}
}
$openingTag = (preg_match($paramSkipCleanCheck, $result)) ? '{!' : '{';
$result = str_replace($openingTag . $value . '}', $captures[$c], $result);
// In preparation for wildcard mapping,
// Swap out any mapping wildcards with their uncleaned values
$value = preg_quote($value);
$result = preg_replace("~\{{$value}\|([a-z]+)\}~i", "($uncleanedCapture|\\1)", $result);
$this->log('- Wildcard Check', "{$c}> {$value} = {$uncleanedCapture} -> {$captures[$c]}");
}
// Trim the result of trailing slashes, and
// add one again if the Destination Path asked for it.
$result = rtrim($result, '/');
if (substr($destination, -1) === '/') {
$result .= '/';
}
return $result;
}, $request);
// Perform any mappings
$convertedWildcards = preg_replace_callback("~\(([\w\-_\/]+)\|([a-z]+)\)~i", function ($mapCaptures) use ($compiledCollections) {
// If we have a match, bring it in
// Otherwise, fill the mapping wildcard with the original data
if (isset($compiledCollections->{$mapCaptures[2]}[$mapCaptures[1]])) {
return $compiledCollections->{$mapCaptures[2]}[$mapCaptures[1]];
} else {
return $mapCaptures[1];
}
}, $convertedWildcards);
// Check for any selectors and get the respective page
$selectorUsed = false;
$selectorMatched = false;
$convertedWildcards = preg_replace_callback("~\[\[([\w\-_\/\s=\",.'|@]+)\]\]~i", function ($selectorCaptures) use (&$selectorUsed, &$selectorMatched) {
$selectorUsed = true;
$page = $this->pages->get($selectorCaptures[1]);
if ($page->id > 0) {
$selectorMatched = true;
return ltrim($page->url, '/');
}
}, $convertedWildcards);
$this->log('Original Destination Path', $jumplink->destination);
// If a match was found, but the selector didn't return a page, then continue the loop
if ($selectorUsed && !$selectorMatched) {
$this->log("\nWhilst a match was found, the selector you specified didn't return a page. As a result, this jumplink will be skipped.");
continue;
}
$this->log('Compiled Destination Path', $convertedWildcards, true);
// Check for Timed Activation and determine if we're in the period specified
$time = time();
$activated = ($starts || $ends)
? ($time >= $starts && $time <= $ends)
: true;
// If we're not debugging, and we're Time-activated, then do the redirect
if (!$this->userHasDebugRights() && $activated) {
$hitsPlusOne = $jumplink->hits + 1;
$this->database->prepare($this->sql->entity->updateHits)->execute([
'hits' => $hitsPlusOne,
'id' => $jumplink->id,
]);
$this->database->prepare($this->sql->entity->updateLastHitDate)->execute([
'last_hit' => date('Y-m-d H:i:s'),
'id' => $jumplink->id,
]);
$this->session->redirect($convertedWildcards, !($starts || $ends));
}
// Otherwise, continue logging
$type = ($starts) ? '302, temporary' : '301, permanent';
$this->log("Match found! We'll do the following redirect ({$type}) when Debug Mode has been turned off:", null, true);
$this->log('From URL', "{$siteRoot}/{$request}");
$this->log('To URL', "{$convertedWildcards}");
if ($starts || $ends) {
// If it ends before it starts, then show the time it starts.
// Otherwise, show the period.
if ($dummyEnd) {
$this->log('Timed', sprintf('From %s onwards', date('r', $starts)));
} else {
$this->log('Timed', sprintf('From %s to %s', date('r', $starts), date('r', $ends)));
}
}
// We can exit at this point.
if ($this->userHasDebugRights()) {
die();
}
}
// If there were no available redirect definitions,
// then inform the debugger.
$this->log("\nNo match there...", null, true);
}
// Considering we don't have one available, let's check to see if the Source Path
// exists on the Legacy Domain, if defined.
$legacyDomain = trim($this->legacyDomain);
if (!empty($legacyDomain)) {
// Fetch the accepted codes
$okCodes = trim(!empty($this->statusCodes))
? array_map('trim', explode(' ', $this->statusCodes))
: explode(',', $this->statusCodes);
// Prepare and do the request
$domainRequest = $this->legacyDomain . $request;
$status = $this->getResponseCode($domainRequest);
// If the response has an accepted code, then 302 redirect (or log)
if (in_array($status, $okCodes)) {
if (!$this->userHasDebugRights()) {
$this->session->redirect($domainRequest, false);
}
$this->log("Found Source Path on Legacy Domain (with status code {$status}); redirect allowed to:");
$this->log("> {$domainRequest}");
}
}
// If set in config, log 404 hits to the database
if ($this->enable404Monitor == true) {
$this->log404($request);
}
// If all fails, say so.
$this->log("No matches, sorry. We'll let your 404 error page take over when Debug Mode is turned off.");
if ($this->userHasDebugRights()) {
die();
}
}
/**
* Admin Page: Module Root
* @return string
*/
public function ___execute()
{
// Assets
$this->injectAssets();
// Get Jumplinks
$jumplinks = $this->database->query($this->sql->entity->selectAll);
// Set Page title
$this->setFuel('processHeadline', $this->_('Manage Jumplinks'));
// Assign the main container (wrapper)
$tabContainer = new InputfieldWrapper();
// Add the Jumplinks tab
$jumplinksTab = new InputfieldWrapper();
$jumplinksTab->attr('title', 'Jumplinks');
// Setup the datatable
$jumplinksTable = $this->modules->get('MarkupAdminDataTable');
$jumplinksTable->setEncodeEntities(false);
$jumplinksTable->setClass('jumplinks redirects');
$jumplinksTable->headerRow([$this->_('Source'), $this->_('Destination'), $this->_('Start'), $this->_('End'), $this->_('Hits')]);
// Setup and add the tab description markup
$pronoun = $this->_n('it', 'one', $jumplinks->rowCount());
if ($jumplinks->rowCount() == 0) {
$description = $this->_("You don't have any jumplinks yet.");
} else {
$description = $this->_n('You have one jumplink registered.', 'Your jumplinks are listed below.', $jumplinks->rowCount()) . ' ' . sprintf($this->_('To edit/delete %s, simply click on its Source.'), $pronoun);
}
$jumplinksDescriptionMarkup = $this->modules->get('InputfieldMarkup');
$jumplinksDescriptionMarkup->value = $description;
$jumplinksTab->append($jumplinksDescriptionMarkup);
// Work through each jumplink, formatting data as we go along.
$hits = 0;
while ($jumplink = $jumplinks->fetchObject()) {
// Source and Destination
$jumplink->source = htmlentities($jumplink->source);
$jumplink->destination = $this->compileDestinationUrl($jumplink->destination, true, false);
// Timed Activation columns
if (strtotime($jumplink->date_start) < $this->lowestDate) {
$jumplink->date_start = null;
}
if (strtotime($jumplink->date_end) < $this->lowestDate) {
$jumplink->date_end = null;
}
$relativeStartTime = str_replace('Never', '', wireRelativeTimeStr($jumplink->date_start, true));
$relativeEndTime = str_replace('Never', '', wireRelativeTimeStr($jumplink->date_end, true));
$relativeStartTime = ($relativeStartTime === '-')
? $relativeStartTime
: "<abbr title=\"{$jumplink->date_start}\">{$relativeStartTime}</abbr>";
$relativeEndTime = ($relativeEndTime === '-')
? $relativeEndTime
: "<abbr title=\"{$jumplink->date_end}\">{$relativeEndTime}</abbr>";
$relativeLastHit = wireRelativeTimeStr($jumplink->last_hit, true);
// Format the Hits column to show the last hit date in a tooltip.
$jumplinkHits = (strtotime($jumplink->last_hit) < $this->lowestDate)
? $jumplink->hits
: "<abbr title=\"Last hit: {$relativeLastHit} ($jumplink->last_hit)\">{$jumplink->hits}</abbr>";
// If the last hit was more than 30 days ago,
// let the user know so that it may be deleted.
if (
strtotime($jumplink->last_hit) > $this->lowestDate &&
strtotime($jumplink->last_hit) < strtotime('-30 days')
) {
$jumplinkHits .= '<span id="staleJumplink"></span>';
}
$hits = $hits + $jumplink->hits;
// Add the row, now that the data has been formatted.
$jumplinksTable->row([
$this->truncate($jumplink->source, 80) => "{$this->entityFormPath}?id={$jumplink->id}",
$jumplink->destination,
$relativeStartTime,
$relativeEndTime,
$jumplinkHits,
]);
}
// Register button setup
switch ($jumplinks->rowCount()) {
case 0:
$registerJumplinkButtonLabel = $this->_('Register First Jumplink');
break;
case 1:
$registerJumplinkButtonLabel = $this->_('Register Another Jumplink');
break;
default:
$registerJumplinkButtonLabel = $this->_('Register New Jumplink');
break;
}
// Init buttons markup string
$buttons = "";
// Build and add Register button
$registerJumplinkButton = $this->populateInputField($this->modules->get('InputfieldButton'), [
'id' => 'registerJumplink',
'href' => $this->entityFormPath,
'value' => $registerJumplinkButtonLabel,
'icon' => 'plus-circle',
])->addClass('head_button_clone');
$buttons .= $registerJumplinkButton->render();
if ($this->user->hasPermission('module-admin')) {
// Build and add config button
$moduleConfigLinkButton = $this->populateInputField($this->modules->get('InputfieldButton'), [
'id' => 'moduleConfigLink',
'href' => $this->getModuleConfigUri(),
'value' => $this->_('Configuration'),
'icon' => 'cog',
])->addClass('ui-priority-secondary ui-button-float-right');
$buttons .= $moduleConfigLinkButton->render();
}
// Render and append the table container
$jumplinksTableContainer = $this->modules->get('InputfieldMarkup');
$jumplinksTableContainer->value = $jumplinksTable->render() . $buttons;
$jumplinksTab->append($jumplinksTableContainer);
// Add the Mapping Collections tab
$mappingCollectionsTab = new InputfieldWrapper();
$mappingCollectionsTab->attr('title', $this->_('Mapping Collections'));
$mappingCollectionsTab->id = 'mappingCollections';
// Get Mapping Collections
$mappingCollections = $this->database->query($this->sql->collection->selectAll);
// Setup the data table
$mappingCollectionsTable = $this->modules->get('MarkupAdminDataTable');
$mappingCollectionsTable->setEncodeEntities(false);
$mappingCollectionsTable->setClass('jumplinks mapping-collections');