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