forked from contao/contao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Versions.php
856 lines (726 loc) · 24.1 KB
/
Versions.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
<?php
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao;
use Contao\CoreBundle\Exception\ResponseException;
use Doctrine\DBAL\Types\BinaryType;
use Doctrine\DBAL\Types\BlobType;
/**
* Provide methods to handle versioning.
*
* @author Leo Feyer <https://github.com/leofeyer>
*/
class Versions extends Controller
{
/**
* Table
* @var string
*/
protected $strTable;
/**
* Parent ID
* @var integer
*/
protected $intPid;
/**
* Edit URL
* @var string
*/
protected $strEditUrl;
/**
* Username
* @var string
*/
protected $strUsername;
/**
* User ID
* @var integer
*/
protected $intUserId;
/**
* Initialize the object
*
* @param string $strTable
* @param integer $intPid
*
* @throws \InvalidArgumentException
*/
public function __construct($strTable, $intPid)
{
$this->import(Database::class, 'Database');
parent::__construct();
$this->loadDataContainer($strTable);
if (!isset($GLOBALS['TL_DCA'][$strTable]))
{
throw new \InvalidArgumentException(sprintf('"%s" is not a valid table', StringUtil::specialchars($strTable)));
}
$this->strTable = $strTable;
$this->intPid = (int) $intPid;
}
/**
* Set the edit URL
*
* @param string $strEditUrl
*/
public function setEditUrl($strEditUrl)
{
$this->strEditUrl = $strEditUrl;
}
/**
* Set the username
*
* @param string $strUsername
*/
public function setUsername($strUsername)
{
$this->strUsername = $strUsername;
}
/**
* Set the user ID
*
* @param integer $intUserId
*/
public function setUserId($intUserId)
{
$this->intUserId = $intUserId;
}
/**
* Returns the latest version
*
* @return integer|null
*/
public function getLatestVersion()
{
if (!($GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning'] ?? null))
{
return null;
}
$objVersion = $this->Database->prepare("SELECT MAX(version) AS version FROM tl_version WHERE fromTable=? AND pid=?")
->limit(1)
->execute($this->strTable, $this->intPid);
return (int) $objVersion->version;
}
/**
* Create the initial version of a record
*/
public function initialize()
{
if (!($GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning'] ?? null))
{
return;
}
$objVersion = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_version WHERE fromTable=? AND pid=?")
->limit(1)
->execute($this->strTable, $this->intPid);
if ($objVersion->count > 0)
{
return;
}
$this->create(true);
}
/**
* Create a new version of a record
*
* @param boolean $blnHideUser
*/
public function create($blnHideUser=false)
{
if (!($GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning'] ?? null))
{
return;
}
// Delete old versions from the database
$tstamp = time() - (int) Config::get('versionPeriod');
$this->Database->query("DELETE FROM tl_version WHERE tstamp<$tstamp");
// Get the new record
$objRecord = $this->Database->prepare("SELECT * FROM " . $this->strTable . " WHERE id=?")
->limit(1)
->execute($this->intPid);
if ($objRecord->numRows < 1 || $objRecord->tstamp < 1)
{
return;
}
$data = $objRecord->row();
// Remove fields that are excluded from versioning
foreach (array_keys($data) as $k)
{
if (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['versionize'] ?? null) === false)
{
unset($data[$k]);
}
}
$strDescription = '';
if (!empty($data['title']))
{
$strDescription = $data['title'];
}
elseif (!empty($data['name']))
{
$strDescription = $data['name'];
}
elseif (!empty($data['firstname']))
{
$strDescription = $data['firstname'] . ' ' . $data['lastname'];
}
elseif (!empty($data['headline']))
{
$chunks = StringUtil::deserialize($data['headline']);
if (\is_array($chunks) && isset($chunks['value']))
{
$strDescription = $chunks['value'];
}
else
{
$strDescription = $data['headline'];
}
}
elseif (!empty($data['selector']))
{
$strDescription = $data['selector'];
}
elseif (!empty($data['subject']))
{
$strDescription = $data['subject'];
}
$intId = $this->Database->prepare("INSERT INTO tl_version (pid, tstamp, version, fromTable, username, userid, description, editUrl, active, data) VALUES (?, ?, IFNULL((SELECT MAX(version) FROM (SELECT version FROM tl_version WHERE pid=? AND fromTable=?) v), 0) + 1, ?, ?, ?, ?, ?, 1, ?)")
->execute($this->intPid, time(), $this->intPid, $this->strTable, $this->strTable, $blnHideUser ? null : $this->getUsername(), $blnHideUser ? 0 : $this->getUserId(), $strDescription, $this->getEditUrl(), serialize($data))
->insertId;
$this->Database->prepare("UPDATE tl_version SET active='' WHERE pid=? AND fromTable=? AND id!=?")
->execute($this->intPid, $this->strTable, $intId);
$intVersion = $this->Database->prepare("SELECT version FROM tl_version WHERE id=?")
->execute($intId)
->version;
// Trigger the oncreate_version_callback
if (\is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['oncreate_version_callback'] ?? null))
{
foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['oncreate_version_callback'] as $callback)
{
if (\is_array($callback))
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($this->strTable, $this->intPid, $intVersion, $data);
}
elseif (\is_callable($callback))
{
$callback($this->strTable, $this->intPid, $intVersion, $data);
}
}
}
$this->log('Version ' . $intVersion . ' of record "' . $this->strTable . '.id=' . $this->intPid . '" has been created' . $this->getParentEntries($this->strTable, $this->intPid), __METHOD__, TL_GENERAL);
}
/**
* Restore a version
*
* @param integer $intVersion
*/
public function restore($intVersion)
{
if (!($GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning'] ?? null))
{
return;
}
$objData = $this->Database->prepare("SELECT * FROM tl_version WHERE fromTable=? AND pid=? AND version=?")
->limit(1)
->execute($this->strTable, $this->intPid, $intVersion);
if ($objData->numRows < 1)
{
return;
}
$data = StringUtil::deserialize($objData->data);
if (!\is_array($data))
{
return;
}
// Get the currently available fields
$arrFields = array_flip($this->Database->getFieldNames($this->strTable));
// Unset fields that do not exist (see #5219)
$data = array_intersect_key($data, $arrFields);
// Reset fields added after storing the version to their default value (see #7755)
foreach (array_diff_key($arrFields, $data) as $k=>$v)
{
$data[$k] = Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['sql'] ?? array());
}
foreach ($data as $k=>$v)
{
// Remove fields that are excluded from versioning
if (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['versionize'] ?? null) === false)
{
unset($data[$k]);
continue;
}
// Reset unique fields if the restored value already exists (see #698)
if (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['unique'] ?? null) === true)
{
$objResult = $this->Database->prepare("SELECT COUNT(*) AS cnt FROM " . $this->strTable . " WHERE " . Database::quoteIdentifier($k) . "=? AND id!=?")
->execute($v, $this->intPid);
if ($objResult->cnt > 0)
{
$data[$k] = Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['sql'] ?? array());
}
}
}
$this->Database->prepare("UPDATE " . $this->strTable . " %s WHERE id=?")
->set($data)
->execute($this->intPid);
$this->Database->prepare("UPDATE tl_version SET active='' WHERE fromTable=? AND pid=?")
->execute($this->strTable, $this->intPid);
$this->Database->prepare("UPDATE tl_version SET active=1 WHERE fromTable=? AND pid=? AND version=?")
->execute($this->strTable, $this->intPid, $intVersion);
// Trigger the onrestore_version_callback
if (\is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_version_callback'] ?? null))
{
foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_version_callback'] as $callback)
{
if (\is_array($callback))
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($this->strTable, $this->intPid, $intVersion, $data);
}
elseif (\is_callable($callback))
{
$callback($this->strTable, $this->intPid, $intVersion, $data);
}
}
}
// Trigger the deprecated onrestore_callback
if (\is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_callback'] ?? null))
{
trigger_deprecation('contao/core-bundle', '4.0', 'Using the "onrestore_callback" has been deprecated and will no longer work in Contao 5.0. Use the "onrestore_version_callback" instead.');
foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['onrestore_callback'] as $callback)
{
if (\is_array($callback))
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($this->intPid, $this->strTable, $data, $intVersion);
}
elseif (\is_callable($callback))
{
$callback($this->intPid, $this->strTable, $data, $intVersion);
}
}
}
$this->log('Version ' . $intVersion . ' of record "' . $this->strTable . '.id=' . $this->intPid . '" has been restored' . $this->getParentEntries($this->strTable, $this->intPid), __METHOD__, TL_GENERAL);
}
/**
* Compare versions
*
* @param bool $blnReturnBuffer
*
* @return string
*
* @throws ResponseException
*/
public function compare($blnReturnBuffer=false)
{
$strBuffer = '';
$arrVersions = array();
$intTo = 0;
$intFrom = 0;
$objVersions = $this->Database->prepare("SELECT * FROM tl_version WHERE pid=? AND fromTable=? ORDER BY version DESC")
->execute($this->intPid, $this->strTable);
if ($objVersions->numRows < 2)
{
$strBuffer = '<p>There are no versions of ' . $this->strTable . '.id=' . $this->intPid . '</p>';
}
else
{
$intIndex = 0;
$from = array();
// Store the versions and mark the active one
while ($objVersions->next())
{
if ($objVersions->active)
{
$intIndex = $objVersions->version;
}
$arrVersions[$objVersions->version] = $objVersions->row();
$arrVersions[$objVersions->version]['info'] = $GLOBALS['TL_LANG']['MSC']['version'] . ' ' . $objVersions->version . ' (' . Date::parse(Config::get('datimFormat'), $objVersions->tstamp) . ') ' . $objVersions->username;
}
// To
if (Input::post('to') && isset($arrVersions[Input::post('to')]))
{
$intTo = Input::post('to');
$to = StringUtil::deserialize($arrVersions[Input::post('to')]['data']);
}
elseif (Input::get('to') && isset($arrVersions[Input::get('to')]))
{
$intTo = Input::get('to');
$to = StringUtil::deserialize($arrVersions[Input::get('to')]['data']);
}
else
{
$intTo = $intIndex;
$to = StringUtil::deserialize($arrVersions[$intTo]['data']);
}
// From
if (Input::post('from') && isset($arrVersions[Input::post('from')]))
{
$intFrom = Input::post('from');
$from = StringUtil::deserialize($arrVersions[Input::post('from')]['data']);
}
elseif (Input::get('from') && isset($arrVersions[Input::get('from')]))
{
$intFrom = Input::get('from');
$from = StringUtil::deserialize($arrVersions[Input::get('from')]['data']);
}
elseif ($objVersions->numRows > $intIndex)
{
$intFrom = $objVersions->first()->version;
$from = StringUtil::deserialize($arrVersions[$intFrom]['data']);
}
elseif ($intIndex > 1)
{
$intFrom = $intIndex - 1;
$from = StringUtil::deserialize($arrVersions[$intFrom]['data']);
}
// Only continue if both version numbers are set
if ($intTo > 0 && $intFrom > 0)
{
System::loadLanguageFile($this->strTable);
// Get the order fields
$objDcaExtractor = DcaExtractor::getInstance($this->strTable);
$arrFields = $objDcaExtractor->getFields();
$arrOrderFields = $objDcaExtractor->getOrderFields();
// Find the changed fields and highlight the changes
foreach ($to as $k=>$v)
{
if ($from[$k] != $to[$k])
{
if (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['doNotShow'] ?? null) || ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['hideInput'] ?? null))
{
continue;
}
if (\is_array($arrFields[$k]))
{
$blnIsBinary = $arrFields[$k]['type'] === BinaryType::class || $arrFields[$k]['type'] === BlobType::class;
}
else
{
$blnIsBinary = strncmp($arrFields[$k], 'binary(', 7) === 0 || strncmp($arrFields[$k], 'blob ', 5) === 0;
}
// Decrypt the values
if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['encrypt'] ?? null)
{
$to[$k] = Encryption::decrypt($to[$k]);
$from[$k] = Encryption::decrypt($from[$k]);
}
if (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['multiple'] ?? null) || \in_array($k, $arrOrderFields))
{
if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['csv']))
{
$delimiter = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['csv'];
if (isset($to[$k]))
{
$to[$k] = preg_replace('/' . preg_quote($delimiter, ' ?/') . '/', $delimiter . ' ', $to[$k]);
}
if (isset($from[$k]))
{
$from[$k] = preg_replace('/' . preg_quote($delimiter, ' ?/') . '/', $delimiter . ' ', $from[$k]);
}
}
else
{
// Convert serialized arrays into strings
if (!\is_array($to[$k]) && \is_array(($tmp = StringUtil::deserialize($to[$k]))))
{
$to[$k] = $this->implodeRecursive($tmp, $blnIsBinary);
}
if (!\is_array($from[$k]) && \is_array(($tmp = StringUtil::deserialize($from[$k]))))
{
$from[$k] = $this->implodeRecursive($tmp, $blnIsBinary);
}
}
}
unset($tmp);
// Convert binary UUIDs to their hex equivalents (see #6365)
if ($blnIsBinary)
{
if (Validator::isBinaryUuid($to[$k]))
{
$to[$k] = StringUtil::binToUuid($to[$k]);
}
if (Validator::isBinaryUuid($from[$k]))
{
$from[$k] = StringUtil::binToUuid($from[$k]);
}
}
// Convert date fields
if (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['rgxp'] ?? null) == 'date')
{
$to[$k] = Date::parse(Config::get('dateFormat'), $to[$k] ?: '');
$from[$k] = Date::parse(Config::get('dateFormat'), $from[$k] ?: '');
}
elseif (($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['rgxp'] ?? null) == 'time')
{
$to[$k] = Date::parse(Config::get('timeFormat'), $to[$k] ?: '');
$from[$k] = Date::parse(Config::get('timeFormat'), $from[$k] ?: '');
}
elseif ($k == 'tstamp' || ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['rgxp'] ?? null) == 'datim')
{
$to[$k] = Date::parse(Config::get('datimFormat'), $to[$k] ?: '');
$from[$k] = Date::parse(Config::get('datimFormat'), $from[$k] ?: '');
}
// Decode entities if the "decodeEntities" flag is not set (see #360)
if (empty($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['eval']['decodeEntities']))
{
$to[$k] = StringUtil::decodeEntities($to[$k]);
$from[$k] = StringUtil::decodeEntities($from[$k]);
}
// Convert strings into arrays
if (!\is_array($to[$k]))
{
$to[$k] = explode("\n", $to[$k]);
}
if (!\is_array($from[$k]))
{
$from[$k] = explode("\n", $from[$k]);
}
$field = $k;
if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['label']))
{
$field = \is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['label']) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['label'][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$k]['label'];
}
elseif (isset($GLOBALS['TL_LANG']['MSC'][$k]))
{
$field = \is_array($GLOBALS['TL_LANG']['MSC'][$k]) ? $GLOBALS['TL_LANG']['MSC'][$k][0] : $GLOBALS['TL_LANG']['MSC'][$k];
}
$objDiff = new \Diff($from[$k], $to[$k]);
$strBuffer .= $objDiff->render(new DiffRenderer(array('field'=>$field)));
}
}
}
}
// Identical versions
if (!$strBuffer)
{
$strBuffer = '<p>' . $GLOBALS['TL_LANG']['MSC']['identicalVersions'] . '</p>';
}
if ($blnReturnBuffer)
{
return $strBuffer;
}
$objTemplate = new BackendTemplate('be_diff');
$objTemplate->content = $strBuffer;
$objTemplate->versions = $arrVersions;
$objTemplate->to = $intTo;
$objTemplate->from = $intFrom;
$objTemplate->showLabel = StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
$objTemplate->theme = Backend::getTheme();
$objTemplate->base = Environment::get('base');
$objTemplate->language = $GLOBALS['TL_LANGUAGE'];
$objTemplate->title = StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
$objTemplate->charset = Config::get('characterSet');
throw new ResponseException($objTemplate->getResponse());
}
/**
* Render the versions dropdown menu
*
* @return string
*/
public function renderDropdown()
{
$objVersion = $this->Database->prepare("SELECT tstamp, version, username, active FROM tl_version WHERE fromTable=? AND pid=? ORDER BY version DESC")
->execute($this->strTable, $this->intPid);
if ($objVersion->numRows < 2)
{
return '';
}
$versions = '';
while ($objVersion->next())
{
$versions .= '
<option value="' . $objVersion->version . '"' . ($objVersion->active ? ' selected="selected"' : '') . '>' . $GLOBALS['TL_LANG']['MSC']['version'] . ' ' . $objVersion->version . ' (' . Date::parse(Config::get('datimFormat'), $objVersion->tstamp) . ') ' . $objVersion->username . '</option>';
}
return '
<div class="tl_version_panel">
<form id="tl_version" class="tl_form" method="post" aria-label="' . StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['versioning']) . '">
<div class="tl_formbody">
<input type="hidden" name="FORM_SUBMIT" value="tl_version">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<select name="version" class="tl_select">' . $versions . '
</select>
<button type="submit" name="showVersion" id="showVersion" class="tl_submit">' . $GLOBALS['TL_LANG']['MSC']['restore'] . '</button>
<a href="' . Backend::addToUrl('versions=1&popup=1') . '" title="' . StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']) . '" onclick="Backend.openModalIframe({\'title\':\'' . StringUtil::specialchars(str_replace("'", "\\'", sprintf($GLOBALS['TL_LANG']['MSC']['recordOfTable'], $this->intPid, $this->strTable))) . '\',\'url\':this.href});return false">' . Image::getHtml('diff.svg') . '</a>
</div>
</form>
</div>
';
}
/**
* Add a list of versions to a template
*
* @param BackendTemplate $objTemplate
*/
public static function addToTemplate(BackendTemplate $objTemplate)
{
$arrVersions = array();
$objUser = BackendUser::getInstance();
$objDatabase = Database::getInstance();
// Get the total number of versions
$objTotal = $objDatabase->prepare("SELECT COUNT(*) AS count FROM tl_version WHERE editUrl IS NOT NULL" . (!$objUser->isAdmin ? " AND userid=?" : ""))
->execute($objUser->id);
$intLast = ceil($objTotal->count / 30);
$intPage = Input::get('vp') ?? 1;
$intOffset = ($intPage - 1) * 30;
// Validate the page number
if ($intPage < 1 || ($intLast > 0 && $intPage > $intLast))
{
header('HTTP/1.1 404 Not Found');
}
// Create the pagination menu
$objPagination = new Pagination($objTotal->count, 30, 7, 'vp', new BackendTemplate('be_pagination'));
$objTemplate->pagination = $objPagination->generate();
// Get the versions
$objVersions = $objDatabase->prepare("SELECT pid, tstamp, version, fromTable, username, userid, description, editUrl, active FROM tl_version WHERE editUrl IS NOT NULL" . (!$objUser->isAdmin ? " AND userid=?" : "") . " ORDER BY tstamp DESC, pid, version DESC")
->limit(30, $intOffset)
->execute($objUser->id);
while ($objVersions->next())
{
// Hide profile changes if the user does not have access to the "user" module (see #1309)
if (!$objUser->isAdmin && $objVersions->fromTable == 'tl_user' && !$objUser->hasAccess('user', 'modules'))
{
continue;
}
$arrRow = $objVersions->row();
// Add some parameters
$arrRow['from'] = max(($objVersions->version - 1), 1); // see #4828
$arrRow['to'] = $objVersions->version;
$arrRow['date'] = date(Config::get('datimFormat'), $objVersions->tstamp);
$arrRow['description'] = StringUtil::substr($arrRow['description'], 32);
$arrRow['shortTable'] = StringUtil::substr($arrRow['fromTable'], 18); // see #5769
if (isset($arrRow['editUrl']))
{
// Adjust the edit URL of files in case they have been renamed (see #671)
if ($arrRow['fromTable'] == 'tl_files' && ($filesModel = FilesModel::findByPk($arrRow['pid'])))
{
$arrRow['editUrl'] = preg_replace('/id=[^&]+/', 'id=' . $filesModel->path, $arrRow['editUrl']);
}
$arrRow['editUrl'] = preg_replace(array('/&(amp;)?popup=1/', '/&(amp;)?rt=[^&]+/'), array('', '&rt=' . REQUEST_TOKEN), StringUtil::ampersand($arrRow['editUrl']));
}
$arrVersions[] = $arrRow;
}
$intCount = -1;
$arrVersions = array_values($arrVersions);
// Add the "even" and "odd" classes
foreach ($arrVersions as $k=>$v)
{
$arrVersions[$k]['class'] = (++$intCount % 2 == 0) ? 'even' : 'odd';
try
{
// Mark deleted versions (see #4336)
$objDeleted = $objDatabase->prepare("SELECT COUNT(*) AS count FROM " . $v['fromTable'] . " WHERE id=?")
->execute($v['pid']);
$arrVersions[$k]['deleted'] = ($objDeleted->count < 1);
}
catch (\Exception $e)
{
// Probably a disabled module
--$intCount;
unset($arrVersions[$k]);
}
// Skip deleted files (see #8480)
if (($v['fromTable'] ?? null) == 'tl_files' && ($arrVersions[$k]['deleted'] ?? null))
{
--$intCount;
unset($arrVersions[$k]);
}
}
$objTemplate->versions = $arrVersions;
}
/**
* Return the edit URL
*
* @return string
*/
protected function getEditUrl()
{
if ($this->strEditUrl !== null)
{
return sprintf($this->strEditUrl, $this->intPid);
}
$strUrl = Environment::get('request');
// Save the real edit URL if the visibility is toggled via Ajax
if (preg_match('/&(amp;)?state=/', $strUrl))
{
$strUrl = preg_replace
(
array('/&(amp;)?id=[^&]+/', '/(&(amp;)?)t(id=[^&]+)/', '/(&(amp;)?)state=[^&]*/'),
array('', '$1$3', '$1act=edit'),
$strUrl
);
}
// Adjust the URL of the "personal data" module (see #7987)
if (preg_match('/do=login(&|$)/', $strUrl))
{
$this->import(BackendUser::class, 'User');
$strUrl = preg_replace('/do=login(&|$)/', 'do=user$1', $strUrl);
$strUrl .= '&act=edit&id=' . $this->User->id . '&rt=' . REQUEST_TOKEN;
}
// Correct the URL in "edit|override multiple" mode (see #7745)
$strUrl = preg_replace('/act=(edit|override)All/', 'act=edit&id=' . $this->intPid, $strUrl);
return $strUrl;
}
/**
* Return the username
*
* @return string
*/
protected function getUsername()
{
if ($this->strUsername !== null)
{
return $this->strUsername;
}
$this->import(BackendUser::class, 'User');
return $this->User->username;
}
/**
* Return the user ID
*
* @return string
*/
protected function getUserId()
{
if ($this->intUserId !== null)
{
return $this->intUserId;
}
$this->import(BackendUser::class, 'User');
return $this->User->id;
}
/**
* Implode a multi-dimensional array recursively
*
* @param mixed $var
* @param boolean $binary
*
* @return string
*/
protected function implodeRecursive($var, $binary=false)
{
if (!\is_array($var))
{
return $binary && Validator::isBinaryUuid($var) ? StringUtil::binToUuid($var) : $var;
}
if (!\is_array(current($var)))
{
if ($binary)
{
$var = array_map(static function ($v) { return Validator::isBinaryUuid($v) ? StringUtil::binToUuid($v) : $v; }, $var);
}
return implode(', ', $var);
}
$buffer = '';
foreach ($var as $k=>$v)
{
$buffer .= $k . ": " . $this->implodeRecursive($v) . "\n";
}
return trim($buffer);
}
}
class_alias(Versions::class, 'Versions');