PageRenderTime 32ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/synergylearning/campusconnect
PHP | 352 lines | 244 code | 29 blank | 79 comment | 59 complexity | e647e8accb6fa7d91ff544ba8a4e45b5 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-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. * 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(dirname(__FILE__).'/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. $chapters[$chapter->id] = $chapter;
  77. $params = array(
  78. 'context' => $context,
  79. 'objectid' => $chapter->id
  80. );
  81. $event = \mod_book\event\chapter_created::create($params);
  82. $event->add_record_snapshot('book_chapters', $chapter);
  83. $event->trigger();
  84. }
  85. }
  86. }
  87. if ($verbose) {
  88. echo $OUTPUT->notification(get_string('relinking', 'booktool_importhtml'), 'notifysuccess');
  89. }
  90. $allchapters = $DB->get_records('book_chapters', array('bookid'=>$book->id), 'pagenum');
  91. foreach ($chapters as $chapter) {
  92. // find references to all files and copy them + relink them
  93. $matches = null;
  94. if (preg_match_all('/(src|codebase|name|href)\s*=\s*"([^"]+)"/i', $chapter->content, $matches)) {
  95. $file_record = array('contextid'=>$context->id, 'component'=>'mod_book', 'filearea'=>'chapter', 'itemid'=>$chapter->id);
  96. foreach ($matches[0] as $i => $match) {
  97. $filepath = dirname($chapter->importsrc).'/'.$matches[2][$i];
  98. $filepath = toolbook_importhtml_fix_path($filepath);
  99. if (strtolower($matches[1][$i]) === 'href') {
  100. // skip linked html files, we will try chapter relinking later
  101. foreach ($allchapters as $target) {
  102. if ($target->importsrc === $filepath) {
  103. continue 2;
  104. }
  105. }
  106. }
  107. if ($file = $fs->get_file_by_hash(sha1("/$context->id/mod_book/importhtmltemp/0$filepath"))) {
  108. if (!$oldfile = $fs->get_file_by_hash(sha1("/$context->id/mod_book/chapter/$chapter->id$filepath"))) {
  109. $fs->create_file_from_storedfile($file_record, $file);
  110. }
  111. $chapter->content = str_replace($match, $matches[1][$i].'="@@PLUGINFILE@@'.$filepath.'"', $chapter->content);
  112. }
  113. }
  114. $DB->set_field('book_chapters', 'content', $chapter->content, array('id'=>$chapter->id));
  115. }
  116. }
  117. unset($chapters);
  118. $allchapters = $DB->get_records('book_chapters', array('bookid'=>$book->id), 'pagenum');
  119. foreach ($allchapters as $chapter) {
  120. $newcontent = $chapter->content;
  121. $matches = null;
  122. if (preg_match_all('/(href)\s*=\s*"([^"]+)"/i', $chapter->content, $matches)) {
  123. foreach ($matches[0] as $i => $match) {
  124. if (strpos($matches[2][$i], ':') !== false or strpos($matches[2][$i], '@') !== false) {
  125. // it is either absolute or pluginfile link
  126. continue;
  127. }
  128. $chapterpath = dirname($chapter->importsrc).'/'.$matches[2][$i];
  129. $chapterpath = toolbook_importhtml_fix_path($chapterpath);
  130. foreach ($allchapters as $target) {
  131. if ($target->importsrc === $chapterpath) {
  132. $newcontent = str_replace($match, 'href="'.new moodle_url('/mod/book/view.php',
  133. array('id'=>$context->instanceid, 'chapterid'=>$target->id)).'"', $newcontent);
  134. }
  135. }
  136. }
  137. }
  138. if ($newcontent !== $chapter->content) {
  139. $DB->set_field('book_chapters', 'content', $newcontent, array('id'=>$chapter->id));
  140. }
  141. }
  142. add_to_log($book->course, 'course', 'update mod', '../mod/book/view.php?id='.$context->instanceid, 'book '.$book->id);
  143. $fs->delete_area_files($context->id, 'mod_book', 'importhtmltemp', 0);
  144. // update the revision flag - this takes a long time, better to refetch the current value
  145. $book = $DB->get_record('book', array('id'=>$book->id));
  146. $DB->set_field('book', 'revision', $book->revision+1, array('id'=>$book->id));
  147. }
  148. /**
  149. * Parse the headings of the imported package of type 'typeonefile'
  150. * (currently unsupported)
  151. *
  152. * @param string $html html content to parse
  153. * @todo implement this once the type 'typeonefile' is enabled
  154. */
  155. function toolbook_importhtml_parse_headings($html) {
  156. }
  157. /**
  158. * Parse the links to external css sheets of the imported html content
  159. *
  160. * @param string $html html content to parse
  161. * @return string all the links to external css sheets
  162. */
  163. function toolbook_importhtml_parse_styles($html) {
  164. $styles = '';
  165. if (preg_match('/<head[^>]*>(.+)<\/head>/is', $html, $matches)) {
  166. $head = $matches[1];
  167. if (preg_match_all('/<link[^>]+rel="stylesheet"[^>]*>/i', $head, $matches)) { // Extract links to css.
  168. for ($i=0; $i<count($matches[0]); $i++) {
  169. $styles .= $matches[0][$i]."\n";
  170. }
  171. }
  172. }
  173. return $styles;
  174. }
  175. /**
  176. * Normalize paths to be absolute
  177. *
  178. * @param string $path original path with MS/relative separators
  179. * @return string the normalized and cleaned absolute path
  180. */
  181. function toolbook_importhtml_fix_path($path) {
  182. $path = str_replace('\\', '/', $path); // anti MS hack
  183. $path = '/'.ltrim($path, './'); // dirname() produces . for top level files + our paths start with /
  184. $cnt = substr_count($path, '..');
  185. for ($i=0; $i<$cnt; $i++) {
  186. $path = preg_replace('|[^/]+/\.\./|', '', $path, 1);
  187. }
  188. $path = clean_param($path, PARAM_PATH);
  189. return $path;
  190. }
  191. /**
  192. * Convert some html content to utf8, getting original encoding from html headers
  193. *
  194. * @param string $html html content to convert
  195. * @return string html content converted to utf8
  196. */
  197. function toolbook_importhtml_fix_encoding($html) {
  198. if (preg_match('/<head[^>]*>(.+)<\/head>/is', $html, $matches)) {
  199. $head = $matches[1];
  200. if (preg_match('/charset=([^"]+)/is', $head, $matches)) {
  201. $enc = $matches[1];
  202. return core_text::convert($html, $enc, 'utf-8');
  203. }
  204. }
  205. return iconv('UTF-8', 'UTF-8//IGNORE', $html);
  206. }
  207. /**
  208. * Extract the body from any html contents
  209. *
  210. * @param string $html the html to parse
  211. * @return string the contents of the body
  212. */
  213. function toolbook_importhtml_parse_body($html) {
  214. $matches = null;
  215. if (preg_match('/<body[^>]*>(.+)<\/body>/is', $html, $matches)) {
  216. return $matches[1];
  217. } else {
  218. return '';
  219. }
  220. }
  221. /**
  222. * Extract the title of any html content, getting it from the title tag
  223. *
  224. * @param string $html the html to parse
  225. * @param string $default default title to apply if no title is found
  226. * @return string the resulting title
  227. */
  228. function toolbook_importhtml_parse_title($html, $default) {
  229. $matches = null;
  230. if (preg_match('/<title>([^<]+)<\/title>/i', $html, $matches)) {
  231. return $matches[1];
  232. } else {
  233. return $default;
  234. }
  235. }
  236. /**
  237. * Returns all the html files (chapters) from a file package
  238. *
  239. * @param stored_file $package file to be processed
  240. * @param string $type type of the package ('typezipdirs' or 'typezipfiles')
  241. *
  242. * @return array the html files found in the package
  243. */
  244. function toolbook_importhtml_get_chapter_files($package, $type) {
  245. $packer = get_file_packer('application/zip');
  246. $files = $package->list_files($packer);
  247. $tophtmlfiles = array();
  248. $subhtmlfiles = array();
  249. $topdirs = array();
  250. foreach ($files as $file) {
  251. if (empty($file->pathname)) {
  252. continue;
  253. }
  254. if (substr($file->pathname, -1) === '/') {
  255. if (substr_count($file->pathname, '/') !== 1) {
  256. // skip subdirs
  257. continue;
  258. }
  259. if (!isset($topdirs[$file->pathname])) {
  260. $topdirs[$file->pathname] = array();
  261. }
  262. } else {
  263. $mime = mimeinfo('icon', $file->pathname);
  264. if ($mime !== 'html') {
  265. continue;
  266. }
  267. $level = substr_count($file->pathname, '/');
  268. if ($level === 0) {
  269. $tophtmlfiles[$file->pathname] = $file;
  270. } else if ($level === 1) {
  271. $subhtmlfiles[$file->pathname] = $file;
  272. $dir = preg_replace('|/.*$|', '', $file->pathname);
  273. $topdirs[$dir][$file->pathname] = $file;
  274. } else {
  275. // lower levels are not interesting
  276. continue;
  277. }
  278. }
  279. }
  280. core_collator::ksort($tophtmlfiles, core_collator::SORT_NATURAL);
  281. core_collator::ksort($subhtmlfiles, core_collator::SORT_NATURAL);
  282. core_collator::ksort($topdirs, core_collator::SORT_NATURAL);
  283. $chapterfiles = array();
  284. if ($type == 2) {
  285. $chapterfiles = $tophtmlfiles;
  286. } else if ($type == 1) {
  287. foreach ($topdirs as $dir => $htmlfiles) {
  288. if (empty($htmlfiles)) {
  289. continue;
  290. }
  291. core_collator::ksort($htmlfiles, core_collator::SORT_NATURAL);
  292. if (isset($htmlfiles[$dir.'/index.html'])) {
  293. $htmlfile = $htmlfiles[$dir.'/index.html'];
  294. } else if (isset($htmlfiles[$dir.'/index.htm'])) {
  295. $htmlfile = $htmlfiles[$dir.'/index.htm'];
  296. } else if (isset($htmlfiles[$dir.'/Default.htm'])) {
  297. $htmlfile = $htmlfiles[$dir.'/Default.htm'];
  298. } else {
  299. $htmlfile = reset($htmlfiles);
  300. }
  301. $chapterfiles[$htmlfile->pathname] = $htmlfile;
  302. }
  303. } else if ($type == 0) {
  304. if ($tophtmlfiles) {
  305. if (isset($tophtmlfiles['index.html'])) {
  306. $htmlfile = $tophtmlfiles['index.html'];
  307. } else if (isset($tophtmlfiles['index.htm'])) {
  308. $htmlfile = $tophtmlfiles['index.htm'];
  309. } else if (isset($tophtmlfiles['Default.htm'])) {
  310. $htmlfile = $tophtmlfiles['Default.htm'];
  311. } else {
  312. $htmlfile = reset($tophtmlfiles);
  313. }
  314. } else {
  315. $htmlfile = reset($subhtmlfiles);
  316. }
  317. $chapterfiles[$htmlfile->pathname] = $htmlfile;
  318. }
  319. return $chapterfiles;
  320. }