lib.php 38.6 KB
Newer Older
1
2
3
4
5
6
<?php
/**
 *
 * @package    mahara
 * @subpackage export-html
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 *
 */

defined('INTERNAL') || die();

/**
 * HTML export plugin
 */
class PluginExportHtml extends PluginExport {

    /**
     * name of resultant zipfile
     */
    protected $zipfile;

    /**
Aaron Wells's avatar
Aaron Wells committed
25
     * The name of the directory under which all the other directories and
26
27
28
29
     * files will be placed in the export
     */
    protected $rootdir;

30
31
32
33
34
35
    /**
     * List of directories of static files provided by artefact plugins
     */
    private $pluginstaticdirs = array();

    /**
36
37
     * List of stylesheets to include in the export.
     *
Aaron Wells's avatar
Aaron Wells committed
38
     * This is keyed by artefact plugin name, the empty string key contains
39
     * stylesheets that will be included on all pages.
40
     */
41
    private $stylesheets = array('' => array());
42

43
44
    /**
     * Whether the user requested to export just one view. In this case,
Aaron Wells's avatar
Aaron Wells committed
45
     * the generated export doesn't have the home page - just the View is
46
47
48
49
     * exported (plus artefacts of course)
     */
    protected $exportingoneview = false;

50
51
52
53
    /**
    * constructor.  overrides the parent class
    * to set up smarty and the attachment directory
    */
54
    public function __construct(User $user, $views, $artefacts, $progresscallback=null) {
55
        global $THEME;
56
        parent::__construct($user, $views, $artefacts, $progresscallback);
57
        $this->rootdir = 'portfolio-for-' . self::text_to_filename($user->get('username'));
58
59

        // Create basic required directories
60
        foreach (array('files', 'views', 'static', 'static/smilies', 'static/profileicons') as $directory) {
61
62
63
64
65
66
            $directory = "{$this->exportdir}/{$this->rootdir}/{$directory}/";
            if (!check_dir_exists($directory)) {
                throw new SystemException("Couldn't create the temporary export directory $directory");
            }
        }
        $this->zipfile = 'mahara-export-html-user'
67
            . $this->get('user')->get('id') . '-' . $this->exporttime . '.zip';
68
69

        // Find what stylesheets need to be included
70
        $themedirs = $THEME->get_path('', true);
71
        foreach ($themedirs as $theme => $themedir) {
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
            if (is_readable($themedir . 'style/')) {
                $files = scandir($themedir . 'style/');
                foreach ($files as $stylesheet) {
                    if (substr_count($stylesheet, '.css') > 0) {
                        array_unshift($this->stylesheets[''], 'theme/' . $theme . '/static/style/' . $stylesheet);
                    }
                }
            }
        }
        // Find what export plugin stylesheets need to be included
        $exportthemedirs = $THEME->get_path('', true, 'export/html');
        foreach ($exportthemedirs as $theme => $themedir) {
            if (is_readable($themedir . 'style/')) {
                $files = scandir($themedir . 'style/');
                foreach ($files as $stylesheet) {
                    if (substr_count($stylesheet, '.css') > 0) {
                        array_unshift($this->stylesheets[''], 'theme/' . $theme . '/static/export/style/' . $stylesheet);
                    }
90
91
92
93
                }
            }
        }

94
95
96
97
98
99
100
        // Don't export the dashboard
        foreach (array_keys($this->views) as $i) {
            if ($this->views[$i]->get('type') == 'dashboard') {
                unset($this->views[$i]);
            }
        }

101
102
103
104
105
106
        $this->exportingoneview = (
            $this->viewexportmode == PluginExport::EXPORT_LIST_OF_VIEWS &&
            $this->artefactexportmode == PluginExport::EXPORT_ARTEFACTS_FOR_VIEWS &&
            count($this->views) == 1
        );

107
        $this->notify_progress_callback(15, get_string('setupcomplete', 'export'));
108
109
    }

110
111
112
113
114
115
116
117
    public static function get_title() {
        return get_string('title', 'export.html');
    }

    public static function get_description() {
        return get_string('description', 'export.html');
    }

118
119
120
121
    public function is_diskspace_available() {
        return true; // need to create a check here
    }

122
    /**
Nigel McNie's avatar
Nigel McNie committed
123
124
     * Main export routine
     */
125
    public function export() {
126
        global $THEME, $SESSION;
127
128
        raise_memory_limit('128M');

129
        $summaries = array();
130
        $plugins = plugins_installed('artefact', true);
131
        $exportplugins = array();
132
        $progressstart = 15;
133
        $progressend   = 25;
134
        $plugincount   = count($plugins);
135

Aaron Wells's avatar
Aaron Wells committed
136
        // First pass: find out which plugins are exporting like us, and ask
137
        // them about the static data they want to include in every template
138
139
        $i = 0;
        foreach ($plugins as $plugin) {
140
            $plugin = $plugin->name;
141
            $this->notify_progress_callback(intval($progressstart + (++$i / $plugincount) * ($progressend - $progressstart)), get_string('preparing', 'export.html', $plugin));
142

143
            if (safe_require('export', 'html/' . $plugin, 'lib.php', 'require_once', true)) {
144
145
                $exportplugins[] = $plugin;

146
147
148
149
150
151
152
                $classname = 'HtmlExport' . ucfirst($plugin);
                if (!is_subclass_of($classname, 'HtmlExportArtefactPlugin')) {
                    throw new SystemException("Class $classname does not extend HtmlExportArtefactPlugin as it should");
                }

                safe_require('artefact', $plugin);

153
                // Find out whether the plugin has static data for us
154
                $themestaticdirs = array_reverse($THEME->get_path('', true, 'artefact/' . $plugin . '/export/html'));
155
156
157
                foreach ($themestaticdirs as $dir) {
                    $staticdir = substr($dir, strlen(get_config('docroot') . 'artefact/'));
                    $this->pluginstaticdirs[] = $staticdir;
158
                    foreach (array('style.css') as $stylesheet) {
159
                        if (is_readable($dir . 'style/' . $stylesheet)) {
160
                            $this->stylesheets[$plugin][] = str_replace('export/html/', '', $staticdir) . 'style/' . $stylesheet;
161
162
                        }
                    }
163
                }
164
165
166
            }
        }

167
168
        // Second pass: actually dump data for active export plugins
        $progressstart = 25;
169
        $progressend   = 50;
170
171
        $i = 0;
        foreach ($exportplugins as $plugin) {
172
            $this->notify_progress_callback(intval($progressstart + (++$i / $plugincount) * ($progressend - $progressstart)), get_string('exportingdatafor', 'export.html', $plugin));
173
174
175
176
            $classname = 'HtmlExport' . ucfirst($plugin);
            $artefactexporter = new $classname($this);
            $artefactexporter->dump_export_data();
            // If just exporting a list of views, we don't care about the summaries for each artefact plugin
177
            if (!(($this->viewexportmode == PluginExport::EXPORT_LIST_OF_VIEWS || $this->viewexportmode == PluginExport::EXPORT_LIST_OF_COLLECTIONS)
178
                && $this->artefactexportmode == PluginExport::EXPORT_ARTEFACTS_FOR_VIEWS)) {
179
180
181
182
                $summaries[$plugin] = array($artefactexporter->get_summary_weight(), $artefactexporter->get_summary());
            }
        }

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        // Views in collections
        if (!$this->exportingoneview && $this->collections) {
            $viewlist = join(',', array_keys($this->views));
            $collectionlist = join(',', array_keys($this->collections));
            $records = get_records_select_array(
                'collection_view',
                "view IN ($viewlist) AND collection IN ($collectionlist)"
            );
            if ($records) {
                foreach ($records as &$r) {
                    $this->collectionview[$r->collection][] = $r->view;
                    $this->viewcollection[$r->view] = $r->collection;
                }
            }
        }

Nigel McNie's avatar
Nigel McNie committed
199
        // Get the view data
200
        $this->notify_progress_callback(55, get_string('exportingviews', 'export'));
Nigel McNie's avatar
Nigel McNie committed
201
202
        $this->dump_view_export_data();

203
        if (!$this->exportingoneview) {
204
205
206
            $viewcollectionsumary = $this->get_view_collection_summary();
            $summaries['view'] = array(100, $viewcollectionsumary['view']);
            $summaries['collection'] = array(110, $viewcollectionsumary['collection']);
207

208
            // Sort by weight (then drop the weight information)
209
210
211
            uasort($summaries, function ($a, $b) {
                return $a[0] > $b[0];
            });
212
213
214
215
216
            foreach ($summaries as &$summary) {
                $summary = $summary[1];
            }

            // Build index.html
217
            $this->notify_progress_callback(75, get_string('buildingindexpage', 'export.html'));
218
219
            $this->build_index_page($summaries);
        }
220
221

        // Copy all static files into the export
222
        $this->notify_progress_callback(80, get_string('copyingextrafiles', 'export.html'));
223
        $this->copy_static_files();
224
225
226
227
228

        // Copy all resized images that were found while rewriting the HTML
        $copyproxy = HtmlExportCopyProxy::singleton();
        $copydata = $copyproxy->get_copy_data();
        foreach ($copydata as $from => $to) {
229
230
            $to = $this->get('exportdir') . '/' . $this->get('rootdir') . $to;
            if (!check_dir_exists(dirname($to))) {
231
                $SESSION->add_error_msg(get_string('couldnotcreatedirectory', 'export', $todir));
232
233
            }
            if (!copy($from, $to)) {
234
                $SESSION->add_error_msg(get_string('couldnotcopystaticfile', 'export', $from));
235
236
            }
        }
237
238

        // zip everything up
239
        $this->notify_progress_callback(90, get_string('creatingzipfile', 'export'));
240
241
242
243
244
        try {
            create_zip_archive($this->exportdir, $this->zipfile, array($this->rootdir));
        }
        catch (SystemException $e) {
            throw new SystemException('Failed to zip the export file: ' . $e->getMessage());
245
        }
246
        $this->notify_progress_callback(100, get_string('Done', 'export'));
247
248
249
250
251
252
253
254
        return $this->zipfile;
    }

    public function cleanup() {
        // @todo remove temporary files and directories
        // @todo maybe move the zip file somewhere else - like to files/export or something
    }

255
256
257
258
259
260
261
    public function get_smarty($rootpath='', $section='') {
        if ($section && isset($this->stylesheets[$section])) {
            $stylesheets = array_merge($this->stylesheets[''], $this->stylesheets[$section]);
        }
        else {
            $stylesheets = $this->stylesheets[''];
        }
262
263
264
        $smarty = smarty_core();
        $smarty->assign('user', $this->get('user'));
        $smarty->assign('rootpath', $rootpath);
265
        $smarty->assign('export_time', $this->exporttime);
266
        $smarty->assign('sitename', get_config('sitename'));
267
        $smarty->assign('stylesheets', $stylesheets);
268
        $smarty->assign('maharalogo', $rootpath . $this->theme_path('images/site-logo.png'));
269
270
271
272

        return $smarty;
    }

273
    /**
Aaron Wells's avatar
Aaron Wells committed
274
     * Converts a relative path to a static file that the HTML export theme
275
276
277
278
279
     * should have, to a path in the static export where the file will reside.
     *
     * This returns the path in the most appropriate theme.
     */
    private function theme_path($path) {
280
        global $THEME;
281
        $themestaticdirs = $THEME->get_path('', true);
282
283
284
285
286
287
288
        foreach ($themestaticdirs as $theme => $dir) {
            if (is_readable($dir . $path)) {
                return 'static/theme/' . $theme . '/static/' . $path;
            }
        }
    }

289
    /**
290
     * Converts the UTF-8 passed text into a a form that could be used in a file name.
291
292
293
294
     *
     * @param string $text The text to convert
     * @return string      The converted text
     */
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    public static function text_to_filename($text) {
        // truncates the text and replaces NOT allowed characters to hyphens
        return preg_replace('#["*/:<>?\\| ]+#', '-', mb_substr($text, 0, parent::MAX_FILENAME_LENGTH, 'utf-8'));
    }

    /**
     * Converts the UTF-8 passed text into a a form that could be used in a URL.
     *
     * @param string $text The text to convert
     * @return string      The converted text
     */
    public static function text_to_URLpath($text) {
        $tab_text = str_split($text);
        $output = '';
        foreach ($tab_text as $id=>$char){
            $hex = dechex(ord($char));
            $output .= '%' . $hex;
        }
        return $output;
314
315
    }

316
317
318
    /**
     * Sanitises a string meant to be used as a filesystem path.
     *
Aaron Wells's avatar
Aaron Wells committed
319
     * Mahara allows file/folder artefact names to have slashes in them, which
320
321
322
     * aren't legal on most real filesystems.
     */
    public static function sanitise_path($path) {
323
        return trim(substr(str_replace('/', '_', $path), 0, 255));
324
325
326
    }


327
328
    private function build_index_page($summaries) {
        $smarty = $this->get_smarty();
329
        $smarty->assign('page_heading', full_name($this->get('user')));
330
331
        $smarty->assign('summaries', $summaries);
        $content = $smarty->fetch('export:html:index.tpl');
332
333
334
        if (!file_put_contents($this->exportdir . '/' . $this->rootdir . '/index.html', $content)) {
            throw new SystemException("Could not create index.html for the export");
        }
335
336
    }

337
338
339
340
341
342
343
344
    private function collection_menu($collectionid) {
        static $menus = array();
        if (!isset($menus[$collectionid])) {
            $menus[$collectionid] = array();
            foreach ($this->collectionview[$collectionid] as $viewid) {
                $title = $this->views[$viewid]->get('title');
                $menus[$collectionid][] = array(
                    'id'   => $viewid,
345
                    'url'  => self::text_to_URLpath(self::text_to_filename($title)) . '/index.html',
346
347
348
349
350
351
352
                    'text' => $title,
                );
            }
        }
        return $menus[$collectionid];
    }

Nigel McNie's avatar
Nigel McNie committed
353
354
355
356
    /**
     * Dumps all views into the HTML export
     */
    private function dump_view_export_data() {
357
        safe_require('artefact', 'comment');
358
359
360
361
        $progressstart = 55;
        $progressend   = 75;
        $i = 0;
        $viewcount = count($this->views);
362
363
        $rootpath = ($this->exportingoneview) ? './' : '../../';
        $smarty = $this->get_smarty($rootpath);
364
        foreach ($this->views as $viewid => $view) {
365
            $this->notify_progress_callback(intval($progressstart + (++$i / $viewcount) * ($progressend - $progressstart)), get_string('exportingviewsprogress', 'export', $i, $viewcount));
366
            $smarty->assign('page_heading', $view->get('title'));
367
            $smarty->assign('viewdescription', $view->get('description'));
368
            $smarty->assign('viewinstructions', $view->get('instructions'));
369

370
371
372
373
374
375
376
377
378
            if ($this->exportingoneview) {
                $smarty->assign('nobreadcrumbs', true);
                $directory = $this->exportdir . '/' . $this->rootdir;
            }
            else {
                $smarty->assign('breadcrumbs', array(
                    array('text' => get_string('Views', 'view')),
                    array('text' => $view->get('title'), 'path' => 'index.html'),
                ));
379
                $directory = $this->exportdir . '/' . $this->rootdir . '/views/' . self::text_to_filename($view->get('title'));
380
381
382
                if (is_dir($directory)) {
                    throw new SystemException(get_string('duplicatepagetitle', 'export.html'));
                }
383
384
385
                if (!check_dir_exists($directory)) {
                    throw new SystemException("Could not create directory for view $viewid");
                }
386
            }
Nigel McNie's avatar
Nigel McNie committed
387

388
            // Collection menu data
389
390
391
            if (isset($this->viewcollection[$viewid])
                && ($this->viewexportmode == PluginExport::EXPORT_LIST_OF_COLLECTIONS
                    || $this->viewexportmode == PluginExport::EXPORT_ALL_VIEWS_COLLECTIONS)) {
392
393
                $smarty->assign('collectionname', $this->collections[$this->viewcollection[$viewid]]->get('name'));
                $smarty->assign('collectionmenu', $this->collection_menu($this->viewcollection[$viewid]));
394
395
396
                $smarty->assign('viewid', $viewid);
            }

397
            $outputfilter = new HtmlExportOutputFilter($rootpath, $this);
398
399
400

            // Include comments
            if ($this->includefeedback) {
401
402
403
404
405
                $commentoptions = ArtefactTypeComment::get_comment_options();
                $commentoptions->view = $view;
                $commentoptions->limit = 0;
                $commentoptions->export = true;
                if ($feedback = ArtefactTypeComment::get_comments($commentoptions)) {
406
407
408
409
410
                    $feedback->tablerows = $outputfilter->filter($feedback->tablerows);
                }
                $smarty->assign('feedback', $feedback);
            }

411
            $smarty->assign('view', $outputfilter->filter($view->build_rows(false, true)));
412
413
414
            $content = $smarty->fetch('export:html:view.tpl');
            if (!file_put_contents("$directory/index.html", $content)) {
                throw new SystemException("Could not write view page for view $viewid");
Nigel McNie's avatar
Nigel McNie committed
415
416
417
418
            }
        }
    }

419
420
421
422
423
424
425
426
427
428
429
430
431
432
    /**
     * Returns a summary about views and/or collections
     *
     * @return array(
     *      'view' => array(
     *          'title' => ...
     *          'description' => ...
     *      )
     *      'collection' => array(
     *          'title' => ...
     *          'description' => ...
     *      )
     */
    private function get_view_collection_summary() {
Nigel McNie's avatar
Nigel McNie committed
433

434
435
        $list = array();
        foreach ($this->collections as $id => $collection) {
436
            $list['collections'][$id] = array(
437
438
439
440
441
                'title' => $collection->get('name'),
                'views' => array(),
            );
        }

442
        $ncollections = count($this->collections);
443
444
        $nviews = 0;
        foreach ($this->views as $id => $view) {
Nigel McNie's avatar
Nigel McNie committed
445
            if ($view->get('type') != 'profile') {
446
                $item = array(
Nigel McNie's avatar
Nigel McNie committed
447
                    'title' => $view->get('title'),
448
                    'folder' => self::text_to_filename($view->get('title')),
Nigel McNie's avatar
Nigel McNie committed
449
                );
450
451
452
453
                if (isset($this->viewcollection[$id])
                    && ($this->viewexportmode == self::EXPORT_ALL_VIEWS_COLLECTIONS
                        || $this->viewexportmode == self::EXPORT_LIST_OF_COLLECTIONS)) {
                    $list['collections'][$this->viewcollection[$id]]['views'][$id] = $item;
454
455
                }
                else {
456
457
                    $list['views'][$id] = $item;
                    $nviews++;
458
                }
Nigel McNie's avatar
Nigel McNie committed
459
460
            }
        }
461
462
463
        function sort_by_title($a, $b) {
            return strnatcasecmp($a['title'], $b['title']);
        }
464
        foreach (array_keys($this->collections) as $id) {
465
            usort($list['collections'][$id]['views'], 'sort_by_title');
466
        }
467
468
469
        if ($nviews) {
            usort($list['views'], 'sort_by_title');
        }
470
471
        if ($ncollections) {
            usort($list['collections'], 'sort_by_title');
472
        }
473
474
475
476
477
478
479

        // View summary
        $summary['view'] = array();
        $smarty = $this->get_smarty('../');
        if (!empty($list['views'])
            && ($this->viewexportmode == self::EXPORT_ALL_VIEWS_COLLECTIONS
                || $this->viewexportmode == self::EXPORT_LIST_OF_VIEWS)) {
480
            $smarty->assign('stryouhaveviews', get_string('youhavenviews', 'view', $nviews, $nviews));
481
482
483
484
485
            $smarty->assign('list', $list['views']);
            $summary['view'] = array(
                'title' => get_string('Views', 'view'),
                'description' => $smarty->fetch('export:html:viewsummary.tpl'),
            );
486
        }
Nigel McNie's avatar
Nigel McNie committed
487

488
489
490
491
492
493
        // Collection summary
        $summary['collection'] = array();
        $smarty = $this->get_smarty('../');
        if (!empty($list['collections'])
            && ($this->viewexportmode == self::EXPORT_ALL_VIEWS_COLLECTIONS
                || $this->viewexportmode == self::EXPORT_LIST_OF_COLLECTIONS)) {
494
            $smarty->assign('stryouhavecollections', get_string('youhavencollections', 'collection', $ncollections, $ncollections));
495
496
497
498
499
500
501
502
            $smarty->assign('list', $list['collections']);
            $summary['collection'] = array(
                'title' => get_string('Collections', 'collection'),
                'description' => $smarty->fetch('export:html:collectionsummary.tpl'),
            );
        }

        return $summary;
Nigel McNie's avatar
Nigel McNie committed
503
504
    }

505
506
507
508
    /**
     * Copies the static files (stylesheets etc.) into the export
     */
    private function copy_static_files() {
509
        global $THEME, $SESSION;
510
        require_once('file.php');
511
        $staticdir = $this->get('exportdir') . '/' . $this->get('rootdir') . '/static/';
512
        $directoriestocopy = array();
513
        $themestaticdirs = $THEME->get_path('', true);
514

515
        $statics = array('style', 'images', 'fonts', 'js');
516
        foreach ($themestaticdirs as $theme => $dir) {
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
            // Get static directories from each theme for HTML export
            foreach ($statics as $static) {
                $themedir = $staticdir . 'theme/' . $theme . '/static/' . $static;
                if (is_readable($dir . $static)) {
                    $directoriestocopy[$dir . '/' . $static] = $themedir;
                    if (!check_dir_exists($themedir)) {
                        throw new SystemException("Could not create theme directory for theme $theme");
                    }
                }
            }
        }
        $exportthemedirs = $THEME->get_path('', true, 'export/html');
        foreach ($exportthemedirs as $theme => $dir) {
            foreach ($statics as $static) {
                $themedir = $staticdir . 'theme/' . $theme . '/static/export/' . $static;
                if (is_readable($dir . $static)) {
                    $directoriestocopy[$dir . '/' . $static] = $themedir;
                    if (!check_dir_exists($themedir)) {
                        throw new SystemException("Could not create theme directory for theme $theme");
                    }
                }
538
539
540
541
            }
        }

        // Smilies
542
        $directoriestocopy[get_config('docroot') . 'js/tinymce/plugins/emoticons/img'] = $staticdir . 'smilies/';
543

544
        foreach ($this->pluginstaticdirs as $dir) {
545
546
            $destinationdir = str_replace('export/html/', '', $dir);
            if (!check_dir_exists($staticdir . $destinationdir)) {
547
                $SESSION->add_error_msg(get_string('couldnotcreatestaticdirectory', 'export', $destinationdir));
548
            }
549
550
551
552
553
            foreach ($themestaticdirs as $theme => $themedir) {
                if (file_exists(get_config('docroot') . 'theme/' . $theme . '/' . $dir)) {
                    $directoriestocopy[get_config('docroot') . 'theme/' . $theme . '/' . $dir] = $staticdir . $destinationdir;
                }
            }
554
555
        }

556
        foreach ($directoriestocopy as $from => $to) {
557
            if (!copyr($from, $to)) {
558
                $SESSION->add_error_msg(get_string('couldnotcopyfilesfromto', 'export', $from, $to));
559
560
            }
        }
561

562
563
    }

564
565
566
567
568
569
570
571
572
573
574
575
576
}

abstract class HtmlExportArtefactPlugin {

    protected $exporter;

    protected $fileroot;

    public function __construct(PluginExportHTML $exporter) {
        $this->exporter = $exporter;
        $pluginname = strtolower(substr(get_class($this), strlen('HtmlExport')));
        $this->fileroot = $this->exporter->get('exportdir') . '/' . $this->exporter->get('rootdir') . '/files/' . $pluginname . '/';
        if (!check_dir_exists($this->fileroot)) {
Nigel McNie's avatar
Nigel McNie committed
577
            throw new SystemException("Could not create the temporary export directory $this->fileroot");
578
        }
579
580
581
582
        $this->extrafileroot = $this->exporter->get('exportdir') . '/' . $this->exporter->get('rootdir') . '/files/extra/';
        if (!check_dir_exists($this->extrafileroot)) {
            throw new SystemException("Could not create the temporary export directory $this->extrafileroot");
        }
583
584
585
586
587
588
589
590
    }

    abstract public function dump_export_data();

    abstract public function get_summary();

    abstract public function get_summary_weight();

591
592
593
    public function paginate($artefact) {

        // Create directory for storing the artefact
594
        $dirname = PluginExportHtml::text_to_filename(trim($artefact->get('title')));
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
        if (!check_dir_exists($this->fileroot . $dirname)) {
            throw new SystemException("Couldn't create artefact directory {$this->fileroot}{$dirname}");
        }

        // Get artefact-specific pagination options
        $options = $this->pagination_data($artefact);

        // Render the first page of the artefact (the only one if there aren't many children)
        $smarty = $this->exporter->get_smarty('../../../', $artefact->get('artefacttype'));
        $smarty->assign('page_heading', $artefact->get('title'));
        $smarty->assign('breadcrumbs', array(
            array('text' => $options['plural']),
            array('text' => $artefact->get('title'), 'path' => 'index.html'),
        ));
        $rendered = $artefact->render_self(array('hidetitle' => true));
        $outputfilter = new HtmlExportOutputFilter('../../../', $this->exporter);
        $smarty->assign('rendered', $outputfilter->filter($rendered['html']));
        $content = $smarty->fetch('export:html:page.tpl');

        if (false === file_put_contents($this->fileroot . $dirname . '/index.html', $content)) {
            throw new SystemException("Unable to create index.html for artefact " . $artefact->get('id'));
        }

        // If the artefact has many children, we'll need to write out archive pages
        if ($options['childcount'] > $options['perpage']) {
            for ($i = $options['perpage']; $i <= $options['childcount']; $i += $options['perpage']) {
                $rendered = $artefact->render_self(array('limit' => $options['perpage'], 'offset' => $i));
                $smarty->assign('rendered', $outputfilter->filter($rendered['html']));
                $content = $smarty->fetch('export:html:page.tpl');

                if (false === file_put_contents($this->fileroot . $dirname . "/{$i}.html", $content)) {
                    throw new SystemException("Unable to create {$i}.html for artefact {$artefact->get('id')}");
                }
            }
        }
    }
631
632
}

633
/**
Aaron Wells's avatar
Aaron Wells committed
634
 * Provides a mechanism for converting the HTML generated by views and
635
636
 * artefacts for the HTML export.
 *
Aaron Wells's avatar
Aaron Wells committed
637
 * Mostly, this means rewriting links to artefacts to point the correct place
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
 * in the export.
 */
class HtmlExportOutputFilter {

    /**
     * The relative path to the root of the generated export - used for link munging
     */
    private $basepath = '';

    /**
     * A cache of view titles. See replace_view_link()
     */
    private $viewtitles = array();

    /**
653
     * A cache of folder data. See get_folder_path_for_file()
654
655
656
     */
    private $folderdata = null;

657
658
659
660
    /**
     */
    private $htmlexportcopyproxy = null;

661
662
663
664
    /**
     */
    private $exporter = null;

665
666
667
668
    /**
     */
    private $owner = null;

669
670
671
    /**
     * @param string $basepath The relative path to the root of the generated export
     */
672
    public function __construct($basepath, &$exporter=null) {
673
        $this->basepath = preg_replace('#/$#', '', $basepath);
674
        $this->htmlexportcopyproxy = HtmlExportCopyProxy::singleton();
675
        $this->exporter = $exporter;
676
        $this->owner = $exporter->get('user')->get('id');
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
    }

    /**
     * Filters the given HTML for HTML export purposes
     *
     * @param string $html The HTML to filter
     * @return string      The filtered HTML
     */
    public function filter($html) {
        $wwwroot = preg_quote(get_config('wwwroot'));
        $html = preg_replace(
            array(
                // We don't care about javascript
                '#<script[^>]*>.*?</script>#si',
                // Fix simlies from tinymce
692
                '#<img ([^>]*)src="(' . $wwwroot . ')?/?js/tinymce/plugins/emoticons/img/([^"]+)"([^>]+)>#',
693
694
                // No forms
                '#<form[^>]*>.*?</form>#si',
695
696
                // Gratuitous hack for the RSS blocktype
                '#<div id="blocktype_externalfeed_lastupdate">[^<]*</div>#',
697
698
699
            ),
            array(
                '',
700
                '<img $1src="' . $this->basepath . '/static/smilies/$3"$4>',
701
                '',
702
                '',
703
704
705
706
707
708
709
710
711
712
713
714
715
            ),
            $html
        );

        // Links to views
        $html = preg_replace_callback(
            '#' . $wwwroot . 'view/view\.php\?id=(\d+)#',
            array($this, 'replace_view_link'),
            $html
        );

        // Links to artefacts
        $html = preg_replace_callback(
716
            '#<a[^>]+href="(' . $wwwroot . ')?/?view/artefact\.php\?artefact=(\d+)(&amp;view=\d+)?(&amp;offset=\d+)?"[^>]*>([^<]*)</a>#',
717
718
719
720
            array($this, 'replace_artefact_link'),
            $html
        );

721
722
723
724
725
726
727
        // Links to image artefacts
        $html = preg_replace_callback(
            '#<a[^>]+href="(' . $wwwroot . ')?/?view/artefact\.php\?artefact=(\d+)(&amp;view=\d+)?(&amp;offset=\d+)?"[^>]*>(<img[^>]+>)</a>#',
            array($this, 'replace_artefact_link'),
            $html
        );

728
729
        // Links to download files
        $html = preg_replace_callback(
730
            '#(?<=[\'"])(' . $wwwroot . ')?/?artefact/file/download\.php\?file=(\d+)(?:(?:&amp;|&|%26)([a-z]+=[x0-9]+)+)*#',
731
732
733
734
            array($this, 'replace_download_link'),
            $html
        );

735
        // Thumbnails
736
        require_once('file.php');
737
        $html = preg_replace_callback(
738
            '#(?<=[\'"])(' . $wwwroot . ')?/?thumb\.php\?type=([a-z]+)((?:(?:&amp;|&|%26)[a-z]+=[x0-9]+)+)*#',
739
740
741
742
            array($this, 'replace_thumbnail_link'),
            $html
        );

743
744
        // Images out of the theme directory
        $html = preg_replace_callback(
745
            '#(?<=[\'"])(' . $wwwroot . '|/)?((?:[a-z]+/)*)theme/([a-zA-Z0-9_.-]+)/static/images/([a-z0-9_.-]+)#',
746
747
748
749
            array($this, 'replace_theme_image_link'),
            $html
        );

750
751
752
753
        return $html;
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
754
     * Callback to replace links to views to point to the correct location in
755
756
757
758
     * the HTML export
     */
    private function replace_view_link($matches) {
        $viewid = $matches[1];
759
760
761
762
        // Don't rewrite links to views that are not going to be included in the export
        if (!isset($this->exporter->views[$viewid])) {
            return $matches[0];
        }
763
        if (!isset($this->viewtitles[$viewid])) {
764
            $this->viewtitles[$viewid] = PluginExportHtml::text_to_URLpath(PluginExportHtml::text_to_filename(get_field('view', 'title', 'id', $viewid)));
765
766
767
768
769
        }
        return $this->basepath . '/views/' . $this->viewtitles[$viewid] . '/index.html';
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
770
     * Callback to replace links to artefact to point to the correct location
771
772
773
774
     * in the HTML export
     */
    private function replace_artefact_link($matches) {
        $artefactid = $matches[2];
775
776
777
778
779
780
        try {
            $artefact = artefact_instance_from_id($artefactid);
        }
        catch (ArtefactNotFoundException $e) {
            return $matches[5];
        }
781

782
783
        $artefacttype = $artefact->get('artefacttype');
        switch ($artefacttype) {
784
        case 'blog':
785
786
        case 'plan':
            $dir = $artefacttype == 'plan' ? 'plans' : $artefacttype;
787
788
            $offset = ($matches[4]) ? intval(substr($matches[4], strlen('&amp;offset='))) : 0;
            $offset = ($offset == 0) ? 'index' : $offset;
789
            return '<a href="' . $this->basepath . "/files/$dir/" . PluginExportHtml::text_to_URLpath(PluginExportHtml::text_to_filename($artefact->get('title'))) . '/' . $offset . '.html">' . $matches[5] . '</a>';
790
        case 'file':
791
        case 'folder':
792
        case 'image':
793
        case 'profileicon':
794
        case 'archive':
795
796
        case 'video':
        case 'audio':
797
            return '<a href="' . $this->get_export_path_for_file($artefact, array()) . '">' . $matches[5] . '</a>';
798
799
800
801
802
803
        default:
            return $matches[5];
        }
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
804
     * Callback to replace links to artefact/file/download.php to point to the
805
806
807
808
     * correct file in the HTML export
     */
    private function replace_download_link($matches) {
        $artefactid = $matches[2];
809
810
811
812
813
814
        try {
            $artefact = artefact_instance_from_id($artefactid);
        }
        catch (ArtefactNotFoundException $e) {
            return '';
        }
815

Aaron Wells's avatar
Aaron Wells committed
816
        // If artefact type not something that would be served by download.php,
817
818
819
820
821
        // replace link with nothing
        if ($artefact->get_plugin_name() != 'file') {
            return '';
        }

822
        $options = array();
823
824
825
        for ($i = 3; $i < count($matches); $i++) {
            list($key, $value) = explode('=', $matches[$i]);
            $options[$key] = $value;
826
827
        }

828
        return $this->get_export_path_for_file($artefact, $options);
829
830
831
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
832
     * Callback to replace links to thumb.php to point to the correct file in
833
834
835
836
837
838
     * the HTML export
     */
    private function replace_thumbnail_link($matches) {
        if (isset($matches[3])) {
            $type = $matches[2];

839
840
            $parts = preg_split('/(&amp;|&|%26)/', $matches[3]);
            array_shift($parts);
841
842
843
844
845
846
847
848
849
850
851
852
853
            foreach ($parts as $part) {
                list($key, $value) = explode('=', $part);
                $options[$key] = $value;
            }

            if (!isset($options['id'])) {
                return '';
            }

            switch ($type) {
            case 'profileicon':
                // Convert the user ID to a profile icon ID
                if (!$options['id'] = get_field_sql('SELECT profileicon FROM {usr} WHERE id = ?', array($options['id']))) {
854
855
856
                    // No profile icon, get the default one
                    list($size, $prefix) = $this->get_size_from_options($options);
                    if ($from = get_dataroot_image_path('artefact/file/profileicons/no_userphoto/' . get_config('theme'), 0, $size)) {
857
                        $to = '/static/profileicons/0-' . $prefix . 'no_userphoto.png';
858
859
860
                        $this->htmlexportcopyproxy->add($from, $to);
                    }
                    return $this->basepath . $to;
861
862
                }
            case 'profileiconbyid':
863
864
865
866
867
868
                try {
                    $icon = artefact_instance_from_id($options['id']);
                }
                catch (ArtefactNotFoundException $e) {
                    return '';
                }
869
870
871
872
873
874
875
876
877
878
879
880
                if ($icon->get_plugin_name() != 'file') {
                    return '';
                }
                return $this->get_export_path_for_file($icon, $options, '/static/profileicons/');
            default:
                return '';
            }
        }

        return '';
    }

881
882
883
884
    /**
     * Callback
     */
    private function replace_theme_image_link($matches) {
885
        $file = $matches[2] . 'theme/' . $matches[3] . '/static/images/' . $matches[4];
886
887
888
889
890
891
892
        $this->htmlexportcopyproxy->add(
            get_config('docroot') . $file,
            '/static/' . $file
        );
        return $this->basepath . '/static/' . $file;
    }

893
894
    /**
     * Given a file, returns the folder path for it in the Mahara files area
895
     *
896
     * The path is pre-sanitised so it can be used when generating the export
897
     *
898
     * @param  $file The file or folder to get the folder path for
899
900
     * @return string
     */
901
    private function get_folder_path_for_file($file) {
902
903
        if ($this->folderdata === null) {
            $this->folderdata = get_records_select_assoc('artefact', "artefacttype = 'folder' AND owner = ?", array($file->get('owner')));
904
905
906
907
            if ($this->folderdata) {
                foreach ($this->folderdata as &$folder) {
                    $folder->title = PluginExportHtml::sanitise_path($folder->title);
                }
908
            }
909
910
911
912
913
        }
        $folderpath = ArtefactTypeFileBase::get_full_path($file->get('parent'), $this->folderdata);
        return $folderpath;
    }

914
    /**
Aaron Wells's avatar
Aaron Wells committed
915
     * Generates a path, relative to the root of the export, that the given
916
917
     * file will appear in the export.
     *
Aaron Wells's avatar
Aaron Wells committed
918
     * If the file is a thumbnail, the copy proxy is informed about it so that
919
920
921
     * the image can later be copied in to place.
     *
     * @param ArtefactTypeFileBase $file The file to get the exported path for
Aaron Wells's avatar
Aaron Wells committed
922
923
924
     * @param array $options             Options from the URL that was linking
     *                                   to the image - most importantly, size
     *                                   related options about how the image
925
     *                                   was thumbnailed, if it was.
Aaron Wells's avatar
Aaron Wells committed
926
     * @param string $basefolder         What folder in the export to dump the
927
     *                                   file in
Aaron Wells's avatar
Aaron Wells committed
928
     * @return string                    The relative path to where the file
929
930
     *                                   will be placed
     */
931
    private function get_export_path_for_file(ArtefactTypeFileBase $file, array $options, $basefolder=null) {
932
        global $SESSION;
933
934
935
936
937
938
939
940
941
        if (is_null($basefolder)) {
            if ($file->get('owner') == $this->owner) {
                $basefolder = '/files/file/' . $this->get_folder_path_for_file($file);
            }
            else {
                $basefolder = '/files/extra/';
            }
        }

942
        unset($options['view']);
943
944
945
946
        if (!$this->exporter->get('user')->can_view_artefact($file)) {
            $SESSION->add_info_msg(get_string('unabletocopyartefact', 'export', $file->get('title')));
            return '';
        }
947
        $prefix = '';
948
        $title = PluginExportHtml::sanitise_path($file->get('title'));
949
        if ($options) {
950
            list($size, $prefix) = $this->get_size_from_options($options);
951
952
            $from = $file->get_path($size);

953
            $to = $basefolder . $file->get('id') . '-' . $prefix . $title;
954
955
956
            $this->htmlexportcopyproxy->add($from, $to);
        }
        else {
957
958
959
960
            if ($basefolder == '/files/extra/') {
                $title = $file->get('id') . '-' . $title;
            }
            $to = $basefolder . $title;
961
962
963
964
965
        }

        return $this->basepath . $to;
    }

966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
    /**
     * Helper method
     */
    private function get_size_from_options($options) {
        $prefix = '';
        foreach (array('size', 'width', 'height', 'maxsize', 'maxwidth', 'maxheight') as $param) {
            if (isset($options[$param])) {
                $$param = $options[$param];
                $prefix .= $param . '-' . $options[$param] . '-';
            }
            else {
                $$param = null;
            }
        }

        return array(imagesize_data_to_internal_form($size, $width, $height, $maxsize, $maxwidth, $maxheight), $prefix);
    }

984
985
986
}

/**
Aaron Wells's avatar
Aaron Wells committed
987
 * Gathers a list of files that need to be copied into the export, as they're
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
 * found by the HtmlExportOutputFilter
 */
class HtmlExportCopyProxy {

    private static $instance = null;
    private $copy = array();

    private function __construct() {
    }

    public static function singleton() {
        if (is_null(self::$instance)) {
            self::$instance = new HtmlExportCopyProxy();
        }
        return self::$instance;
    }

    public function add($from, $to) {
        $this->copy[$from] = $to;
    }

    public function get_copy_data() {
        return $this->copy;
    }
1012
}