lib.php 41.9 KB
Newer Older
1
2
3
4
5
6
<?php
/**
 *
 * @package    mahara
 * @subpackage export-leap
 * @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
 *
 */

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

/**
Francois Marier's avatar
Francois Marier committed
15
* LEAP export plugin.  See http://wiki.cetis.ac.uk/2009-03/Leap2A_specification and
16
* https://wiki.mahara.org/wiki/Developer_Area/Import//Export/LEAP_Export
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
*/
class PluginExportLeap extends PluginExport {

    /**
    * xml string to build up.  Maybe later
    * this could change to an open file buffer
    * for performance.
    */
    protected $xml;

    /**
    * smarty object for main xml object
    * at the moment individual entries have their own
    * as well, because I can't figure out whether to unset
    * each entry template vars each time, or to create a new one
    * is more performant.
    */
    protected $smarty;

    /**
    * array of attachment objects
    * like this: (object)array('file' => '/path/to/file', 'name' => 'something.jpg');
    */
    protected $attachments = array();

    /**
    * filename to use for the feed
    */
    protected $leapfile    = 'leap2a.xml';

    /**
    * attachment directory for files
    */
    protected $filedir     = 'files/';

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

    /**
    * special cases - artefact plugins that want to override stuff PER PLUGIN
    * rather than per type or per instance.
    */
    protected $specialcases = array();

    /**
    * extra person data injected by plugins other than internal
    */
    protected $extrapersondata = array();

    /**
    * constructor.  overrides the parent class
    * to set up smarty and the attachment directory
    */
72
73
    public function __construct(User $user, $views, $artefacts, $progresshandler=null) {
        parent::__construct($user, $views, $artefacts, $progresshandler);
74
75
76
77
78
79
        $this->smarty = smarty_core();

        if (!check_dir_exists($this->exportdir . '/' . $this->filedir)) {
            throw new SystemException("Couldn't create the temporary export directory $this->exportdir");
        }
        $this->zipfile = 'mahara-export-leap-user'
80
            . $this->get('user')->get('id') . '-' . date('Y-m-d_H-i', $this->exporttime) . '_' . get_random_key() . '.zip';
81
        // some plugins might want to do their own special thing
82
        foreach (plugins_installed('artefact', true) as $plugin) {
83
84
            $plugin = $plugin->name;
            if (safe_require('export', 'leap/' . $plugin, 'lib.php', 'require_once', true)) {
85
86
87
88
89
90
                $classname = 'LeapExport' . ucfirst($plugin);
                if (class_exists($classname) && call_static_method($classname, 'override_entire_export')) {
                    $this->specialcases[$plugin] = array();
                }
            }
        }
91
92
93
94

        $outputfilter = LeapExportOutputFilter::singleton();
        $outputfilter->set_artefactids(array_keys($this->artefacts));

95
        $this->notify_progress_callback(5, get_string('setupcomplete', 'export'));
96
97
    }

98
99
100
101
102
    public static function get_title() {
        return get_string('title', 'export.leap');
    }

    public static function get_description() {
Kristina Hoeppner's avatar
Kristina Hoeppner committed
103
        return get_string('description1', 'export.leap');
104
105
    }

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    /**
     * Basic check to make sure all the files we are dealing with don't add
     * up to being greater in size than the space available on disk. This will be a ballpark figure
     * as it will not take into account a) the size of html/text and b) the data will be zipped up.
     */
    public function is_diskspace_available() {
        $rawtotal = 1024; // the resulting zip is bound to be bigger than 1kb so we start with that
        foreach ($this->artefacts as $key => $artefact) {
            if ($artefact instanceof ArtefactTypeFile) {
                $rawtotal += $artefact->get('size');
            }
        }
        return disk_free_space(get_config('dataroot')) > $rawtotal;
    }

121
122
123
124
    /**
    * main export routine
    */
    public function export() {
125
        global $SESSION;
126
127
        // the xml stuff
        $this->export_header();
128
        $this->setup_links();
129
        $this->notify_progress_callback(10, get_string('exportingviews', 'export'));
130
131
        if ($this->viewexportmode == PluginExport::EXPORT_LIST_OF_COLLECTIONS
            || $this->viewexportmode == PluginExport::EXPORT_ALL_VIEWS_COLLECTIONS) {
132
133
            $this->export_collections();
        }
134
        $this->export_views();
135
        $this->notify_progress_callback(50, get_string('exportingartefacts', 'export'));
136
137
        $this->export_artefacts();

138
        $this->notify_progress_callback(80, get_string('exportingartefactplugindata', 'export'));
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        $internal = null;
        foreach ($this->specialcases as $plugin => $artefacts) {
            if ($plugin == 'internal') {
                $internal = $artefacts;
                continue; // do it last so other plugins can inject persondata
            }
            $classname = 'LeapExport' . ucfirst($plugin);
            $pluginexport = new $classname($this, $artefacts);
            $this->xml .= $pluginexport->get_export_xml();
        }

        if (!empty($internal)) {
            $pluginexport = new LeapExportInternal($this, $internal);
            $this->xml .= $pluginexport->get_export_xml();
        }
154
        $this->notify_progress_callback(85, get_string('exportingfooter', 'export'));
155
156

        $this->export_footer();
157
        $this->notify_progress_callback(90, get_string('writingfiles', 'export'));
158

159
160
161
162
        // Filter invalid XML characters out of the final product
        require_once('file.php');
        $this->xml = preg_replace(xml_filter_regex(), '', $this->xml);

163
164
        // write out xml to a file
        if (!file_put_contents($this->exportdir . $this->leapfile, $this->xml)) {
165
            $SESSION->add_error_msg(get_string('couldnotwriteLEAPdata', 'export'));
166
167
168
169
170
171
        }

        // copy attachments over
        foreach ($this->attachments as $id => $fileinfo) {
            $existingfile = $fileinfo->file;
            $desiredname  = $fileinfo->name;
172
173
174
            if (!is_file($existingfile) || !copy($existingfile, $this->exportdir . $this->filedir . $id . '-' . $desiredname)) {
                $SESSION->add_error_msg(get_string('couldnotcopyattachment', 'export', $desiredname));
            }
175
        }
176
        $this->notify_progress_callback(95, get_string('creatingzipfile', 'export'));
177
178

        // zip everything up
179
180
181
182
183
        try {
            create_zip_archive($this->exportdir, $this->zipfile, array($this->leapfile, $this->filedir));
        }
        catch (SystemException $e) {
            throw new SystemException('Failed to zip the export file: ' . $e->getMessage());
184
        }
185
        $this->notify_progress_callback(100, get_string('Done', 'export'));
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        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
    }
    /**
    * create the feed header and author info
    */
    private function export_header() {
        $this->smarty->assign('userid', $this->get('user')->get('id'));
        $this->smarty->assign('name', full_name($this->get('user')));
        $this->smarty->assign('email', $this->get('user')->get('email'));
200
201
        $this->smarty->assign('export_time', $this->exporttime);
        $this->smarty->assign('export_time_rfc3339', PluginExportLeap::format_rfc3339_date($this->exporttime));
202
203
204
205
206
        require(get_config('docroot') . 'export/leap/version.php');
        $this->smarty->assign('leap_export_version', $config->version);
        $this->xml .= $this->smarty->fetch('export:leap:header.tpl');
    }

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

    /**
     * Export the collections
     */
    private function export_collections() {
        foreach ($this->collections as $id => $collection) {
            $this->smarty->assign('title',       $collection->get('name'));
            $this->smarty->assign('id',          'portfolio:collection' . $id);
            $this->smarty->assign('updated',     self::format_rfc3339_date(strtotime($collection->get('mtime'))));
            $this->smarty->assign('created',     self::format_rfc3339_date(strtotime($collection->get('ctime'))));
            $this->smarty->assign('summarytype', 'text');
            $this->smarty->assign('summary',     $collection->get('description'));
            $this->smarty->assign('contenttype', 'text');
            $this->smarty->assign('content',     $collection->get('description'));
            $this->smarty->assign('leaptype',    'selection');

223
224
225
226
227
228
229
230
231
232
233
234
235
236
            $tags = $collection->get('tags');
            if ($tags) {
                $tags = array_map(function ($a) {
                    return array(
                        'term'  => LeapExportElement::normalise_tag($a),
                        'label' => $a
                    );}, $tags);
            }
            $this->smarty->assign('categories', array_merge(array(
                    array(
                        'scheme' => 'selection_type',
                        'term'   => 'Website',
                    )
            ), $tags));
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

            $links = array();
            if (!empty($this->links->collectionview[$id])) {
                foreach (array_keys($this->links->collectionview[$id]) as $viewid) {
                    $links[] = (object)array(
                        'type' => 'has_part',
                        'id'   => 'portfolio:view' . $viewid,
                    );
                }
            }
            $this->smarty->assign('links', $links);
            $this->xml .= $this->smarty->fetch("export:leap:entry.tpl");
        }
    }


253
    /**
254
255
     * Export the views
     */
256
    private function export_views() {
257
258
259
260
261
262
263
        $progressstart = 10;
        $progressend   = 50;
        $views = $this->get('views');
        $viewcount = count($views);
        $i = 0;
        foreach ($views as $view) {
            $percent = intval($progressstart + ($i++ / $viewcount) * ($progressend - $progressstart));
264
            $this->notify_progress_callback($percent, get_string('exportingviewsprogress', 'export', $i, $viewcount));
265

266
            $config = $this->rewrite_artefact_ids($view->export_config('leap'));
267
268
269
270
            $this->smarty->assign('title',       $config['title']);
            $this->smarty->assign('id',          'portfolio:view' . $view->get('id'));
            $this->smarty->assign('updated',     self::format_rfc3339_date(strtotime($view->get('mtime'))));
            $this->smarty->assign('created',     self::format_rfc3339_date(strtotime($view->get('ctime'))));
Penny Leach's avatar
Penny Leach committed
271
272
273
274
275
276
277
278
279
            $content = $config['description'];
            if ($newcontent = self::parse_xhtmlish_content($content)) {
                $this->smarty->assign('summarytype', 'xhtml');
                $this->smarty->assign('summary',     $newcontent);
            } else {
                $this->smarty->assign('summarytype', 'text');
                $this->smarty->assign('summary',     $content);
            }
            $this->smarty->assign('contenttype', 'xhtml');
280
            if ($viewcontent = self::parse_xhtmlish_content($view->build_rows(false, true), $view->get('id'))) {
281
282
                $this->smarty->assign('content', $viewcontent);
            }
283
284
            $this->smarty->assign('viewdata',    $config['rows']);
            $layout = $view->get_layout();
285
            $widths = '';
286
287
288
289
290
            foreach ($layout->rows as $row){
                $widths .= $row['widths'] . '-';
            }
            $widths = substr($widths, 0, -1);
            $this->smarty->assign('layout',      $widths);
291
            $this->smarty->assign('type',        $config['type']);
292
293
            $ownerformat = ($config['ownerformat']) ? $config['ownerformat'] : FORMAT_NAME_DISPLAYNAME;
            $this->smarty->assign('ownerformat', $ownerformat);
294
            $this->smarty->assign('leaptype',    'selection');
Nigel McNie's avatar
Nigel McNie committed
295
296
297

            $tags = array();
            if ($config['tags']) {
298
299
300
301
302
                $tags = array_map(function ($a) {
                    return array(
                        'term' => LeapExportElement::normalise_tag($a),
                        'label' => $a
                    );}, $config['tags']);
Nigel McNie's avatar
Nigel McNie committed
303
304
            }
            $this->smarty->assign('categories', array_merge(array(
305
306
307
308
                array(
                    'scheme' => 'selection_type',
                    'term' => 'Webpage',
                )
Nigel McNie's avatar
Nigel McNie committed
309
310
            ), $tags));

311
            $this->smarty->assign('links', $this->get_links_for_view($view->get('id')));
312
            $this->xml .= $this->smarty->fetch("export:leap:view.tpl");
313
314
315
        }
    }

316
317
318

    // Some links can be determined in advance
    private function setup_links() {
319
320
321

        // If there are no pages, no links to set up.
        if (empty($this->views)) {
322
323
324
325
326
            return;
        }

        $viewlist = join(',', array_keys($this->views));

327
328
329
330
331
        // Views in collections
        if ($this->collections) {
            $collectionlist = join(',', array_keys($this->collections));
            $records = get_records_select_array(
                'collection_view',
332
333
334
                "view IN ($viewlist) AND collection IN ($collectionlist)",
                array(),
                'displayorder'
335
336
337
338
339
340
341
342
343
            );
            if ($records) {
                foreach ($records as &$r) {
                    $this->links->collectionview[$r->collection][$r->view] = 1;
                    $this->links->viewcollection[$r->view][$r->collection] = 1;
                }
            }
        }

344
345
346
347
348
349
350
        // If there are no artefacts, no need to try to set those up.
        if (empty($this->artefacts)) {
            return;
        }

        $artefactlist = join(',', array_keys($this->artefacts));

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
        // Artefacts directly in views
        $records = get_records_select_array(
            'view_artefact',
            "view IN ($viewlist) OR artefact IN ($artefactlist)"
        );
        if ($records) {
            foreach ($records as &$r) {
                $this->links->viewcontents[$r->view][$r->artefact] = 1;
                $this->links->artefactinview[$r->artefact][$r->view] = 1;
            }
        }

        // Artefact parent-child relationships
        $records = get_records_select_array(
            'artefact',
            "parent IN ($artefactlist) AND id IN ($artefactlist)",
            array(),
            '',
            'id,parent'
        );
        if ($records) {
            foreach ($records as &$r) {
                $this->links->children[$r->parent][$r->id] = 1;
                $this->links->parent[$r->id] = $r->parent;
            }
        }

        // Artefact-attachment relationships
        $records = get_records_select_array(
            'artefact_attachment',
            "artefact IN ($artefactlist) AND attachment IN ($artefactlist)"
        );
        if ($records) {
            foreach ($records as &$r) {
                $this->links->attachments[$r->artefact][$r->attachment] = 1;
            }
        }

        // Other leap2a relationships
        $this->links->viewartefact = array();
        $this->links->artefactview = array();
        $this->links->artefactartefact = array();
        foreach (require_artefact_plugins() as $plugin) {
            safe_require('export', 'leap/' . $plugin->name, 'lib.php', 'require_once', true);
        }
        foreach (plugins_installed('artefact') as $plugin) {
            $classname = 'LeapExportElement' . ucfirst($plugin->name);
            if (is_callable($classname . '::setup_links')) {
399
400
401
402
403
404
405
406
                // You must explicitly pass variables by reference when calling
                // call_user_func, or else they get copied automatically.
                // Using a dummy variable here to avoid the "Call time pass by reference
                // is deprecated" warning that php displays on the screen.
                $dummyref =& $this->links;
                call_user_func(
                    array($classname, 'setup_links'),
                    $dummyref,
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
440
441
442
443
444
445
446
447
448
449
                    array_keys($this->views),
                    array_keys($this->artefacts)
                );
            }
        }
    }

    public function artefact_in_view_links($artefactid) {
        if (isset($this->links->artefactinview[$artefactid])) {
            return array_keys($this->links->artefactinview[$artefactid]);
        }
    }

    public function artefact_parent_link($artefactid) {
        if (isset($this->links->parent[$artefactid])) {
            return $this->artefacts[$this->links->parent[$artefactid]];
        }
    }

    public function artefact_child_links($artefactid) {
        if (isset($this->links->children[$artefactid])) {
            return array_intersect_key($this->artefacts, $this->links->children[$artefactid]);
        }
    }

    public function artefact_attachment_links($artefactid) {
        if (isset($this->links->attachments[$artefactid])) {
            return array_intersect_key($this->artefacts, $this->links->attachments[$artefactid]);
        }
    }

    public function artefact_artefact_links($artefactid) {
        if (isset($this->links->artefactartefact[$artefactid])) {
            return $this->links->artefactartefact[$artefactid];
        }
    }

    public function artefact_view_links($artefactid) {
        if (isset($this->links->artefactview[$artefactid])) {
            return $this->links->artefactview[$artefactid];
        }
    }

450
451
452
453
454
455
456
457
458
459
    /**
     * Looks at all blockinstance configurations, and rewrites the artefact IDs
     * found to be IDs in the generated export.
     *
     * This only works for the 'artefactid' and 'artefactids' fields, which is
     * somewhat of a limitation, as it makes it hard for blocks that want to
     * store artefact ids in other configdata fields. We might have to address
     * this limitation later.
     */
    private function rewrite_artefact_ids($config) {
460
461
462
463
464
465
466
467
468
469
470
        foreach ($config['rows'] as &$row) {
            foreach ($row['columns'] as &$column) {
                foreach ($column as &$blockinstance) {
                    if (isset($blockinstance['config']['artefactid'])) {
                        $id = json_decode($blockinstance['config']['artefactid']);
                        if ($id[0] != null) {
                            $blockinstance['config']['artefactid'] = json_encode(array('portfolio:artefact' . $id[0]));
                        }
                        else {
                            $blockinstance['config']['artefactid'] = null;
                        }
471
                    }
472
473
                    else if (isset($blockinstance['config']['artefactids'])) {
                        $ids = json_decode($blockinstance['config']['artefactids']);
474
475
476
                        if ($ids[0]) {
                            $blockinstance['config']['artefactids'] = json_encode(array(array_map(array($this, 'prepend_artefact_identifier'), $ids[0])));
                        }
477
                    }
478
                }
479
480
            } // cols
        } //rows
481
482
483
484
485
486
487
        return $config;
    }

    private function prepend_artefact_identifier($artefactid) {
        return 'portfolio:artefact' . $artefactid;
    }

488
489
    private function get_links_for_view($viewid) {
        $links = array();
490

491
492
493
494
495
496
497
498
499
        if (!empty($this->links->viewcollection[$viewid])) {
            foreach (array_keys($this->links->viewcollection[$viewid]) as $collectionid) {
                $links[] = (object)array(
                    'type' => 'is_part_of',
                    'id'   => 'portfolio:collection' . $collectionid,
                );
            }
        }

500
501
        if (!empty($this->links->viewcontents[$viewid])) {
            foreach (array_keys($this->links->viewcontents[$viewid]) as $artefactid) {
502
                $links[] = (object)array(
503
                    'type' => 'leap2:has_part',
504
                    'id'   => 'portfolio:artefact' . $artefactid,
505
506
507
                );
            }
        }
508

509
510
511
512
513
514
515
516
        if (!empty($this->links->viewartefact[$viewid])) {
            foreach ($this->links->viewartefact[$viewid] as $artefactid => $linktypes) {
                foreach ($linktypes as $linktype) {
                    $links[] = (object)array(
                        'type' => $linktype,
                        'id'   => 'portfolio:artefact' . $artefactid,
                    );
                }
517
518
            }
        }
519

520
521
522
        return $links;
    }

523
    /**
524
525
     * Export the artefacts
     */
526
    private function export_artefacts() {
527
528
        $progressstart = 50;
        $progressend   = 80;
529
530
531
532
        $artefacts     = $this->get('artefacts');
        $artefactcount = count($artefacts);
        $i = 0;
        foreach ($artefacts as $artefact) {
533
            if ($i++ % 3 == 0) {
534
                $percent = intval($progressstart + ($i / $artefactcount) * ($progressend - $progressstart));
535
                $this->notify_progress_callback($percent, get_string('exportingartefactsprogress', 'export', $i, $artefactcount));
536
            }
537
538
            $element = null;
            // go see if we have to do anything special for this artefact type.
539
540
541
542
543
            if (safe_require('export', 'leap/' . $artefact->get_plugin_name(), 'lib.php', 'require_once', true)) {
                $classname = 'LeapExportElement' . ucfirst($artefact->get('artefacttype'));
                if (class_exists($classname)) {
                    $element = new $classname($artefact, $this);
                }
544

545
546
547
548
549
550
551
552
553
554
                if (is_null($element)) {
                    $element = new LeapExportElement($artefact, $this);
                }
                if (array_key_exists($artefact->get_plugin_name(), $this->specialcases) && !$element->override_plugin_specialcase()) {
                    $this->specialcases[$artefact->get_plugin_name()][] = $artefact;
                    continue;
                }
                if (!$element->is_leap()) {
                    continue;
                }
555
556
557
558
559
560
561
562
563
564
565
                try {
                    $element->add_attachments();
                    $element->assign_smarty_vars();
                    $this->xml .= $element->get_export_xml();
                }
                catch (FileNotFoundException $e) {
                    // If we don't find a file on disk, just continue the export,
                    // but leave this artefact out.
                    $this->messages[] = $e->getMessage();
                    log_debug('Missing file in leap2a export for artefact ' . $artefact->get('id'));
                }
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
            }
        }
    }

    /**
    * somewhat hacky way for other plugins to inject data into persondata
    * which is what artefact/internal creates
    *
    * @param array $data array of of keyed arrays. required keys are:
    *                     artefacttype, artefactplugin field, label,  value.
    *                     optional keys are service, displayorder and mahara (non leap persondata)
    */
    public function inject_persondata($data) {
        $this->extrapersondata = array_merge($this->extrapersondata, $data);
    }

    /**
    * export the feed footer
    */
    private function export_footer() {
        $this->xml .= $this->smarty->fetch('export:leap:footer.tpl');
    }


    /**
    * entry point for adding attachments into this export
    * USE THIS FUNCTION, and keep the return variable for the filename
    *
    * @param string $filepath path to file to add
    * @param string $newname proper resulting filename
    *
597
    * @return filename string use this to pass to add_enclosure_link
598
599
    */
    public function add_attachment($filepath, $newname) {
600
        global $SESSION;
601
        if (!file_exists($filepath) || empty($newname)) {
602
            $SESSION->add_error_msg(get_string('nonexistentfile', 'export', $newname));
603
        }
604
        $newname = substr(str_replace('/', '_', $newname), 0, 245);
605
606
607
608
609
610
611
612
613
614
615
616
617
618
        $this->attachments[] = (object)array('file' => $filepath, 'name' => $newname);
        return (count($this->attachments) -1) . '-' . $newname;
    }

    /**
     * format a date to the w3 datetime format
     *
     * @param integer unix timestamp to format
     * @return string W3 Date format
     */
    public static function format_rfc3339_date($date) {
        $d = format_date($date, 'strftimew3cdatetime');
        return substr($d, 0, -2) . ':' . substr($d, -2);
    }
Penny Leach's avatar
Penny Leach committed
619
620
621
622
623
624
625
626
627


    /**
     * given some content that might be html or xhtml, try to coerce it to xhtml and return it.
     *
     * @param string $content some html or xhtmlish content
     *
     * @return xhtml content or false for unmodified text content
     */
628
    public static function parse_xhtmlish_content($content, $viewid=null) {
629
        libxml_before(true);
Penny Leach's avatar
Penny Leach committed
630
631
632
633
        $dom = new DomDocument();
        $topel = $dom->createElement('tmp');
        $tmp = new DomDocument();
        if (strpos($content, '<') === false && strpos($content, '>') === false) {
634
            libxml_after();
Penny Leach's avatar
Penny Leach committed
635
636
637
638
639
640
641
642
            return false;
        }
        if (@$tmp->loadXML('<div>' . $content . '</div>')) {
            $topel->setAttribute('type', 'xhtml');
            $content = $dom->importNode($tmp->documentElement, true);
            $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
            $topel->appendChild($content);
            // if that fails, it could still be html
643
644
645
646
647
648
649
            // DomDocument::loadHTML() parses the input as iso-8859-1 if no
            // encoding is declared. Since we are only loading a HTML fragment
            // there is no  encoding declared which results in garbled output
            // since the content is actually in utf-8. To work around this
            // we force the encoding by appending an xml declaration.
            // see http://php.net/manual/de/domdocument.loadhtml.php#95251
        } else if (@$tmp->loadHTML('<?xml encoding="UTF-8"><div>' . $content . '</div>')) {
Penny Leach's avatar
Penny Leach committed
650
651
            $xpath = new DOMXpath($tmp);
            $elements = $xpath->query('/html/body/div');
652
653
654
655
656
            if ($elements->length != 1) {
                if ($viewid) {
                    log_warn("Leap2a export: invalid html found in view $viewid");
                }
                if ($elements->length < 1) {
657
                    libxml_after();
658
659
                    return false;
                }
Penny Leach's avatar
Penny Leach committed
660
            }
661
            $ourelement = $elements->item(0);
Penny Leach's avatar
Penny Leach committed
662
663
664
665
            $content = $dom->importNode($ourelement, true);
            $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
            $topel->appendChild($content);
        } else {
666
            libxml_after();
Penny Leach's avatar
Penny Leach committed
667
668
            return false; // wtf is it then?
        }
669
        $dom->appendChild($topel->firstChild);
670
671
        libxml_after();

Penny Leach's avatar
Penny Leach committed
672
673
        return $dom->saveXML($dom->documentElement);
    }
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
}

/**
* LEAP Element class
* one per entry
*/
class LeapExportElement {

    /**
    * the artefact this element represents
    */
    protected $artefact;

    /**
    * the exporter object
    */
    protected $exporter;

    /**
    * smarty object to assign variables to
    */
    protected $smarty;

    /**
    * the links this element has to other elements
    */
    protected $links;

    /**
    * constructor.
    *
    * @param ArtefactType $artefact artefact this element represents
706
    * @param PluginExportLeap $exporter the exporter object
707
    */
708
    public function __construct(ArtefactType $artefact=null, PluginExportLeap $exporter=null) {
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
        $this->artefact = $artefact;
        $this->exporter = $exporter;
        $this->smarty   = smarty_core();
    }

    /**
    * Return the xml for this element
    *
    * @return string XML
    */
    public function get_export_xml() {
        return $this->smarty->fetch($this->get_template_path());
    }

    /**
    * assign the smarty vars used in this template
    */
    public function assign_smarty_vars() {
727
728
729
730
731
        if (!($this->artefact instanceof ArtefactType)) {
            // If you're seeing this error, this means you have subclassed
            // LeapExportElement and are using it to represent something more
            // than just one artefact. In this case, you must override this
            // method.
732
            throw new ExportException($this, "LeapExportElement::assign_smarty_vars was called with null artefact. "
733
734
735
                . "If you are using LeapExportElement as a dummy class for exporting more than one artefact, "
                . "you must override assign_smarty_vars yourself.");
        }
736
737
738
739
740
741
742
743
        $this->smarty->assign('artefacttype', $this->artefact->get('artefacttype'));
        $this->smarty->assign('artefactplugin', $this->artefact->get_plugin_name());
        $this->smarty->assign('title', $this->artefact->get('title'));
        $this->smarty->assign('id', 'portfolio:artefact' . $this->artefact->get('id'));
        $this->smarty->assign('updated', PluginExportLeap::format_rfc3339_date($this->artefact->get('mtime')));
        $this->smarty->assign('created', PluginExportLeap::format_rfc3339_date($this->artefact->get('ctime')));
        // these are the ones we really need to override
        $this->add_links();
Penny Leach's avatar
Penny Leach committed
744
745
746
747
748
749
750
751
752
        $content = $this->get_content();
        // try to coerce it to xhtml
        if ($this->get_content_type() != 'text' && $newcontent = PluginExportLeap::parse_xhtmlish_content($content)) {
            $this->smarty->assign('contenttype', 'xhtml');
            $this->smarty->assign('content', $newcontent);
        } else {
            $this->smarty->assign('contenttype', 'text');
            $this->smarty->assign('content', $content);
        }
753
        $this->smarty->assign('leaptype', $this->get_leap_type());
754
        $this->smarty->assign('author', $this->get_entry_author());
755
        $this->smarty->assign('dates', $this->get_dates());
756
757

        if ($tags = $this->artefact->get('tags')) {
758
759
760
761
762
            $tags = array_map(function ($a) {
                return array(
                    'term' => LeapExportElement::normalise_tag($a),
                    'label' => $a
                );}, $tags);
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
        }
        if (!$categories = $this->get_categories()) {
            $categories = array();
        }
        $this->smarty->assign('categories', array_merge($tags, $categories));
        $this->smarty->assign('links', $this->links);
    }

    /**
    * add a link to a view
    * uses get_view_relationship to figure out which LEAP relationship to use
    * use this function, as it makes sure the view we're linking to is included
    * in the feed.
    *
    * @param View $view to link to
    */
779
780
781
782
    public function add_view_link($viewid, $rel=null) {
        if (is_null($rel)) {
            $rel = $this->get_view_relationship($viewid);
        }
783
        if (array_key_exists($viewid, $this->exporter->get('views'))) {
784
            $this->add_generic_link('view' . $viewid, $rel);
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
        }
    }

    /**
    * add a link to another artefact
    * use this function, as it makes sure the artefact we're linking to is included
    * in the feed.
    *
    * @param ArtefactType $artefact artefact to link to
    * @param string rel the LEAP relationship to use
    */
    public function add_artefact_link(ArtefactType $artefact, $rel) {
        if (array_key_exists($artefact->get('id'), $this->exporter->get('artefacts'))) {
            $this->add_generic_link('artefact' . $artefact->get('id'), $rel);
        }
    }

    /**
    * Adds a link to this element that isn't necessarily to a view or artefact
    *
    * @param string $id id to link to, not including portfolio: ns
    *                                  eg resumecomposite6
    * @param string $rel the LEAP relationship to use
    * @param keyed array $extras any extra bits to go in (eg display_order => 1)
    */
    public function add_generic_link($id, $rel, $extras=null) {
811
        if (!in_array($rel, array('related', 'alternate', 'enclosure'))) {
812
            $rel = 'leap2:' . $rel;
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
        }
        $link = array(
            'id'   => 'portfolio:' . $id,
            'type' => $rel,
        );
        if (is_array($extras)) {
            $link = array_merge($extras, $link);
        }
        $this->links['portfolio:' . $id] = (object)$link;
    }

    /**
    * Add links to other artefacts and views
    * By default just the parents, children, and views.
    * You can override this to add extra links, eg files/blogposts
    *
    * The resulting array is keyed on the LEAP portfolio:id (eg portfolio:artefact2)
    */
    public function add_links() {
832
833
        $id = $this->artefact->get('id');
        if ($views = $this->exporter->artefact_in_view_links($id)) {
834
            foreach ($views as $view) {
835
                $this->add_view_link($view);
836
837
            }
        }
838
        if ($parent = $this->exporter->artefact_parent_link($id)) {
839
840
            $this->add_artefact_link($parent, $this->get_parent_relationship($parent));
        }
841
        if ($children = $this->exporter->artefact_child_links($id)) {
842
843
844
845
            foreach ($children as $child) {
                $this->add_artefact_link($child, $this->get_child_relationship($child));
            }
        }
846
847
        if ($attachments = $this->exporter->artefact_attachment_links($id)) {
            foreach ($attachments as $a) {
848
                $this->add_artefact_link($a, 'related');
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
            }
        }
        if ($views = $this->exporter->artefact_view_links($id)) {
            foreach ($views as $viewid => $linktypes) {
                foreach ($linktypes as $linktype) {
                    $this->add_view_link($viewid, $linktype);
                }
            }
        }
        if ($artefacts = $this->exporter->artefact_artefact_links($id)) {
            foreach ($artefacts as $artefactid => $linktypes) {
                foreach ($linktypes as $linktype) {
                    $this->add_artefact_link($this->exporter->artefacts[$artefactid], $linktype);
                }
            }
        }
865
866
    }

867
868
869
870
871
872
    /**
     * add an enclosure link to the export
     * for where we previously used the src attribute of the content tag.
     * this does not attach the file to the expot, you have to use the
     * {@link add_attachment} method on the exporter object.
     *
873
     * @param string $filename the relative path of the file (NOT including the filesdir)
874
875
     * @param string $mimetype the (optional) mimetype of the file (according to atom
     *                          spec the type attribute on an enclosure is optional)
876
     */
877
    public function add_enclosure_link($filename, $mimetype = '') {
878
        $this->links[$filename] = (object)array(
879
            'id' => $this->exporter->get('filedir') . $filename,
880
            'type' => 'enclosure',
881
882
            'file' => true,
            'mimetype' => $mimetype
883
884
885
        );
    }

886
887
888
889
890
891
892
893
894
895
896
897
898
899
    /**
    * Path to main entry template.
    * this can be overridden per artefact plugin... eg
    * export:leap/file:imageentry.tpl
    * export:leap/plugin:artefacttypeentry.tpl
    *
    * @return string
    */
    public function get_template_path() {
        return 'export:leap:entry.tpl';
    }

    /**
    * The LEAP element type
Francois Marier's avatar
Francois Marier committed
900
    * See http://wiki.cetis.ac.uk/2009-03/Leap2A_types
901
902
903
904
905
906
907
908
    *
    * @return string
    */
    public function get_leap_type() {
        return 'entry'; // default base type that everything inherits from
    }

    /**
909
910
     * The content type of whatever is going in the <content> element.
     *
Aaron Wells's avatar
Aaron Wells committed
911
     * Can only be one of 'text', 'html' or 'xhtml', and we're currently not
912
913
914
915
916
917
918
919
920
921
922
923
     * using XHTML in Mahara.
     *
     * @return string
     */
    public function get_content_type() {
        return 'text';
    }


    /**
    * The main content of the element, which goes between <content> tags.
    *
Aaron Wells's avatar
Aaron Wells committed
924
    * Escaping of this value happens in the template, depending on the content
925
926
927
    * type, which can be set with {@link get_content_type()}.
    *
    * The default is to use the artefact description.
928
    *
929
    * @return string
930
931
    */
    public function get_content() {
932
933
934
935
936
937
938
939
        switch ($this->get_content_type()) {
        case 'text':
        case 'html':
        case 'xhtml':
            return $this->artefact->get('description');
        default:
            throw new SystemException("Unrecognised content type");
        }
940
941
    }

942
    /**
943
    * The name of the entry's author
944
    *
945
    * @return string
946
947
    */
    public function get_entry_author() {
948
949
950
951
952
953
954
        if ($author = $this->artefact->get('author')) {
            if ($author != $this->artefact->get('owner')) {
                return display_name($author);
            }
            return;
        }
        return $this->artefact->get('authorname');
955
956
    }

957
958
959
960
961
962
963
964
965
    /**
    * Get leap:date items for the entry
    *
    * @return array
    */
    public function get_dates() {
        return array();
    }

966
967
968
969
970
971
    /**
    * The relationship this artefact has to a view.
    * Almost always is_part_of, but could also be supports or anything else.
    *
    * @return string
    */
972
    public function get_view_relationship($viewid) {
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
        return 'is_part_of';
    }

    /**
    * The relationship this artefact has to the given child.
    * By default, has_part
    *
    * @return string
    */
    public function get_child_relationship(ArtefactType $child) {
        return 'has_part';
    }

    /**
    * The relationship this artefact has to the given parent.
    * By default, is_part_of
    *
    * @return string
    */
    public function get_parent_relationship(ArtefactType $parent) {
        return 'is_part_of';
    }

    /**
    * Add the attachments this element has to the export
    * Use the add_attachment method on the exporter object
    * For each attachments
    */
    public function add_attachments() { }

    /**
    * If the entire plugin overrides export
    * but there are individual artefact types that should be exported
    * override this to return true.
    *
    * For example, internal gets overridden to do persondata
    * but industry, introduction & occupation are entries in their own right
    */
    public function override_plugin_specialcase() {
        return false;
    }

    /**
    * is this element even a LEAP element.
    * return false to have this artefact skipped
    * (this is essentially opt-out for artefact types)
    */
    public function is_leap() {
        return true;
    }

    public function get_categories() {
        return array();
    }

    /**
    * Getter
    *
    * @param String key
    */
    public function get($field) {
        if (!property_exists($this, $field)) {
            throw new ParamOutOfRangeException("Field $field wasn't found in class " . get_class($this));
        }
        return $this->{$field};
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
1041
     * Converts a tag to a 'normalised' tag, as per
Francois Marier's avatar
Francois Marier committed
1042
     * http://wiki.cetis.ac.uk/2009-03/Leap2A_categories#Plain_tags
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
     *
     * The method of normalisation isn't specified at
     * the time of this being written.
     */
    public static function normalise_tag($tag) {
        $tag = preg_replace('#[^a-zA-Z0-9-]#', '-', $tag);
        $tag = preg_replace('#\-{2,}#', '-', $tag);
        return $tag;
    }
}

/**
* Class to extend for entire plugin exports
*
* when each artefact isn't just an ordinary entry
* eg internal & resume
*/
abstract class LeapExportArtefactPlugin {

    protected $exporter;
    protected $artefacts;

1065
    public function __construct(PluginExportLeap $exporter, array $artefacts) {
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
        $this->exporter = $exporter;
        $this->artefacts = $artefacts;
    }

    /**
    * contract method used to detect whether the entire plugin should override the export
    * here for consistency but there's really no point overriding this to return false
    * the existance of a subclass kind of implies overriding.
    */
    public static function override_entire_export() {
        return true;
    }

    /**
    * export xml for the subclass.
    *
    * @return XML string
    */
    abstract public function get_export_xml();

}

1088
1089
1090
1091
1092
function export_leap_rewrite_links($html) {
    $outputfilter = LeapExportOutputFilter::singleton();
    return $outputfilter->filter($html);
}
/**
Aaron Wells's avatar
Aaron Wells committed
1093
 * Provides a mechanism for converting the HTML generated by views and
1094
1095
 * artefacts for the LEAP export.
 *
Aaron Wells's avatar
Aaron Wells committed
1096
 * This is primarily so that the content of view blocktypes and links to
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
 * artefacts get rewritten to point to entries within the export.
 */
class LeapExportOutputFilter {

    private static $instance = null;

    private $artefactids = array();

    private function __construct() {
    }

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

    public function set_artefactids(array $artefactids) {
        $this->artefactids = $artefactids;
    }

    public function filter($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(
            array(
1130
                '#<(a[^>]+)href="(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)(&amp;view=\d+)?"([^>]*)>#',
1131
                '#<(img[^>]+)src="(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)([^"]*)?"([^>]*)>#',
1132
1133
1134
1135
1136
1137
1138
1139
1140
            ),
            array($this, 'replace_download_link'),
            $html
        );

        return $html;
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
1141
     * Callback to replace links to artefact to point to the correct entry
1142
1143
1144
1145
1146
     * in the LEAP export
     */
    private function replace_artefact_link($matches) {
        $artefactid = $matches[2];
        if (in_array($artefactid, $this->artefactids)) {
1147
            return '<a rel="leap2:has_part" href="portfolio:artefact' . hsc($artefactid) . '"' . $matches[5] . '>';
1148
1149
        }

Aaron Wells's avatar
Aaron Wells committed
1150
        // If the artefact isn't in the export, then we can't provide an
1151
1152
1153
1154
1155
1156
        // export-relative link to it
        log_debug("Not providing an export-relative link for $artefactid");
        return $matches[0];
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
1157
     * Callback to replace links to artefact/file/download.php to point to the
1158
1159
1160
1161
1162
     * correct entry in the LEAP export
     */
    private function replace_download_link($matches) {
        $artefactid = $matches[3];
        if (in_array($artefactid, $this->artefactids)) {
1163
            return '<' . $matches[1] . 'rel="leap2:has_part" href="portfolio:artefact' . hsc($artefactid) . '"' . $matches[5] . ($matches[1] == 'img' ? '/' : '') . '>';
1164
1165
1166
1167
1168
1169
        }

        log_debug("Not providing an export-relative link for $artefactid");
        return $matches[0];
    }

1170
}