lib.php 15.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
/**
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    mahara
 * @subpackage export-html
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
 *
 */

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

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

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

    /**
     * The name of the directory under which all the other directories and 
     * files will be placed in the export
     */
    protected $rootdir;

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

        // Create basic required directories
54
        foreach (array('files', 'views', 'static', 'static/smilies') as $directory) {
55
56
57
58
59
60
            $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'
61
            . $this->get('user')->get('id') . '-' . $this->exporttime . '.zip';
62
        $this->notify_progress_callback(15, 'Setup complete');
63
64
    }

65
66
67
68
69
70
71
72
    public static function get_title() {
        return get_string('title', 'export.html');
    }

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

73
    /**
Nigel McNie's avatar
Nigel McNie committed
74
75
     * Main export routine
     */
76
    public function export() {
Nigel McNie's avatar
Nigel McNie committed
77
78
        // For each artefact plugin, if it implements leap export, ask it to 
        // dump out its structure
79
        $summaries = array();
80
81
82
83
84
85
        $plugins = plugins_installed('artefact', true);
        $progressstart = 15;
        $progressend   = 60;
        $plugincount   = count($plugins);
        $i = 0;
        foreach ($plugins as $plugin) {
86
            $plugin = $plugin->name;
87
88
            $this->notify_progress_callback(intval($progressstart + ($i++ / $plugincount) * ($progressend - $progressstart)), 'Exporting data for ' . $plugin);

89
90
91
92
93
94
95
96
97
98
            if (safe_require('export', 'html/' . $plugin, 'lib.php', 'require_once', true)) {
                $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);

                $artefactexporter = new $classname($this);
                $artefactexporter->dump_export_data();
99
100
101
102
                // If just exporting a list of views, we don't care about the summaries for each artefact plugin
                if (!($this->viewexportmode == PluginExport::EXPORT_LIST_OF_VIEWS && $this->artefactexportmode == PluginExport::EXPORT_ARTEFACTS_FOR_VIEWS)) {
                    $summaries[$plugin] = array($artefactexporter->get_summary_weight(), $artefactexporter->get_summary());
                }
103
104
105
            }
        }

Nigel McNie's avatar
Nigel McNie committed
106
        // Get the view data
107
        $this->notify_progress_callback(60, 'Exporting Views');
Nigel McNie's avatar
Nigel McNie committed
108
109
110
        $this->dump_view_export_data();
        $summaries['view'] = array(100, $this->get_view_summary());

111
        // Sort by weight (then drop the weight information)
112
        $this->notify_progress_callback(65, 'Building index page');
113
114
115
116
117
        uasort($summaries, create_function('$a, $b', 'return $a[0] > $b[0];'));
        foreach ($summaries as &$summary) {
            $summary = $summary[1];
        }

Nigel McNie's avatar
Nigel McNie committed
118
        // Build index.html
119
        $this->build_index_page($summaries);
120
121

        // Copy all static files into the export
122
        $this->notify_progress_callback(75, 'Copying static files');
123
        $this->copy_static_files();
124
125
126
        

        // zip everything up
127
        $this->notify_progress_callback(80, 'Creating zipfile');
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        $cwd = getcwd();
        $command = sprintf('%s %s %s %s',
            get_config('pathtozip'),
            get_config('ziprecursearg'),
            escapeshellarg($this->exportdir .  $this->zipfile),
            escapeshellarg($this->rootdir)
        );
        $output = array();
        chdir($this->exportdir);
        exec($command, $output, $returnvar);
        chdir($cwd);
        if ($returnvar != 0) {
            throw new SystemException('Failed to zip the export file');
        }
142
        $this->notify_progress_callback(100, 'Done');
143
144
145
146
147
148
149
150
151
152
153
154
        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
    }

    public function get_smarty($rootpath='') {
        $smarty = smarty_core();
        $smarty->assign('user', $this->get('user'));
        $smarty->assign('rootpath', $rootpath);
155
        $smarty->assign('export_time', $this->exporttime);
156
        $smarty->assign('sitename', get_config('sitename'));
157
158
159
160

        return $smarty;
    }

161
162
163
164
165
166
167
168
169
170
171
    /**
     * Converts the passed text, which is assumed to be a reasonably short 
     * string, 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_path($text) {
        return preg_replace('#[^a-zA-Z0-9_-]+#', '-', $text);
    }

172
173
174
175
    private function build_index_page($summaries) {
        $smarty = $this->get_smarty();
        $smarty->assign('summaries', $summaries);
        $content = $smarty->fetch('export:html:index.tpl');
176
177
178
        if (!file_put_contents($this->exportdir . '/' . $this->rootdir . '/index.html', $content)) {
            throw new SystemException("Could not create index.html for the export");
        }
179
180
    }

Nigel McNie's avatar
Nigel McNie committed
181
182
183
184
    /**
     * Dumps all views into the HTML export
     */
    private function dump_view_export_data() {
185
186
187
188
189
190
191
192
193
194
195
        $smarty = $this->get_smarty('../../');
        foreach ($this->views as $viewid => $view) {
            $smarty->assign('breadcrumbs', array(
                array('text' => get_string('Views', 'view')),
                array('text' => $view->get('title'), 'path' => 'index.html'),
            ));

            $directory = $this->exportdir . '/' . $this->rootdir . '/views/' . self::text_to_path($view->get('title'));
            if (!check_dir_exists($directory)) {
                throw new SystemException("Could not create directory for view $viewid");
            }
Nigel McNie's avatar
Nigel McNie committed
196

197
198
199
200
201
            $outputfilter = new HtmlExportOutputFilter('../../');
            $smarty->assign('view', $outputfilter->filter($view->build_columns()));
            $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
202
203
204
205
206
207
208
209
210
211
212
213
            }
        }
    }

    private function get_view_summary() {
        $smarty = $this->get_smarty('../');

        $views = array();
        foreach ($this->views as $view) {
            if ($view->get('type') != 'profile') {
                $views[] = array(
                    'title' => $view->get('title'),
214
                    'folder' => self::text_to_path($view->get('title')),
Nigel McNie's avatar
Nigel McNie committed
215
216
217
218
                );
            }
        }
        $smarty->assign('views', $views);
219
220
221
222
223
224
225
226
227
228

        if ($views) {
            $stryouhaveviews = (count($views) == 1)
                ? get_string('youhaveoneview', 'view')
                : get_string('youhaveviews', 'view', count($views));
        }
        else {
            $stryouhaveviews = get_string('youhavenoviews', 'view');
        }
        $smarty->assign('stryouhaveviews', $stryouhaveviews);
Nigel McNie's avatar
Nigel McNie committed
229
230

        return array(
231
            'title' => get_string('Views', 'view'),
Nigel McNie's avatar
Nigel McNie committed
232
233
234
235
            'description' => $smarty->fetch('export:html:viewsummary.tpl'),
        );
    }

236
237
238
239
240
    /**
     * Copies the static files (stylesheets etc.) into the export
     */
    private function copy_static_files() {
        $staticdir = $this->get('exportdir') . '/' . $this->get('rootdir') . '/static/';
241
242
243
244
245

        $directoriestocopy = array(
            get_config('docroot') . 'export/html/static/' => $staticdir,
            get_config('docroot') . 'js/tinymce/plugins/emotions/images' => $staticdir . 'smilies/',
        );
246
247
248
        $filestocopy = array(
            get_config('docroot') . 'theme/views.css' => $staticdir . 'views.css',
        );
249
250
251
252
253
254
255
256
257

        foreach ($directoriestocopy as $from => $to) {
            foreach (new RecursiveDirectoryIterator($from) as $fileinfo) {
                if (!$fileinfo->isFile() || substr($fileinfo->getFilename(), 0, 1) == '.') {
                    continue;
                }
                if (!copy($fileinfo->getPathname(), $to . $fileinfo->getFilename())) {
                    throw new SystemException("Could not copy static file " . $fileinfo->getPathname());
                }
258
259
            }
        }
260
261
262
263
264
265

        foreach ($filestocopy as $from => $to) {
            if (!copy($from, $to)) {
                throw new SystemException("Could not copy static file $from");
            }
        }
266
267
    }

268
269
270
271
272
273
274
275
276
277
278
279
280
}

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
281
            throw new SystemException("Could not create the temporary export directory $this->fileroot");
282
283
284
285
286
287
288
289
290
291
292
        }
    }

    abstract public function dump_export_data();

    abstract public function get_summary();

    abstract public function get_summary_weight();

}

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/**
 * Provides a mechanism for converting the HTML generated by views and 
 * artefacts for the HTML export.
 *
 * Mostly, this means rewriting links to artefacts to point the correct place 
 * 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();

    /**
     * A cache of folder data. See get_path_for_file()
     */
    private $folderdata = null;

    /**
     * @param string $basepath The relative path to the root of the generated export
     */
    public function __construct($basepath) {
        $this->basepath = preg_replace('#/$#', '', $basepath);
    }

    /**
     * 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
                '#<img src="(' . $wwwroot . ')?/?js/tinymce/plugins/emotions/images/([^"]+)"([^>]+)>#',
            ),
            array(
                '',
                '<img src="' . $this->basepath . '/static/smilies/$2"$3>',
            ),
            $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(
            '#<a[^>]+href="(' . preg_quote(get_config('wwwroot')) . ')?/?view/artefact\.php\?artefact=(\d+)(&amp;view=\d+)?(&amp;page=\d+)?"[^>]*>([^<]*)</a>#',
            array($this, 'replace_artefact_link'),
            $html
        );

        // Links to download files
        $html = preg_replace_callback(
            '#(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)(&amp;view=\d+)?#',
            array($this, 'replace_download_link'),
            $html
        );

        return $html;
    }

    /**
     * Callback to replace links to views to point to the correct location in 
     * the HTML export
     */
    private function replace_view_link($matches) {
        $viewid = $matches[1];
        if (!isset($this->viewtitles[$viewid])) {
            $this->viewtitles[$viewid] = PluginExportHtml::text_to_path(get_field('view', 'title', 'id', $viewid));
        }
        return $this->basepath . '/views/' . $this->viewtitles[$viewid] . '/index.html';
    }

    /**
     * Callback to replace links to artefact to point to the correct location 
     * in the HTML export
     */
    private function replace_artefact_link($matches) {
        $artefactid = $matches[2];
        $artefact = artefact_instance_from_id($artefactid);

        switch ($artefact->get('artefacttype')) {
        case 'blog':
            $page = ($matches[4]) ? intval(substr($matches[4], strlen('&amp;page='))) : 1;
            $page = ($page == 1) ? 'index' : $page;
            return '<a href="' . $this->basepath . '/files/blog/' . PluginExportHtml::text_to_path($artefact->get('title')) . '/' . $page . '.html">' . $matches[5] . '</a>';
        case 'file':
        case 'image':
            $folderpath = $this->get_path_for_file($artefact);
            return '<a href="' . $this->basepath . '/files/file/' . $folderpath . $artefact->get('title') . '">' . $matches[5] . '</a>';
        default:
            return $matches[5];
        }
    }

    /**
     * Callback to replace links to artefact/file/download.php to point to the 
     * correct file in the HTML export
     */
    private function replace_download_link($matches) {
        $artefactid = $matches[2];
        $artefact = artefact_instance_from_id($artefactid);

        // If artefact type not something that would be served by download.php, 
        // replace link with nothing
        if ($artefact->get_plugin_name() != 'file') {
            return '';
        }

        $folderpath = $this->get_path_for_file($artefact);
        return $this->basepath . '/files/file/' . $folderpath . $artefact->get('title');
    }

    /**
     * Given a file, returns the folder path in the HTML export for it
     *
     * TODO: slash escaping in file/folder names
     *
     * @param ArtefactTypeFileBase $file The file to get the folder path for
     * @return string
     */
    private function get_path_for_file(ArtefactTypeFileBase $file) {
        if ($this->folderdata === null) {
            $this->folderdata = get_records_select_assoc('artefact', "artefacttype = 'folder' AND owner = ?", array($file->get('owner')));
        }
        $folderpath = ArtefactTypeFileBase::get_full_path($file->get('parent'), $this->folderdata);
        return $folderpath;
    }

}

440
?>