lib.php 41.3 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
* http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/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
103
104
105
    public static function get_title() {
        return get_string('title', 'export.leap');
    }

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

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_COLLECTIONS
            || $this->viewexportmode == PluginExport::EXPORT_ALL_VIEWS) {
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

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

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

        // zip everything up
175
176
177
178
179
        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());
180
        }
181
        $this->notify_progress_callback(100, get_string('Done', 'export'));
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        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'));
196
197
        $this->smarty->assign('export_time', $this->exporttime);
        $this->smarty->assign('export_time_rfc3339', PluginExportLeap::format_rfc3339_date($this->exporttime));
198
199
200
201
202
        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');
    }

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

    /**
     * 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');

219
220
221
222
223
224
225
226
227
228
229
230
231
232
            $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));
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

            $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");
        }
    }


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

262
            $config = $this->rewrite_artefact_ids($view->export_config('leap'));
263
264
265
266
            $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
267
268
269
270
271
272
273
274
275
            $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');
276
            if ($viewcontent = self::parse_xhtmlish_content($view->build_rows(false, true), $view->get('id'))) {
277
278
                $this->smarty->assign('content', $viewcontent);
            }
279
280
            $this->smarty->assign('viewdata',    $config['rows']);
            $layout = $view->get_layout();
281
            $widths = '';
282
283
284
285
286
            foreach ($layout->rows as $row){
                $widths .= $row['widths'] . '-';
            }
            $widths = substr($widths, 0, -1);
            $this->smarty->assign('layout',      $widths);
287
            $this->smarty->assign('type',        $config['type']);
288
289
            $ownerformat = ($config['ownerformat']) ? $config['ownerformat'] : FORMAT_NAME_DISPLAYNAME;
            $this->smarty->assign('ownerformat', $ownerformat);
290
            $this->smarty->assign('leaptype',    'selection');
Nigel McNie's avatar
Nigel McNie committed
291
292
293

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

307
            $this->smarty->assign('links', $this->get_links_for_view($view->get('id')));
308
            $this->xml .= $this->smarty->fetch("export:leap:view.tpl");
309
310
311
        }
    }

312
313
314
315
316
317
318
319
320
321

    // Some links can be determined in advance
    private function setup_links() {
        if (empty($this->views) || empty($this->artefacts)) {
            return;
        }

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

322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
        // Views in collections
        if ($this->collections) {
            $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->links->collectionview[$r->collection][$r->view] = 1;
                    $this->links->viewcollection[$r->view][$r->collection] = 1;
                }
            }
        }

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
        // 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')) {
385
386
387
388
389
390
391
392
                // 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,
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
                    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];
        }
    }

436
437
438
439
440
441
442
443
444
445
    /**
     * 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) {
446
447
448
449
450
451
452
453
454
455
456
        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;
                        }
457
                    }
458
459
460
                    else if (isset($blockinstance['config']['artefactids'])) {
                        $ids = json_decode($blockinstance['config']['artefactids']);
                        $blockinstance['config']['artefactids'] = json_encode(array(array_map(array($this, 'prepend_artefact_identifier'), $ids[0])));
461
                    }
462
                }
463
464
            } // cols
        } //rows
465
466
467
468
469
470
471
        return $config;
    }

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

472
473
    private function get_links_for_view($viewid) {
        $links = array();
474

475
476
477
478
479
480
481
482
483
        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,
                );
            }
        }

484
485
        if (!empty($this->links->viewcontents[$viewid])) {
            foreach (array_keys($this->links->viewcontents[$viewid]) as $artefactid) {
486
                $links[] = (object)array(
487
                    'type' => 'leap2:has_part',
488
                    'id'   => 'portfolio:artefact' . $artefactid,
489
490
491
                );
            }
        }
492

493
494
495
496
497
498
499
500
        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,
                    );
                }
501
502
            }
        }
503

504
505
506
        return $links;
    }

507
    /**
508
509
     * Export the artefacts
     */
510
    private function export_artefacts() {
511
512
        $progressstart = 50;
        $progressend   = 80;
513
514
515
516
        $artefacts     = $this->get('artefacts');
        $artefactcount = count($artefacts);
        $i = 0;
        foreach ($artefacts as $artefact) {
517
            if ($i++ % 3 == 0) {
518
                $percent = intval($progressstart + ($i / $artefactcount) * ($progressend - $progressstart));
519
                $this->notify_progress_callback($percent, get_string('exportingartefactsprogress', 'export', $i, $artefactcount));
520
            }
521
522
            $element = null;
            // go see if we have to do anything special for this artefact type.
523
524
525
526
527
            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);
                }
528

529
530
531
532
533
534
535
536
537
538
                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;
                }
539
540
541
542
543
544
545
546
547
548
549
                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'));
                }
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
            }
        }
    }

    /**
    * 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
    *
581
    * @return filename string use this to pass to add_enclosure_link
582
583
    */
    public function add_attachment($filepath, $newname) {
584
        global $SESSION;
585
        if (!file_exists($filepath) || empty($newname)) {
586
            $SESSION->add_error_msg(get_string('nonexistentfile', 'export', $newname));
587
        }
588
        $newname = substr(str_replace('/', '_', $newname), 0, 245);
589
590
591
592
593
594
595
596
597
598
599
600
601
602
        $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
603
604
605
606
607
608
609
610
611


    /**
     * 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
     */
612
    public static function parse_xhtmlish_content($content, $viewid=null) {
Penny Leach's avatar
Penny Leach committed
613
614
615
616
617
618
619
620
621
622
623
624
        $dom = new DomDocument();
        $topel = $dom->createElement('tmp');
        $tmp = new DomDocument();
        if (strpos($content, '<') === false && strpos($content, '>') === false) {
            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
625
626
627
628
629
630
631
            // 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
632
633
            $xpath = new DOMXpath($tmp);
            $elements = $xpath->query('/html/body/div');
634
635
636
637
638
639
640
            if ($elements->length != 1) {
                if ($viewid) {
                    log_warn("Leap2a export: invalid html found in view $viewid");
                }
                if ($elements->length < 1) {
                    return false;
                }
Penny Leach's avatar
Penny Leach committed
641
            }
642
            $ourelement = $elements->item(0);
Penny Leach's avatar
Penny Leach committed
643
644
645
646
647
648
            $content = $dom->importNode($ourelement, true);
            $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
            $topel->appendChild($content);
        } else {
            return false; // wtf is it then?
        }
649
        $dom->appendChild($topel->firstChild);
Penny Leach's avatar
Penny Leach committed
650
651
        return $dom->saveXML($dom->documentElement);
    }
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
}

/**
* 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
684
    * @param PluginExportLeap $exporter the exporter object
685
    */
686
    public function __construct(ArtefactType $artefact=null, PluginExportLeap $exporter=null) {
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
        $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() {
705
706
707
708
709
        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.
710
            throw new ExportException($this, "LeapExportElement::assign_smarty_vars was called with null artefact. "
711
712
713
                . "If you are using LeapExportElement as a dummy class for exporting more than one artefact, "
                . "you must override assign_smarty_vars yourself.");
        }
714
715
716
717
718
719
720
721
        $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
722
723
724
725
726
727
728
729
730
        $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);
        }
731
        $this->smarty->assign('leaptype', $this->get_leap_type());
732
        $this->smarty->assign('author', $this->get_entry_author());
733
        $this->smarty->assign('dates', $this->get_dates());
734
735

        if ($tags = $this->artefact->get('tags')) {
736
737
738
739
740
            $tags = array_map(function ($a) {
                return array(
                    'term' => LeapExportElement::normalise_tag($a),
                    'label' => $a
                );}, $tags);
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
        }
        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
    */
757
758
759
760
    public function add_view_link($viewid, $rel=null) {
        if (is_null($rel)) {
            $rel = $this->get_view_relationship($viewid);
        }
761
        if (array_key_exists($viewid, $this->exporter->get('views'))) {
762
            $this->add_generic_link('view' . $viewid, $rel);
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
        }
    }

    /**
    * 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) {
789
        if (!in_array($rel, array('related', 'alternate', 'enclosure'))) {
790
            $rel = 'leap2:' . $rel;
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        }
        $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() {
810
811
        $id = $this->artefact->get('id');
        if ($views = $this->exporter->artefact_in_view_links($id)) {
812
            foreach ($views as $view) {
813
                $this->add_view_link($view);
814
815
            }
        }
816
        if ($parent = $this->exporter->artefact_parent_link($id)) {
817
818
            $this->add_artefact_link($parent, $this->get_parent_relationship($parent));
        }
819
        if ($children = $this->exporter->artefact_child_links($id)) {
820
821
822
823
            foreach ($children as $child) {
                $this->add_artefact_link($child, $this->get_child_relationship($child));
            }
        }
824
825
        if ($attachments = $this->exporter->artefact_attachment_links($id)) {
            foreach ($attachments as $a) {
826
                $this->add_artefact_link($a, 'related');
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
            }
        }
        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);
                }
            }
        }
843
844
    }

845
846
847
848
849
850
    /**
     * 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.
     *
851
     * @param string $filename the relative path of the file (NOT including the filesdir)
852
853
     * @param string $mimetype the (optional) mimetype of the file (according to atom
     *                          spec the type attribute on an enclosure is optional)
854
     */
855
    public function add_enclosure_link($filename, $mimetype = '') {
856
        $this->links[$filename] = (object)array(
857
            'id' => $this->exporter->get('filedir') . $filename,
858
            'type' => 'enclosure',
859
860
            'file' => true,
            'mimetype' => $mimetype
861
862
863
        );
    }

864
865
866
867
868
869
870
871
872
873
874
875
876
877
    /**
    * 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
878
    * See http://wiki.cetis.ac.uk/2009-03/Leap2A_types
879
880
881
882
883
884
885
886
    *
    * @return string
    */
    public function get_leap_type() {
        return 'entry'; // default base type that everything inherits from
    }

    /**
887
888
     * The content type of whatever is going in the <content> element.
     *
Aaron Wells's avatar
Aaron Wells committed
889
     * Can only be one of 'text', 'html' or 'xhtml', and we're currently not
890
891
892
893
894
895
896
897
898
899
900
901
     * 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
902
    * Escaping of this value happens in the template, depending on the content
903
904
905
    * type, which can be set with {@link get_content_type()}.
    *
    * The default is to use the artefact description.
906
    *
907
    * @return string
908
909
    */
    public function get_content() {
910
911
912
913
914
915
916
917
        switch ($this->get_content_type()) {
        case 'text':
        case 'html':
        case 'xhtml':
            return $this->artefact->get('description');
        default:
            throw new SystemException("Unrecognised content type");
        }
918
919
    }

920
    /**
921
    * The name of the entry's author
922
    *
923
    * @return string
924
925
    */
    public function get_entry_author() {
926
927
928
929
930
931
932
        if ($author = $this->artefact->get('author')) {
            if ($author != $this->artefact->get('owner')) {
                return display_name($author);
            }
            return;
        }
        return $this->artefact->get('authorname');
933
934
    }

935
936
937
938
939
940
941
942
943
    /**
    * Get leap:date items for the entry
    *
    * @return array
    */
    public function get_dates() {
        return array();
    }

944
945
946
947
948
949
    /**
    * The relationship this artefact has to a view.
    * Almost always is_part_of, but could also be supports or anything else.
    *
    * @return string
    */
950
    public function get_view_relationship($viewid) {
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
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
        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
1019
     * Converts a tag to a 'normalised' tag, as per
Francois Marier's avatar
Francois Marier committed
1020
     * http://wiki.cetis.ac.uk/2009-03/Leap2A_categories#Plain_tags
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
     *
     * 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;

1043
    public function __construct(PluginExportLeap $exporter, array $artefacts) {
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
        $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();

}

1066
1067
1068
1069
1070
function export_leap_rewrite_links($html) {
    $outputfilter = LeapExportOutputFilter::singleton();
    return $outputfilter->filter($html);
}
/**
Aaron Wells's avatar
Aaron Wells committed
1071
 * Provides a mechanism for converting the HTML generated by views and
1072
1073
 * artefacts for the LEAP export.
 *
Aaron Wells's avatar
Aaron Wells committed
1074
 * This is primarily so that the content of view blocktypes and links to
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
 * 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(
1108
                '#<(a[^>]+)href="(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)(&amp;view=\d+)?"([^>]*)>#',
1109
                '#<(img[^>]+)src="(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)([^"]*)?"([^>]*)>#',
1110
1111
1112
1113
1114
1115
1116
1117
1118
            ),
            array($this, 'replace_download_link'),
            $html
        );

        return $html;
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
1119
     * Callback to replace links to artefact to point to the correct entry
1120
1121
1122
1123
1124
     * in the LEAP export
     */
    private function replace_artefact_link($matches) {
        $artefactid = $matches[2];
        if (in_array($artefactid, $this->artefactids)) {
1125
            return '<a rel="leap2:has_part" href="portfolio:artefact' . hsc($artefactid) . '"' . $matches[5] . '>';
1126
1127
        }

Aaron Wells's avatar
Aaron Wells committed
1128
        // If the artefact isn't in the export, then we can't provide an
1129
1130
1131
1132
1133
1134
        // 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
1135
     * Callback to replace links to artefact/file/download.php to point to the
1136
1137
1138
1139
1140
     * correct entry in the LEAP export
     */
    private function replace_download_link($matches) {
        $artefactid = $matches[3];
        if (in_array($artefactid, $this->artefactids)) {
1141
            return '<' . $matches[1] . 'rel="leap2:has_part" href="portfolio:artefact' . hsc($artefactid) . '"' . $matches[5] . ($matches[1] == 'img' ? '/' : '') . '>';
1142
1143
1144
1145
1146
1147
        }

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

1148
}