PageRenderTime 49ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/backup/converter/moodle1/lib.php

https://bitbucket.org/moodle/moodle
PHP | 1562 lines | 785 code | 222 blank | 555 comment | 96 complexity | 473885dfcbadff383b5b238b20aacfa6 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  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 classes used by the moodle1 converter
  18. *
  19. * @package backup-convert
  20. * @subpackage moodle1
  21. * @copyright 2011 Mark Nielsen <mark@moodlerooms.com>
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. require_once($CFG->dirroot . '/backup/converter/convertlib.php');
  26. require_once($CFG->dirroot . '/backup/util/xml/parser/progressive_parser.class.php');
  27. require_once($CFG->dirroot . '/backup/util/xml/parser/processors/grouped_parser_processor.class.php');
  28. require_once($CFG->dirroot . '/backup/util/dbops/backup_dbops.class.php');
  29. require_once($CFG->dirroot . '/backup/util/dbops/backup_controller_dbops.class.php');
  30. require_once($CFG->dirroot . '/backup/util/dbops/restore_dbops.class.php');
  31. require_once($CFG->dirroot . '/backup/util/xml/contenttransformer/xml_contenttransformer.class.php');
  32. require_once(__DIR__ . '/handlerlib.php');
  33. /**
  34. * Converter of Moodle 1.9 backup into Moodle 2.x format
  35. */
  36. class moodle1_converter extends base_converter {
  37. /** @var progressive_parser moodle.xml file parser */
  38. protected $xmlparser;
  39. /** @var moodle1_parser_processor */
  40. protected $xmlprocessor;
  41. /** @var array of {@link convert_path} to process */
  42. protected $pathelements = array();
  43. /** @var null|string the current module being processed - used to expand the MOD paths */
  44. protected $currentmod = null;
  45. /** @var null|string the current block being processed - used to expand the BLOCK paths */
  46. protected $currentblock = null;
  47. /** @var string path currently locking processing of children */
  48. protected $pathlock;
  49. /** @var int used by the serial number {@link get_nextid()} */
  50. private $nextid = 1;
  51. /**
  52. * Instructs the dispatcher to ignore all children below path processor returning it
  53. */
  54. const SKIP_ALL_CHILDREN = -991399;
  55. /**
  56. * Log a message
  57. *
  58. * @see parent::log()
  59. * @param string $message message text
  60. * @param int $level message level {@example backup::LOG_WARNING}
  61. * @param null|mixed $a additional information
  62. * @param null|int $depth the message depth
  63. * @param bool $display whether the message should be sent to the output, too
  64. */
  65. public function log($message, $level, $a = null, $depth = null, $display = false) {
  66. parent::log('(moodle1) '.$message, $level, $a, $depth, $display);
  67. }
  68. /**
  69. * Detects the Moodle 1.9 format of the backup directory
  70. *
  71. * @param string $tempdir the name of the backup directory
  72. * @return null|string backup::FORMAT_MOODLE1 if the Moodle 1.9 is detected, null otherwise
  73. */
  74. public static function detect_format($tempdir) {
  75. global $CFG;
  76. $tempdirpath = make_backup_temp_directory($tempdir, false);
  77. $filepath = $tempdirpath . '/moodle.xml';
  78. if (file_exists($filepath)) {
  79. // looks promising, lets load some information
  80. $handle = fopen($filepath, 'r');
  81. $first_chars = fread($handle, 200);
  82. fclose($handle);
  83. // check if it has the required strings
  84. if (strpos($first_chars,'<?xml version="1.0" encoding="UTF-8"?>') !== false and
  85. strpos($first_chars,'<MOODLE_BACKUP>') !== false and
  86. strpos($first_chars,'<INFO>') !== false) {
  87. return backup::FORMAT_MOODLE1;
  88. }
  89. }
  90. return null;
  91. }
  92. /**
  93. * Initialize the instance if needed, called by the constructor
  94. *
  95. * Here we create objects we need before the execution.
  96. */
  97. protected function init() {
  98. // ask your mother first before going out playing with toys
  99. parent::init();
  100. $this->log('initializing '.$this->get_name().' converter', backup::LOG_INFO);
  101. // good boy, prepare XML parser and processor
  102. $this->log('setting xml parser', backup::LOG_DEBUG, null, 1);
  103. $this->xmlparser = new progressive_parser();
  104. $this->xmlparser->set_file($this->get_tempdir_path() . '/moodle.xml');
  105. $this->log('setting xml processor', backup::LOG_DEBUG, null, 1);
  106. $this->xmlprocessor = new moodle1_parser_processor($this);
  107. $this->xmlparser->set_processor($this->xmlprocessor);
  108. // make sure that MOD and BLOCK paths are visited
  109. $this->xmlprocessor->add_path('/MOODLE_BACKUP/COURSE/MODULES/MOD');
  110. $this->xmlprocessor->add_path('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK');
  111. // register the conversion handlers
  112. foreach (moodle1_handlers_factory::get_handlers($this) as $handler) {
  113. $this->log('registering handler', backup::LOG_DEBUG, get_class($handler), 1);
  114. $this->register_handler($handler, $handler->get_paths());
  115. }
  116. }
  117. /**
  118. * Converts the contents of the tempdir into the target format in the workdir
  119. */
  120. protected function execute() {
  121. $this->log('creating the stash storage', backup::LOG_DEBUG);
  122. $this->create_stash_storage();
  123. $this->log('parsing moodle.xml starts', backup::LOG_DEBUG);
  124. $this->xmlparser->process();
  125. $this->log('parsing moodle.xml done', backup::LOG_DEBUG);
  126. $this->log('dropping the stash storage', backup::LOG_DEBUG);
  127. $this->drop_stash_storage();
  128. }
  129. /**
  130. * Register a handler for the given path elements
  131. */
  132. protected function register_handler(moodle1_handler $handler, array $elements) {
  133. // first iteration, push them to new array, indexed by name
  134. // to detect duplicates in names or paths
  135. $names = array();
  136. $paths = array();
  137. foreach($elements as $element) {
  138. if (!$element instanceof convert_path) {
  139. throw new convert_exception('path_element_wrong_class', get_class($element));
  140. }
  141. if (array_key_exists($element->get_name(), $names)) {
  142. throw new convert_exception('path_element_name_alreadyexists', $element->get_name());
  143. }
  144. if (array_key_exists($element->get_path(), $paths)) {
  145. throw new convert_exception('path_element_path_alreadyexists', $element->get_path());
  146. }
  147. $names[$element->get_name()] = true;
  148. $paths[$element->get_path()] = $element;
  149. }
  150. // now, for each element not having a processing object yet, assign the handler
  151. // if the element is not a memeber of a group
  152. foreach($paths as $key => $element) {
  153. if (is_null($element->get_processing_object()) and !$this->grouped_parent_exists($element, $paths)) {
  154. $paths[$key]->set_processing_object($handler);
  155. }
  156. // add the element path to the processor
  157. $this->xmlprocessor->add_path($element->get_path(), $element->is_grouped());
  158. }
  159. // done, store the paths (duplicates by path are discarded)
  160. $this->pathelements = array_merge($this->pathelements, $paths);
  161. // remove the injected plugin name element from the MOD and BLOCK paths
  162. // and register such collapsed path, too
  163. foreach ($elements as $element) {
  164. $path = $element->get_path();
  165. $path = preg_replace('/^\/MOODLE_BACKUP\/COURSE\/MODULES\/MOD\/(\w+)\//', '/MOODLE_BACKUP/COURSE/MODULES/MOD/', $path);
  166. $path = preg_replace('/^\/MOODLE_BACKUP\/COURSE\/BLOCKS\/BLOCK\/(\w+)\//', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/', $path);
  167. if (!empty($path) and $path != $element->get_path()) {
  168. $this->xmlprocessor->add_path($path, false);
  169. }
  170. }
  171. }
  172. /**
  173. * Helper method used by {@link self::register_handler()}
  174. *
  175. * @param convert_path $pelement path element
  176. * @param array of convert_path instances
  177. * @return bool true if grouped parent was found, false otherwise
  178. */
  179. protected function grouped_parent_exists($pelement, $elements) {
  180. foreach ($elements as $element) {
  181. if ($pelement->get_path() == $element->get_path()) {
  182. // don't compare against itself
  183. continue;
  184. }
  185. // if the element is grouped and it is a parent of pelement, return true
  186. if ($element->is_grouped() and strpos($pelement->get_path() . '/', $element->get_path()) === 0) {
  187. return true;
  188. }
  189. }
  190. // no grouped parent found
  191. return false;
  192. }
  193. /**
  194. * Process the data obtained from the XML parser processor
  195. *
  196. * This methods receives one chunk of information from the XML parser
  197. * processor and dispatches it, following the naming rules.
  198. * We are expanding the modules and blocks paths here to include the plugin's name.
  199. *
  200. * @param array $data
  201. */
  202. public function process_chunk($data) {
  203. $path = $data['path'];
  204. // expand the MOD paths so that they contain the module name
  205. if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
  206. $this->currentmod = strtoupper($data['tags']['MODTYPE']);
  207. $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
  208. } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
  209. $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
  210. }
  211. // expand the BLOCK paths so that they contain the module name
  212. if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
  213. $this->currentblock = strtoupper($data['tags']['NAME']);
  214. $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
  215. } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
  216. $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock, $path);
  217. }
  218. if ($path !== $data['path']) {
  219. if (!array_key_exists($path, $this->pathelements)) {
  220. // no handler registered for the transformed MOD or BLOCK path
  221. $this->log('no handler attached', backup::LOG_WARNING, $path);
  222. return;
  223. } else {
  224. // pretend as if the original $data contained the tranformed path
  225. $data['path'] = $path;
  226. }
  227. }
  228. if (!array_key_exists($data['path'], $this->pathelements)) {
  229. // path added to the processor without the handler
  230. throw new convert_exception('missing_path_handler', $data['path']);
  231. }
  232. $element = $this->pathelements[$data['path']];
  233. $object = $element->get_processing_object();
  234. $method = $element->get_processing_method();
  235. $returned = null; // data returned by the processing method, if any
  236. if (empty($object)) {
  237. throw new convert_exception('missing_processing_object', null, $data['path']);
  238. }
  239. // release the lock if we aren't anymore within children of it
  240. if (!is_null($this->pathlock) and strpos($data['path'], $this->pathlock) === false) {
  241. $this->pathlock = null;
  242. }
  243. // if the path is not locked, apply the element's recipes and dispatch
  244. // the cooked tags to the processing method
  245. if (is_null($this->pathlock)) {
  246. $rawdatatags = $data['tags'];
  247. $data['tags'] = $element->apply_recipes($data['tags']);
  248. // if the processing method exists, give it a chance to modify data
  249. if (method_exists($object, $method)) {
  250. $returned = $object->$method($data['tags'], $rawdatatags);
  251. }
  252. }
  253. // if the dispatched method returned SKIP_ALL_CHILDREN, remember the current path
  254. // and lock it so that its children are not dispatched
  255. if ($returned === self::SKIP_ALL_CHILDREN) {
  256. // check we haven't any previous lock
  257. if (!is_null($this->pathlock)) {
  258. throw new convert_exception('already_locked_path', $data['path']);
  259. }
  260. // set the lock - nothing below the current path will be dispatched
  261. $this->pathlock = $data['path'] . '/';
  262. // if the method has returned any info, set element data to it
  263. } else if (!is_null($returned)) {
  264. $element->set_tags($returned);
  265. // use just the cooked parsed data otherwise
  266. } else {
  267. $element->set_tags($data['tags']);
  268. }
  269. }
  270. /**
  271. * Executes operations required at the start of a watched path
  272. *
  273. * For MOD and BLOCK paths, this is supported only for the sub-paths, not the root
  274. * module/block element. For the illustration:
  275. *
  276. * You CAN'T attach on_xxx_start() listener to a path like
  277. * /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP because the <MOD> must
  278. * be processed first in {@link self::process_chunk()} where $this->currentmod
  279. * is set.
  280. *
  281. * You CAN attach some on_xxx_start() listener to a path like
  282. * /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP/SUBMISSIONS because it is
  283. * a sub-path under <MOD> and we have $this->currentmod already set when the
  284. * <SUBMISSIONS> is reached.
  285. *
  286. * @param string $path in the original file
  287. */
  288. public function path_start_reached($path) {
  289. if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
  290. $this->currentmod = null;
  291. $forbidden = true;
  292. } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
  293. // expand the MOD paths so that they contain the module name
  294. $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
  295. }
  296. if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
  297. $this->currentblock = null;
  298. $forbidden = true;
  299. } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
  300. // expand the BLOCK paths so that they contain the module name
  301. $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock, $path);
  302. }
  303. if (empty($this->pathelements[$path])) {
  304. return;
  305. }
  306. $element = $this->pathelements[$path];
  307. $pobject = $element->get_processing_object();
  308. $method = $element->get_start_method();
  309. if (method_exists($pobject, $method)) {
  310. if (empty($forbidden)) {
  311. $pobject->$method();
  312. } else {
  313. // this path is not supported because we do not know the module/block yet
  314. throw new coding_exception('Attaching the on-start event listener to the root MOD or BLOCK element is forbidden.');
  315. }
  316. }
  317. }
  318. /**
  319. * Executes operations required at the end of a watched path
  320. *
  321. * @param string $path in the original file
  322. */
  323. public function path_end_reached($path) {
  324. // expand the MOD paths so that they contain the current module name
  325. if ($path === '/MOODLE_BACKUP/COURSE/MODULES/MOD') {
  326. $path = '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod;
  327. } else if (strpos($path, '/MOODLE_BACKUP/COURSE/MODULES/MOD') === 0) {
  328. $path = str_replace('/MOODLE_BACKUP/COURSE/MODULES/MOD', '/MOODLE_BACKUP/COURSE/MODULES/MOD/' . $this->currentmod, $path);
  329. }
  330. // expand the BLOCK paths so that they contain the module name
  331. if ($path === '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') {
  332. $path = '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock;
  333. } else if (strpos($path, '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK') === 0) {
  334. $path = str_replace('/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK', '/MOODLE_BACKUP/COURSE/BLOCKS/BLOCK/' . $this->currentblock, $path);
  335. }
  336. if (empty($this->pathelements[$path])) {
  337. return;
  338. }
  339. $element = $this->pathelements[$path];
  340. $pobject = $element->get_processing_object();
  341. $method = $element->get_end_method();
  342. $tags = $element->get_tags();
  343. if (method_exists($pobject, $method)) {
  344. $pobject->$method($tags);
  345. }
  346. }
  347. /**
  348. * Creates the temporary storage for stashed data
  349. *
  350. * This implementation uses backup_ids_temp table.
  351. */
  352. public function create_stash_storage() {
  353. backup_controller_dbops::create_backup_ids_temp_table($this->get_id());
  354. }
  355. /**
  356. * Drops the temporary storage of stashed data
  357. *
  358. * This implementation uses backup_ids_temp table.
  359. */
  360. public function drop_stash_storage() {
  361. backup_controller_dbops::drop_backup_ids_temp_table($this->get_id());
  362. }
  363. /**
  364. * Stores some information for later processing
  365. *
  366. * This implementation uses backup_ids_temp table to store data. Make
  367. * sure that the $stashname + $itemid combo is unique.
  368. *
  369. * @param string $stashname name of the stash
  370. * @param mixed $info information to stash
  371. * @param int $itemid optional id for multiple infos within the same stashname
  372. */
  373. public function set_stash($stashname, $info, $itemid = 0) {
  374. try {
  375. restore_dbops::set_backup_ids_record($this->get_id(), $stashname, $itemid, 0, null, $info);
  376. } catch (dml_exception $e) {
  377. throw new moodle1_convert_storage_exception('unable_to_restore_stash', null, $e->getMessage());
  378. }
  379. }
  380. /**
  381. * Restores a given stash stored previously by {@link self::set_stash()}
  382. *
  383. * @param string $stashname name of the stash
  384. * @param int $itemid optional id for multiple infos within the same stashname
  385. * @throws moodle1_convert_empty_storage_exception if the info has not been stashed previously
  386. * @return mixed stashed data
  387. */
  388. public function get_stash($stashname, $itemid = 0) {
  389. $record = restore_dbops::get_backup_ids_record($this->get_id(), $stashname, $itemid);
  390. if (empty($record)) {
  391. throw new moodle1_convert_empty_storage_exception('required_not_stashed_data', array($stashname, $itemid));
  392. } else {
  393. if (empty($record->info)) {
  394. return array();
  395. }
  396. return $record->info;
  397. }
  398. }
  399. /**
  400. * Restores a given stash or returns the given default if there is no such stash
  401. *
  402. * @param string $stashname name of the stash
  403. * @param int $itemid optional id for multiple infos within the same stashname
  404. * @param mixed $default information to return if the info has not been stashed previously
  405. * @return mixed stashed data or the default value
  406. */
  407. public function get_stash_or_default($stashname, $itemid = 0, $default = null) {
  408. try {
  409. return $this->get_stash($stashname, $itemid);
  410. } catch (moodle1_convert_empty_storage_exception $e) {
  411. return $default;
  412. }
  413. }
  414. /**
  415. * Returns the list of existing stashes
  416. *
  417. * @return array
  418. */
  419. public function get_stash_names() {
  420. global $DB;
  421. $search = array(
  422. 'backupid' => $this->get_id(),
  423. );
  424. return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemname'));
  425. }
  426. /**
  427. * Returns the list of stashed $itemids in the given stash
  428. *
  429. * @param string $stashname
  430. * @return array
  431. */
  432. public function get_stash_itemids($stashname) {
  433. global $DB;
  434. $search = array(
  435. 'backupid' => $this->get_id(),
  436. 'itemname' => $stashname
  437. );
  438. return array_keys($DB->get_records('backup_ids_temp', $search, '', 'itemid'));
  439. }
  440. /**
  441. * Generates an artificial context id
  442. *
  443. * Moodle 1.9 backups do not contain any context information. But we need them
  444. * in Moodle 2.x format so here we generate fictive context id for every given
  445. * context level + instance combo.
  446. *
  447. * CONTEXT_SYSTEM and CONTEXT_COURSE ignore the $instance as they represent a
  448. * single system or the course being restored.
  449. *
  450. * @see context_system::instance()
  451. * @see context_course::instance()
  452. * @param int $level the context level, like CONTEXT_COURSE or CONTEXT_MODULE
  453. * @param int $instance the instance id, for example $course->id for courses or $cm->id for activity modules
  454. * @return int the context id
  455. */
  456. public function get_contextid($level, $instance = 0) {
  457. $stashname = 'context' . $level;
  458. if ($level == CONTEXT_SYSTEM or $level == CONTEXT_COURSE) {
  459. $instance = 0;
  460. }
  461. try {
  462. // try the previously stashed id
  463. return $this->get_stash($stashname, $instance);
  464. } catch (moodle1_convert_empty_storage_exception $e) {
  465. // this context level + instance is required for the first time
  466. $newid = $this->get_nextid();
  467. $this->set_stash($stashname, $newid, $instance);
  468. return $newid;
  469. }
  470. }
  471. /**
  472. * Simple autoincrement generator
  473. *
  474. * @return int the next number in a row of numbers
  475. */
  476. public function get_nextid() {
  477. return $this->nextid++;
  478. }
  479. /**
  480. * Creates and returns new instance of the file manager
  481. *
  482. * @param int $contextid the default context id of the files being migrated
  483. * @param string $component the default component name of the files being migrated
  484. * @param string $filearea the default file area of the files being migrated
  485. * @param int $itemid the default item id of the files being migrated
  486. * @param int $userid initial user id of the files being migrated
  487. * @return moodle1_file_manager
  488. */
  489. public function get_file_manager($contextid = null, $component = null, $filearea = null, $itemid = 0, $userid = null) {
  490. return new moodle1_file_manager($this, $contextid, $component, $filearea, $itemid, $userid);
  491. }
  492. /**
  493. * Creates and returns new instance of the inforef manager
  494. *
  495. * @param string $name the name of the annotator (like course, section, activity, block)
  496. * @param int $id the id of the annotator if required
  497. * @return moodle1_inforef_manager
  498. */
  499. public function get_inforef_manager($name, $id = 0) {
  500. return new moodle1_inforef_manager($this, $name, $id);
  501. }
  502. /**
  503. * Migrates all course files referenced from the hypertext using the given filemanager
  504. *
  505. * This is typically used to convert images embedded into the intro fields.
  506. *
  507. * @param string $text hypertext containing $@FILEPHP@$ referenced
  508. * @param moodle1_file_manager $fileman file manager to use for the file migration
  509. * @return string the original $text with $@FILEPHP@$ references replaced with the new @@PLUGINFILE@@
  510. */
  511. public static function migrate_referenced_files($text, moodle1_file_manager $fileman) {
  512. $files = self::find_referenced_files($text);
  513. if (!empty($files)) {
  514. foreach ($files as $file) {
  515. try {
  516. $fileman->migrate_file('course_files'.$file, dirname($file));
  517. } catch (moodle1_convert_exception $e) {
  518. // file probably does not exist
  519. $fileman->log('error migrating file', backup::LOG_WARNING, 'course_files'.$file);
  520. }
  521. }
  522. $text = self::rewrite_filephp_usage($text, $files);
  523. }
  524. return $text;
  525. }
  526. /**
  527. * Detects all links to file.php encoded via $@FILEPHP@$ and returns the files to migrate
  528. *
  529. * @see self::migrate_referenced_files()
  530. * @param string $text
  531. * @return array
  532. */
  533. public static function find_referenced_files($text) {
  534. $files = array();
  535. if (empty($text) or is_numeric($text)) {
  536. return $files;
  537. }
  538. $matches = array();
  539. $pattern = '|(["\'])(\$@FILEPHP@\$.+?)\1|';
  540. $result = preg_match_all($pattern, $text, $matches);
  541. if ($result === false) {
  542. throw new moodle1_convert_exception('error_while_searching_for_referenced_files');
  543. }
  544. if ($result == 0) {
  545. return $files;
  546. }
  547. foreach ($matches[2] as $match) {
  548. $file = str_replace(array('$@FILEPHP@$', '$@SLASH@$', '$@FORCEDOWNLOAD@$'), array('', '/', ''), $match);
  549. if ($file === clean_param($file, PARAM_PATH)) {
  550. $files[] = rawurldecode($file);
  551. }
  552. }
  553. return array_unique($files);
  554. }
  555. /**
  556. * Given the list of migrated files, rewrites references to them from $@FILEPHP@$ form to the @@PLUGINFILE@@ one
  557. *
  558. * @see self::migrate_referenced_files()
  559. * @param string $text
  560. * @param array $files
  561. * @return string
  562. */
  563. public static function rewrite_filephp_usage($text, array $files) {
  564. foreach ($files as $file) {
  565. // Expect URLs properly encoded by default.
  566. $parts = explode('/', $file);
  567. $encoded = implode('/', array_map('rawurlencode', $parts));
  568. $fileref = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $encoded);
  569. $text = str_replace($fileref.'$@FORCEDOWNLOAD@$', '@@PLUGINFILE@@'.$encoded.'?forcedownload=1', $text);
  570. $text = str_replace($fileref, '@@PLUGINFILE@@'.$encoded, $text);
  571. // Add support for URLs without any encoding.
  572. $fileref = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $file);
  573. $text = str_replace($fileref.'$@FORCEDOWNLOAD@$', '@@PLUGINFILE@@'.$encoded.'?forcedownload=1', $text);
  574. $text = str_replace($fileref, '@@PLUGINFILE@@'.$encoded, $text);
  575. }
  576. return $text;
  577. }
  578. /**
  579. * @see parent::description()
  580. */
  581. public static function description() {
  582. return array(
  583. 'from' => backup::FORMAT_MOODLE1,
  584. 'to' => backup::FORMAT_MOODLE,
  585. 'cost' => 10,
  586. );
  587. }
  588. }
  589. /**
  590. * Exception thrown by this converter
  591. */
  592. class moodle1_convert_exception extends convert_exception {
  593. }
  594. /**
  595. * Exception thrown by the temporary storage subsystem of moodle1_converter
  596. */
  597. class moodle1_convert_storage_exception extends moodle1_convert_exception {
  598. }
  599. /**
  600. * Exception thrown by the temporary storage subsystem of moodle1_converter
  601. */
  602. class moodle1_convert_empty_storage_exception extends moodle1_convert_exception {
  603. }
  604. /**
  605. * XML parser processor used for processing parsed moodle.xml
  606. */
  607. class moodle1_parser_processor extends grouped_parser_processor {
  608. /** @var moodle1_converter */
  609. protected $converter;
  610. public function __construct(moodle1_converter $converter) {
  611. $this->converter = $converter;
  612. parent::__construct();
  613. }
  614. /**
  615. * Provides NULL decoding
  616. *
  617. * Note that we do not decode $@FILEPHP@$ and friends here as we are going to write them
  618. * back immediately into another XML file.
  619. */
  620. public function process_cdata($cdata) {
  621. if ($cdata === '$@NULL@$') {
  622. return null;
  623. }
  624. return $cdata;
  625. }
  626. /**
  627. * Dispatches the data chunk to the converter class
  628. *
  629. * @param array $data the chunk of parsed data
  630. */
  631. protected function dispatch_chunk($data) {
  632. $this->converter->process_chunk($data);
  633. }
  634. /**
  635. * Informs the converter at the start of a watched path
  636. *
  637. * @param string $path
  638. */
  639. protected function notify_path_start($path) {
  640. $this->converter->path_start_reached($path);
  641. }
  642. /**
  643. * Informs the converter at the end of a watched path
  644. *
  645. * @param string $path
  646. */
  647. protected function notify_path_end($path) {
  648. $this->converter->path_end_reached($path);
  649. }
  650. }
  651. /**
  652. * XML transformer that modifies the content of the files being written during the conversion
  653. *
  654. * @see backup_xml_transformer
  655. */
  656. class moodle1_xml_transformer extends xml_contenttransformer {
  657. /**
  658. * Modify the content before it is writter to a file
  659. *
  660. * @param string|mixed $content
  661. */
  662. public function process($content) {
  663. // the content should be a string. If array or object is given, try our best recursively
  664. // but inform the developer
  665. if (is_array($content)) {
  666. debugging('Moodle1 XML transformer should not process arrays but plain content always', DEBUG_DEVELOPER);
  667. foreach($content as $key => $plaincontent) {
  668. $content[$key] = $this->process($plaincontent);
  669. }
  670. return $content;
  671. } else if (is_object($content)) {
  672. debugging('Moodle1 XML transformer should not process objects but plain content always', DEBUG_DEVELOPER);
  673. foreach((array)$content as $key => $plaincontent) {
  674. $content[$key] = $this->process($plaincontent);
  675. }
  676. return (object)$content;
  677. }
  678. // try to deal with some trivial cases first
  679. if (is_null($content)) {
  680. return '$@NULL@$';
  681. } else if ($content === '') {
  682. return '';
  683. } else if (is_numeric($content)) {
  684. return $content;
  685. } else if (strlen($content) < 32) {
  686. return $content;
  687. }
  688. return $content;
  689. }
  690. }
  691. /**
  692. * Class representing a path to be converted from XML file
  693. *
  694. * This was created as a copy of {@link restore_path_element} and should be refactored
  695. * probably.
  696. */
  697. class convert_path {
  698. /** @var string name of the element */
  699. protected $name;
  700. /** @var string path within the XML file this element will handle */
  701. protected $path;
  702. /** @var bool flag to define if this element will get child ones grouped or no */
  703. protected $grouped;
  704. /** @var object object instance in charge of processing this element. */
  705. protected $pobject = null;
  706. /** @var string the name of the processing method */
  707. protected $pmethod = null;
  708. /** @var string the name of the path start event handler */
  709. protected $smethod = null;
  710. /** @var string the name of the path end event handler */
  711. protected $emethod = null;
  712. /** @var mixed last data read for this element or returned data by processing method */
  713. protected $tags = null;
  714. /** @var array of deprecated fields that are dropped */
  715. protected $dropfields = array();
  716. /** @var array of fields renaming */
  717. protected $renamefields = array();
  718. /** @var array of new fields to add and their initial values */
  719. protected $newfields = array();
  720. /**
  721. * Constructor
  722. *
  723. * The optional recipe array can have three keys, and for each key, the value is another array.
  724. * - newfields => array fieldname => defaultvalue indicates fields that have been added to the table,
  725. * and so should be added to the XML.
  726. * - dropfields => array fieldname indicates fieldsthat have been dropped from the table,
  727. * and so can be dropped from the XML.
  728. * - renamefields => array oldname => newname indicates fieldsthat have been renamed in the table,
  729. * and so should be renamed in the XML.
  730. * {@line moodle1_course_outline_handler} is a good example that uses all of these.
  731. *
  732. * @param string $name name of the element
  733. * @param string $path path of the element
  734. * @param array $recipe basic description of the structure conversion
  735. * @param bool $grouped to gather information in grouped mode or no
  736. */
  737. public function __construct($name, $path, array $recipe = array(), $grouped = false) {
  738. $this->validate_name($name);
  739. $this->name = $name;
  740. $this->path = $path;
  741. $this->grouped = $grouped;
  742. // set the default method names
  743. $this->set_processing_method('process_' . $name);
  744. $this->set_start_method('on_'.$name.'_start');
  745. $this->set_end_method('on_'.$name.'_end');
  746. if ($grouped and !empty($recipe)) {
  747. throw new convert_path_exception('recipes_not_supported_for_grouped_elements');
  748. }
  749. if (isset($recipe['dropfields']) and is_array($recipe['dropfields'])) {
  750. $this->set_dropped_fields($recipe['dropfields']);
  751. }
  752. if (isset($recipe['renamefields']) and is_array($recipe['renamefields'])) {
  753. $this->set_renamed_fields($recipe['renamefields']);
  754. }
  755. if (isset($recipe['newfields']) and is_array($recipe['newfields'])) {
  756. $this->set_new_fields($recipe['newfields']);
  757. }
  758. }
  759. /**
  760. * Validates and sets the given processing object
  761. *
  762. * @param object $pobject processing object, must provide a method to be called
  763. */
  764. public function set_processing_object($pobject) {
  765. $this->validate_pobject($pobject);
  766. $this->pobject = $pobject;
  767. }
  768. /**
  769. * Sets the name of the processing method
  770. *
  771. * @param string $pmethod
  772. */
  773. public function set_processing_method($pmethod) {
  774. $this->pmethod = $pmethod;
  775. }
  776. /**
  777. * Sets the name of the path start event listener
  778. *
  779. * @param string $smethod
  780. */
  781. public function set_start_method($smethod) {
  782. $this->smethod = $smethod;
  783. }
  784. /**
  785. * Sets the name of the path end event listener
  786. *
  787. * @param string $emethod
  788. */
  789. public function set_end_method($emethod) {
  790. $this->emethod = $emethod;
  791. }
  792. /**
  793. * Sets the element tags
  794. *
  795. * @param array $tags
  796. */
  797. public function set_tags($tags) {
  798. $this->tags = $tags;
  799. }
  800. /**
  801. * Sets the list of deprecated fields to drop
  802. *
  803. * @param array $fields
  804. */
  805. public function set_dropped_fields(array $fields) {
  806. $this->dropfields = $fields;
  807. }
  808. /**
  809. * Sets the required new names of the current fields
  810. *
  811. * @param array $fields (string)$currentname => (string)$newname
  812. */
  813. public function set_renamed_fields(array $fields) {
  814. $this->renamefields = $fields;
  815. }
  816. /**
  817. * Sets the new fields and their values
  818. *
  819. * @param array $fields (string)$field => (mixed)value
  820. */
  821. public function set_new_fields(array $fields) {
  822. $this->newfields = $fields;
  823. }
  824. /**
  825. * Cooks the parsed tags data by applying known recipes
  826. *
  827. * Recipes are used for common trivial operations like adding new fields
  828. * or renaming fields. The handler's processing method receives cooked
  829. * data.
  830. *
  831. * @param array $data the contents of the element
  832. * @return array
  833. */
  834. public function apply_recipes(array $data) {
  835. $cooked = array();
  836. foreach ($data as $name => $value) {
  837. // lower case rocks!
  838. $name = strtolower($name);
  839. if (is_array($value)) {
  840. if ($this->is_grouped()) {
  841. $value = $this->apply_recipes($value);
  842. } else {
  843. throw new convert_path_exception('non_grouped_path_with_array_values');
  844. }
  845. }
  846. // drop legacy fields
  847. if (in_array($name, $this->dropfields)) {
  848. continue;
  849. }
  850. // fields renaming
  851. if (array_key_exists($name, $this->renamefields)) {
  852. $name = $this->renamefields[$name];
  853. }
  854. $cooked[$name] = $value;
  855. }
  856. // adding new fields
  857. foreach ($this->newfields as $name => $value) {
  858. $cooked[$name] = $value;
  859. }
  860. return $cooked;
  861. }
  862. /**
  863. * @return string the element given name
  864. */
  865. public function get_name() {
  866. return $this->name;
  867. }
  868. /**
  869. * @return string the path to the element
  870. */
  871. public function get_path() {
  872. return $this->path;
  873. }
  874. /**
  875. * @return bool flag to define if this element will get child ones grouped or no
  876. */
  877. public function is_grouped() {
  878. return $this->grouped;
  879. }
  880. /**
  881. * @return object the processing object providing the processing method
  882. */
  883. public function get_processing_object() {
  884. return $this->pobject;
  885. }
  886. /**
  887. * @return string the name of the method to call to process the element
  888. */
  889. public function get_processing_method() {
  890. return $this->pmethod;
  891. }
  892. /**
  893. * @return string the name of the path start event listener
  894. */
  895. public function get_start_method() {
  896. return $this->smethod;
  897. }
  898. /**
  899. * @return string the name of the path end event listener
  900. */
  901. public function get_end_method() {
  902. return $this->emethod;
  903. }
  904. /**
  905. * @return mixed the element data
  906. */
  907. public function get_tags() {
  908. return $this->tags;
  909. }
  910. /// end of public API //////////////////////////////////////////////////////
  911. /**
  912. * Makes sure the given name is a valid element name
  913. *
  914. * Note it may look as if we used exceptions for code flow control here. That's not the case
  915. * as we actually validate the code, not the user data. And the code is supposed to be
  916. * correct.
  917. *
  918. * @param string @name the element given name
  919. * @throws convert_path_exception
  920. * @return void
  921. */
  922. protected function validate_name($name) {
  923. // Validate various name constraints, throwing exception if needed
  924. if (empty($name)) {
  925. throw new convert_path_exception('convert_path_emptyname', $name);
  926. }
  927. if (preg_replace('/\s/', '', $name) != $name) {
  928. throw new convert_path_exception('convert_path_whitespace', $name);
  929. }
  930. if (preg_replace('/[^\x30-\x39\x41-\x5a\x5f\x61-\x7a]/', '', $name) != $name) {
  931. throw new convert_path_exception('convert_path_notasciiname', $name);
  932. }
  933. }
  934. /**
  935. * Makes sure that the given object is a valid processing object
  936. *
  937. * The processing object must be an object providing at least element's processing method
  938. * or path-reached-end event listener or path-reached-start listener method.
  939. *
  940. * Note it may look as if we used exceptions for code flow control here. That's not the case
  941. * as we actually validate the code, not the user data. And the code is supposed to be
  942. * correct.
  943. *
  944. * @param object $pobject
  945. * @throws convert_path_exception
  946. * @return void
  947. */
  948. protected function validate_pobject($pobject) {
  949. if (!is_object($pobject)) {
  950. throw new convert_path_exception('convert_path_no_object', get_class($pobject));
  951. }
  952. if (!method_exists($pobject, $this->get_processing_method()) and
  953. !method_exists($pobject, $this->get_end_method()) and
  954. !method_exists($pobject, $this->get_start_method())) {
  955. throw new convert_path_exception('convert_path_missing_method', get_class($pobject));
  956. }
  957. }
  958. }
  959. /**
  960. * Exception being thrown by {@link convert_path} methods
  961. */
  962. class convert_path_exception extends moodle_exception {
  963. /**
  964. * Constructor
  965. *
  966. * @param string $errorcode key for the corresponding error string
  967. * @param mixed $a extra words and phrases that might be required by the error string
  968. * @param string $debuginfo optional debugging information
  969. */
  970. public function __construct($errorcode, $a = null, $debuginfo = null) {
  971. parent::__construct($errorcode, '', '', $a, $debuginfo);
  972. }
  973. }
  974. /**
  975. * The class responsible for files migration
  976. *
  977. * The files in Moodle 1.9 backup are stored in moddata, user_files, group_files,
  978. * course_files and site_files folders.
  979. */
  980. class moodle1_file_manager implements loggable {
  981. /** @var moodle1_converter instance we serve to */
  982. public $converter;
  983. /** @var int context id of the files being migrated */
  984. public $contextid;
  985. /** @var string component name of the files being migrated */
  986. public $component;
  987. /** @var string file area of the files being migrated */
  988. public $filearea;
  989. /** @var int item id of the files being migrated */
  990. public $itemid = 0;
  991. /** @var int user id */
  992. public $userid;
  993. /** @var string the root of the converter temp directory */
  994. protected $basepath;
  995. /** @var array of file ids that were migrated by this instance */
  996. protected $fileids = array();
  997. /**
  998. * Constructor optionally accepting some default values for the migrated files
  999. *
  1000. * @param moodle1_converter $converter the converter instance we serve to
  1001. * @param int $contextid initial context id of the files being migrated
  1002. * @param string $component initial component name of the files being migrated
  1003. * @param string $filearea initial file area of the files being migrated
  1004. * @param int $itemid initial item id of the files being migrated
  1005. * @param int $userid initial user id of the files being migrated
  1006. */
  1007. public function __construct(moodle1_converter $converter, $contextid = null, $component = null, $filearea = null, $itemid = 0, $userid = null) {
  1008. // set the initial destination of the migrated files
  1009. $this->converter = $converter;
  1010. $this->contextid = $contextid;
  1011. $this->component = $component;
  1012. $this->filearea = $filearea;
  1013. $this->itemid = $itemid;
  1014. $this->userid = $userid;
  1015. // set other useful bits
  1016. $this->basepath = $converter->get_tempdir_path();
  1017. }
  1018. /**
  1019. * Migrates one given file stored on disk
  1020. *
  1021. * @param string $sourcepath the path to the source local file within the backup archive {@example 'moddata/foobar/file.ext'}
  1022. * @param string $filepath the file path of the migrated file, defaults to the root directory '/' {@example '/sub/dir/'}
  1023. * @param string $filename the name of the migrated file, defaults to the same as the source file has
  1024. * @param int $sortorder the sortorder of the file (main files have sortorder set to 1)
  1025. * @param int $timecreated override the timestamp of when the migrated file should appear as created
  1026. * @param int $timemodified override the timestamp of when the migrated file should appear as modified
  1027. * @return int id of the migrated file
  1028. */
  1029. public function migrate_file($sourcepath, $filepath = '/', $filename = null, $sortorder = 0, $timecreated = null, $timemodified = null) {
  1030. // Normalise Windows paths a bit.
  1031. $sourcepath = str_replace('\\', '/', $sourcepath);
  1032. // PARAM_PATH must not be used on full OS path!
  1033. if ($sourcepath !== clean_param($sourcepath, PARAM_PATH)) {
  1034. throw new moodle1_convert_exception('file_invalid_path', $sourcepath);
  1035. }
  1036. $sourcefullpath = $this->basepath.'/'.$sourcepath;
  1037. if (!is_readable($sourcefullpath)) {
  1038. throw new moodle1_convert_exception('file_not_readable', $sourcefullpath);
  1039. }
  1040. // sanitize filepath
  1041. if (empty($filepath)) {
  1042. $filepath = '/';
  1043. }
  1044. if (substr($filepath, -1) !== '/') {
  1045. $filepath .= '/';
  1046. }
  1047. $filepath = clean_param($filepath, PARAM_PATH);
  1048. if (core_text::strlen($filepath) > 255) {
  1049. throw new moodle1_convert_exception('file_path_longer_than_255_chars');
  1050. }
  1051. if (is_null($filename)) {
  1052. $filename = basename($sourcefullpath);
  1053. }
  1054. $filename = clean_param($filename, PARAM_FILE);
  1055. if ($filename === '') {
  1056. throw new moodle1_convert_exception('unsupported_chars_in_filename');
  1057. }
  1058. if (is_null($timecreated)) {
  1059. $timecreated = filectime($sourcefullpath);
  1060. }
  1061. if (is_null($timemodified)) {
  1062. $timemodified = filemtime($sourcefullpath);
  1063. }
  1064. $filerecord = $this->make_file_record(array(
  1065. 'filepath' => $filepath,
  1066. 'filename' => $filename,
  1067. 'sortorder' => $sortorder,
  1068. 'mimetype' => mimeinfo('type', $sourcefullpath),
  1069. 'timecreated' => $timecreated,
  1070. 'timemodified' => $timemodified,
  1071. ));
  1072. list($filerecord['contenthash'], $filerecord['filesize'], $newfile) = $this->add_file_to_pool($sourcefullpath);
  1073. $this->stash_file($filerecord);
  1074. return $filerecord['id'];
  1075. }
  1076. /**
  1077. * Migrates all files in the given directory
  1078. *
  1079. * @param string $rootpath path within the backup archive to the root directory containing the files {@example 'course_files'}
  1080. * @param string $relpath relative path used during the recursion - do not provide when calling this!
  1081. * @return array ids of the migrated files, empty array if the $rootpath not found
  1082. */
  1083. public function migrate_directory($rootpath, $relpath='/') {
  1084. // Check the trailing slash in the $rootpath
  1085. if (substr($rootpath, -1) === '/') {
  1086. debugging('moodle1_file_manager::migrate_directory() expects $rootpath without the trailing slash', DEBUG_DEVELOPER);
  1087. $rootpath = substr($rootpath, 0, strlen($rootpath) - 1);
  1088. }
  1089. if (!file_exists($this->basepath.'/'.$rootpath.$relpath)) {
  1090. return array();
  1091. }
  1092. $fileids = array();
  1093. // make the fake file record for the directory itself
  1094. $filerecord = $this->make_file_record(array('filepath' => $relpath, 'filename' => '.'));
  1095. $this->stash_file($filerecord);
  1096. $fileids[] = $filerecord['id'];
  1097. $items = new DirectoryIterator($this->basepath.'/'.$rootpath.$relpath);
  1098. foreach ($items as $item) {
  1099. if ($item->isDot()) {
  1100. continue;
  1101. }
  1102. if ($item->isLink()) {
  1103. throw new moodle1_convert_exception('unexpected_symlink');
  1104. }
  1105. if ($item->isFile()) {
  1106. $fileids[] = $this->migrate_file(substr($item->getPathname(), strlen($this->basepath.'/')),
  1107. $relpath, $item->getFilename(), 0, $item->getCTime(), $item->getMTime());
  1108. } else {
  1109. $dirname = clean_param($item->getFilename(), PARAM_PATH);
  1110. if ($dirname === '') {
  1111. throw new moodle1_convert_exception('unsupported_chars_in_filename');
  1112. }
  1113. // migrate subdirectories recursively
  1114. $fileids = array_merge($fileids, $this->migrate_directory($rootpath, $relpath.$item->getFilename().'/'));
  1115. }
  1116. }
  1117. return $fileids;
  1118. }
  1119. /**
  1120. * Returns the list of all file ids migrated by this instance so far
  1121. *
  1122. * @return array of int
  1123. */
  1124. public function get_fileids() {
  1125. return $this->fileids;
  1126. }
  1127. /**
  1128. * Explicitly clear the list of file ids migrated by this instance so far
  1129. */
  1130. public function reset_fileids() {
  1131. $this->fileids = array();
  1132. }
  1133. /**
  1134. * Log a message using the converter's logging mechanism
  1135. *
  1136. * @param string $message message text
  1137. * @param int $level message level {@example backup::LOG_WARNING}
  1138. * @param null|mixed $a additional information
  1139. * @param null|int $depth the message depth
  1140. * @param bool $display whether the message should be sent to the output, too
  1141. */
  1142. public function log($message, $level, $a = null, $depth = null, $display = false) {
  1143. $this->converter->log($message, $level, $a, $depth, $display);
  1144. }
  1145. /// internal implementation details ////////////////////////////////////////
  1146. /**
  1147. * Prepares a fake record from the files table
  1148. *
  1149. * @param array $fileinfo explicit file data
  1150. * @return array
  1151. */
  1152. protected function make_file_record(array $fileinfo) {
  1153. $defaultrecord = array(
  1154. 'contenthash' => file_storage::hash_from_string(''),
  1155. 'contextid' => $this->contextid,
  1156. 'component' => $this->component,
  1157. 'filearea' => $this->filearea,
  1158. 'itemid' => $this->itemid,
  1159. 'filepath' => null,
  1160. 'filename' => null,
  1161. 'filesize' => 0,
  1162. 'userid' => $this->userid,
  1163. 'mimetype' => null,
  1164. 'status' => 0,
  1165. 'timecreated' => $now = time(),
  1166. 'timemodified' => $now,
  1167. 'source' => null,
  1168. 'author' => null,
  1169. 'license' => null,
  1170. 'sortorder' => 0,
  1171. );
  1172. if (!array_key_exists('id', $fileinfo)) {
  1173. $defaultrecord['id'] = $this->converter->get_nextid();
  1174. }
  1175. // override the default values with the explicit data provided and return
  1176. return array_merge($defaultrecord, $fileinfo);
  1177. }
  1178. /**
  1179. * Copies the given file to the pool directory
  1180. *
  1181. * Returns an array containing SHA1 hash of the file contents, the file size
  1182. * and a flag indicating whether the file was actually added to the pool or whether
  1183. * it was already there.
  1184. *
  1185. * @param string $pathname the full path to the file

Large files files are truncated, but you can click here to view the full file