-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAutoUpdater.php
More file actions
executable file
·837 lines (685 loc) · 22.1 KB
/
AutoUpdater.php
File metadata and controls
executable file
·837 lines (685 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
<?php
namespace FeatherBB\Core;
/**
* Copyright (C) 2015-2019 FeatherBB
* based on code "VisualAppeal/PHP-Auto-Update" by Tim Helfensdörfer
* https://github.com/VisualAppeal/PHP-Auto-Update
* License: https://github.com/VisualAppeal/PHP-Auto-Update/blob/master/LICENSE.md Apache-2.0
*/
use vierbergenlars\SemVer\version;
/**
* Auto update class.
*/
class AutoUpdater
{
/**
* The latest version.
*
* @var vierbergenlars\SemVer\version
*/
private $_latestVersion = null;
/**
* Updates not yet installed.
*
* @var array
*/
private $_updates = null;
/**
* Result of simulated install.
*
* @var array
*/
private $_simulationResults = [];
/**
* Temporary download directory.
*
* @var string
*/
private $_tempDir = '';
/**
* Install directory.
*
* @var string
*/
private $_installDir = '';
/**
* Root folder name.
* Used to override root folder in archive
*
* @var string
*/
private $_rootFolder = '';
/**
* Url to the update folder on the server.
*
* @var string
*/
protected $_updateUrl = 'https://marketplace.featherbb.org/updates/';
/**
* Version filename on the server.
*
* @var string
*/
protected $_updateFile = 'update.json';
/**
* Content of errors occurred when updating.
*
* @var array
*/
protected $_errors = [];
/**
* Content of warnings fired when updating.
*
* @var array
*/
protected $_warnings = [];
/**
* Current version.
*
* @var vierbergenlars\SemVer\version
*/
protected $_currentVersion = null;
/**
* Create new folders with this privileges.
*
* @var int
*/
public $dirPermissions = 0755;
/**
* Update script filename.
*
* @var string
*/
public $updateScriptName = '_upgrade.php';
/**
* No update available.
*/
const NO_UPDATE_AVAILABLE = 0;
/**
* Zip file could not be opened.
*/
const ERROR_INVALID_ZIP = 10;
/**
* Could not check for last version.
*/
const ERROR_VERSION_CHECK = 20;
/**
* Temp directory does not exist or is not writable.
*/
const ERROR_TEMP_DIR = 30;
/**
* Install directory does not exist or is not writable.
*/
const ERROR_INSTALL_DIR = 35;
/**
* Could not download update.
*/
const ERROR_DOWNLOAD_UPDATE = 40;
/**
* Could not delete zip update file.
*/
const ERROR_DELETE_TEMP_UPDATE = 50;
/**
* Error while installing the update.
*/
const ERROR_INSTALL = 60;
/**
* Error in simulated install.
*/
const ERROR_SIMULATE = 70;
/**
* Create new instance
*
* @param string $tempDir
* @param string $installDir
* @param int $maxExecutionTime
*/
public function __construct($tempDir = null, $installDir = null, $maxExecutionTime = 60)
{
$this->setTempDir(($tempDir !== null) ? $tempDir : __DIR__ . '/temp/');
$this->setInstallDir(($installDir !== null) ? $installDir : __DIR__ . '/../../');
$this->_latestVersion = new version('0.0.0');
$this->_currentVersion = new version('0.0.0');
$this->_errors = [];
$this->_warnings = [];
ini_set('max_execution_time', $maxExecutionTime);
}
/**
* Set the temporary download directory.
*
* @param string $dir
* @return $this|void
*/
public function setTempDir($dir)
{
// Add slash at the end of the path
if (substr($dir, -1 != '/')) {
$dir = $dir . '/';
}
if (!is_dir($dir)) {
if (!mkdir($dir, 0755, true)) {
// $this->_log->addCritical(sprintf('Could not create temporary directory "%s"', $dir));
return;
}
}
$this->_tempDir = $dir;
return $this;
}
/**
* Set the install directory.
*
* @param string $dir
* @return $this|void
*/
public function setInstallDir($dir)
{
// Add slash at the end of the path
if (substr($dir, -1 != '/')) {
$dir = $dir . '/';
}
if (!is_dir($dir)) {
if (!mkdir($dir, 0755, true)) {
// $this->_log->addCritical(sprintf('Could not create temporary directory "%s"', $dir));
return;
}
}
$this->_installDir = $dir;
return $this;
}
/**
* Set the root folder name.
*
* @param string $folder
* @return $this|void
*/
public function setRootFolder($folder)
{
$this->_rootFolder = $folder;
return $this;
}
/**
* Set the update filename.
*
* @param string $updateFile
* @return $this
*/
public function setUpdateFile($updateFile)
{
$this->_updateFile = $updateFile;
return $this;
}
/**
* Set the update filename.
*
* @param string $updateUrl
* @return $this
*/
public function setUpdateUrl($updateUrl)
{
$this->_updateUrl = $updateUrl;
return $this;
}
/**
* Set the version of the current installed software.
*
* @param string $currentVersion
*
* @return bool
*/
public function setCurrentVersion($currentVersion)
{
$version = new version($currentVersion);
if ($version->valid() === null) {
// $this->_log->addError(sprintf('Invalid current version "%s"', $currentVersion));
return false;
}
$this->_currentVersion = $version;
return $this;
}
/**
* Get the name of the latest version.
*
* @return vierbergenlars\SemVer\version
*/
public function getLatestVersion()
{
return $this->_latestVersion;
}
/**
* Get an array of versions which will be installed.
*
* @return array
*/
public function getVersionsToUpdate()
{
return array_map(function ($update) {
return $update['version'];
}, $this->_updates);
}
/**
* Get the results of the last simulation.
*
* @return array
*/
public function getSimulationResults()
{
return $this->_simulationResults;
}
/**
* Get the results of errors encountered.
*
* @return array
*/
public function getErrors()
{
return $this->_errors;
}
/**
* Get the results of warnings encountered.
*
* @return array
*/
public function getWarnings()
{
return $this->_warnings;
}
/**
* Add a warning
*
* @param $warning warning to add
*/
public function addWarning($warning)
{
$this->_warnings[] = $warning;
}
/**
* Remove directory recursively.
*
* @param string $dir
*
* @return void
*/
private function _removeDir($dir)
{
// $this->_log->addDebug(sprintf('Remove directory "%s"', $dir));
if (!is_dir($dir)) {
// $this->_log->addWarning(sprintf('"%s" is not a directory!', $dir));
return false;
}
$objects = array_diff(scandir($dir), ['.', '..']);
foreach ($objects as $object) {
if (is_dir($dir . '/' . $object)) {
$this->_removeDir($dir . '/' . $object);
} else {
unlink($dir . '/' . $object);
}
}
return rmdir($dir);
}
/**
* Check for a new version
*
* @return int|bool
* true: New version is available
* false: Error while checking for update
* int: Status code (i.e. AutoUpdate::NO_UPDATE_AVAILABLE)
*/
public function checkUpdate()
{
// Reset previous updates
$this->_latestVersion = new version('0.0.0');
$this->_updates = [];
// $releases = $this->_cache->get('update-versions');
// Check if cache is empty
// if ($releases === false) {
// Create absolute url to update file
// $updateFile = $this->_updateUrl . '/' . $this->_updateFile;
$updateFile = $this->_updateUrl;
// Read update file from update server
$update = AdminUtils::getContent($updateFile);
if ($update === false) {
$this->_errors[] = sprintf(__('Could not check for updates'), $updateFile);
return false;
}
$releases = (array)@json_decode($update);
if (!is_array($releases)) {
$this->_errors[] = __('Unable to parse json update file');
return false;
}
// $this->_cache->set('update-versions', $releases);
// }
// Check for latest version
foreach ($releases as $releaseContent) {
$versionRaw = $releaseContent->tag_name;
$updateUrl = $releaseContent->zipball_url;
$version = new version($versionRaw);
if ($version->valid() === null) {
$this->_errors[] = sprintf(__('Could not parse version'), $versionRaw, $updateFile);
continue;
}
if (version::gt($version, $this->_currentVersion)) {
if (version::gt($version, $this->_latestVersion)) {
$this->_latestVersion = $version;
}
$this->_updates[] = [
'version' => $version,
'url' => $updateUrl
];
}
}
// Sort versions to install
usort($this->_updates, function ($a, $b) {
return version::compare($a['version'], $b['version']);
});
if ($this->newVersionAvailable()) {
return true;
} else {
return self::NO_UPDATE_AVAILABLE;
}
}
/**
* Check if a new version is available.
*
* @return bool
*/
public function newVersionAvailable()
{
return version::gt($this->_latestVersion, $this->_currentVersion);
}
/**
* Download the update
*
* @param string $updateUrl Url where to download from
* @param string $updateFile Path where to save the download
*
* @return bool
*/
protected function _downloadUpdate($updateUrl, $updateFile)
{
$update = AdminUtils::getContent($updateUrl);
if ($update === false) {
$this->_errors[] = sprintf(__('Could not download update'), $updateUrl);
return false;
}
$handle = fopen($updateFile, 'w');
if (!$handle) {
$this->_errors[] = sprintf(__('Could not open file handle'), $updateFile);
return false;
}
if (!fwrite($handle, $update)) {
$this->_errors[] = sprintf(__('Could not write update to file'), $updateFile);
fclose($handle);
return false;
}
fclose($handle);
return true;
}
/**
* Simulate update process.
*
* @param string $updateFile
*
* @return bool
*/
protected function _simulateInstall($updateFile)
{
clearstatcache();
// Check if zip file could be opened
$zip = zip_open($updateFile);
if (!is_resource($zip)) {
$this->_errors[] = sprintf(__('Could not open zip file'), $updateFile, $zip);
return false;
}
$i = -1;
$files = [];
$simulateSuccess = true;
while ($file = zip_read($zip)) {
$i++;
$filename = zip_entry_name($file);
// Manipulate and do verifications on file path
$parts = explode('/', $filename);
// If we are upgrading core
array_shift($parts);
if ($parts[0] == '') {
continue;
}
if ($this->_rootFolder == 'featherbb') {
// // Skip if entry is not in targetted files
if ($parts[0] == 'cache' || $parts[0] == 'style') {
continue;
}
}
$filename = implode('/', $parts);
$foldername = $this->_installDir . dirname($filename);
$absoluteFilename = $this->_installDir . $filename;
$files[$i] = [
'filename' => $filename,
'foldername' => $foldername,
'absolute_filename' => $absoluteFilename,
];
// Check if parent directory is writable
if (!is_dir($foldername)) {
// $this->_errors[] = sprintf('[SIMULATE] Create directory "%s"', $foldername);
$files[$i]['parent_folder_exists'] = false;
$parent = dirname($foldername);
if (!mkdir($foldername, $this->dirPermissions, true) && !is_writable($parent)) {
$files[$i]['parent_folder_writable'] = false;
$simulateSuccess = false;
$this->_errors[] = sprintf(__('Directory not writable'), $parent);
} else {
$files[$i]['parent_folder_writable'] = true;
}
}
// Skip if entry is a directory
if (substr($filename, -1, 1) == '/') {
continue;
}
// Read file contents from archive
$contents = zip_entry_read($file, zip_entry_filesize($file));
if ($contents === false) {
$files[$i]['extractable'] = false;
$simulateSuccess = false;
$this->_errors[] = sprintf(__('Coud not read zip entry'), $filename);
}
// Write to file
if (file_exists($absoluteFilename)) {
$files[$i]['file_exists'] = true;
if (!is_writable($absoluteFilename)) {
$files[$i]['file_writable'] = false;
$simulateSuccess = false;
$this->_errors[] = sprintf(__('Could not overwrite file'), $absoluteFilename);
}
} else {
$files[$i]['file_exists'] = false;
if (is_dir($foldername)) {
if (!is_writable($foldername)) {
if (!mkdir($foldername, $this->dirPermissions, true)) {
$files[$i]['file_writable'] = false;
$simulateSuccess = false;
$this->_errors[] = sprintf(__('File could not be created'), $absoluteFilename);
}
} else {
$files[$i]['file_writable'] = true;
}
} else {
$files[$i]['file_writable'] = true;
}
}
if ($filename == $this->updateScriptName) {
$files[$i]['update_script'] = true;
} else {
$files[$i]['update_script'] = false;
}
}
$this->_simulationResults = $files;
return $simulateSuccess;
}
/**
* Install update.
*
* @param string $updateFile Path to the update file
* @param bool $simulateInstall Check for directory and file permissions before copying files
*
* @return bool
*/
protected function _install($updateFile, $simulateInstall, $version)
{
// Check if install should be simulated
if ($simulateInstall && !$this->_simulateInstall($updateFile)) {
// $this->_errors[] = 'Simulation of update process failed!';
return self::ERROR_SIMULATE;
}
clearstatcache();
// Check if zip file could be opened
$zip = zip_open($updateFile);
if (!is_resource($zip)) {
$this->_errors[] = sprintf(__('Could not open zip file'), $updateFile, $zip);
return false;
}
// Read every file from archive
while ($file = zip_read($zip)) {
$filename = zip_entry_name($file);
// Remove first part of archive path
$parts = explode('/', $filename);
array_shift($parts);
if ($parts[0] == '') {
continue;
}
if ($this->_rootFolder == 'featherbb') {
// // Skip if entry is not in targetted files
if ($parts[0] == 'cache' || $parts[0] == 'style') {
continue;
}
}
$filename = implode('/', $parts);
$foldername = $this->_installDir . dirname($filename);
$absoluteFilename = $this->_installDir . $filename;
if (!is_dir($foldername)) {
if (!mkdir($foldername, $this->dirPermissions, true)) {
$this->_errors[] = sprintf(__('Directory not writable'), $parent);
return false;
}
}
// Skip if entry is a directory
if (substr($filename, -1, 1) == '/') {
continue;
}
// Read file contents from archive
$contents = zip_entry_read($file, zip_entry_filesize($file));
if ($contents === false) {
$this->_errors[] = sprintf(__('Coud not read zip entry'), $file);
continue;
}
// Write to file
if (file_exists($absoluteFilename)) {
if (!is_writable($absoluteFilename)) {
$this->_errors[] = sprintf(__('Could not overwrite file'), $absoluteFilename);
zip_close($zip);
return false;
}
} else {
if (!touch($absoluteFilename)) {
$this->_errors[] = sprintf(__('File could not be created'), $absoluteFilename);
zip_close($zip);
return false;
}
}
$updateHandle = @fopen($absoluteFilename, 'w');
if (!$updateHandle) {
$this->_errors[] = sprintf(__('Could not open file'), $absoluteFilename);
zip_close($zip);
return false;
}
if (!fwrite($updateHandle, $contents)) {
$this->_errors[] = sprintf(__('Could not write to file'), $absoluteFilename);
zip_close($zip);
return false;
}
fclose($updateHandle);
//If file is a update script, include
if ($filename == $this->updateScriptName) {
$upgradeScript = true;
require($absoluteFilename);
if (!unlink($absoluteFilename)) {
$this->_warnings[] = sprintf(__('Could not delete update script'), $absoluteFilename);
}
}
}
zip_close($zip);
return true;
}
/**
* Update to the latest version
*
* @param bool $simulateInstall Check for directory and file permissions before copying files (Default: true)
* @param bool $deleteDownload Delete download after update (Default: true)
*
* @return mixed integer|bool
*/
public function update($simulateInstall = true, $deleteDownload = true)
{
// Check for latest version
if ($this->_latestVersion === null || count($this->_updates) === 0) {
$this->checkUpdate();
}
if ($this->_latestVersion === null || count($this->_updates) === 0) {
$this->_errors[] = __('Could not get latest version');
return self::ERROR_VERSION_CHECK;
}
// Check if current version is up to date
if (!$this->newVersionAvailable()) {
// $this->_log->addWarning('No update available!');
return self::NO_UPDATE_AVAILABLE;
}
foreach ($this->_updates as $update) {
// Check for temp directory
if (empty($this->_tempDir) || !is_dir($this->_tempDir) || !is_writable($this->_tempDir)) {
$this->_errors[] = sprintf(__('Temporary directory not writable'), $this->_tempDir);
return self::ERROR_TEMP_DIR;
}
// Check for install directory
if (empty($this->_installDir) || !is_dir($this->_installDir) || !is_writable($this->_installDir)) {
$this->_errors[] = sprintf(__('Install directory not writable'), $this->_installDir);
return self::ERROR_INSTALL_DIR;
}
$updateFile = $this->_tempDir . $this->_rootFolder .'-v' . $update['version'] . '.zip';
// Download update
if (!is_file($updateFile)) {
if (!$this->_downloadUpdate($update['url'], $updateFile)) {
$this->_errors[] = sprintf(__('Failed to download update'), $update['url'], $updateFile);
return self::ERROR_DOWNLOAD_UPDATE;
}
}
// Install update
$result = $this->_install($updateFile, $simulateInstall, $update['version']);
if ($result === true) {
if ($deleteDownload) {
if (!@unlink($updateFile)) {
$this->_warnings[] = sprintf(__('Could not delete update file'), $updateFile);
// return self::ERROR_DELETE_TEMP_UPDATE;
}
}
} else {
if ($deleteDownload) {
if (!@unlink($updateFile)) {
$this->_warnings[] = sprintf(__('Could not delete update file'), $updateFile);
}
}
return $result;
}
}
return true;
}
}
class PluginAutoUpdater extends AutoUpdater
{
public function __construct($plugin)
{
// Construct parent class
parent::__construct(getcwd().'/temp', getcwd().'/plugins/'.$plugin->name);
// Set plugin informations
$this->setRootFolder($plugin->name);
$this->setCurrentVersion($plugin->version);
$this->setUpdateUrl(isset($plugin->updateUrl) ? $plugin->updateUrl : 'https://api.github.com/repos/featherbb/'.$plugin->name.'/releases');
}
}