PageRenderTime 154ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/admin/tool/installaddon/classes/validator.php

https://bitbucket.org/moodle/moodle
PHP | 575 lines | 306 code | 88 blank | 181 comment | 53 complexity | d6291dfffd6f7e532f340aa3ff88876a MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Provides validation class to check the plugin ZIP contents
  18. *
  19. * Uses fragments of the local_plugins_archive_validator class copyrighted by
  20. * Marina Glancy that is part of the local_plugins plugin.
  21. *
  22. * @package tool_installaddon
  23. * @subpackage classes
  24. * @copyright 2013 David Mudrak <david@moodle.com>
  25. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26. */
  27. defined('MOODLE_INTERNAL') || die();
  28. if (!defined('T_ML_COMMENT')) {
  29. define('T_ML_COMMENT', T_COMMENT);
  30. } else {
  31. define('T_DOC_COMMENT', T_ML_COMMENT);
  32. }
  33. /**
  34. * Validates the contents of extracted plugin ZIP file
  35. *
  36. * @copyright 2013 David Mudrak <david@moodle.com>
  37. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  38. */
  39. class tool_installaddon_validator {
  40. /** Critical error message level, causes the validation fail. */
  41. const ERROR = 'error';
  42. /** Warning message level, validation does not fail but the admin should be always informed. */
  43. const WARNING = 'warning';
  44. /** Information message level that the admin should be aware of. */
  45. const INFO = 'info';
  46. /** Debugging message level, should be displayed in debugging mode only. */
  47. const DEBUG = 'debug';
  48. /** @var string full path to the extracted ZIP contents */
  49. protected $extractdir = null;
  50. /** @var array as returned by {@link zip_packer::extract_to_pathname()} */
  51. protected $extractfiles = null;
  52. /** @var bool overall result of validation */
  53. protected $result = null;
  54. /** @var string the name of the plugin root directory */
  55. protected $rootdir = null;
  56. /** @var array explicit list of expected/required characteristics of the ZIP */
  57. protected $assertions = null;
  58. /** @var array of validation log messages */
  59. protected $messages = array();
  60. /** @var array|null array of relevant data obtained from version.php */
  61. protected $versionphp = null;
  62. /** @var string|null the name of found English language file without the .php extension */
  63. protected $langfilename = null;
  64. /** @var moodle_url|null URL to continue with the installation of validated add-on */
  65. protected $continueurl = null;
  66. /**
  67. * Factory method returning instance of the validator
  68. *
  69. * @param string $zipcontentpath full path to the extracted ZIP contents
  70. * @param array $zipcontentfiles (string)filerelpath => (bool|string)true or error
  71. * @return tool_installaddon_validator
  72. */
  73. public static function instance($zipcontentpath, array $zipcontentfiles) {
  74. return new static($zipcontentpath, $zipcontentfiles);
  75. }
  76. /**
  77. * Set the expected plugin type, fail the validation otherwise
  78. *
  79. * @param string $required plugin type
  80. */
  81. public function assert_plugin_type($required) {
  82. $this->assertions['plugintype'] = $required;
  83. }
  84. /**
  85. * Set the expectation that the plugin can be installed into the given Moodle version
  86. *
  87. * @param string $required Moodle version we are about to install to
  88. */
  89. public function assert_moodle_version($required) {
  90. $this->assertions['moodleversion'] = $required;
  91. }
  92. /**
  93. * Execute the validation process against all explicit and implicit requirements
  94. *
  95. * Returns true if the validation passes (all explicit and implicit requirements
  96. * pass) and the plugin can be installed. Returns false if the validation fails
  97. * (some explicit or implicit requirement fails) and the plugin must not be
  98. * installed.
  99. *
  100. * @return bool
  101. */
  102. public function execute() {
  103. $this->result = (
  104. $this->validate_files_layout()
  105. and $this->validate_version_php()
  106. and $this->validate_language_pack()
  107. and $this->validate_target_location()
  108. );
  109. return $this->result;
  110. }
  111. /**
  112. * Returns overall result of the validation.
  113. *
  114. * Null is returned if the validation has not been executed yet. Otherwise
  115. * this method returns true (the installation can continue) or false (it is not
  116. * safe to continue with the installation).
  117. *
  118. * @return bool|null
  119. */
  120. public function get_result() {
  121. return $this->result;
  122. }
  123. /**
  124. * Return the list of validation log messages
  125. *
  126. * Each validation message is a plain object with properties level, msgcode
  127. * and addinfo.
  128. *
  129. * @return array of (int)index => (stdClass) validation message
  130. */
  131. public function get_messages() {
  132. return $this->messages;
  133. }
  134. /**
  135. * Return the information provided by the the plugin's version.php
  136. *
  137. * If version.php was not found in the plugin (which is tolerated for
  138. * themes only at the moment), null is returned. Otherwise the array
  139. * is returned. It may be empty if no information was parsed (which
  140. * should not happen).
  141. *
  142. * @return null|array
  143. */
  144. public function get_versionphp_info() {
  145. return $this->versionphp;
  146. }
  147. /**
  148. * Returns the name of the English language file without the .php extension
  149. *
  150. * This can be used as a suggestion for fixing the plugin root directory in the
  151. * ZIP file during the upload. If no file was found, or multiple PHP files are
  152. * located in lang/en/ folder, then null is returned.
  153. *
  154. * @return null|string
  155. */
  156. public function get_language_file_name() {
  157. return $this->langfilename;
  158. }
  159. /**
  160. * Returns the rootdir of the extracted package (after eventual renaming)
  161. *
  162. * @return string|null
  163. */
  164. public function get_rootdir() {
  165. return $this->rootdir;
  166. }
  167. /**
  168. * Sets the URL to continue to after successful validation
  169. *
  170. * @param moodle_url $url
  171. */
  172. public function set_continue_url(moodle_url $url) {
  173. $this->continueurl = $url;
  174. }
  175. /**
  176. * Get the URL to continue to after successful validation
  177. *
  178. * Null is returned if the URL has not been explicitly set by the caller.
  179. *
  180. * @return moodle_url|null
  181. */
  182. public function get_continue_url() {
  183. return $this->continueurl;
  184. }
  185. // End of external API /////////////////////////////////////////////////////
  186. /**
  187. * @param string $zipcontentpath full path to the extracted ZIP contents
  188. * @param array $zipcontentfiles (string)filerelpath => (bool|string)true or error
  189. */
  190. protected function __construct($zipcontentpath, array $zipcontentfiles) {
  191. $this->extractdir = $zipcontentpath;
  192. $this->extractfiles = $zipcontentfiles;
  193. }
  194. // Validation methods //////////////////////////////////////////////////////
  195. /**
  196. * @return bool false if files in the ZIP do not have required layout
  197. */
  198. protected function validate_files_layout() {
  199. if (!is_array($this->extractfiles) or count($this->extractfiles) < 4) {
  200. // We need the English language pack with the name of the plugin at least
  201. $this->add_message(self::ERROR, 'filesnumber');
  202. return false;
  203. }
  204. foreach ($this->extractfiles as $filerelname => $filestatus) {
  205. if ($filestatus !== true) {
  206. $this->add_message(self::ERROR, 'filestatus', array('file' => $filerelname, 'status' => $filestatus));
  207. return false;
  208. }
  209. }
  210. foreach (array_keys($this->extractfiles) as $filerelname) {
  211. if (!file_exists($this->extractdir.'/'.$filerelname)) {
  212. $this->add_message(self::ERROR, 'filenotexists', array('file' => $filerelname));
  213. return false;
  214. }
  215. }
  216. foreach (array_keys($this->extractfiles) as $filerelname) {
  217. $matches = array();
  218. if (!preg_match("#^([^/]+)/#", $filerelname, $matches) or (!is_null($this->rootdir) and $this->rootdir !== $matches[1])) {
  219. $this->add_message(self::ERROR, 'onedir');
  220. return false;
  221. }
  222. $this->rootdir = $matches[1];
  223. }
  224. if ($this->rootdir !== clean_param($this->rootdir, PARAM_PLUGIN)) {
  225. $this->add_message(self::ERROR, 'rootdirinvalid', $this->rootdir);
  226. return false;
  227. } else {
  228. $this->add_message(self::INFO, 'rootdir', $this->rootdir);
  229. }
  230. return is_dir($this->extractdir.'/'.$this->rootdir);
  231. }
  232. /**
  233. * @return bool false if the version.php file does not declare required information
  234. */
  235. protected function validate_version_php() {
  236. if (!isset($this->assertions['plugintype'])) {
  237. throw new coding_exception('Required plugin type must be set before calling this');
  238. }
  239. if (!isset($this->assertions['moodleversion'])) {
  240. throw new coding_exception('Required Moodle version must be set before calling this');
  241. }
  242. $fullpath = $this->extractdir.'/'.$this->rootdir.'/version.php';
  243. if (!file_exists($fullpath)) {
  244. // This is tolerated for themes only.
  245. if ($this->assertions['plugintype'] === 'theme') {
  246. $this->add_message(self::DEBUG, 'missingversionphp');
  247. return true;
  248. } else {
  249. $this->add_message(self::ERROR, 'missingversionphp');
  250. return false;
  251. }
  252. }
  253. $this->versionphp = array();
  254. $info = $this->parse_version_php($fullpath);
  255. if ($this->assertions['plugintype'] === 'mod') {
  256. $type = 'module';
  257. } else {
  258. $type = 'plugin';
  259. }
  260. if (!isset($info[$type.'->version'])) {
  261. if ($type === 'module' and isset($info['plugin->version'])) {
  262. // Expect the activity module using $plugin in version.php instead of $module.
  263. $type = 'plugin';
  264. $this->versionphp['version'] = $info[$type.'->version'];
  265. $this->add_message(self::INFO, 'pluginversion', $this->versionphp['version']);
  266. } else {
  267. $this->add_message(self::ERROR, 'missingversion');
  268. return false;
  269. }
  270. } else {
  271. $this->versionphp['version'] = $info[$type.'->version'];
  272. $this->add_message(self::INFO, 'pluginversion', $this->versionphp['version']);
  273. }
  274. if (isset($info[$type.'->requires'])) {
  275. $this->versionphp['requires'] = $info[$type.'->requires'];
  276. if ($this->versionphp['requires'] > $this->assertions['moodleversion']) {
  277. $this->add_message(self::ERROR, 'requiresmoodle', $this->versionphp['requires']);
  278. return false;
  279. }
  280. $this->add_message(self::INFO, 'requiresmoodle', $this->versionphp['requires']);
  281. }
  282. if (isset($info[$type.'->component'])) {
  283. $this->versionphp['component'] = $info[$type.'->component'];
  284. list($reqtype, $reqname) = core_component::normalize_component($this->versionphp['component']);
  285. if ($reqtype !== $this->assertions['plugintype']) {
  286. $this->add_message(self::ERROR, 'componentmismatchtype', array(
  287. 'expected' => $this->assertions['plugintype'],
  288. 'found' => $reqtype));
  289. return false;
  290. }
  291. if ($reqname !== $this->rootdir) {
  292. $this->add_message(self::ERROR, 'componentmismatchname', $reqname);
  293. return false;
  294. }
  295. $this->add_message(self::INFO, 'componentmatch', $this->versionphp['component']);
  296. }
  297. if (isset($info[$type.'->maturity'])) {
  298. $this->versionphp['maturity'] = $info[$type.'->maturity'];
  299. if ($this->versionphp['maturity'] === 'MATURITY_STABLE') {
  300. $this->add_message(self::INFO, 'maturity', $this->versionphp['maturity']);
  301. } else {
  302. $this->add_message(self::WARNING, 'maturity', $this->versionphp['maturity']);
  303. }
  304. }
  305. if (isset($info[$type.'->release'])) {
  306. $this->versionphp['release'] = $info[$type.'->release'];
  307. $this->add_message(self::INFO, 'release', $this->versionphp['release']);
  308. }
  309. return true;
  310. }
  311. /**
  312. * @return bool false if the English language pack is not provided correctly
  313. */
  314. protected function validate_language_pack() {
  315. if (!isset($this->assertions['plugintype'])) {
  316. throw new coding_exception('Required plugin type must be set before calling this');
  317. }
  318. if (!isset($this->extractfiles[$this->rootdir.'/lang/en/'])
  319. or $this->extractfiles[$this->rootdir.'/lang/en/'] !== true
  320. or !is_dir($this->extractdir.'/'.$this->rootdir.'/lang/en')) {
  321. $this->add_message(self::ERROR, 'missinglangenfolder');
  322. return false;
  323. }
  324. $langfiles = array();
  325. foreach (array_keys($this->extractfiles) as $extractfile) {
  326. $matches = array();
  327. if (preg_match('#^'.preg_quote($this->rootdir).'/lang/en/([^/]+).php?$#i', $extractfile, $matches)) {
  328. $langfiles[] = $matches[1];
  329. }
  330. }
  331. if (empty($langfiles)) {
  332. $this->add_message(self::ERROR, 'missinglangenfile');
  333. return false;
  334. } else if (count($langfiles) > 1) {
  335. $this->add_message(self::WARNING, 'multiplelangenfiles');
  336. } else {
  337. $this->langfilename = $langfiles[0];
  338. $this->add_message(self::DEBUG, 'foundlangfile', $this->langfilename);
  339. }
  340. if ($this->assertions['plugintype'] === 'mod') {
  341. $expected = $this->rootdir.'.php';
  342. } else {
  343. $expected = $this->assertions['plugintype'].'_'.$this->rootdir.'.php';
  344. }
  345. if (!isset($this->extractfiles[$this->rootdir.'/lang/en/'.$expected])
  346. or $this->extractfiles[$this->rootdir.'/lang/en/'.$expected] !== true
  347. or !is_file($this->extractdir.'/'.$this->rootdir.'/lang/en/'.$expected)) {
  348. $this->add_message(self::ERROR, 'missingexpectedlangenfile', $expected);
  349. return false;
  350. }
  351. return true;
  352. }
  353. /**
  354. * @return bool false of the given add-on can't be installed into its location
  355. */
  356. public function validate_target_location() {
  357. if (!isset($this->assertions['plugintype'])) {
  358. throw new coding_exception('Required plugin type must be set before calling this');
  359. }
  360. $plugintypepath = $this->get_plugintype_location($this->assertions['plugintype']);
  361. if (is_null($plugintypepath)) {
  362. $this->add_message(self::ERROR, 'unknowntype', $this->assertions['plugintype']);
  363. return false;
  364. }
  365. if (!is_dir($plugintypepath)) {
  366. throw new coding_exception('Plugin type location does not exist!');
  367. }
  368. $target = $plugintypepath.'/'.$this->rootdir;
  369. if (file_exists($target)) {
  370. $this->add_message(self::ERROR, 'targetexists', $target);
  371. return false;
  372. }
  373. if (is_writable($plugintypepath)) {
  374. $this->add_message(self::INFO, 'pathwritable', $plugintypepath);
  375. } else {
  376. $this->add_message(self::ERROR, 'pathwritable', $plugintypepath);
  377. return false;
  378. }
  379. return true;
  380. }
  381. // Helper methods //////////////////////////////////////////////////////////
  382. /**
  383. * Get as much information from existing version.php as possible
  384. *
  385. * @param string full path to the version.php file
  386. * @return array of found meta-info declarations
  387. */
  388. protected function parse_version_php($fullpath) {
  389. $content = $this->get_stripped_file_contents($fullpath);
  390. preg_match_all('#\$((plugin|module)\->(version|maturity|release|requires))=()(\d+(\.\d+)?);#m', $content, $matches1);
  391. preg_match_all('#\$((plugin|module)\->(maturity))=()(MATURITY_\w+);#m', $content, $matches2);
  392. preg_match_all('#\$((plugin|module)\->(release))=([\'"])(.*?)\4;#m', $content, $matches3);
  393. preg_match_all('#\$((plugin|module)\->(component))=([\'"])(.+?_.+?)\4;#m', $content, $matches4);
  394. if (count($matches1[1]) + count($matches2[1]) + count($matches3[1]) + count($matches4[1])) {
  395. $info = array_combine(
  396. array_merge($matches1[1], $matches2[1], $matches3[1], $matches4[1]),
  397. array_merge($matches1[5], $matches2[5], $matches3[5], $matches4[5])
  398. );
  399. } else {
  400. $info = array();
  401. }
  402. return $info;
  403. }
  404. /**
  405. * Append the given message to the messages log
  406. *
  407. * @param string $level e.g. self::ERROR
  408. * @param string $msgcode may form a string
  409. * @param string|array|object $a optional additional info suitable for {@link get_string()}
  410. */
  411. protected function add_message($level, $msgcode, $a = null) {
  412. $msg = (object)array(
  413. 'level' => $level,
  414. 'msgcode' => $msgcode,
  415. 'addinfo' => $a,
  416. );
  417. $this->messages[] = $msg;
  418. }
  419. /**
  420. * Returns bare PHP code from the given file
  421. *
  422. * Returns contents without PHP opening and closing tags, text outside php code,
  423. * comments and extra whitespaces.
  424. *
  425. * @param string $fullpath full path to the file
  426. * @return string
  427. */
  428. protected function get_stripped_file_contents($fullpath) {
  429. $source = file_get_contents($fullpath);
  430. $tokens = token_get_all($source);
  431. $output = '';
  432. $doprocess = false;
  433. foreach ($tokens as $token) {
  434. if (is_string($token)) {
  435. // Simple one character token.
  436. $id = -1;
  437. $text = $token;
  438. } else {
  439. // Token array.
  440. list($id, $text) = $token;
  441. }
  442. switch ($id) {
  443. case T_WHITESPACE:
  444. case T_COMMENT:
  445. case T_ML_COMMENT:
  446. case T_DOC_COMMENT:
  447. // Ignore whitespaces, inline comments, multiline comments and docblocks.
  448. break;
  449. case T_OPEN_TAG:
  450. // Start processing.
  451. $doprocess = true;
  452. break;
  453. case T_CLOSE_TAG:
  454. // Stop processing.
  455. $doprocess = false;
  456. break;
  457. default:
  458. // Anything else is within PHP tags, return it as is.
  459. if ($doprocess) {
  460. $output .= $text;
  461. if ($text === 'function') {
  462. // Explicitly keep the whitespace that would be ignored.
  463. $output .= ' ';
  464. }
  465. }
  466. break;
  467. }
  468. }
  469. return $output;
  470. }
  471. /**
  472. * Returns the full path to the root directory of the given plugin type
  473. *
  474. * @param string $plugintype
  475. * @return string|null
  476. */
  477. public function get_plugintype_location($plugintype) {
  478. $plugintypepath = null;
  479. foreach (core_component::get_plugin_types() as $type => $fullpath) {
  480. if ($type === $plugintype) {
  481. $plugintypepath = $fullpath;
  482. break;
  483. }
  484. }
  485. return $plugintypepath;
  486. }
  487. }