Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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