-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdeploy.php
1539 lines (1263 loc) · 49.8 KB
/
mdeploy.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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Moodle deployment utility
*
* This script looks after deploying new add-ons and available updates for them
* to the local Moodle site. It can operate via both HTTP and CLI mode.
* Moodle itself calls this utility via the HTTP mode when the admin is about to
* install or update an add-on. You can use the CLI mode in your custom deployment
* shell scripts.
*
* CLI usage example:
*
* $ sudo -u apache php mdeploy.php --install \
* --package=https://moodle.org/plugins/download.php/...zip \
* --typeroot=/var/www/moodle/htdocs/blocks
* --name=loancalc
* --md5=...
* --dataroot=/var/www/moodle/data
*
* $ sudo -u apache php mdeploy.php --upgrade \
* --package=https://moodle.org/plugins/download.php/...zip \
* --typeroot=/var/www/moodle/htdocs/blocks
* --name=loancalc
* --md5=...
* --dataroot=/var/www/moodle/data
*
* When called via HTTP, additional parameters returnurl, passfile and password must be
* provided. Optional proxy configuration can be passed using parameters proxy, proxytype
* and proxyuserpwd.
*
* Changes
*
* 1.1 - Added support to install a new plugin from the Moodle Plugins directory.
* 1.0 - Initial version used in Moodle 2.4 to deploy available updates.
*
* @package core
* @subpackage mdeploy
* @version 1.1
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (defined('MOODLE_INTERNAL')) {
die('This is a standalone utility that should not be included by any other Moodle code.');
}
// Exceptions //////////////////////////////////////////////////////////////////
class invalid_coding_exception extends Exception {}
class missing_option_exception extends Exception {}
class invalid_option_exception extends Exception {}
class unauthorized_access_exception extends Exception {}
class download_file_exception extends Exception {}
class backup_folder_exception extends Exception {}
class zip_exception extends Exception {}
class filesystem_exception extends Exception {}
class checksum_exception extends Exception {}
// Various support classes /////////////////////////////////////////////////////
/**
* Base class implementing the singleton pattern using late static binding feature.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class singleton_pattern {
/** @var array singleton_pattern instances */
protected static $singletoninstances = array();
/**
* Factory method returning the singleton instance.
*
* Subclasses may want to override the {@link self::initialize()} method that is
* called right after their instantiation.
*
* @return mixed the singleton instance
*/
final public static function instance() {
$class = get_called_class();
if (!isset(static::$singletoninstances[$class])) {
static::$singletoninstances[$class] = new static();
static::$singletoninstances[$class]->initialize();
}
return static::$singletoninstances[$class];
}
/**
* Optional post-instantiation code.
*/
protected function initialize() {
// Do nothing in this base class.
}
/**
* Direct instantiation not allowed, use the factory method {@link instance()}
*/
final protected function __construct() {
}
/**
* Sorry, this is singleton.
*/
final protected function __clone() {
}
}
// User input handling /////////////////////////////////////////////////////////
/**
* Provides access to the script options.
*
* Implements the delegate pattern by dispatching the calls to appropriate
* helper class (CLI or HTTP).
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class input_manager extends singleton_pattern {
const TYPE_FILE = 'file'; // File name
const TYPE_FLAG = 'flag'; // No value, just a flag (switch)
const TYPE_INT = 'int'; // Integer
const TYPE_PATH = 'path'; // Full path to a file or a directory
const TYPE_RAW = 'raw'; // Raw value, keep as is
const TYPE_URL = 'url'; // URL to a file
const TYPE_PLUGIN = 'plugin'; // Plugin name
const TYPE_MD5 = 'md5'; // MD5 hash
/** @var input_cli_provider|input_http_provider the provider of the input */
protected $inputprovider = null;
/**
* Returns the value of an option passed to the script.
*
* If the caller passes just the $name, the requested argument is considered
* required. The caller may specify the second argument which then
* makes the argument optional with the given default value.
*
* If the type of the $name option is TYPE_FLAG (switch), this method returns
* true if the flag has been passed or false if it was not. Specifying the
* default value makes no sense in this case and leads to invalid coding exception.
*
* The array options are not supported.
*
* @example $filename = $input->get_option('f');
* @example $filename = $input->get_option('filename');
* @example if ($input->get_option('verbose')) { ... }
* @param string $name
* @return mixed
*/
public function get_option($name, $default = 'provide_default_value_explicitly') {
$this->validate_option_name($name);
$info = $this->get_option_info($name);
if ($info->type === input_manager::TYPE_FLAG) {
return $this->inputprovider->has_option($name);
}
if (func_num_args() == 1) {
return $this->get_required_option($name);
} else {
return $this->get_optional_option($name, $default);
}
}
/**
* Returns the meta-information about the given option.
*
* @param string|null $name short or long option name, defaults to returning the list of all
* @return array|object|false array with all, object with the specific option meta-information or false of no such an option
*/
public function get_option_info($name=null) {
$supportedoptions = array(
array('', 'passfile', input_manager::TYPE_FILE, 'File name of the passphrase file (HTTP access only)'),
array('', 'password', input_manager::TYPE_RAW, 'Session passphrase (HTTP access only)'),
array('', 'proxy', input_manager::TYPE_RAW, 'HTTP proxy host and port (e.g. \'our.proxy.edu:8888\')'),
array('', 'proxytype', input_manager::TYPE_RAW, 'Proxy type (HTTP or SOCKS5)'),
array('', 'proxyuserpwd', input_manager::TYPE_RAW, 'Proxy username and password (e.g. \'username:password\')'),
array('', 'returnurl', input_manager::TYPE_URL, 'Return URL (HTTP access only)'),
array('d', 'dataroot', input_manager::TYPE_PATH, 'Full path to the dataroot (moodledata) directory'),
array('h', 'help', input_manager::TYPE_FLAG, 'Prints usage information'),
array('i', 'install', input_manager::TYPE_FLAG, 'Installation mode'),
array('m', 'md5', input_manager::TYPE_MD5, 'Expected MD5 hash of the ZIP package to deploy'),
array('n', 'name', input_manager::TYPE_PLUGIN, 'Plugin name (the name of its folder)'),
array('p', 'package', input_manager::TYPE_URL, 'URL to the ZIP package to deploy'),
array('r', 'typeroot', input_manager::TYPE_PATH, 'Full path of the container for this plugin type'),
array('u', 'upgrade', input_manager::TYPE_FLAG, 'Upgrade mode'),
);
if (is_null($name)) {
$all = array();
foreach ($supportedoptions as $optioninfo) {
$info = new stdClass();
$info->shortname = $optioninfo[0];
$info->longname = $optioninfo[1];
$info->type = $optioninfo[2];
$info->desc = $optioninfo[3];
$all[] = $info;
}
return $all;
}
$found = false;
foreach ($supportedoptions as $optioninfo) {
if (strlen($name) == 1) {
// Search by the short option name
if ($optioninfo[0] === $name) {
$found = $optioninfo;
break;
}
} else {
// Search by the long option name
if ($optioninfo[1] === $name) {
$found = $optioninfo;
break;
}
}
}
if (!$found) {
return false;
}
$info = new stdClass();
$info->shortname = $found[0];
$info->longname = $found[1];
$info->type = $found[2];
$info->desc = $found[3];
return $info;
}
/**
* Casts the value to the given type.
*
* @param mixed $raw the raw value
* @param string $type the expected value type, e.g. {@link input_manager::TYPE_INT}
* @return mixed
*/
public function cast_value($raw, $type) {
if (is_array($raw)) {
throw new invalid_coding_exception('Unsupported array option.');
} else if (is_object($raw)) {
throw new invalid_coding_exception('Unsupported object option.');
}
switch ($type) {
case input_manager::TYPE_FILE:
$raw = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $raw);
$raw = preg_replace('~\.\.+~', '', $raw);
if ($raw === '.') {
$raw = '';
}
return $raw;
case input_manager::TYPE_FLAG:
return true;
case input_manager::TYPE_INT:
return (int)$raw;
case input_manager::TYPE_PATH:
if (strpos($raw, '~') !== false) {
throw new invalid_option_exception('Using the tilde (~) character in paths is not supported');
}
$colonpos = strpos($raw, ':');
if ($colonpos !== false) {
if ($colonpos !== 1 or strrpos($raw, ':') !== 1) {
throw new invalid_option_exception('Using the colon (:) character in paths is supported for Windows drive labels only.');
}
if (preg_match('/^[a-zA-Z]:/', $raw) !== 1) {
throw new invalid_option_exception('Using the colon (:) character in paths is supported for Windows drive labels only.');
}
}
$raw = str_replace('\\', '/', $raw);
$raw = preg_replace('~[[:cntrl:]]|[&<>"`\|\']~u', '', $raw);
$raw = preg_replace('~\.\.+~', '', $raw);
$raw = preg_replace('~//+~', '/', $raw);
$raw = preg_replace('~/(\./)+~', '/', $raw);
return $raw;
case input_manager::TYPE_RAW:
return $raw;
case input_manager::TYPE_URL:
$regex = '^(https?|ftp)\:\/\/'; // protocol
$regex .= '([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?'; // optional user and password
$regex .= '[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*'; // hostname or IP (one word like http://localhost/ allowed)
$regex .= '(\:[0-9]{2,5})?'; // port (optional)
$regex .= '(\/([a-z0-9+\$_-]\.?)+)*\/?'; // path to the file
$regex .= '(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?'; // HTTP params
if (preg_match('#'.$regex.'#i', $raw)) {
return $raw;
} else {
throw new invalid_option_exception('Not a valid URL');
}
case input_manager::TYPE_PLUGIN:
if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $raw)) {
throw new invalid_option_exception('Invalid plugin name');
}
if (strpos($raw, '__') !== false) {
throw new invalid_option_exception('Invalid plugin name');
}
return $raw;
case input_manager::TYPE_MD5:
if (!preg_match('/^[a-f0-9]{32}$/', $raw)) {
throw new invalid_option_exception('Invalid MD5 hash format');
}
return $raw;
default:
throw new invalid_coding_exception('Unknown option type.');
}
}
/**
* Picks the appropriate helper class to delegate calls to.
*/
protected function initialize() {
if (PHP_SAPI === 'cli') {
$this->inputprovider = input_cli_provider::instance();
} else {
$this->inputprovider = input_http_provider::instance();
}
}
// End of external API
/**
* Validates the parameter name.
*
* @param string $name
* @throws invalid_coding_exception
*/
protected function validate_option_name($name) {
if (empty($name)) {
throw new invalid_coding_exception('Invalid empty option name.');
}
$meta = $this->get_option_info($name);
if (empty($meta)) {
throw new invalid_coding_exception('Invalid option name: '.$name);
}
}
/**
* Returns cleaned option value or throws exception.
*
* @param string $name the name of the parameter
* @param string $type the parameter type, e.g. {@link input_manager::TYPE_INT}
* @return mixed
*/
protected function get_required_option($name) {
if ($this->inputprovider->has_option($name)) {
return $this->inputprovider->get_option($name);
} else {
throw new missing_option_exception('Missing required option: '.$name);
}
}
/**
* Returns cleaned option value or the default value
*
* @param string $name the name of the parameter
* @param string $type the parameter type, e.g. {@link input_manager::TYPE_INT}
* @param mixed $default the default value.
* @return mixed
*/
protected function get_optional_option($name, $default) {
if ($this->inputprovider->has_option($name)) {
return $this->inputprovider->get_option($name);
} else {
return $default;
}
}
}
/**
* Base class for input providers.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class input_provider extends singleton_pattern {
/** @var array list of all passed valid options */
protected $options = array();
/**
* Returns the casted value of the option.
*
* @param string $name option name
* @throws invalid_coding_exception if the option has not been passed
* @return mixed casted value of the option
*/
public function get_option($name) {
if (!$this->has_option($name)) {
throw new invalid_coding_exception('Option not passed: '.$name);
}
return $this->options[$name];
}
/**
* Was the given option passed?
*
* @param string $name optionname
* @return bool
*/
public function has_option($name) {
return array_key_exists($name, $this->options);
}
/**
* Initializes the input provider.
*/
protected function initialize() {
$this->populate_options();
}
// End of external API
/**
* Parses and validates all supported options passed to the script.
*/
protected function populate_options() {
$input = input_manager::instance();
$raw = $this->parse_raw_options();
$cooked = array();
foreach ($raw as $k => $v) {
if (is_array($v) or is_object($v)) {
// Not supported.
}
$info = $input->get_option_info($k);
if (!$info) {
continue;
}
$casted = $input->cast_value($v, $info->type);
if (!empty($info->shortname)) {
$cooked[$info->shortname] = $casted;
}
if (!empty($info->longname)) {
$cooked[$info->longname] = $casted;
}
}
// Store the options.
$this->options = $cooked;
}
}
/**
* Provides access to the script options passed via CLI.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class input_cli_provider extends input_provider {
/**
* Parses raw options passed to the script.
*
* @return array as returned by getopt()
*/
protected function parse_raw_options() {
$input = input_manager::instance();
// Signatures of some in-built PHP functions are just crazy, aren't they.
$short = '';
$long = array();
foreach ($input->get_option_info() as $option) {
if ($option->type === input_manager::TYPE_FLAG) {
// No value expected for this option.
$short .= $option->shortname;
$long[] = $option->longname;
} else {
// A value expected for the option, all considered as optional.
$short .= empty($option->shortname) ? '' : $option->shortname.'::';
$long[] = empty($option->longname) ? '' : $option->longname.'::';
}
}
return getopt($short, $long);
}
}
/**
* Provides access to the script options passed via HTTP request.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class input_http_provider extends input_provider {
/**
* Parses raw options passed to the script.
*
* @return array of raw values passed via HTTP request
*/
protected function parse_raw_options() {
return $_POST;
}
}
// Output handling /////////////////////////////////////////////////////////////
/**
* Provides output operations.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class output_manager extends singleton_pattern {
/** @var output_cli_provider|output_http_provider the provider of the output functionality */
protected $outputprovider = null;
/**
* Magic method triggered when invoking an inaccessible method.
*
* @param string $name method name
* @param array $arguments method arguments
*/
public function __call($name, array $arguments = array()) {
call_user_func_array(array($this->outputprovider, $name), $arguments);
}
/**
* Picks the appropriate helper class to delegate calls to.
*/
protected function initialize() {
if (PHP_SAPI === 'cli') {
$this->outputprovider = output_cli_provider::instance();
} else {
$this->outputprovider = output_http_provider::instance();
}
}
}
/**
* Base class for all output providers.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class output_provider extends singleton_pattern {
}
/**
* Provides output to the command line.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class output_cli_provider extends output_provider {
/**
* Prints help information in CLI mode.
*/
public function help() {
$this->outln('mdeploy.php - Moodle (http://moodle.org) deployment utility');
$this->outln();
$this->outln('Usage: $ sudo -u apache php mdeploy.php [options]');
$this->outln();
$input = input_manager::instance();
foreach($input->get_option_info() as $info) {
$option = array();
if (!empty($info->shortname)) {
$option[] = '-'.$info->shortname;
}
if (!empty($info->longname)) {
$option[] = '--'.$info->longname;
}
$this->outln(sprintf('%-20s %s', implode(', ', $option), $info->desc));
}
}
// End of external API
/**
* Writes a text to the STDOUT followed by a new line character.
*
* @param string $text text to print
*/
protected function outln($text='') {
fputs(STDOUT, $text.PHP_EOL);
}
}
/**
* Provides HTML output as a part of HTTP response.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class output_http_provider extends output_provider {
/**
* Prints help on the script usage.
*/
public function help() {
// No help available via HTTP
}
/**
* Display the information about uncaught exception
*
* @param Exception $e uncaught exception
*/
public function exception(Exception $e) {
$docslink = 'http://docs.moodle.org/en/admin/mdeploy/'.get_class($e);
$this->start_output();
echo('<h1>Oops! It did it again</h1>');
echo('<p><strong>Moodle deployment utility had a trouble with your request.
See <a href="'.$docslink.'">the docs page</a> and the debugging information for more details.</strong></p>');
echo('<pre>');
echo exception_handlers::format_exception_info($e);
echo('</pre>');
$this->end_output();
}
// End of external API
/**
* Produce the HTML page header
*/
protected function start_output() {
echo '<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
body {background-color:#666;font-family:"DejaVu Sans","Liberation Sans",Freesans,sans-serif;}
h1 {text-align:center;}
pre {white-space: pre-wrap;}
#page {background-color:#eee;width:1024px;margin:5em auto;border:3px solid #333;border-radius: 15px;padding:1em;}
</style>
</head>
<body>
<div id="page">';
}
/**
* Produce the HTML page footer
*/
protected function end_output() {
echo '</div></body></html>';
}
}
// The main class providing all the functionality //////////////////////////////
/**
* The actual worker class implementing the main functionality of the script.
*
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class worker extends singleton_pattern {
const EXIT_OK = 0; // Success exit code.
const EXIT_HELP = 1; // Explicit help required.
const EXIT_UNKNOWN_ACTION = 127; // Neither -i nor -u provided.
/** @var input_manager */
protected $input = null;
/** @var output_manager */
protected $output = null;
/** @var int the most recent cURL error number, zero for no error */
private $curlerrno = null;
/** @var string the most recent cURL error message, empty string for no error */
private $curlerror = null;
/** @var array|false the most recent cURL request info, if it was successful */
private $curlinfo = null;
/** @var string the full path to the log file */
private $logfile = null;
/**
* Main - the one that actually does something
*/
public function execute() {
$this->log('=== MDEPLOY EXECUTION START ===');
// Authorize access. None in CLI. Passphrase in HTTP.
$this->authorize();
// Asking for help in the CLI mode.
if ($this->input->get_option('help')) {
$this->output->help();
$this->done(self::EXIT_HELP);
}
if ($this->input->get_option('upgrade')) {
$this->log('Plugin upgrade requested');
// Fetch the ZIP file into a temporary location.
$source = $this->input->get_option('package');
$target = $this->target_location($source);
$this->log('Downloading package '.$source);
if ($this->download_file($source, $target)) {
$this->log('Package downloaded into '.$target);
} else {
$this->log('cURL error ' . $this->curlerrno . ' ' . $this->curlerror);
$this->log('Unable to download the file from ' . $source . ' into ' . $target);
throw new download_file_exception('Unable to download the package');
}
// Compare MD5 checksum of the ZIP file
$md5remote = $this->input->get_option('md5');
$md5local = md5_file($target);
if ($md5local !== $md5remote) {
$this->log('MD5 checksum failed. Expected: '.$md5remote.' Got: '.$md5local);
throw new checksum_exception('MD5 checksum failed');
}
$this->log('MD5 checksum ok');
// Backup the current version of the plugin
$plugintyperoot = $this->input->get_option('typeroot');
$pluginname = $this->input->get_option('name');
$sourcelocation = $plugintyperoot.'/'.$pluginname;
$backuplocation = $this->backup_location($sourcelocation);
$this->log('Current plugin code location: '.$sourcelocation);
$this->log('Moving the current code into archive: '.$backuplocation);
if (file_exists($sourcelocation)) {
// We don't want to touch files unless we are pretty sure it would be all ok.
if (!$this->move_directory_source_precheck($sourcelocation)) {
throw new backup_folder_exception('Unable to backup the current version of the plugin (source precheck failed)');
}
if (!$this->move_directory_target_precheck($backuplocation)) {
throw new backup_folder_exception('Unable to backup the current version of the plugin (backup precheck failed)');
}
// Looking good, let's try it.
if (!$this->move_directory($sourcelocation, $backuplocation, true)) {
throw new backup_folder_exception('Unable to backup the current version of the plugin (moving failed)');
}
} else {
// Upgrading missing plugin - this happens often during upgrades.
if (!$this->create_directory_precheck($sourcelocation)) {
throw new filesystem_exception('Unable to prepare the plugin location (cannot create new directory)');
}
}
// Unzip the plugin package file into the target location.
$this->unzip_plugin($target, $plugintyperoot, $sourcelocation, $backuplocation);
$this->log('Package successfully extracted');
// Redirect to the given URL (in HTTP) or exit (in CLI).
$this->done();
} else if ($this->input->get_option('install')) {
$this->log('Plugin installation requested');
$plugintyperoot = $this->input->get_option('typeroot');
$pluginname = $this->input->get_option('name');
$source = $this->input->get_option('package');
$md5remote = $this->input->get_option('md5');
// Check if the plugin location if available for us.
$pluginlocation = $plugintyperoot.'/'.$pluginname;
$this->log('New plugin code location: '.$pluginlocation);
if (file_exists($pluginlocation)) {
throw new filesystem_exception('Unable to prepare the plugin location (directory already exists)');
}
if (!$this->create_directory_precheck($pluginlocation)) {
throw new filesystem_exception('Unable to prepare the plugin location (cannot create new directory)');
}
// Fetch the ZIP file into a temporary location.
$target = $this->target_location($source);
$this->log('Downloading package '.$source);
if ($this->download_file($source, $target)) {
$this->log('Package downloaded into '.$target);
} else {
$this->log('cURL error ' . $this->curlerrno . ' ' . $this->curlerror);
$this->log('Unable to download the file');
throw new download_file_exception('Unable to download the package');
}
// Compare MD5 checksum of the ZIP file
$md5local = md5_file($target);
if ($md5local !== $md5remote) {
$this->log('MD5 checksum failed. Expected: '.$md5remote.' Got: '.$md5local);
throw new checksum_exception('MD5 checksum failed');
}
$this->log('MD5 checksum ok');
// Unzip the plugin package file into the plugin location.
$this->unzip_plugin($target, $plugintyperoot, $pluginlocation, false);
$this->log('Package successfully extracted');
// Redirect to the given URL (in HTTP) or exit (in CLI).
$this->done();
}
// Print help in CLI by default.
$this->output->help();
$this->done(self::EXIT_UNKNOWN_ACTION);
}
/**
* Attempts to log a thrown exception
*
* @param Exception $e uncaught exception
*/
public function log_exception(Exception $e) {
$this->log($e->__toString());
}
/**
* Initialize the worker class.
*/
protected function initialize() {
$this->input = input_manager::instance();
$this->output = output_manager::instance();
}
// End of external API
/**
* Finish this script execution.
*
* @param int $exitcode
*/
protected function done($exitcode = self::EXIT_OK) {
if (PHP_SAPI === 'cli') {
exit($exitcode);
} else {
$returnurl = $this->input->get_option('returnurl');
$this->redirect($returnurl);
exit($exitcode);
}
}
/**
* Authorize access to the script.
*
* In CLI mode, the access is automatically authorized. In HTTP mode, the
* passphrase submitted via the request params must match the contents of the
* file, the name of which is passed in another parameter.
*
* @throws unauthorized_access_exception
*/
protected function authorize() {
if (PHP_SAPI === 'cli') {
$this->log('Successfully authorized using the CLI SAPI');
return;
}
$dataroot = $this->input->get_option('dataroot');
$passfile = $this->input->get_option('passfile');
$password = $this->input->get_option('password');
$passpath = $dataroot.'/mdeploy/auth/'.$passfile;
if (!is_readable($passpath)) {
throw new unauthorized_access_exception('Unable to read the passphrase file.');
}
$stored = file($passpath, FILE_IGNORE_NEW_LINES);
// "This message will self-destruct in five seconds." -- Mission Commander Swanbeck, Mission: Impossible II
unlink($passpath);
if (is_readable($passpath)) {
throw new unauthorized_access_exception('Unable to remove the passphrase file.');
}
if (count($stored) < 2) {
throw new unauthorized_access_exception('Invalid format of the passphrase file.');
}
if (time() - (int)$stored[1] > 30 * 60) {
throw new unauthorized_access_exception('Passphrase timeout.');
}
if (strlen($stored[0]) < 24) {
throw new unauthorized_access_exception('Session passphrase not long enough.');
}
if ($password !== $stored[0]) {
throw new unauthorized_access_exception('Session passphrase does not match the stored one.');
}
$this->log('Successfully authorized using the passphrase file');
}
/**
* Returns the full path to the log file.
*
* @return string
*/
protected function log_location() {
if (!is_null($this->logfile)) {
return $this->logfile;
}
$dataroot = $this->input->get_option('dataroot', '');
if (empty($dataroot)) {
$this->logfile = false;
return $this->logfile;
}
$myroot = $dataroot.'/mdeploy';
if (!is_dir($myroot)) {
mkdir($myroot, 02777, true);
}
$this->logfile = $myroot.'/mdeploy.log';
return $this->logfile;
}
/**
* Choose the target location for the given ZIP's URL.
*
* @param string $source URL
* @return string
*/
protected function target_location($source) {
$dataroot = $this->input->get_option('dataroot');
$pool = $dataroot.'/mdeploy/var';
if (!is_dir($pool)) {
mkdir($pool, 02777, true);
}
$target = $pool.'/'.md5($source);