/
AdminSelfUpgrade.php
executable file
·4825 lines (4382 loc) · 167 KB
/
AdminSelfUpgrade.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
/*
* 2007-2012 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2012 PrestaShop SA
* @version Release: $Revision: 15321 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
// _PS_ADMIN_DIR_ is defined in ajax-upgradetab, but may be not defined in direct call
if (!defined('_PS_ADMIN_DIR_') && defined('PS_ADMIN_DIR'))
define('_PS_ADMIN_DIR_', PS_ADMIN_DIR);
// Note : we cannot use the native AdminTab because
// we don't know the current PrestaShop version number
require_once(_PS_ROOT_DIR_.'/modules/autoupgrade/AdminSelfTab.php');
require_once(_PS_ROOT_DIR_.'/modules/autoupgrade/Upgrader.php');
if (!class_exists('Upgrader', false))
{
if(file_exists(_PS_ROOT_DIR_.'/override/classes/Upgrader.php'))
require_once(_PS_ROOT_DIR_.'/override/classes/Upgrader.php');
else
eval('class Upgrader extends UpgraderCore{}');
}
require_once(_PS_ROOT_DIR_.'/modules/autoupgrade/Tools14.php');
if (!class_exists('Tools', false))
eval('class Tools extends Tools14{}');
class AdminSelfUpgrade extends AdminSelfTab
{
// used for translations
public static $l_cache;
// retrocompatibility
public $noTabLink = array();
public $id = -1;
public $ajax = false;
public $nextResponseType = 'json'; // json, xml
public $next = 'N/A';
public $upgrader = null;
public $standalone = true;
/**
* set to false if the current step is a loop
*
* @var boolean
*/
public $stepDone = true;
public $status = true;
public $error = '0';
public $next_desc = '.';
public $nextParams = array();
public $nextQuickInfo = array();
public $currentParams = array();
/**
* @var array theses values will be automatically added in "nextParams"
* if their properties exists
*/
public $ajaxParams = array(
// autoupgrade options
'install_version',
'backupName',
'backupFilesFilename',
'backupDbFilename',
'restoreName',
'restoreFilesFilename',
'restoreDbFilenames',
'installedLanguagesIso',
);
/**
* installedLanguagesIso is an array of iso_code of each installed languages
*
* @var array
* @access public
*/
public $installedLanguagesIso = array();
public $autoupgradePath = null;
/**
* autoupgradeDir
*
* @var string directory relative to admin dir
*/
public $autoupgradeDir = 'autoupgrade';
public $latestRootDir = '';
public $prodRootDir = '';
public $adminDir = '';
public $root_writable = null;
public $module_version = null;
public $lastAutoupgradeVersion = '';
public $destDownloadFilename = 'prestashop.zip';
/**
* configFilename contains all configuration specific to the autoupgrade module
*
* @var string
* @access public
*/
public $configFilename = 'config.var';
/**
* during upgradeFiles process,
* this files contains the list of queries left to upgrade in a serialized array.
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $toUpgradeQueriesList = 'queriesToUpgrade.list';
/**
* during upgradeFiles process,
* this files contains the list of files left to upgrade in a serialized array.
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $toUpgradeFileList = 'filesToUpgrade.list';
/**
* during upgradeFiles process,
* this files contains the list of files left to upgrade in a serialized array.
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $diffFileList = 'filesDiff.list';
/**
* during backupFiles process,
* this files contains the list of files left to save in a serialized array.
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $toBackupFileList = 'filesToBackup.list';
/**
* during backupDb process,
* this files contains the list of tables left to save in a serialized array.
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $toBackupDbList = 'tablesToBackup.list';
/**
* during restoreDb process,
* this file contains a serialized array of queries which left to execute for restoring database
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $toRestoreQueryList = 'queryToRestore.list';
/**
* during restoreFiles process,
* this file contains difference between files present in a backupFiles archive
* and files currently in directories, in a serialized array.
* (this file is deleted in init() method if you reload the page)
* @var string
*/
public $toRemoveFileList = 'filesToRemove.list';
/**
* during restoreFiles process,
* contains list of files present in backupFiles archive
*
* @var string
*/
public $fromArchiveFileList = 'filesFromArchive.list';
/**
* mailCustomList contains list of mails files which are customized,
* relative to original files for the current PrestaShop version
*
* @var string
*/
public $mailCustomList = 'mails-custom.list';
/**
* tradCustomList contains list of mails files which are customized,
* relative to original files for the current PrestaShop version
*
* @var string
*/
public $tradCustomList = 'translations-custom.list';
/**
* tmp_files contains an array of filename which will be removed
* at the beginning of the upgrade process
*
* @var array
*/
public $tmp_files = array(
'toUpgradeFileList',
'toUpgradeQueriesList',
'diffFileList',
'toBackupFileList',
'toBackupDbList',
'toRestoreQueryList',
'toRemoveFileList',
'fromArchiveFileList',
'tradCustomList',
'mailCustomList',
);
public $install_version;
public $keepImages = null;
public $keepDefaultTheme = null;
public $keepTrad = null;
public $keepMails = null;
public $manualMode = null;
public $deactivateCustomModule = null;
public $sampleFileList = array();
private $restoreIgnoreFiles = array();
private $restoreIgnoreAbsoluteFiles = array();
private $backupIgnoreFiles = array();
private $backupIgnoreAbsoluteFiles = array();
private $excludeFilesFromUpgrade = array();
private $excludeAbsoluteFilesFromUpgrade = array();
private $restoreName = null;
private $backupName = null;
private $backupFilesFilename = null;
private $backupDbFilename = null;
private $restoreFilesFilename = null;
private $restoreDbFilenames = array();
/**
* int loopBackupFiles : if your server has a low memory size, lower this value
* @TODO remove the static, add a const, and use it like this : min(AdminUpgrade::DEFAULT_LOOP_ADD_FILE_TO_ZIP, $this->getConfig('LOOP_ADD_FILE_TO_ZIP');
*/
public static $loopBackupFiles = 500;
/**
* int loopBackupDbTime : if your server has a low memory size, lower this value
* @TODO remove the static, add a const, and use it like this : min(AdminUpgrade::DEFAULT_LOOP_ADD_FILE_TO_ZIP, $this->getConfig('LOOP_ADD_FILE_TO_ZIP');
*/
public static $loopBackupDbTime = 6;
/** int max_written_allowed : if your server has a low memory size, lower this value
*
*/
public static $max_written_allowed = 4194304; // 4096 ko
/**
* int loopUpgradeFiles : if your server has a low memory size, lower this value
*/
public static $loopUpgradeFiles = 1000;
/**
* int loopRestoreFiles : if your server has a low memory size, lower this value
*/
public static $loopRestoreFiles = 500;
/**
* int loopRestoreQueryTime : if your server has a low memory size, lower this value (in sec)
*/
public static $loopRestoreQueryTime = 6;
/**
* int loopRemoveSamples : if your server has a low memory size, lower this value
*/
public static $loopRemoveSamples = 1000;
/* usage : key = the step you want to ski
* value = the next step you want instead
* example : public static $skipAction = array();
* initial order upgrade:
* download, unzip, removeSamples, backupFiles, backupDb, upgradeFiles, upgradeDb, upgradeComplete
* initial order rollback: rollback, restoreFiles, restoreDb, rollbackComplete
*/
public static $skipAction = array();
/**
* if set to true, will use pclZip library
* even if ZipArchive is available
*/
public static $force_pclZip = false;
protected $_includeContainer = false;
/**
* replace tools encrypt
*
* @param mixed $string
* @return void
*/
public function encrypt($string)
{
return md5(_COOKIE_KEY_.$string);
}
public function checkToken()
{
// simple checkToken in ajax-mode, to be free of Cookie class (and no Tools::encrypt() too )
if ($this->ajax)
return ($_COOKIE['autoupgrade'] == $this->encrypt($_COOKIE['id_employee']));
else
return parent::checkToken();
}
/**
* create cookies id_employee, id_tab and autoupgrade (token)
*/
public function createCustomToken()
{
// ajax-mode for autoupgrade, we can't use the classic authentication
// so, we'll create a cookie in admin dir, based on cookie key
global $cookie;
$id_employee = $cookie->id_employee;
$iso_code = $_COOKIE['iso_code'] = Language::getIsoById($cookie->id_lang);
$admin_dir = trim(str_replace($this->prodRootDir, '', $this->adminDir), DIRECTORY_SEPARATOR);
$cookiePath = __PS_BASE_URI__.$admin_dir;
setcookie('id_employee', $id_employee, time()+7200, $cookiePath);
setcookie('id_tab', $this->id, time()+7200, $cookiePath);
setcookie('iso_code', $iso_code, time()+7200, $cookiePath);
setcookie('autoupgrade', $this->encrypt($id_employee), time()+7200, $cookiePath);
return false;
}
public function viewAccess($disable = false)
{
if ($this->ajax)
return true;
else
{
// simple access : we'll allow only admin
global $cookie;
if ($cookie->profile == 1)
return true;
}
return false;
}
public function __construct()
{
// @todo : do this only in ajax mode and if we are allowed to use theses functions
@set_time_limit(0);
@ini_set('max_execution_time', '0');
global $ajax;
if (!empty($ajax))
$this->ajax = true;
$this->init();
// retrocompatibility when used in module : Tab can't work,
// but we saved the tab id in a cookie.
if(class_exists('Tab',false))
parent::__construct();
else
{
if (isset($_COOKIE['id_tab']))
$this->id = $_COOKIE['id_tab'];
}
}
protected function l($string, $class = 'AdminTab', $addslashes = FALSE, $htmlentities = TRUE)
{
// need to be called in order to populate $classInModule
$str = self::findTranslation('autoupgrade', $string, 'AdminSelfUpgrade');
$str = $htmlentities ? htmlentities($str, ENT_QUOTES, 'utf-8') : $str;
return str_replace('"', '"', ($addslashes ? addslashes($str) : stripslashes($str)));
}
/**
* findTranslation (initially in Module class), to make translations works
*
* @param string $name module name
* @param string $string string to translate
* @param string $source current class
* @return string translated string
*/
public static function findTranslation($name, $string, $source)
{
static $_MODULES;
if (!is_array($_MODULES))
{
// note: $_COOKIE[iso_code] is set in createCustomToken();
$file = _PS_MODULE_DIR_.'autoupgrade'.DIRECTORY_SEPARATOR.$_COOKIE['iso_code'].'.php';
if (file_exists($file) && include($file))
$_MODULES = !empty($_MODULES)?array_merge($_MODULES, $_MODULE):$_MODULE;
}
$cache_key = $name . '|' . $string . '|' . $source;
if (!isset(self::$l_cache[$cache_key]))
{
if (!is_array($_MODULES))
return $string;
// set array key to lowercase for 1.3 compatibility
$_MODULES = array_change_key_case($_MODULES);
if (defined('_THEME_NAME_'))
$currentKey = '<{'.strtolower($name).'}'.strtolower(_THEME_NAME_).'>'.strtolower($source).'_'.md5($string);
else
$currentKey = '<{'.strtolower($name).'}default>'.strtolower($source).'_'.md5($string);
// note : we should use a variable to define the default theme (instead of "prestashop")
$defaultKey = '<{'.strtolower($name).'}prestashop>'.strtolower($source).'_'.md5($string);
$currentKey = $defaultKey;
if (isset($_MODULES[$currentKey]))
$ret = stripslashes($_MODULES[$currentKey]);
elseif (isset($_MODULES[strtolower($currentKey)]))
$ret = stripslashes($_MODULES[strtolower($currentKey)]);
elseif (isset($_MODULES[$defaultKey]))
$ret = stripslashes($_MODULES[$defaultKey]);
elseif (isset($_MODULES[strtolower($defaultKey)]))
$ret = stripslashes($_MODULES[strtolower($defaultKey)]);
else
$ret = stripslashes($string);
self::$l_cache[$cache_key] = $ret;
}
return self::$l_cache[$cache_key];
}
/**
* function to set configuration fields display
*
* @return void
*/
private function _setFields()
{
$this->_fieldsAutoUpgrade['PS_AUTOUP_KEEP_IMAGES'] = array(
'title' => $this->l('Also save images'), 'cast' => 'intval', 'validation' => 'isBool',
'type' => 'bool', 'desc'=>$this->l('You can exclude the image directory from backup if you already saved it by another method (not recommended)'),
);
$this->_fieldsAutoUpgrade['PS_AUTOUP_KEEP_DEFAULT_THEME'] = array(
'title' => $this->l('Keep theme "prestashop"'), 'cast' => 'intval', 'validation' => 'isBool',
'type' => 'bool', 'desc'=>$this->l('If you have customized PrestaShop default theme, you can protect it from upgrade (not recommended)'),
);
$this->_fieldsAutoUpgrade['PS_AUTOUP_KEEP_TRAD'] = array(
'title' => $this->l('Keep translations'), 'cast' => 'intval', 'validation' => 'isBool',
'type' => 'bool', 'desc'=>$this->l('If set to yes, you will keep all your translations. Otherwise, they will be merged with the new ones'),
);
$this->_fieldsAutoUpgrade['PS_AUTOUP_KEEP_MAILS'] = array(
'title' => $this->l('Keep default mails'), 'cast' => 'intval', 'validation' => 'isBool',
'type' => 'bool', 'desc'=>$this->l('If set to yes, new mailtemplate will be added but old will not be overwritten (not recommended)'),
);
$this->_fieldsAutoUpgrade['PS_AUTOUP_CUSTOM_MOD_DESACT'] = array(
'title' => $this->l('Deactivate custom modules'), 'cast' => 'intval', 'validation' => 'isBool',
'type' => 'bool', 'desc'=>$this->l('If you don\'t deactivate your modules, you can have some compatibility problems and the Modules page might not load correctly.'),
);
// allow manual mode only for dev
if (defined('_PS_MODE_DEV_') AND _PS_MODE_DEV_)
$this->_fieldsAutoUpgrade['PS_AUTOUP_MANUAL_MODE'] = array(
'title' => $this->l('Manual mode'), 'cast' => 'intval', 'validation' => 'isBool',
'type' => 'bool', 'desc'=>$this->l('Check this if you want to stop after each step'),
);
}
public function configOk()
{
$allowed_array = $this->getCheckCurrentPsConfig();
$allowed = array_product($allowed_array);
return $allowed;
}
public function getCheckCurrentPsConfig()
{
static $allowed_array;
if(empty($allowed_array))
{
$allowed_array = array();
$allowed_array['fopen'] = ConfigurationTest::test_fopen();
$allowed_array['root_writable'] = $this->getRootWritable();
$allowed_array['shop_deactivated'] = !Configuration::get('PS_SHOP_ENABLE');
$allowed_array['cache_deactivated'] = !(defined('_PS_CACHE_ENABLED_') && _PS_CACHE_ENABLED_);
$allowed_array['module_version_ok'] = $this->checkAutoupgradeLastVersion();
// if one option has been defined, all options are.
$allowed_array['module_configured'] = ($this->getConfig('PS_AUTOUP_KEEP_MAILS') !== false);
}
return $allowed_array;
}
public function getRootWritable()
{
// test if prodRootDir is writable recursively
$this->root_writable = ConfigurationTest::test_dir($this->prodRootDir, true);
return $this->root_writable;
}
public function getModuleVersion()
{
if (is_null($this->module_version))
{
if (file_exists(_PS_ROOT_DIR_.'/modules/autoupgrade/config.xml')
&& $xml_module_version = simplexml_load_file(_PS_ROOT_DIR_.'/modules/autoupgrade/config.xml')
)
$this->module_version = (string)$xml_module_version->version;
else
$this->module_version = false;
}
return $this->module_version;
}
public function checkAutoupgradeLastVersion()
{
if ($this->getModuleVersion())
$this->lastAutoupgradeVersion = version_compare($this->module_version, $this->upgrader->autoupgrade_last_version, '>=');
else
$this->lastAutoupgradeVersion = true;
return $this->lastAutoupgradeVersion;
}
public function cleanTmpFiles()
{
foreach($this->tmp_files as $tmp_file)
if (file_exists($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->$tmp_file))
unlink($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->$tmp_file);
}
/**
* init to build informations we need
*
* @return void
*/
public function init()
{
// For later use, let's set up prodRootDir and adminDir
// This way it will be easier to upgrade a different path if needed
$this->prodRootDir = _PS_ROOT_DIR_;
$this->adminDir = _PS_ADMIN_DIR_;
if (!defined('__PS_BASE_URI__'))
{
// _PS_DIRECTORY_ replaces __PS_BASE_URI__ in 1.5
if (defined('_PS_DIRECTORY_'))
define('__PS_BASE_URI__', _PS_DIRECTORY_);
else
define('__PS_BASE_URI__', realpath(dirname($_SERVER['SCRIPT_NAME'])).'/../../');
}
// from $_POST or $_GET
$this->action = empty($_REQUEST['action'])?null:$_REQUEST['action'];
$this->currentParams = empty($_REQUEST['params'])?null:$_REQUEST['params'];
// test writable recursively
if(version_compare(_PS_VERSION_,'1.4.6.0','<') || !class_exists('ConfigurationTest', false))
{
require_once('ConfigurationTest.php');
if(!class_exists('ConfigurationTest', false) AND class_exists('ConfigurationTestCore'))
eval('class ConfigurationTest extends ConfigurationTestCore{}');
}
$this->initPath();
// @todo is it correct to select branch with config ?
$upgrader = new Upgrader();
preg_match('#([0-9]+\.[0-9]+)(?:\.[0-9]+){1,2}#', _PS_VERSION_, $matches);
$upgrader->branch = $matches[1];
$channel = $this->getConfig('channel');
switch ($channel)
{
case 'archive':
$this->install_version = $this->getConfig('archive.version_num');
$this->destDownloadFilename = $this->getConfig('archive.filename');
break;
case 'directory';
$this->install_version = $this->getConfig('directory.version_num');
break;
default:
$upgrader->channel = $channel;
if ($this->getConfig('channel') == 'private' && !$this->getConfig('private_allow_major'))
$upgrader->checkPSVersion(false, array('private', 'minor'));
else
$upgrader->checkPSVersion(false, array('minor'));
$this->install_version = $upgrader->version_num;
}
// If you have defined this somewhere, you know what you do
/* load options from configuration if we're not in ajax mode */
if (!$this->ajax)
{
$this->createCustomToken();
// installedLanguagesIso is used to merge translations files
$iso_ids = Language::getIsoIds(false);
foreach($iso_ids as $v)
$this->installedLanguagesIso[] = $v['iso_code'];
$rand = dechex ( mt_rand(0, min(0xffffffff, mt_getrandmax() ) ) );
$date = date('Ymd-His');
$this->backupName = 'V'._PS_VERSION_.'_'.$date.'-'.$rand;
$this->backupFilesFilename = 'auto-backupfiles_'.$this->backupName.'.zip';
$this->backupDbFilename = 'auto-backupdb_XXXXXX_'.$this->backupName.'.sql';
// removing temporary files
$this->cleanTmpFiles();
}
else
{
foreach($this->ajaxParams as $prop)
if(property_exists($this, $prop))
$this->{$prop} = isset($this->currentParams[$prop])?$this->currentParams[$prop]:'';
}
$this->keepImages = $this->getConfig('PS_AUTOUP_KEEP_IMAGES');
$this->keepDefaultTheme = $this->getConfig('PS_AUTOUP_KEEP_DEFAULT_THEME');
$this->keepTrad = $this->getConfig('PS_AUTOUP_KEEP_TRAD');
$this->keepMails = $this->getConfig('PS_AUTOUP_KEEP_MAILS');
$this->manualMode = $this->getConfig('PS_AUTOUP_MANUAL_MODE');
$this->deactivateCustomModule = $this->getConfig('PS_AUTOUP_CUSTOM_MOD_DESACT');
// We can add any file or directory in the exclude dir : theses files will be not removed or overwritten
// @TODO cache should be ignored recursively, but we have to reconstruct it after upgrade
// - compiled from smarty
// - .svn
// during restoration, do not remove :
$this->restoreIgnoreAbsoluteFiles[] = '/config/settings.inc.php';
$this->restoreIgnoreAbsoluteFiles[] = '/modules/autoupgrade';
$this->restoreIgnoreAbsoluteFiles[] = '/admin/autoupgrade';
$this->restoreIgnoreAbsoluteFiles[] = '.';
$this->restoreIgnoreAbsoluteFiles[] = '..';
// during backup, do not save
$this->backupIgnoreAbsoluteFiles[] = '/tools/smarty_v2/compile';
$this->backupIgnoreAbsoluteFiles[] = '/tools/smarty_v2/cache';
$this->backupIgnoreAbsoluteFiles[] = '/tools/smarty/compile';
$this->backupIgnoreAbsoluteFiles[] = '/tools/smarty/cache';
// do not care about the two autoupgrade dir we use;
$this->backupIgnoreAbsoluteFiles[] = '/modules/autoupgrade';
$this->backupIgnoreAbsoluteFiles[] = '/admin/autoupgrade';
$this->excludeFilesFromUpgrade[] = '.';
$this->excludeFilesFromUpgrade[] = '..';
$this->excludeFilesFromUpgrade[] = '.svn';
// do not copy install, neither settings.inc.php in case it would be present
$this->excludeFilesFromUpgrade[] = '/config/settings.inc.php';
// this will exclude autoupgrade dir from admin, and autoupgrade from modules
$this->excludeFilesFromUpgrade[] = 'autoupgrade';
$this->backupIgnoreFiles[] = '.';
$this->backupIgnoreFiles[] = '..';
// @TODO : add option to enable .svn backup
$this->backupIgnoreFiles[] = '.svn';
$this->backupIgnoreFiles[] = 'autoupgrade';
if ($this->keepImages === '0')
{
$this->backupIgnoreAbsoluteFiles[] = '/img';
$this->restoreIgnoreAbsoluteFiles[] = '/img';
}
// do not copy install dir
$this->excludeAbsoluteFilesFromUpgrade[] = '/install';
if ($this->keepDefaultTheme)
{
$this->excludeAbsoluteFilesFromUpgrade[] = '/themes/prestashop';
$this->excludeAbsoluteFilesFromUpgrade[] = '/themes/default';
}
if ($this->keepTrad)
{
$this->excludeAbsoluteFilesFromUpgrade[] = '/themes/prestashop/lang';
$this->excludeAbsoluteFilesFromUpgrade[] = '/themes/default/lang';
$this->excludeAbsoluteFilesFromUpgrade[] = '/translations';
$this->excludeFilesFromUpgrade[] = 'de.php';
$this->excludeFilesFromUpgrade[] = 'en.php';
$this->excludeFilesFromUpgrade[] = 'es.php';
$this->excludeFilesFromUpgrade[] = 'fr.php';
$this->excludeFilesFromUpgrade[] = 'it.php';
}
if ($this->keepMails)
{
// @TODO : add a way to exclude pattern (mails/*.html / mails/*.txt )
$this->excludeAbsoluteFilesFromUpgrade[] = '/mails';
$this->excludeFilesFromUpgrade[] = 'mails';
}
}
/**
* create some required directories if they does not exists
*
* Also set nextParams (removeList and filesToUpgrade) if they
* exists in currentParams
*
*/
public function initPath()
{
// If not exists in this sessions, "create"
// session handling : from current to next params
if (isset($this->currentParams['removeList']))
$this->nextParams['removeList'] = $this->currentParams['removeList'];
if (isset($this->currentParams['filesToUpgrade']))
$this->nextParams['filesToUpgrade'] = $this->currentParams['filesToUpgrade'];
// set autoupgradePath, to be used in backupFiles and backupDb config values
$this->autoupgradePath = $this->adminDir.DIRECTORY_SEPARATOR.$this->autoupgradeDir;
// directory missing
if (!file_exists($this->autoupgradePath))
if (!@mkdir($this->autoupgradePath,0777))
$this->_errors[] = sprintf($this->l('unable to create directory %s'),$this->autoupgradePath);
$this->downloadPath = $this->autoupgradePath.DIRECTORY_SEPARATOR.'download';
if (!file_exists($this->downloadPath))
if (!@mkdir($this->downloadPath,0777))
$this->_errors[] = sprintf($this->l('unable to create directory %s'),$this->downloadPath);
$this->backupPath = $this->autoupgradePath.DIRECTORY_SEPARATOR.'backup';
if (!file_exists($this->backupPath))
if (!@mkdir($this->backupPath,0777))
$this->_errors[] = sprintf($this->l('unable to create directory %s'),$this->backupPath);
// directory missing
// @todo move this in upgrade step
$this->latestPath = $this->autoupgradePath.DIRECTORY_SEPARATOR.'latest';
if (!file_exists($this->latestPath))
if (!@mkdir($this->latestPath,0777))
$this->_errors[] = sprintf($this->l('unable to create directory %s'),$this->latestPath);
$this->latestRootDir = $this->latestPath.DIRECTORY_SEPARATOR.'prestashop';
// @TODO future option "install in test dir"
// $this->testRootDir = $this->autoupgradePath.DIRECTORY_SEPARATOR.'test';
}
/**
* getFilePath return the path to the zipfile containing prestashop.
*
* @return void
*/
private function getFilePath()
{
return $this->downloadPath.DIRECTORY_SEPARATOR.$this->destDownloadFilename;
}
public function postProcess()
{
global $currentIndex;
$this->_setFields();
// set default configuration to default channel
// (can be modified in expert mode)
$config = $this->getConfig('channel');
if ($config === false)
{
$config = array();
$config['channel'] = Upgrader::DEFAULT_CHANNEL;
$this->writeConfig($config);
}
if (Tools::isSubmit('customSubmitAutoUpgrade'))
{
$config_keys = array_keys($this->_fieldsAutoUpgrade);
$config = array();
foreach ($config_keys as $key)
if (isset($_POST[$key]))
$config[$key] = $_POST[$key];
$res = $this->writeConfig($config);
if ($res)
Tools::redirectAdmin($currentIndex.'&conf=6&token='.Tools::getValue('token'));
}
if (Tools::isSubmit('deletebackup'))
{
$res = true;
$name = Tools::getValue('name');
$filelist = scandir($this->backupPath);
foreach($filelist as $filename)
// the following will match file or dir related to the selected backup
if (preg_match('#^.*'.preg_quote($name).'.*$#', $filename, $matches))
{
if (is_file($this->backupPath.DIRECTORY_SEPARATOR.$filename))
$res &= unlink($this->backupPath.DIRECTORY_SEPARATOR.$filename);
if (!empty($name) && is_dir($this->backupPath.DIRECTORY_SEPARATOR.$name))
self::deleteDirectory($this->backupPath.DIRECTORY_SEPARATOR.$name);
}
if ($res)
Tools::redirectAdmin($currentIndex.'&conf=1&token='.Tools::getValue('token'));
else
$this->_errors[] = sprintf($this->l('Error when trying to delete backups %s'), $name);
}
parent::postProcess();
}
/**
* ends the rollback process
*
* @return void
*/
public function ajaxProcessRollbackComplete()
{
$this->next_desc = $this->l('Restoration process done. Congratulations ! You can now reactive your shop.');
$this->next = '';
}
/**
* ends the upgrade process
*
* @return void
*/
public function ajaxProcessUpgradeComplete()
{
$this->next_desc = $this->l('Upgrade process done. Congratulations ! You can now reactive your shop.');
$this->next = '';
}
/**
* ends the upgrade process
*
* @return void
*/
public function ajaxProcessUpgradeCompleteWithWarnings()
{
$this->next_desc = $this->l('Upgrade process done, but some warnings has been found. Please restore your shop.');
$this->next = '';
}
// Simplification of _displayForm original function
protected function _displayForm($name, $fields, $tabname, $size, $icon)
{
global $currentIndex;
$confValues = $this->getConfig();
$required = false;
echo '
<form action="'.$currentIndex.'&customSubmitAutoUpgrade=1&token='.$this->token.'" method="post" enctype="multipart/form-data">
<fieldset><legend><img src="../img/admin/'.strval($icon).'.gif" />'.$tabname.'</legend>';
foreach ($fields AS $key => $field)
{
if (isset($field['required']) AND $field['required'])
$required = true;
$val = isset($confValues[$key])?$confValues[$key]:'';
if (!in_array($field['type'], array('image', 'radio', 'container', 'container_end')) OR isset($field['show']))
echo '<div style="clear: both; padding-top:15px;">'.($field['title'] ? '<label >'.$field['title'].'</label>' : '').'<div class="margin-form" style="padding-top:5px;">';
/* Display the appropriate input type for each field */
switch ($field['type'])
{
case 'disabled': echo $field['disabled'];break;
case 'bool':
echo '<label class="t" for="'.$key.'_on"><img src="../img/admin/enabled.gif" alt="'.$this->l('Yes').'" title="'.$this->l('Yes').'" /></label>
<input type="radio" name="'.$key.'" id="'.$key.'_on" value="1"'.($val ? ' checked="checked"' : '').(isset($field['js']['on']) ? $field['js']['on'] : '').' />
<label class="t" for="'.$key.'_on"> '.$this->l('Yes').'</label>
<label class="t" for="'.$key.'_off"><img src="../img/admin/disabled.gif" alt="'.$this->l('No').'" title="'.$this->l('No').'" style="margin-left: 10px;" /></label>
<input type="radio" name="'.$key.'" id="'.$key.'_off" value="0" '.(!$val ? 'checked="checked"' : '').(isset($field['js']['off']) ? $field['js']['off'] : '').'/>
<label class="t" for="'.$key.'_off"> '.$this->l('No').'</label>';
break;
case 'radio':
foreach ($field['choices'] AS $cValue => $cKey)
echo '<input type="radio" name="'.$key.'" id="'.$key.$cValue.'_on" value="'.(int)($cValue).'"'.(($cValue == $val) ? ' checked="checked"' : '').(isset($field['js'][$cValue]) ? ' '.$field['js'][$cValue] : '').' /><label class="t" for="'.$key.$cValue.'_on"> '.$cKey.'</label><br />';
echo '<br />';
break;
case 'textarea':
echo '<textarea name='.$key.' cols="'.$field['cols'].'" rows="'.$field['rows'].'">'.htmlentities($val, ENT_COMPAT, 'UTF-8').'</textarea>';
break;
case 'container':
echo '<div id="'.$key.'">';
break;
case 'container_end':
echo (isset($field['content']) === true ? $field['content'] : '').'</div>';
break;
case 'text':
default:
echo '<input type="'.$field['type'].'"'.(isset($field['id']) === true ? ' id="'.$field['id'].'"' : '').' size="'.(isset($field['size']) ? (int)($field['size']) : 5).'" name="'.$key.'" value="'.($field['type'] == 'password' ? '' : htmlentities($val, ENT_COMPAT, 'UTF-8')).'" />'.(isset($field['next']) ? ' '.strval($field['next']) : '');
}
echo ((isset($field['required']) AND $field['required'] AND !in_array($field['type'], array('image', 'radio'))) ? ' <sup>*</sup>' : '');
echo (isset($field['desc']) ? '<p style="clear:both">'.((isset($field['thumb']) AND $field['thumb'] AND $field['thumb']['pos'] == 'after') ? '<img src="'.$field['thumb']['file'].'" alt="'.$field['title'].'" title="'.$field['title'].'" style="float:left;" />' : '' ).$field['desc'].'</p>' : '');
if (!in_array($field['type'], array('image', 'radio', 'container', 'container_end')) OR isset($field['show']))
echo '</div></div>';
}
echo ' <div align="center" style="margin-top: 20px;">
<input type="submit" value="'.$this->l(' Save ', 'AdminPreferences').'" name="customSubmitAutoUpgrade" class="button" />
</div>
'.($required ? '<div class="small"><sup>*</sup> '.$this->l('Required field', 'AdminPreferences').'</div>' : '').'
</fieldset>
</form>';
}
/**
* return the value of $key, configuration saved in $this->configFilename.
* if $key is empty, will return an array with all configuration;
*
* @param string $key
* @access public
* @return array or string
*/
public function getConfig($key = '')
{
static $config = array();
if (count($config) == 0)
{
if (file_exists($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->configFilename))
{
$config_content = file_get_contents($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->configFilename);
$config = unserialize($config_content);
}
else
$config = array();
}
if (!empty($key))
{
if (isset($config[$key]))
return $config[$key];
else
return false;
}
else
return $config;
}
/**
* reset module configuration with $new_config values (previous config will be totally lost)
*
* @param array $new_config
* @return boolean true if success
*/
public function resetConfig($new_config)
{
return file_put_contents($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->configFilename, serialize($new_config));
}
/**
* update module configuration (saved in file $this->configFilename) with $new_config
*
* @param array $new_config
* @return boolean true if success
*/
public function writeConfig($new_config)
{
if (!file_exists($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->configFilename))
return $this->resetConfig($new_config);
$config = file_get_contents($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->configFilename);
$config = unserialize($config);
foreach($new_config as $key => $val)
$config[$key] = $val;
$this->next_desc = $this->l('Configuration successfully updated');
return file_put_contents($this->autoupgradePath.DIRECTORY_SEPARATOR.$this->configFilename, serialize($config));
}
/**
* update configuration after validating the new values
*
* @access public
*/
public function ajaxProcessUpdateConfig()
{
$config = array();
// nothing next
$this->next = '';
// update channel
if (isset($this->currentParams['channel']))
{
$config['channel'] = $this->currentParams['channel'];
}
if (isset($this->currentParams['private_release_key']))
{
$config['channel'] = 'private';
$config['private_release_key'] = $this->currentParams['private_release_key'];
$config['private_allow_major'] = $this->currentParams['private_allow_major'];
}
// if (!empty($this->currentParams['archive_name']) && !empty($this->currentParams['archive_num']))
if (!empty($this->currentParams['archive_prestashop']))
{
$file = $this->currentParams['archive_prestashop'];
if (!file_exists($this->downloadPath.DIRECTORY_SEPARATOR.$file))
{
$this->error = 1;
$this->next_desc = sprintf($this->l('file %s does not exists. Unable to select that channel.'), $file);
return false;
}
if (empty($this->currentParams['archive_num']))
{
$this->error = 1;
$this->next_desc = sprintf($this->l('version number is missing. Unable to select that channel.'), $file);
return false;
}
$config['channel'] = 'archive';
$config['archive.filename'] = $this->currentParams['archive_prestashop'];
$config['archive.version_num'] = $this->currentParams['archive_num'];
// $config['archive_name'] = $this->currentParams['archive_name'];
$this->next_desc = $this->l('Upgrade process will use archive.');
}
if (isset($this->currentParams['directory_num']))
{