PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/mod/book/tool/importhtml/locallib.php

http://github.com/moodle/moodle
PHP | 346 lines | 238 code | 29 blank | 79 comment | 59 complexity | 837ea5246adb043b62b256acc77f1890 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  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. * HTML import lib
  18. *
  19. * @package booktool_importhtml
  20. * @copyright 2011 Petr Skoda {@link http://skodak.org}
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die;
  24. require_once(__DIR__.'/lib.php');
  25. require_once($CFG->dirroot.'/mod/book/locallib.php');
  26. /**
  27. * Import HTML pages packaged into one zip archive
  28. *
  29. * @param stored_file $package
  30. * @param string $type type of the package ('typezipdirs' or 'typezipfiles')
  31. * @param stdClass $book
  32. * @param context_module $context
  33. * @param bool $verbose
  34. */
  35. function toolbook_importhtml_import_chapters($package, $type, $book, $context, $verbose = true) {
  36. global $DB, $OUTPUT;
  37. $fs = get_file_storage();
  38. $chapterfiles = toolbook_importhtml_get_chapter_files($package, $type);
  39. $packer = get_file_packer('application/zip');
  40. $fs->delete_area_files($context->id, 'mod_book', 'importhtmltemp', 0);
  41. $package->extract_to_storage($packer, $context->id, 'mod_book', 'importhtmltemp', 0, '/');
  42. // $datafiles = $fs->get_area_files($context->id, 'mod_book', 'importhtmltemp', 0, 'id', false);
  43. // echo "<pre>";p(var_export($datafiles, true));
  44. $chapters = array();
  45. if ($verbose) {
  46. echo $OUTPUT->notification(get_string('importing', 'booktool_importhtml'), 'notifysuccess');
  47. }
  48. if ($type == 0) {
  49. $chapterfile = reset($chapterfiles);
  50. if ($file = $fs->get_file_by_hash(sha1("$context->id/mod_book/importhtmltemp/0/$chapterfile->pathname"))) {
  51. $htmlcontent = toolbook_importhtml_fix_encoding($file->get_content());
  52. $htmlchapters = toolbook_importhtml_parse_headings(toolbook_importhtml_parse_body($htmlcontent));
  53. // TODO: process h1 as main chapter and h2 as subchapters
  54. }
  55. } else {
  56. foreach ($chapterfiles as $chapterfile) {
  57. if ($file = $fs->get_file_by_hash(sha1("/$context->id/mod_book/importhtmltemp/0/$chapterfile->pathname"))) {
  58. $chapter = new stdClass();
  59. $htmlcontent = toolbook_importhtml_fix_encoding($file->get_content());
  60. $chapter->bookid = $book->id;
  61. $chapter->pagenum = $DB->get_field_sql('SELECT MAX(pagenum) FROM {book_chapters} WHERE bookid = ?', array($book->id)) + 1;
  62. $chapter->importsrc = '/'.$chapterfile->pathname;
  63. $chapter->content = toolbook_importhtml_parse_styles($htmlcontent);
  64. $chapter->content .= toolbook_importhtml_parse_body($htmlcontent);
  65. $chapter->title = toolbook_importhtml_parse_title($htmlcontent, $chapterfile->pathname);
  66. $chapter->contentformat = FORMAT_HTML;
  67. $chapter->hidden = 0;
  68. $chapter->timecreated = time();
  69. $chapter->timemodified = time();
  70. if (preg_match('/_sub(\/|\.htm)/i', $chapter->importsrc)) { // If filename or directory ends with *_sub treat as subchapters
  71. $chapter->subchapter = 1;
  72. } else {
  73. $chapter->subchapter = 0;
  74. }
  75. $chapter->id = $DB->insert_record('book_chapters', $chapter);
  76. $chapter = $DB->get_record('book_chapters', array('id' => $chapter->id));
  77. $chapters[$chapter->id] = $chapter;
  78. \mod_book\event\chapter_created::create_from_chapter($book, $context, $chapter)->trigger();
  79. }
  80. }
  81. }
  82. if ($verbose) {
  83. echo $OUTPUT->notification(get_string('relinking', 'booktool_importhtml'), 'notifysuccess');
  84. }
  85. $allchapters = $DB->get_records('book_chapters', array('bookid'=>$book->id), 'pagenum');
  86. foreach ($chapters as $chapter) {
  87. // find references to all files and copy them + relink them
  88. $matches = null;
  89. if (preg_match_all('/(src|codebase|name|href)\s*=\s*"([^"]+)"/i', $chapter->content, $matches)) {
  90. $file_record = array('contextid'=>$context->id, 'component'=>'mod_book', 'filearea'=>'chapter', 'itemid'=>$chapter->id);
  91. foreach ($matches[0] as $i => $match) {
  92. $filepath = dirname($chapter->importsrc).'/'.$matches[2][$i];
  93. $filepath = toolbook_importhtml_fix_path($filepath);
  94. if (strtolower($matches[1][$i]) === 'href') {
  95. // skip linked html files, we will try chapter relinking later
  96. foreach ($allchapters as $target) {
  97. if ($target->importsrc === $filepath) {
  98. continue 2;
  99. }
  100. }
  101. }
  102. if ($file = $fs->get_file_by_hash(sha1("/$context->id/mod_book/importhtmltemp/0$filepath"))) {
  103. if (!$oldfile = $fs->get_file_by_hash(sha1("/$context->id/mod_book/chapter/$chapter->id$filepath"))) {
  104. $fs->create_file_from_storedfile($file_record, $file);
  105. }
  106. $chapter->content = str_replace($match, $matches[1][$i].'="@@PLUGINFILE@@'.$filepath.'"', $chapter->content);
  107. }
  108. }
  109. $DB->set_field('book_chapters', 'content', $chapter->content, array('id'=>$chapter->id));
  110. }
  111. }
  112. unset($chapters);
  113. $allchapters = $DB->get_records('book_chapters', array('bookid'=>$book->id), 'pagenum');
  114. foreach ($allchapters as $chapter) {
  115. $newcontent = $chapter->content;
  116. $matches = null;
  117. if (preg_match_all('/(href)\s*=\s*"([^"]+)"/i', $chapter->content, $matches)) {
  118. foreach ($matches[0] as $i => $match) {
  119. if (strpos($matches[2][$i], ':') !== false or strpos($matches[2][$i], '@') !== false) {
  120. // it is either absolute or pluginfile link
  121. continue;
  122. }
  123. $chapterpath = dirname($chapter->importsrc).'/'.$matches[2][$i];
  124. $chapterpath = toolbook_importhtml_fix_path($chapterpath);
  125. foreach ($allchapters as $target) {
  126. if ($target->importsrc === $chapterpath) {
  127. $newcontent = str_replace($match, 'href="'.new moodle_url('/mod/book/view.php',
  128. array('id'=>$context->instanceid, 'chapterid'=>$target->id)).'"', $newcontent);
  129. }
  130. }
  131. }
  132. }
  133. if ($newcontent !== $chapter->content) {
  134. $DB->set_field('book_chapters', 'content', $newcontent, array('id'=>$chapter->id));
  135. }
  136. }
  137. $fs->delete_area_files($context->id, 'mod_book', 'importhtmltemp', 0);
  138. // update the revision flag - this takes a long time, better to refetch the current value
  139. $book = $DB->get_record('book', array('id'=>$book->id));
  140. $DB->set_field('book', 'revision', $book->revision+1, array('id'=>$book->id));
  141. }
  142. /**
  143. * Parse the headings of the imported package of type 'typeonefile'
  144. * (currently unsupported)
  145. *
  146. * @param string $html html content to parse
  147. * @todo implement this once the type 'typeonefile' is enabled
  148. */
  149. function toolbook_importhtml_parse_headings($html) {
  150. }
  151. /**
  152. * Parse the links to external css sheets of the imported html content
  153. *
  154. * @param string $html html content to parse
  155. * @return string all the links to external css sheets
  156. */
  157. function toolbook_importhtml_parse_styles($html) {
  158. $styles = '';
  159. if (preg_match('/<head[^>]*>(.+)<\/head>/is', $html, $matches)) {
  160. $head = $matches[1];
  161. if (preg_match_all('/<link[^>]+rel="stylesheet"[^>]*>/i', $head, $matches)) { // Extract links to css.
  162. for ($i=0; $i<count($matches[0]); $i++) {
  163. $styles .= $matches[0][$i]."\n";
  164. }
  165. }
  166. }
  167. return $styles;
  168. }
  169. /**
  170. * Normalize paths to be absolute
  171. *
  172. * @param string $path original path with MS/relative separators
  173. * @return string the normalized and cleaned absolute path
  174. */
  175. function toolbook_importhtml_fix_path($path) {
  176. $path = str_replace('\\', '/', $path); // anti MS hack
  177. $path = '/'.ltrim($path, './'); // dirname() produces . for top level files + our paths start with /
  178. $cnt = substr_count($path, '..');
  179. for ($i=0; $i<$cnt; $i++) {
  180. $path = preg_replace('|[^/]+/\.\./|', '', $path, 1);
  181. }
  182. $path = clean_param($path, PARAM_PATH);
  183. return $path;
  184. }
  185. /**
  186. * Convert some html content to utf8, getting original encoding from html headers
  187. *
  188. * @param string $html html content to convert
  189. * @return string html content converted to utf8
  190. */
  191. function toolbook_importhtml_fix_encoding($html) {
  192. if (preg_match('/<head[^>]*>(.+)<\/head>/is', $html, $matches)) {
  193. $head = $matches[1];
  194. if (preg_match('/charset=([^"]+)/is', $head, $matches)) {
  195. $enc = $matches[1];
  196. return core_text::convert($html, $enc, 'utf-8');
  197. }
  198. }
  199. return iconv('UTF-8', 'UTF-8//IGNORE', $html);
  200. }
  201. /**
  202. * Extract the body from any html contents
  203. *
  204. * @param string $html the html to parse
  205. * @return string the contents of the body
  206. */
  207. function toolbook_importhtml_parse_body($html) {
  208. $matches = null;
  209. if (preg_match('/<body[^>]*>(.+)<\/body>/is', $html, $matches)) {
  210. return $matches[1];
  211. } else {
  212. return '';
  213. }
  214. }
  215. /**
  216. * Extract the title of any html content, getting it from the title tag
  217. *
  218. * @param string $html the html to parse
  219. * @param string $default default title to apply if no title is found
  220. * @return string the resulting title
  221. */
  222. function toolbook_importhtml_parse_title($html, $default) {
  223. $matches = null;
  224. if (preg_match('/<title>([^<]+)<\/title>/i', $html, $matches)) {
  225. return $matches[1];
  226. } else {
  227. return $default;
  228. }
  229. }
  230. /**
  231. * Returns all the html files (chapters) from a file package
  232. *
  233. * @param stored_file $package file to be processed
  234. * @param string $type type of the package ('typezipdirs' or 'typezipfiles')
  235. *
  236. * @return array the html files found in the package
  237. */
  238. function toolbook_importhtml_get_chapter_files($package, $type) {
  239. $packer = get_file_packer('application/zip');
  240. $files = $package->list_files($packer);
  241. $tophtmlfiles = array();
  242. $subhtmlfiles = array();
  243. $topdirs = array();
  244. foreach ($files as $file) {
  245. if (empty($file->pathname)) {
  246. continue;
  247. }
  248. if (substr($file->pathname, -1) === '/') {
  249. if (substr_count($file->pathname, '/') !== 1) {
  250. // skip subdirs
  251. continue;
  252. }
  253. if (!isset($topdirs[$file->pathname])) {
  254. $topdirs[$file->pathname] = array();
  255. }
  256. } else {
  257. $mime = mimeinfo('icon', $file->pathname);
  258. if ($mime !== 'html') {
  259. continue;
  260. }
  261. $level = substr_count($file->pathname, '/');
  262. if ($level === 0) {
  263. $tophtmlfiles[$file->pathname] = $file;
  264. } else if ($level === 1) {
  265. $subhtmlfiles[$file->pathname] = $file;
  266. $dir = preg_replace('|/.*$|', '', $file->pathname);
  267. $topdirs[$dir][$file->pathname] = $file;
  268. } else {
  269. // lower levels are not interesting
  270. continue;
  271. }
  272. }
  273. }
  274. core_collator::ksort($tophtmlfiles, core_collator::SORT_NATURAL);
  275. core_collator::ksort($subhtmlfiles, core_collator::SORT_NATURAL);
  276. core_collator::ksort($topdirs, core_collator::SORT_NATURAL);
  277. $chapterfiles = array();
  278. if ($type == 2) {
  279. $chapterfiles = $tophtmlfiles;
  280. } else if ($type == 1) {
  281. foreach ($topdirs as $dir => $htmlfiles) {
  282. if (empty($htmlfiles)) {
  283. continue;
  284. }
  285. core_collator::ksort($htmlfiles, core_collator::SORT_NATURAL);
  286. if (isset($htmlfiles[$dir.'/index.html'])) {
  287. $htmlfile = $htmlfiles[$dir.'/index.html'];
  288. } else if (isset($htmlfiles[$dir.'/index.htm'])) {
  289. $htmlfile = $htmlfiles[$dir.'/index.htm'];
  290. } else if (isset($htmlfiles[$dir.'/Default.htm'])) {
  291. $htmlfile = $htmlfiles[$dir.'/Default.htm'];
  292. } else {
  293. $htmlfile = reset($htmlfiles);
  294. }
  295. $chapterfiles[$htmlfile->pathname] = $htmlfile;
  296. }
  297. } else if ($type == 0) {
  298. if ($tophtmlfiles) {
  299. if (isset($tophtmlfiles['index.html'])) {
  300. $htmlfile = $tophtmlfiles['index.html'];
  301. } else if (isset($tophtmlfiles['index.htm'])) {
  302. $htmlfile = $tophtmlfiles['index.htm'];
  303. } else if (isset($tophtmlfiles['Default.htm'])) {
  304. $htmlfile = $tophtmlfiles['Default.htm'];
  305. } else {
  306. $htmlfile = reset($tophtmlfiles);
  307. }
  308. } else {
  309. $htmlfile = reset($subhtmlfiles);
  310. }
  311. $chapterfiles[$htmlfile->pathname] = $htmlfile;
  312. }
  313. return $chapterfiles;
  314. }