3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This library includes all the necessary stuff to use the one-click
20 * download and install feature of Moodle, used to keep updated some
21 * items like languages, pear, enviroment... i.e, components.
23 * It has been developed harcoding some important limits that are
25 * - It only can check, download and install items under moodledata.
26 * - Every downloadeable item must be one zip file.
27 * - The zip file root content must be 1 directory, i.e, everything
28 * is stored under 1 directory.
29 * - Zip file name and root directory must have the same name (but
30 * the .zip extension, of course).
31 * - Every .zip file must be defined in one .md5 file that will be
32 * stored in the same remote directory than the .zip file.
33 * - The name of such .md5 file is free, although it's recommended
34 * to use the same name than the .zip (that's the default
35 * assumption if no specified).
36 * - Every remote .md5 file will be a comma separated (CVS) file where each
37 * line will follow this format:
38 * - Field 1: name of the zip file (without extension). Mandatory.
39 * - Field 2: md5 of the zip file. Mandatory.
40 * - Field 3: whatever you want (or need). Optional.
41 * -Every local .md5 file will:
42 * - Have the zip file name (without the extension) plus -md5
43 * - Will reside inside the expanded zip file dir
44 * - Will contain the md5 od the latest installed component
45 * With all these details present, the process will perform this tasks:
46 * - Perform security checks. Only admins are allowed to use this for now.
47 * - Read the .md5 file from source (1).
48 * - Extract the correct line for the .zip being requested.
49 * - Compare it with the local .md5 file (2).
51 * - Download the newer .zip file from source.
52 * - Calculate its md5 (3).
53 * - Compare (1) and (3).
55 * - Delete old directory.
56 * - Uunzip the newer .zip file.
57 * - Create the new local .md5 file.
58 * - Delete the .zip file.
60 * - ERROR. Old package won't be modified. We shouldn't
62 * - If component download is not possible, a message text about how to do
63 * the process manually (remotedownloaderror) must be displayed to explain it.
67 * To install one component:
69 * require_once($CFG->libdir.'/componentlib.class.php');
70 * if ($cd = new component_installer('https://download.moodle.org', 'langpack/2.0',
71 * 'es.zip', 'languages.md5', 'lang')) {
72 * $status = $cd->install(); //returns COMPONENT_(ERROR | UPTODATE | INSTALLED)
74 * case COMPONENT_ERROR:
75 * if ($cd->get_error() == 'remotedownloaderror') {
76 * $a = new stdClass();
77 * $a->url = 'https://download.moodle.org/langpack/2.0/es.zip';
78 * $a->dest= $CFG->dataroot.'/lang';
79 * print_error($cd->get_error(), 'error', '', $a);
81 * print_error($cd->get_error(), 'error');
84 * case COMPONENT_UPTODATE:
85 * //Print error string or whatever you want to do
87 * case COMPONENT_INSTALLED:
88 * //Print/do whatever you want
91 * //We shouldn't reach this point
94 * //We shouldn't reach this point
98 * To switch of component (maintaining the rest of settings):
100 * $status = $cd->change_zip_file('en.zip'); //returns boolean false on error
103 * To retrieve all the components in one remote md5 file
105 * $components = $cd->get_all_components_md5(); //returns boolean false on error, array instead
108 * To check if current component needs to be updated
110 * $status = $cd->need_upgrade(); //returns COMPONENT_(ERROR | UPTODATE | NEEDUPDATE)
113 * To get the 3rd field of the md5 file (optional)
115 * $field = $cd->get_extra_md5_field(); //returns string (empty if not exists)
118 * For all the error situations the $cd->get_error() method should return always the key of the
119 * error to be retrieved by one standard get_string() call against the error.php lang file.
124 * @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
128 defined('MOODLE_INTERNAL') ||
die();
131 * @global object $CFG
135 require_once($CFG->libdir
.'/filelib.php');
137 // Some needed constants
138 define('COMPONENT_ERROR', 0);
139 define('COMPONENT_UPTODATE', 1);
140 define('COMPONENT_NEEDUPDATE', 2);
141 define('COMPONENT_INSTALLED', 3);
144 * This class is used to check, download and install items from
145 * download.moodle.org to the moodledata directory.
147 * It always return true/false in all their public methods to say if
148 * execution has ended succesfuly or not. If there is any problem
149 * its getError() method can be called, returning one error string
150 * to be used with the standard get/print_string() functions.
152 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
153 * @package moodlecore
155 class component_installer
{
159 var $sourcebase; /// Full http URL, base for downloadable items
160 var $zippath; /// Relative path (from sourcebase) where the
161 /// downloadeable item resides.
162 var $zipfilename; /// Name of the .zip file to be downloaded
163 var $md5filename; /// Name of the .md5 file to be read
164 var $componentname;/// Name of the component. Must be the zip name without
165 /// the extension. And it defines a lot of things:
166 /// the md5 line to search for, the default m5 file name
167 /// and the name of the root dir stored inside the zip file
168 var $destpath; /// Relative path (from moodledata) where the .zip
169 /// file will be expanded.
170 var $errorstring; /// Latest error produced. It will contain one lang string key.
171 var $extramd5info; /// Contents of the optional third field in the .md5 file.
172 var $requisitesok; /// Flag to see if requisites check has been passed ok.
176 var $cachedmd5components; /// Array of cached components to avoid to
177 /// download the same md5 file more than once per request.
180 * Standard constructor of the class. It will initialize all attributes.
181 * without performing any check at all.
183 * @param string $sourcebase Full http URL, base for downloadeable items
184 * @param string $zippath Relative path (from sourcebase) where the
185 * downloadeable item resides
186 * @param string $zipfilename Name of the .zip file to be downloaded
187 * @param string $md5filename Name of the .md5 file to be read (default '' = same
189 * @param string $destpath Relative path (from moodledata) where the .zip file will
190 * be expanded (default='' = moodledataitself)
193 public function __construct($sourcebase, $zippath, $zipfilename, $md5filename='', $destpath='') {
195 $this->sourcebase
= $sourcebase;
196 $this->zippath
= $zippath;
197 $this->zipfilename
= $zipfilename;
198 $this->md5filename
= $md5filename;
199 $this->componentname
= '';
200 $this->destpath
= $destpath;
201 $this->errorstring
= '';
202 $this->extramd5info
= '';
203 $this->requisitesok
= false;
204 $this->cachedmd5components
= array();
206 $this->check_requisites();
210 * Old syntax of class constructor. Deprecated in PHP7.
212 public function component_installer($sourcebase, $zippath, $zipfilename, $md5filename='', $destpath='') {
213 self
::__construct($sourcebase, $zippath, $zipfilename, $md5filename, $destpath);
217 * This function will check if everything is properly set to begin
218 * one installation. Also, it will check for required settings
219 * and will fill everything as needed.
222 * @return boolean true/false (plus detailed error in errorstring)
224 function check_requisites() {
227 $this->requisitesok
= false;
229 /// Check that everything we need is present
230 if (empty($this->sourcebase
) ||
empty($this->zipfilename
)) {
231 $this->errorstring
='missingrequiredfield';
234 /// Check for correct sourcebase (this will be out in the future)
235 if (!PHPUNIT_TEST
and $this->sourcebase
!= 'https://download.moodle.org') {
236 $this->errorstring
='wrongsourcebase';
239 /// Check the zip file is a correct one (by extension)
240 if (stripos($this->zipfilename
, '.zip') === false) {
241 $this->errorstring
='wrongzipfilename';
244 /// Check that exists under dataroot
245 if (!empty($this->destpath
)) {
246 if (!file_exists($CFG->dataroot
.'/'.$this->destpath
)) {
247 $this->errorstring
='wrongdestpath';
251 /// Calculate the componentname
252 $pos = stripos($this->zipfilename
, '.zip');
253 $this->componentname
= substr($this->zipfilename
, 0, $pos);
254 /// Calculate md5filename if it's empty
255 if (empty($this->md5filename
)) {
256 $this->md5filename
= $this->componentname
.'.md5';
258 /// Set the requisites passed flag
259 $this->requisitesok
= true;
264 * This function will perform the full installation if needed, i.e.
265 * compare md5 values, download, unzip, install and regenerate
269 * @uses COMPONENT_ERROR
270 * @uses COMPONENT_UPTODATE
271 * @uses COMPONENT_ERROR
272 * @uses COMPONENT_INSTALLED
273 * @return int COMPONENT_(ERROR | UPTODATE | INSTALLED)
279 /// Check requisites are passed
280 if (!$this->requisitesok
) {
281 return COMPONENT_ERROR
;
283 /// Confirm we need upgrade
284 if ($this->need_upgrade() === COMPONENT_ERROR
) {
285 return COMPONENT_ERROR
;
286 } else if ($this->need_upgrade() === COMPONENT_UPTODATE
) {
287 $this->errorstring
='componentisuptodate';
288 return COMPONENT_UPTODATE
;
290 /// Create temp directory if necesary
291 if (!make_temp_directory('', false)) {
292 $this->errorstring
='cannotcreatetempdir';
293 return COMPONENT_ERROR
;
295 /// Download zip file and save it to temp
296 if ($this->zippath
) {
297 $source = $this->sourcebase
.'/'.$this->zippath
.'/'.$this->zipfilename
;
299 $source = $this->sourcebase
.'/'.$this->zipfilename
;
302 $zipfile= $CFG->tempdir
.'/'.$this->zipfilename
;
304 if($contents = download_file_content($source)) {
305 if ($file = fopen($zipfile, 'w')) {
306 if (!fwrite($file, $contents)) {
308 $this->errorstring
='cannotsavezipfile';
309 return COMPONENT_ERROR
;
312 $this->errorstring
='cannotsavezipfile';
313 return COMPONENT_ERROR
;
317 $this->errorstring
='cannotdownloadzipfile';
318 return COMPONENT_ERROR
;
320 /// Calculate its md5
321 $new_md5 = md5($contents);
322 /// Compare it with the remote md5 to check if we have the correct zip file
323 if (!$remote_md5 = $this->get_component_md5()) {
324 return COMPONENT_ERROR
;
326 if ($new_md5 != $remote_md5) {
327 $this->errorstring
='downloadedfilecheckfailed';
328 return COMPONENT_ERROR
;
330 /// Move current revision to a safe place
331 $destinationdir = $CFG->dataroot
.'/'.$this->destpath
;
332 $destinationcomponent = $destinationdir.'/'.$this->componentname
;
333 @remove_dir
($destinationcomponent.'_old'); // Deleting a possible old version.
335 // Moving to a safe place.
336 @rename
($destinationcomponent, $destinationcomponent.'_old');
338 /// Unzip new version
339 if (!unzip_file($zipfile, $destinationdir, false)) {
340 /// Error so, go back to the older
341 @remove_dir
($destinationcomponent);
342 @rename
($destinationcomponent.'_old', $destinationcomponent);
343 $this->errorstring
='cannotunzipfile';
344 return COMPONENT_ERROR
;
346 /// Delete old component version
347 @remove_dir
($destinationcomponent.'_old');
349 if ($file = fopen($destinationcomponent.'/'.$this->componentname
.'.md5', 'w')) {
350 if (!fwrite($file, $new_md5)) {
352 $this->errorstring
='cannotsavemd5file';
353 return COMPONENT_ERROR
;
356 $this->errorstring
='cannotsavemd5file';
357 return COMPONENT_ERROR
;
360 /// Delete temp zip file
363 return COMPONENT_INSTALLED
;
367 * This function will detect if remote component needs to be installed
368 * because it's different from the local one
370 * @uses COMPONENT_ERROR
371 * @uses COMPONENT_UPTODATE
372 * @uses COMPONENT_NEEDUPDATE
373 * @return int COMPONENT_(ERROR | UPTODATE | NEEDUPDATE)
375 function need_upgrade() {
377 /// Check requisites are passed
378 if (!$this->requisitesok
) {
379 return COMPONENT_ERROR
;
382 $local_md5 = $this->get_local_md5();
384 if (!$remote_md5 = $this->get_component_md5()) {
385 return COMPONENT_ERROR
;
388 if ($local_md5 == $remote_md5) {
389 return COMPONENT_UPTODATE
;
391 return COMPONENT_NEEDUPDATE
;
396 * This function will change the zip file to install on the fly
397 * to allow the class to process different components of the
398 * same md5 file without intantiating more objects.
400 * @param string $newzipfilename New zip filename to process
401 * @return boolean true/false
403 function change_zip_file($newzipfilename) {
405 $this->zipfilename
= $newzipfilename;
406 return $this->check_requisites();
410 * This function will get the local md5 value of the installed
414 * @return bool|string md5 of the local component (false on error)
416 function get_local_md5() {
419 /// Check requisites are passed
420 if (!$this->requisitesok
) {
424 $return_value = 'needtobeinstalled'; /// Fake value to force new installation
426 /// Calculate source to read
427 $source = $CFG->dataroot
.'/'.$this->destpath
.'/'.$this->componentname
.'/'.$this->componentname
.'.md5';
428 /// Read md5 value stored (if exists)
429 if (file_exists($source)) {
430 if ($temp = file_get_contents($source)) {
431 $return_value = $temp;
434 return $return_value;
438 * This function will download the specified md5 file, looking for the
439 * current componentname, returning its md5 field and storing extramd5info
440 * if present. Also it caches results to cachedmd5components for better
441 * performance in the same request.
443 * @return mixed md5 present in server (or false if error)
445 function get_component_md5() {
447 /// Check requisites are passed
448 if (!$this->requisitesok
) {
451 /// Get all components of md5 file
452 if (!$comp_arr = $this->get_all_components_md5()) {
453 if (empty($this->errorstring
)) {
454 $this->errorstring
='cannotdownloadcomponents';
458 /// Search for the componentname component
459 if (empty($comp_arr[$this->componentname
]) ||
!$component = $comp_arr[$this->componentname
]) {
460 $this->errorstring
='cannotfindcomponent';
463 /// Check we have a valid md5
464 if (empty($component[1]) ||
strlen($component[1]) != 32) {
465 $this->errorstring
='invalidmd5';
468 /// Set the extramd5info field
469 if (!empty($component[2])) {
470 $this->extramd5info
= $component[2];
472 return $component[1];
476 * This function allows you to retrieve the complete array of components found in
479 * @return bool|array array of components in md5 file or false if error
481 function get_all_components_md5() {
483 /// Check requisites are passed
484 if (!$this->requisitesok
) {
488 /// Initialize components array
491 /// Define and retrieve the full md5 file
492 if ($this->zippath
) {
493 $source = $this->sourcebase
.'/'.$this->zippath
.'/'.$this->md5filename
;
495 $source = $this->sourcebase
.'/'.$this->md5filename
;
498 /// Check if we have downloaded the md5 file before (per request cache)
499 if (!empty($this->cachedmd5components
[$source])) {
500 $comp_arr = $this->cachedmd5components
[$source];
502 /// Not downloaded, let's do it now
503 $availablecomponents = array();
505 if ($contents = download_file_content($source)) {
506 /// Split text into lines
507 $lines=preg_split('/\r?\n/',$contents);
508 /// Each line will be one component
509 foreach($lines as $line) {
510 $availablecomponents[] = explode(',', $line);
512 /// If no components have been found, return error
513 if (empty($availablecomponents)) {
514 $this->errorstring
='cannotdownloadcomponents';
517 /// Build an associative array of components for easily search
518 /// applying trim to avoid linefeeds and other...
520 foreach ($availablecomponents as $component) {
521 /// Avoid sometimes empty lines
522 if (empty($component[0])) {
525 $component[0]=trim($component[0]);
526 if (!empty($component[1])) {
527 $component[1]=trim($component[1]);
529 if (!empty($component[2])) {
530 $component[2]=trim($component[2]);
532 $comp_arr[$component[0]] = $component;
535 $this->cachedmd5components
[$source] = $comp_arr;
538 $this->errorstring
='remotedownloaderror';
542 /// If there is no commponents or erros found, error
543 if (!empty($this->errorstring
)) {
546 } else if (empty($comp_arr)) {
547 $this->errorstring
='cannotdownloadcomponents';
554 * This function returns the errorstring
556 * @return string the error string
558 function get_error() {
559 return $this->errorstring
;
562 /** This function returns the extramd5 field (optional in md5 file)
564 * @return string the extramd5 field
566 function get_extra_md5_field() {
567 return $this->extramd5info
;
570 } /// End of component_installer class
574 * Language packs installer
576 * This class wraps the functionality provided by {@link component_installer}
577 * and adds support for installing a set of language packs.
579 * Given an array of required language packs, this class fetches them all
580 * and installs them. It detects eventual dependencies and installs
581 * all parent languages, too.
583 * @copyright 2011 David Mudrak <david@moodle.com>
584 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
586 class lang_installer
{
588 /** lang pack was successfully downloaded and deployed */
589 const RESULT_INSTALLED
= 'installed';
590 /** lang pack was up-to-date so no download was needed */
591 const RESULT_UPTODATE
= 'uptodate';
592 /** there was a problem with downloading the lang pack */
593 const RESULT_DOWNLOADERROR
= 'downloaderror';
595 /** @var array of languages to install */
596 protected $queue = array();
597 /** @var string the code of language being currently installed */
599 /** @var array of languages already installed by this instance */
600 protected $done = array();
601 /** @var string this Moodle major version */
605 * Prepare the installer
607 * @param string|array $langcode a code of the language to install
609 public function __construct($langcode = '') {
612 $this->set_queue($langcode);
613 $this->version
= moodle_major_version(true);
615 if (!empty($CFG->langotherroot
) and $CFG->langotherroot
!== $CFG->dataroot
. '/lang') {
616 debugging('The in-built language pack installer does not support alternative location ' .
617 'of languages root directory. You are supposed to install and update your language '.
618 'packs on your own.');
623 * Sets the queue of language packs to be installed
625 * @param string|array $langcodes language code like 'cs' or a list of them
627 public function set_queue($langcodes) {
628 if (is_array($langcodes)) {
629 $this->queue
= $langcodes;
630 } else if (!empty($langcodes)) {
631 $this->queue
= array($langcodes);
638 * This method calls {@link self::install_language_pack} for every language in the
639 * queue. If a dependency is detected, the parent language is added to the queue.
641 * @return array results, array of self::RESULT_xxx constants indexed by language code
643 public function run() {
647 while ($this->current
= array_shift($this->queue
)) {
649 if ($this->was_processed($this->current
)) {
650 // do not repeat yourself
654 if ($this->current
=== 'en') {
655 $this->mark_processed($this->current
);
659 $results[$this->current
] = $this->install_language_pack($this->current
);
661 if (in_array($results[$this->current
], array(self
::RESULT_INSTALLED
, self
::RESULT_UPTODATE
))) {
662 if ($parentlang = $this->get_parent_language($this->current
)) {
663 if (!$this->is_queued($parentlang) and !$this->was_processed($parentlang)) {
664 $this->add_to_queue($parentlang);
669 $this->mark_processed($this->current
);
676 * Returns the URL where a given language pack can be downloaded
678 * Alternatively, if the parameter is empty, returns URL of the page with the
679 * list of all available language packs.
681 * @param string $langcode language code like 'cs' or empty for unknown
684 public function lang_pack_url($langcode = '') {
686 if (empty($langcode)) {
687 return 'https://download.moodle.org/langpack/'.$this->version
.'/';
689 return 'https://download.moodle.org/download.php/langpack/'.$this->version
.'/'.$langcode.'.zip';
694 * Returns the list of available language packs from download.moodle.org
696 * @return array|bool false if can not download
698 public function get_remote_list_of_languages() {
699 $source = 'https://download.moodle.org/langpack/' . $this->version
. '/languages.md5';
700 $availablelangs = array();
702 if ($content = download_file_content($source)) {
703 $alllines = explode("\n", $content);
704 foreach($alllines as $line) {
706 $availablelangs[] = explode(',', $line);
709 return $availablelangs;
716 // Internal implementation /////////////////////////////////////////////////
719 * Adds a language pack (or a list of them) to the queue
721 * @param string|array $langcodes code of the language to install or a list of them
723 protected function add_to_queue($langcodes) {
724 if (is_array($langcodes)) {
725 $this->queue
= array_merge($this->queue
, $langcodes);
726 } else if (!empty($langcodes)) {
727 $this->queue
[] = $langcodes;
732 * Checks if the given language is queued or if the queue is empty
734 * @example $installer->is_queued('es'); // is Spanish going to be installed?
735 * @example $installer->is_queued(); // is there a language queued?
737 * @param string $langcode language code or empty string for "any"
740 protected function is_queued($langcode = '') {
742 if (empty($langcode)) {
743 return !empty($this->queue
);
746 return in_array($langcode, $this->queue
);
751 * Checks if the given language has already been processed by this instance
753 * @see self::mark_processed()
754 * @param string $langcode
757 protected function was_processed($langcode) {
758 return isset($this->done
[$langcode]);
762 * Mark the given language pack as processed
764 * @see self::was_processed()
765 * @param string $langcode
767 protected function mark_processed($langcode) {
768 $this->done
[$langcode] = 1;
772 * Returns a parent language of the given installed language
774 * @param string $langcode
775 * @return string parent language's code
777 protected function get_parent_language($langcode) {
778 return get_parent_language($langcode);
782 * Perform the actual language pack installation
784 * @uses component_installer
785 * @param string $langcode
786 * @return int return status
788 protected function install_language_pack($langcode) {
790 // initialise new component installer to process this language
791 $installer = new component_installer('https://download.moodle.org', 'download.php/direct/langpack/' . $this->version
,
792 $langcode . '.zip', 'languages.md5', 'lang');
794 if (!$installer->requisitesok
) {
795 throw new lang_installer_exception('installer_requisites_check_failed');
798 $status = $installer->install();
800 if ($status == COMPONENT_ERROR
) {
801 if ($installer->get_error() === 'remotedownloaderror') {
802 return self
::RESULT_DOWNLOADERROR
;
804 throw new lang_installer_exception($installer->get_error(), $langcode);
807 } else if ($status == COMPONENT_UPTODATE
) {
808 return self
::RESULT_UPTODATE
;
810 } else if ($status == COMPONENT_INSTALLED
) {
811 return self
::RESULT_INSTALLED
;
814 throw new lang_installer_exception('unexpected_installer_result', $status);
821 * Exception thrown by {@link lang_installer}
823 * @copyright 2011 David Mudrak <david@moodle.com>
824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
826 class lang_installer_exception
extends moodle_exception
{
828 public function __construct($errorcode, $debuginfo = null) {
829 parent
::__construct($errorcode, 'error', '', null, $debuginfo);