lib.php 46 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
*/
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
    */
50
    protected $filedir     = 'export_info/files/';
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

    /**
    * 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
        $this->smarty = smarty_core();
75
        $this->exporttype = 'leap';
76

77
78
79
80
        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'
81
            . $this->get('user')->get('id') . '-' . date('Y-m-d_H-i', $this->exporttime) . '_' . get_random_key() . '.zip';
82
        // some plugins might want to do their own special thing
83
        foreach (plugins_installed('artefact', true) as $plugin) {
84
85
            $plugin = $plugin->name;
            if (safe_require('export', 'leap/' . $plugin, 'lib.php', 'require_once', true)) {
86
87
88
89
90
91
                $classname = 'LeapExport' . ucfirst($plugin);
                if (class_exists($classname) && call_static_method($classname, 'override_entire_export')) {
                    $this->specialcases[$plugin] = array();
                }
            }
        }
92
93
94
95

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

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

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

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

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    /**
     * 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;
    }

122
    /**
123
124
125
126
127
     * Main export routine
     * @param $createarchive Boolean specifies whether a zipfile will be created here
     * or later on, i.e. in PluginExportAll which creates a zipfile of all export formats.
     */
    public function export($createarchive=false) {
128
        global $SESSION;
129
130
        // the xml stuff
        $this->export_header();
131
        $this->setup_links();
132
        $this->notify_progress_callback(10, get_string('exportingviews', 'export'));
133
134
        if ($this->viewexportmode == PluginExport::EXPORT_LIST_OF_COLLECTIONS
            || $this->viewexportmode == PluginExport::EXPORT_ALL_VIEWS_COLLECTIONS) {
135
136
            $this->export_collections();
        }
137
        $this->export_views();
138
        $this->notify_progress_callback(50, get_string('exportingartefacts', 'export'));
139
140
        $this->export_artefacts();

141
        $this->notify_progress_callback(80, get_string('exportingartefactplugindata', 'export'));
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
        $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();
        }
157
        $this->notify_progress_callback(85, get_string('exportingfooter', 'export'));
158
159

        $this->export_footer();
160
        $this->notify_progress_callback(90, get_string('writingfiles', 'export'));
161

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

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

        // copy attachments over
        foreach ($this->attachments as $id => $fileinfo) {
            $existingfile = $fileinfo->file;
            $desiredname  = $fileinfo->name;
175
            if (!is_file($existingfile) || !copy($existingfile, $this->exportdir . $this->filedir . $desiredname)) {
176
177
                $SESSION->add_error_msg(get_string('couldnotcopyattachment', 'export', $desiredname));
            }
178
        }
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

        if (!$createarchive) {
            return array(
                'exportdir' => $this->exportdir,
                'dirs' => array(
                    $this->leapfile,
                    $this->filedir,
                ),
            );
        }

        // zip everything up
        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());
        }
        $this->notify_progress_callback(100, get_string('Done', 'export'));
        return $this->zipfile;
199
200
201
202
203
204
205
206
207
208
209
210
211
    }

    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'));
212
213
        $this->smarty->assign('export_time', $this->exporttime);
        $this->smarty->assign('export_time_rfc3339', PluginExportLeap::format_rfc3339_date($this->exporttime));
214
215
216
217
218
        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');
    }

219
220
221
222
223
224
225
226
227
228
229

    /**
     * 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');
230
            $this->smarty->assign('summary',     clean_html($collection->get('description')));
231
            $this->smarty->assign('contenttype', 'text');
232
            $this->smarty->assign('content',     clean_html($collection->get('description')));
233
234
            $this->smarty->assign('leaptype',    'selection');

235
236
237
238
239
240
241
242
243
244
245
246
247
248
            $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));
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263

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

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    /**
     * Get any extra configdata that should export to a blockinstance, i.e tags for taggedposts
     * by getting all distinct, installed blocktypes on a view then calling the get_blocktype_export_data(...)
     * for each block type where necessary.
     * @param array &$config    by reference, the configdata array containing block data
     * @param int  $viewid    id of the view containing the blocks
     *
     */
    private function get_block_export_data_for_blocktype(&$config, $viewid, $oldlayout=false) {
        $blocktypes = get_records_sql_array('
        SELECT DISTINCT bi.blocktype, b.artefactplugin
        FROM {block_instance} bi
        JOIN {blocktype_installed} b
        ON b.name = bi.blocktype
        WHERE view = ?',
        array($viewid));
280
281
282
283
284
285
        if ($blocktypes) {
            foreach ($blocktypes as $blocktype) {
                $classname = 'LeapExport' . $blocktype->blocktype;
                if (class_exists($classname) && method_exists($classname, 'get_blocktype_export_data')) {
                    call_user_func_array(array($classname, 'get_blocktype_export_data'), array(&$config, $viewid, $oldlayout));
                }
286
287
288
            }
        }
    }
289

290
    /**
291
292
     * Export the views
     */
293
    private function export_views() {
294
295
296
297
298
299
300
        $progressstart = 10;
        $progressend   = 50;
        $views = $this->get('views');
        $viewcount = count($views);
        $i = 0;
        foreach ($views as $view) {
            $percent = intval($progressstart + ($i++ / $viewcount) * ($progressend - $progressstart));
301
            $this->notify_progress_callback($percent, get_string('exportingviewsprogressleap', 'export', $i, $viewcount));
302

303
            $config = $this->rewrite_artefact_ids($view->export_config('leap'));
304
305
306
307
            $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
308
            $content = $config['description'];
309

Penny Leach's avatar
Penny Leach committed
310
311
            if ($newcontent = self::parse_xhtmlish_content($content)) {
                $this->smarty->assign('summarytype', 'xhtml');
312
                $this->smarty->assign('summary',     clean_html($newcontent, true));
313
314
            }
            else {
Penny Leach's avatar
Penny Leach committed
315
                $this->smarty->assign('summarytype', 'text');
316
                $this->smarty->assign('summary',     clean_html($content));
Penny Leach's avatar
Penny Leach committed
317
            }
318
319
320
321
322
323
324
325
326
327
328

            $instructions = $config['instructions'];
            if ($newinstructions = self::parse_xhtmlish_content($instructions)) {
                $this->smarty->assign('instructionstype', 'xhtml');
                $this->smarty->assign('instructions',     clean_html($newinstructions, true));
            }
            else {
                $this->smarty->assign('instructionstype', 'text');
                $this->smarty->assign('instructions',     clean_html($instructions));
            }

Penny Leach's avatar
Penny Leach committed
329
            $this->smarty->assign('contenttype', 'xhtml');
330
            if (!$view->uses_new_layout()) {
331
                if ($viewcontent = self::parse_xhtmlish_content($view->build_rows(false, $this->exporttype), $view->get('id'))) {
332
333
334
335
336
337
338
339
340
                    $this->smarty->assign('content', clean_html($viewcontent, true));
                }
                $layout = $view->get_layout();
                $widths = '';
                foreach ($layout->rows as $row){
                  $widths .= $row['widths'] . '-';
                }
                $widths = substr($widths, 0, -1);
                $this->smarty->assign('layout',      $widths);
341
342
343
                $this->get_block_export_data_for_blocktype($config['rows'], $view->get('id'), true);

                $this->smarty->assign('viewdata',    $config['rows']);
344
            }
345
            else {
346
                if ($viewblocks = self::parse_xhtmlish_content($view->get_blocks(false, $this->exporttype), $view->get('id'))) {
347
                    $this->smarty->assign('content', clean_html($viewblocks, true));
348
                    $this->get_block_export_data_for_blocktype($config['grid'], $view->get('id'));
349
                }
350
                $this->smarty->assign('blocks', $config['grid']);
351
                $this->smarty->assign('newlayout', true);
352
            }
353

354
            $this->smarty->assign('type',        $config['type']);
355
356
            $ownerformat = ($config['ownerformat']) ? $config['ownerformat'] : FORMAT_NAME_DISPLAYNAME;
            $this->smarty->assign('ownerformat', $ownerformat);
357
            $this->smarty->assign('leaptype',    'selection');
Nigel McNie's avatar
Nigel McNie committed
358
359
360

            $tags = array();
            if ($config['tags']) {
361
362
363
364
365
                $tags = array_map(function ($a) {
                    return array(
                        'term' => LeapExportElement::normalise_tag($a),
                        'label' => $a
                    );}, $config['tags']);
Nigel McNie's avatar
Nigel McNie committed
366
367
            }
            $this->smarty->assign('categories', array_merge(array(
368
369
370
371
                array(
                    'scheme' => 'selection_type',
                    'term' => 'Webpage',
                )
Nigel McNie's avatar
Nigel McNie committed
372
373
            ), $tags));

374
            $this->smarty->assign('links', $this->get_links_for_view($view->get('id')));
375
            $this->xml .= $this->smarty->fetch("export:leap:view.tpl");
376
377
378
        }
    }

379
380
381

    // Some links can be determined in advance
    private function setup_links() {
382
383
384

        // If there are no pages, no links to set up.
        if (empty($this->views)) {
385
386
387
            return;
        }

388
389
390
        if (!isset($this->links)) {
            $this->links = new stdClass();
        }
391
392
        $viewlist = join(',', array_keys($this->views));

393
394
395
396
397
        // Views in collections
        if ($this->collections) {
            $collectionlist = join(',', array_keys($this->collections));
            $records = get_records_select_array(
                'collection_view',
398
399
400
                "view IN ($viewlist) AND collection IN ($collectionlist)",
                array(),
                'displayorder'
401
402
403
404
405
406
407
408
409
            );
            if ($records) {
                foreach ($records as &$r) {
                    $this->links->collectionview[$r->collection][$r->view] = 1;
                    $this->links->viewcollection[$r->view][$r->collection] = 1;
                }
            }
        }

410
411
412
413
414
415
416
        // If there are no artefacts, no need to try to set those up.
        if (empty($this->artefacts)) {
            return;
        }

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

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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        // 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')) {
465
                call_user_func_array(
466
                    array($classname, 'setup_links'),
467
                    array(&$this->links, array_keys($this->views), array_keys($this->artefacts))
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
                );
            }
        }
    }

    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];
        }
    }

509
510
511
512
513
514
515
516
517
518
    /**
     * 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) {
519
520
521
522
        $newlayout = isset($config['newlayout']) && $config['newlayout'];
        if (!$newlayout) {
            foreach ($config['rows'] as &$row) {
              foreach ($row['columns'] as &$column) {
523
                foreach ($column as &$blockinstance) {
524
525
526
527
528
529
530
                  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;
531
                    }
532
533
534
535
536
                  }
                  else if (isset($blockinstance['config']['artefactids'])) {
                    $ids = json_decode($blockinstance['config']['artefactids']);
                    if ($ids[0]) {
                      $blockinstance['config']['artefactids'] = json_encode(array(array_map(array($this, 'prepend_artefact_identifier'), $ids[0])));
537
                    }
538
539
540
541
542
543
544
545
546
547
548
549
550
551
                  }
                }
              } // cols
            } //rows
        }
        else {
            foreach ($config['grid'] 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;
552
                }
553
554
555
556
557
558
559
560
561
              }
              else if (isset($blockinstance['config']['artefactids'])) {
                $ids = json_decode($blockinstance['config']['artefactids']);
                if ($ids[0]) {
                  $blockinstance['config']['artefactids'] = json_encode(array(array_map(array($this, 'prepend_artefact_identifier'), $ids[0])));
                }
              }
            }
        }
562
563
564
565
566
567
568
        return $config;
    }

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

569
570
    private function get_links_for_view($viewid) {
        $links = array();
571

572
573
574
575
576
577
578
579
580
        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,
                );
            }
        }

581
582
        if (!empty($this->links->viewcontents[$viewid])) {
            foreach (array_keys($this->links->viewcontents[$viewid]) as $artefactid) {
583
                $links[] = (object)array(
584
                    'type' => 'leap2:has_part',
585
                    'id'   => 'portfolio:artefact' . $artefactid,
586
587
588
                );
            }
        }
589

590
591
592
593
594
595
596
597
        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,
                    );
                }
598
599
            }
        }
600

601
602
603
        return $links;
    }

604
    /**
605
606
     * Export the artefacts
     */
607
    private function export_artefacts() {
608
609
        $progressstart = 50;
        $progressend   = 80;
610
611
612
613
        $artefacts     = $this->get('artefacts');
        $artefactcount = count($artefacts);
        $i = 0;
        foreach ($artefacts as $artefact) {
614
            if ($i++ % 3 == 0) {
615
                $percent = intval($progressstart + ($i / $artefactcount) * ($progressend - $progressstart));
616
                $this->notify_progress_callback($percent, get_string('exportingartefactsprogress', 'export', $i, $artefactcount));
617
            }
618
619
            $element = null;
            // go see if we have to do anything special for this artefact type.
620
621
622
623
624
            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);
                }
625

626
627
628
629
630
631
632
633
634
635
                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;
                }
636
637
638
639
640
641
642
643
644
645
646
                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'));
                }
647
648
649
650
651
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
            }
        }
    }

    /**
    * 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
    *
678
    * @return filename string use this to pass to add_enclosure_link
679
680
    */
    public function add_attachment($filepath, $newname) {
681
        global $SESSION;
682
        if (!file_exists($filepath) || empty($newname)) {
683
            $SESSION->add_error_msg(get_string('nonexistentfile', 'export', $newname));
684
        }
685
        $newname = substr(str_replace('/', '_', $newname), 0, 245);
686
        $this->attachments[] = (object)array('file' => $filepath, 'name' => $newname);
687
688
        // return (count($this->attachments) -1) . '-' . $newname;
        return $newname;
689
690
691
692
693
694
695
696
697
698
699
700
    }

    /**
     * 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
701
702
703
704
705
706
707
708
709


    /**
     * 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
     */
710
    public static function parse_xhtmlish_content($content, $viewid=null) {
711
        libxml_before(true);
Penny Leach's avatar
Penny Leach committed
712
713
714
        $dom = new DomDocument();
        $topel = $dom->createElement('tmp');
        $tmp = new DomDocument();
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729

        if (is_array($content)) {
            $contenthtml = '';
            foreach ($content as $block) {
                if (strpos($block['content'], '<') === false && strpos($block['content'], '>') === false) {
                    continue;
                }
                $contenthtml .= '<div id="block_' . $block['id'] . '"' .
                ' positionx=' . $block['positionx'] .
                ' positiony=' . $block['positiony'] .
                ' width=' . $block['width'] .
                ' height=' . $block['height'] . '>' .
                $block['content'] . '</div>';
            }
            $content = $contenthtml;
Penny Leach's avatar
Penny Leach committed
730
        }
731

Penny Leach's avatar
Penny Leach committed
732
733
734
735
736
737
        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
738
739
740
741
742
743
744
            // 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
745
746
            $xpath = new DOMXpath($tmp);
            $elements = $xpath->query('/html/body/div');
747
748
749
750
751
            if ($elements->length != 1) {
                if ($viewid) {
                    log_warn("Leap2a export: invalid html found in view $viewid");
                }
                if ($elements->length < 1) {
752
                    libxml_after();
753
754
                    return false;
                }
Penny Leach's avatar
Penny Leach committed
755
            }
756
            $ourelement = $elements->item(0);
Penny Leach's avatar
Penny Leach committed
757
758
759
760
            $content = $dom->importNode($ourelement, true);
            $content->setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
            $topel->appendChild($content);
        } else {
761
            libxml_after();
Penny Leach's avatar
Penny Leach committed
762
763
            return false; // wtf is it then?
        }
764
        $dom->appendChild($topel->firstChild);
765
766
        libxml_after();

Penny Leach's avatar
Penny Leach committed
767
768
        return $dom->saveXML($dom->documentElement);
    }
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
}

/**
* 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
801
    * @param PluginExportLeap $exporter the exporter object
802
    */
803
    public function __construct(ArtefactType $artefact=null, PluginExportLeap $exporter=null) {
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
        $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() {
822
823
824
825
826
        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.
827
            throw new ExportException($this, "LeapExportElement::assign_smarty_vars was called with null artefact. "
828
829
830
                . "If you are using LeapExportElement as a dummy class for exporting more than one artefact, "
                . "you must override assign_smarty_vars yourself.");
        }
831
832
833
834
835
836
837
838
        $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
839
840
841
842
        $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');
843
            $this->smarty->assign('content', clean_html($newcontent, true));
Penny Leach's avatar
Penny Leach committed
844
845
        } else {
            $this->smarty->assign('contenttype', 'text');
846
            $this->smarty->assign('content', clean_html($content));
Penny Leach's avatar
Penny Leach committed
847
        }
848
        $this->smarty->assign('leaptype', $this->get_leap_type());
849
        $this->smarty->assign('author', $this->get_entry_author());
850
        $this->smarty->assign('dates', $this->get_dates());
851
852

        if ($tags = $this->artefact->get('tags')) {
853
854
855
856
857
            $tags = array_map(function ($a) {
                return array(
                    'term' => LeapExportElement::normalise_tag($a),
                    'label' => $a
                );}, $tags);
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
        }
        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
    */
874
875
876
877
    public function add_view_link($viewid, $rel=null) {
        if (is_null($rel)) {
            $rel = $this->get_view_relationship($viewid);
        }
878
        if (array_key_exists($viewid, $this->exporter->get('views'))) {
879
            $this->add_generic_link('view' . $viewid, $rel);
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
        }
    }

    /**
    * 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) {
906
        if (!in_array($rel, array('related', 'alternate', 'enclosure'))) {
907
            $rel = 'leap2:' . $rel;
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        }
        $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() {
927
928
        $id = $this->artefact->get('id');
        if ($views = $this->exporter->artefact_in_view_links($id)) {
929
            foreach ($views as $view) {
930
                $this->add_view_link($view);
931
932
            }
        }
933
        if ($parent = $this->exporter->artefact_parent_link($id)) {
934
935
            $this->add_artefact_link($parent, $this->get_parent_relationship($parent));
        }
936
        if ($children = $this->exporter->artefact_child_links($id)) {
937
938
939
940
            foreach ($children as $child) {
                $this->add_artefact_link($child, $this->get_child_relationship($child));
            }
        }
941
942
        if ($attachments = $this->exporter->artefact_attachment_links($id)) {
            foreach ($attachments as $a) {
943
                $this->add_artefact_link($a, 'related');
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
            }
        }
        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);
                }
            }
        }
960
961
    }

962
963
964
965
966
967
    /**
     * 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.
     *
968
     * @param string $filename the relative path of the file (NOT including the filesdir)
969
970
     * @param string $mimetype the (optional) mimetype of the file (according to atom
     *                          spec the type attribute on an enclosure is optional)
971
     */
972
    public function add_enclosure_link($filename, $mimetype = '') {
973
        $this->links[$filename] = (object)array(
974
            'id' => $this->exporter->get('filedir') . $filename,
975
            'type' => 'enclosure',
976
977
            'file' => true,
            'mimetype' => $mimetype
978
979
980
        );
    }

981
982
983
984
985
986
987
988
989
990
991
992
993
994
    /**
    * 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
995
    * See http://wiki.cetis.ac.uk/2009-03/Leap2A_types
996
997
998
999
1000
1001
1002
1003
    *
    * @return string
    */
    public function get_leap_type() {
        return 'entry'; // default base type that everything inherits from
    }

    /**
1004
1005
     * The content type of whatever is going in the <content> element.
     *
Aaron Wells's avatar
Aaron Wells committed
1006
     * Can only be one of 'text', 'html' or 'xhtml', and we're currently not
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
     * 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
1019
    * Escaping of this value happens in the template, depending on the content
1020
1021
1022
    * type, which can be set with {@link get_content_type()}.
    *
    * The default is to use the artefact description.
1023
    *
1024
    * @return string
1025
1026
    */
    public function get_content() {
1027
1028
1029
1030
1031
1032
1033
1034
        switch ($this->get_content_type()) {
        case 'text':
        case 'html':
        case 'xhtml':
            return $this->artefact->get('description');
        default:
            throw new SystemException("Unrecognised content type");
        }
1035
1036
    }

1037
    /**
1038
    * The name of the entry's author
1039
    *
1040
    * @return string
1041
1042
    */
    public function get_entry_author() {
1043
1044
1045
1046
1047
1048
1049
        if ($author = $this->artefact->get('author')) {
            if ($author != $this->artefact->get('owner')) {
                return display_name($author);
            }
            return;
        }
        return $this->artefact->get('authorname');
1050
1051
    }

1052
1053
1054
1055
1056
1057
1058
1059
1060
    /**
    * Get leap:date items for the entry
    *
    * @return array
    */
    public function get_dates() {
        return array();
    }

1061
1062
1063
1064
1065
1066
    /**
    * The relationship this artefact has to a view.
    * Almost always is_part_of, but could also be supports or anything else.
    *
    * @return string
    */
1067
    public function get_view_relationship($viewid) {
1068
1069
1070
1071
1072
1073
1074
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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
        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
1136
     * Converts a tag to a 'normalised' tag, as per
Francois Marier's avatar
Francois Marier committed
1137
     * http://wiki.cetis.ac.uk/2009-03/Leap2A_categories#Plain_tags
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
     *
     * 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;

1160
    public function __construct(PluginExportLeap $exporter, array $artefacts) {
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
        $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();

}

1183
1184
1185
1186
1187
function export_leap_rewrite_links($html) {
    $outputfilter = LeapExportOutputFilter::singleton();
    return $outputfilter->filter($html);
}
/**
Aaron Wells's avatar
Aaron Wells committed
1188
 * Provides a mechanism for converting the HTML generated by views and
1189
1190
 * artefacts for the LEAP export.
 *
Aaron Wells's avatar
Aaron Wells committed
1191
 * This is primarily so that the content of view blocktypes and links to
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
 * 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(
1225
                '#<(a[^>]+)href="(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)(&amp;view=\d+)?"([^>]*)>#',
1226
                '#<(img[^>]+)src="(' . preg_quote(get_config('wwwroot')) . ')?/?artefact/file/download\.php\?file=(\d+)([^"]*)?"([^>]*)>#',
1227
1228
1229
1230
1231
1232
1233
1234
1235
            ),
            array($this, 'replace_download_link'),
            $html
        );

        return $html;
    }

    /**
Aaron Wells's avatar
Aaron Wells committed
1236
     * Callback to replace links to artefact to point to the correct entry
1237
1238
1239
1240
1241
     * in the LEAP export
     */
    private function replace_artefact_link($matches) {
        $artefactid = $matches[2];
        if (in_array($artefactid, $this->artefactids)) {
1242
            return '<a rel="leap2:has_part" href="portfolio:artefact' . hsc($artefactid) . '"' . $matches[5] . '>';
1243
1244
        }

Aaron Wells's avatar
Aaron Wells committed
1245
        // If the artefact isn't in the export, then we can't provide an
1246
1247
1248
1249
1250
1251
        // 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
1252
     * Callback to replace links to artefact/file/download.php to point to the
1253
1254
1255
1256
1257
     * correct entry in the LEAP export
     */
    private function replace_download_link($matches) {
        $artefactid = $matches[3];
        if (in_array($artefactid, $this->artefactids)) {
1258
            return '<' . $matches[1] . 'rel="leap2:has_part" href="portfolio:artefact' . hsc($artefactid) . '"' . $matches[5] . ($matches[1] == 'img' ? '/' : '') . '>';
1259
1260
1261
1262
1263
1264
        }

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

1265
}