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

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

/**
Francois Marier's avatar
Francois Marier committed
31
 * Implements import of Leap2A files
32
33
34
35
36
37
38
39
40
41
 *
 * For more documentation, please see:
 * http://wiki.mahara.org/index.php?title=Developer_Area/Import%2F%2FExport/LEAP_Import
 */
class PluginImportLeap extends PluginImport {

    private $xml = null;
    private $namespaces = array();
    private $strategylisting = array();
    private $loadmapping = array();
42
    private $coreloadmapping = array();
43
    private $artefactids = array();
44
    private $viewids = array();
45
46
    private $collectionids = array();
    private $collectionviewentries = array();
47
    protected $filename;
48

49
50
    protected $persondataid = null;

51
52
    protected $loglevel = 0;
    protected $logtargets = LOG_TARGET_ERRORLOG;
53
    protected $logfile = '';
54
    protected $profile = false;
55
56
    protected $leap2anamespace = null;
    protected $leap2atypenamespace = null;
57
    protected $leap2acategories = null;
58
59
60
    // the version is stored with the full url since the url might change in
    // future versions (as it has between 2009-03 and 2010-07)
    protected $supportedleap2aversions = array('http://www.leapspecs.org/2010-07/2A/');
61
62
63
64
65
66
67
68

    private $snapshots = array();

    const LOG_LEVEL_STANDARD = 1;
    const LOG_LEVEL_VERBOSE  = 2;

    const NS_ATOM       = 'http://www.w3.org/2005/Atom';
    const NS_RDF        = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
69
70
71
72
73
    const NS_LEAP_200903       = 'http://wiki.cetis.ac.uk/2009-03/LEAP2A_predicates#';
    const NS_LEAPTYPE_200903   = 'http://wiki.cetis.ac.uk/2009-03/LEAP2A_types#';
    const NS_CATEGORIES_200903 = 'http://wiki.cetis.ac.uk/2009-03/LEAP2A_categories/';
    const NS_LEAP              = 'http://terms.leapspecs.org/';
    const NS_CATEGORIES        = 'http://wiki.leapspecs.org/2A/categories';
74
75
    const NS_MAHARA     = 'http://wiki.mahara.org/Developer_Area/Import%2F%2FExport/LEAP_Extensions#';

76
77
78
    const XHTML_DIV       = '<div xmlns="http://www.w3.org/1999/xhtml">';
    const XHTML_DIV_EMPTY = '<div xmlns="http://www.w3.org/1999/xhtml"/>';

Nigel McNie's avatar
Nigel McNie committed
79
    const STRATEGY_IMPORT_AS_VIEW = 1;
80
    const STRATEGY_IMPORT_AS_COLLECTION = 2;
Nigel McNie's avatar
Nigel McNie committed
81

82
83
    public static function validate_transported_data(ImporterTransport $transport) {
        $importdata = $transport->files_info();
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        if (!$file = self::find_file($importdata)) {
            throw new ImportException(null, 'Missing leap xml file');
        }
    }

    public static function find_file($importdata) {
        $path = $importdata['tempdir'] . 'extract/';
        if (!empty($importdata['manifestfile'])) {
            $files = array($importdata['manifestfile']);
        } else {
            $files = array('leap.xml', 'leap2.xml', 'leap2a.xml');
        }
        foreach ($files as $f) {
            if (file_exists($path . $f)) {
                return $path . $f;
            }
        }
101
102
103
104
105
106
107
108
109
110
    }

    public function get($field) {
        if ($field == 'xml') {
            return $this->xml;
        }
        return parent::get($field);
    }

    public function process() {
111
112
        db_begin();

113
114
115
        $this->filename = self::find_file($this->get('importertransport')->files_info());
        $this->logfile = dirname($this->filename) . '/import.log';
        $this->trace('Loading import from ' . $this->filename);
116
117
118
119
120
121
        $this->snapshot('begin');

        $options =
            LIBXML_COMPACT |    // Reported to greatly speed XML parsing
            LIBXML_NONET        // Disable network access - security check
        ;
122
        if (!$this->xml = simplexml_load_file($this->filename, 'SimpleXMLElement', $options)) {
123
124
125
126
127
128
129
130
            // TODO: bail out in a much nicer way...
            throw new ImportException($this, "FATAL: XML file is not well formed! Please consult Mahara's error log for more information");
        }
        $this->namespaces = array_flip($this->xml->getDocNamespaces());
        $this->registerXpathNamespaces($this->xml);
        $this->trace("Document loaded, entries: " . count($this->xml->entry));
        $this->snapshot('loaded XML');

131
132
        $this->detect_leap2a_namespace();

133
134
135
136
137
138
139
140
141
142
        $this->ensure_document_valid();

        $this->create_strategy_listing();
        $this->snapshot('created strategy listing');
        $this->strategy_listing_to_load_mapping();
        $this->snapshot('converted strategy listing to load mapping');
        $this->import_from_load_mapping();
        $this->snapshot('imported data based on load mapping');
        $this->import_completed();

143
        db_commit();
144
145
    }

146
147
148
149
150
151
    /**
     * detect the leap2a namespace of the import document by looking for the 'version' element
     *
     *
     */
    private function detect_leap2a_namespace () {
152

153
        // check for the leap2a version used
154
155
156
157
158
159
160
161
162
163
164
        // disable xml warnings. The initial LEAP2A spec hasn't got the leap2
        // namespace so the following xpath expression triggers a warning
        // which we want to suppress.
        $oldvalue = libxml_use_internal_errors(true);
        $version = $this->xml->xpath('//leap2:version');
        libxml_use_internal_errors($oldvalue);

        // if there is no version string we assume the first version of the
        // LEAP2A spec which doesn't contain the version element
        if(!empty($version) && !in_array($version[0][0], $this->supportedleap2aversions)) {
            throw new ImportException($this, "FATAL: The version of the uploaded LEAP2A file is not supported by this Mahara version");
165
        }
166
167

        if($version) {
168
169
            $this->leap2anamespace = self::NS_LEAP;
            $this->leap2atypenamespace = self::NS_LEAP;
170
            $this->leap2acategories = self::NS_CATEGORIES;
171
172
173
        } else {
            $this->leap2anamespace = self::NS_LEAP_200903;
            $this->leap2atypenamespace = self::NS_LEAPTYPE_200903;
174
            $this->leap2acategories = self::NS_CATEGORIES_200903;
175
176
177
        }
    }

178
179
180
181
182
183
184
185
186
187
188
189
190
    private function ensure_document_valid() {
        // TODO: http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/Import%3a_Implementation_Plan#beginning
        //
        // Do a bunch of checks that will ensure the feed is valid, and thus 
        // allow future code to make assumptions that the feed is valid

        // Things to check:
        // - all content src="X": make sure the src actually exists
        // - feed has a <feed> element with an <author> and <entry>s
        // - feed element has correct namespaces (keep in mind we need to be 
        // able to import raw ATOM feeds too)

        //throw new ImportException($this, "Import wasn't valid. TODO: error reporting");
191
192
193

        // Check all the namespaces we're gonna need are declared, and warn if 
        // they're not there
194
195
196
197
198
199
        if($this->leap2anamespace == self::NS_LEAP) {
            $namespaces = array(self::NS_ATOM, self::NS_RDF, self::NS_LEAP, self::NS_CATEGORIES);
        } else {
            $namespaces = array(self::NS_ATOM, self::NS_RDF, self::NS_LEAP_200903, self::NS_LEAPTYPE_200903, self::NS_CATEGORIES_200903);
        }
        foreach ($namespaces as $ns) {
200
201
202
203
            if (!isset($this->namespaces[$ns])) {
                $this->trace("WARNING: Namespaces $ns wasn't declared - this will make importing data correctly difficult");
            }
        }
204
205
206
207
208
209
210
211
212
    }

    /**
     * http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/Import%3a_Implementation_Plan#first_pass_-_get_scores_from_plugins_for_each_entry
     *
     * Each list of strategies for each entry should be sorted from highest to lowest score once this is done
     */
    private function create_strategy_listing() {
        $this->trace("-------------------------\ncreate_strategy_listing()");
213
214
215
216
217
218
        // Give all plugins a chance to perform setup tasks
        foreach (plugins_installed('artefact') as $plugin) {
            $plugin = $plugin->name;
            if (safe_require('import', 'leap/' . $plugin, 'lib.php', 'require_once', true)) {
                $classname = 'LeapImport' . ucfirst($plugin);
                if (method_exists($classname, 'setup')) {
219
                    safe_require('artefact', $plugin);
220
221
222
223
                    call_static_method($classname, 'setup', $this);
                }
            }
        }
224
225
226
227
228
229
230
231
232
233
234

        // First, try to establish whether there is an element representing the 
        // author of the feed
        // TODO: also check this element has the right leaptype (person)
        if (is_null($this->persondataid)) {
            $author = $this->get('xml')->xpath('//a:feed/a:author[1]');
            $author = $author[0];
            if (isset($author->uri) && $this->get_entry_by_id((string)$author->uri)) {
                $this->persondataid = (string)$author->uri;
            }
            else {
235
                $persondata = $this->get('xml')->xpath('//a:feed/a:entry/a:category[('
236
                    . $this->curie_xpath('@scheme', $this->get_categories_namespace(), 'person_type#') . ') and @term="Self"]/../a:id');
237
238
239
240
241
242
                if (isset($persondata[0])) {
                    $this->persondataid = (string)$persondata[0][0];
                }
                else {
                    $this->persondataid = false;
                }
243
244
245
246
            }
        }

        // Generate strategy listing
247
248
249
250
251
        foreach ($this->xml->xpath('//a:feed/a:entry') as $entry) {
            $this->registerXpathNamespaces($entry);
            $entryid = (string)$entry->id;
            $this->trace(" * $entryid ({$entry->title})");

252
253
254
255
256
            if ($this->persondataid && $entryid == $this->persondataid) {
                // We don't offer this element to any plugin to be imported
                continue;
            }

257
            foreach (plugins_installed('artefact') as $plugin) {
258
                $plugin = $plugin->name;
259
260
                $classname = 'LeapImport' . ucfirst($plugin);
                if (class_exists($classname)) {
261
262
263
                    if (!is_subclass_of($classname, 'LeapImportArtefactPlugin')) {
                        throw new SystemException("Class $classname does not extend LeapImportArtefactPlugin as it should");
                    }
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
                    if (method_exists($classname, 'get_import_strategies_for_entry')) {
                        $strategies = call_static_method($classname, 'get_import_strategies_for_entry', $entry, $this);
                        $this->trace("   artefact.$plugin strategies: " . count($strategies));
                        if ($strategies) {
                            $this->trace($strategies, self::LOG_LEVEL_VERBOSE);
                            foreach ($strategies as $strategy) {
                                // Verify they're in valid form
                                if (!array_key_exists('strategy', $strategy)
                                    || !array_key_exists('score', $strategy)
                                    || !array_key_exists('other_required_entries', $strategy)) {
                                    throw new SystemException("$classname::get_import_strategies_for_entry returned a strategy missing "
                                        . "one or more of the strategy, score or other_required_entries keys");
                                }
                                $strategy['artefactplugin'] = $plugin;
                                $this->strategylisting[$entryid][] = $strategy;
Nigel McNie's avatar
Nigel McNie committed
279
                            }
280
281
282
283
284
                        }
                    }
                }
            }

Nigel McNie's avatar
Nigel McNie committed
285
286
287
288
289
290
291
292
293
294
            $strategies = $this->get_import_strategies_for_entry($entry);
            $this->trace("   core strategies: " . count($strategies));
            if ($strategies) {
                $this->trace($strategies, self::LOG_LEVEL_VERBOSE);
                foreach ($strategies as $strategy) {
                    $strategy['artefactplugin'] = null;
                    $this->strategylisting[$entryid][] = $strategy;
                }
            }

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
            if (!isset($this->strategylisting[$entryid])) {
                $this->trace(" ** Could not find any strategies for $entryid **");
                // TODO: we might need to expose this information later
                continue;
            }

            // Sort by score descending
            usort($this->strategylisting[$entryid], create_function('$a, $b', 'return $a["score"] < $b["score"];'));
        }
        $this->trace('*** Strategy listing: ***');
        $this->trace($this->strategylisting);
    }

    /**
     * Converts a strategy listing into the "best" load mapping that can be 
     * gleaned from the strategy listing.
     *
     * The best mapping is decided by sorting the strategy listing by score and 
     * importing all entries on a first-met, first used basis. The algorithm is 
     * described at:
     * http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/Import%3a_Implementation_Plan#non-interactive_import
     */
    private function strategy_listing_to_load_mapping() {
        $this->trace("----------------------------------\nstrategy_listing_to_load_mapping()");
        $usedlist = array();

        // Each entry has its strategies sorted from best to worst score, then 
        // we sort the entire list of entries by the best scores they have 
        // available. This is so we get the "best" plan for importing
        uasort($this->strategylisting, array($this, 'strategy_listing_sort'));
        $this->trace('*** Sorted strategy listing ***', self::LOG_LEVEL_VERBOSE);
        $this->trace($this->strategylisting, self::LOG_LEVEL_VERBOSE);

        // We're only interested in the first listing really. It's the strategy 
        // with the highest score for this entry. Most of the loop mechanics is 
        // so that if we choose to import an entry that requires other entries, 
        // we don't import those other entries separately as well.
        foreach($this->strategylisting as $entryid => $strategies) {
            foreach ($strategies as $strategydata) {
                $this->trace("entry: $entryid");
                if (in_array($entryid, $usedlist)) {
                    $this->trace(" * already in used list, skipped");
                    continue;
                }
                if (isset($strategydata['other_required_entries'])) {
                    foreach ($strategydata['other_required_entries'] as $otherentryid) {
                        if (in_array($otherentryid, $usedlist)) {
                            $this->trace(" * other required entry $otherentryid already in used list, skipped");
                            continue;
                        }
                    }
                }

                $this->trace(" * using strategy $strategydata[strategy] from plugin $strategydata[artefactplugin]");
349
350
351
352
353
354
                if ($strategydata['artefactplugin']) {
                    $this->loadmapping[$entryid] = $strategydata;
                }
                else {
                    $this->coreloadmapping[$entryid] = $strategydata;
                }
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

                $usedlist[] = $entryid;

                if (isset($strategydata['other_required_entries'])) {
                    foreach ($strategydata['other_required_entries'] as $otherentryid) {
                        $usedlist[] = $otherentryid;
                    }
                }

                // We've found how we're going to import this entry now
                // TODO: we should check the next strategy here and see if it 
                // has the same score, if it does we should note that for later 
                // for debugging purposes
                break;
            }
        }
371
        $this->trace("*** Plugin load mapping: ***");
372
        $this->trace($this->loadmapping);
373
374
        $this->trace("*** Core load mapping: ***");
        $this->trace($this->coreloadmapping);
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
    }

    private function strategy_listing_sort($a, $b) {
        // NOTE: the strategy listing should already have the strategies for 
        // each entry sorted from highest to lowest score. If it doesn't, these 
        // two sorts fix that, but this should never happen.
        //usort($a, create_function('$a, $b', 'return $a["score"] < $b["score"];'));
        //usort($b, create_function('$a, $b', 'return $a["score"] < $b["score"];'));
        return $a[0]['score'] < $b[0]['score'];
    }

    /**
     * Import entries using our load mapping. See:
     * http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/Import%3a_Implementation_Plan#second_pass.3a_load_all_entries_into_mahara_as_per_load_mapping
     */
    private function import_from_load_mapping() {
        $this->trace("--------------------------\nimport_from_load_mapping()");
        // TODO: do both usedlists as by key instead of by value for faster checks
        $usedlist = $loadedentries = array();
394
        uasort($this->loadmapping, create_function('$a, $b', 'return $a["score"] < $b["score"];'));
395
396
397
398
399
400
401
402
403
404
405
406
407
408
        foreach ($this->loadmapping as $entryid => $strategydata) {
            if (in_array($entryid, $usedlist)) {
                $this->trace("WARNING: $entryid has already been imported as part of a previous entry");
                continue;
            }
            if (isset($strategydata['other_required_entries'])) {
                foreach ($strategydata['other_required_entries'] as $otherentryid) {
                    if (in_array($otherentryid, $usedlist)) {
                        $this->trace("WARNING: $entryid has already been imported as part of a previous entry");
                        continue(2);
                    }
                }
            }

409
410
411
412
413
414
415
416
417
            $this->trace("Importing $entryid using strategy $strategydata[strategy] of plugin $strategydata[artefactplugin]");
            safe_require('artefact', $strategydata['artefactplugin']);
            $entry = $this->get_entry_by_id($entryid);
            $classname = 'LeapImport' . ucfirst($strategydata['artefactplugin']);
            // TODO: this throws ImportException if it can't be imported, need
            // to decide if this exception can bubble up or whether it should
            // be caught here
            $artefactmapping = call_static_method($classname, 'import_using_strategy',
                $entry, $this, $strategydata['strategy'], $strategydata['other_required_entries']);
418
419
420
421
422

            if (!is_array($artefactmapping)) {
                throw new SystemException("import_from_load_mapping(): $classname::import_using_strategy has not return a list");
            }

423
            $this->artefactids = array_merge_recursive($this->artefactids, $artefactmapping);
424
425
426
427
428
429
430
431
432
433
434

            $usedlist[] = $entryid;
            if (isset($strategydata['other_required_entries'])) {
                foreach ($strategydata['other_required_entries'] as $otherentryid) {
                    $usedlist[] = $otherentryid;
                }
            }

            $loadedentries[] = $entryid;
        }

435
436
        // Give plugins a chance to import stuff about the feed author from the 
        // persondata entry
437
438
        // TODO: this should return an artefact mapping so things can create 
        // links to profile fields, but nothing actually needs it yet
439
        if (!is_array($this->data) || !array_key_exists('skippersondata', $this->data) || $this->data['skippersondata'] !== true) {
440
441
442
443
444
            foreach (plugins_installed('artefact') as $plugin) {
                $classname = 'LeapImport' . ucfirst($plugin->name);
                if (method_exists($classname, 'import_author_data')) {
                    call_static_method($classname, 'import_author_data', $this, $this->persondataid);
                }
445
            }
446
        }
447
448
449
450
451

        // Now all artefacts are loaded, allow each plugin to load 
        // relationships for them if they need to
        foreach ($loadedentries as $entryid) {
            $strategydata = $this->loadmapping[$entryid];
452
453
            $classname = 'LeapImport' . ucfirst($strategydata['artefactplugin']);
            $entry = $this->get_entry_by_id($entryid);
454
            $maybeartefacts = call_static_method($classname, 'setup_relationships',
455
                $entry, $this, $strategydata['strategy'], $strategydata['other_required_entries']);
456
457
458
            if (is_array($maybeartefacts)) { // some might add new artefacts (eg files attached by relpath, rather than leap id)
                $this->artefactids = array_merge_recursive($this->artefactids, $maybeartefacts);
            }
459
460
        }

461
        // Fix up any artefact references in the content of imported artefacts
462
        // TODO: restrict this to the ones that were imported right now
463
464
465
466
467
468
        if ($artefacts = get_records_array('artefact', 'owner', $this->get('usr'), '', 'id, title, description')) {
            foreach ($artefacts as $artefact) {
                $this->fix_artefact_references($artefact);
            }
        }

469
470
471
472
473
474
475
476
477
478
479
480
481
        // Now import views
        foreach ($this->coreloadmapping as $entryid => $strategydata) {
            if (in_array($entryid, $usedlist)) {
                $this->trace("WARNING: $entryid has already been imported as part of a previous entry");
                continue;
            }
            if (isset($strategydata['other_required_entries'])) {
                foreach ($strategydata['other_required_entries'] as $otherentryid) {
                    if (in_array($otherentryid, $usedlist)) {
                        $this->trace("WARNING: $entryid has already been imported as part of a previous entry");
                        continue(2);
                    }
                }
Nigel McNie's avatar
Nigel McNie committed
482
            }
483
484
485
486
487
488
489
490
491
492
493
494
495

            $this->trace("Importing $entryid using the core");
            $entry = $this->get_entry_by_id($entryid);
            $this->import_using_strategy($entry, $strategydata['strategy'], $strategydata['other_required_entries']);

            $usedlist[] = $entryid;
            if (isset($strategydata['other_required_entries'])) {
                foreach ($strategydata['other_required_entries'] as $otherentryid) {
                    $usedlist[] = $otherentryid;
                }
            }

            $loadedentries[] = $entryid;
496
        }
497

498
        // Put views into collections
499
500
501
502
503

        // Keep track of which views have been placed in a collection, because
        // Mahara can't handle more one collection per view.
        $incollection = array();

504
505
506
        foreach ($this->collectionviewentries as $cid => $entryids) {
            $i = 0;
            foreach ($entryids as $entryid) {
507
508
                $viewid = self::get_viewid_imported_by_entryid($entryid);
                if ($viewid && !isset($incollection[$viewid])) {
509
510
511
512
513
514
                    $record = (object) array(
                        'collection' => $cid,
                        'view' => $viewid,
                        'displayorder' => $i,
                    );
                    insert_record('collection_view', $record);
515
                    $incollection[$viewid] = $cid;
516
517
518
519
520
                    $i++;
                }
            }
        }

521
522
523
524
525
526
527
528
529
530
        // Allow each plugin to load relationships to views if they need to
        foreach ($loadedentries as $entryid) {
            if (isset($this->loadmapping[$entryid])) {
                $strategydata = $this->loadmapping[$entryid];
                $classname = 'LeapImport' . ucfirst($strategydata['artefactplugin']);
                $entry = $this->get_entry_by_id($entryid);
                call_static_method($classname, 'setup_view_relationships',
                    $entry, $this, $strategydata['strategy'], $strategydata['other_required_entries']);
            }
        }
531
532
    }

533
534
535
536
537
538
539
540
541
542
543
544
545
    public function entry_has_strategy($entryid, $strategyid, $artefactplugin=null) {
        if (isset($this->loadmapping[$entryid])) {
            if (empty($this->loadmapping[$entryid]['artefactplugin']) && !empty($artefactplugin)) {
                return false;
            }
            if ($this->loadmapping[$entryid]['artefactplugin'] != $artefactplugin) {
                return false;
            }
            return $this->loadmapping[$entryid]['strategy'] == $strategyid;
        }
        return false;
    }

546
    private function import_completed() {
547
548
549
550
551
552
553
        // Give all plugins a chance to perform final tasks
        foreach (plugins_installed('artefact') as $plugin) {
            $classname = 'LeapImport' . ucfirst($plugin->name);
            if (method_exists($classname, 'cleanup')) {
                call_static_method($classname, 'cleanup', $this);
            }
        }
554
555
556
        $this->trace("------------------\nimport_completed()");

        unset($this->loadmapping);
557
        unset($this->coreloadmapping);
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        unset($this->strategylisting);
        unset($this->xpath);
        unset($this->dom);
        $this->snapshot('end');

        if ($this->profile) {
            $this->trace("k: abstime\ttime\tmemafter\tmemdiff");
            $firstdata = $lastdata = $this->snapshots['begin'];
            $i = 0;
            foreach ($this->snapshots as $identifier => $data) {
                $i++;
                $timetaken = $data['time'] - $lastdata['time'];
                $abstime   = $data['time'] - $firstdata['time'];
                $memoryafter = $data['ram'] / 1024;
                $memorygrowth = ($data['ram'] - $lastdata['ram']) / 1024;
                $this->trace(sprintf("$i: %.3f\t%.3f\t%.3fK\t%8.3fK", $abstime, $timetaken, $memoryafter, $memorygrowth));
                $lastdata = $data;
            }

            $i = 0;
            foreach (array_keys($this->snapshots) as $identifier) {
                $i++;
                $this->trace("$i = $identifier");
            }
            $this->trace("abstime = time after beginning step of import that this step completed\n"
                . "time = time taken to complete this step\n"
                . "memafter = script memory usage after this step\n"
                . "memdiff = difference in memory usage compared with the last step");
        }
    }

    /**
     * Logs a message for debugging purposes
     *
     * The user can configure the amount of logging, and where it goes, by 
     * setting the 'loglevel' and 'logtargets' fields.
     *
     * loglevel is one of {0, PluginImportLeap::LOG_LEVEL_STANDARD, PluginImportLeap::LOG_LEVEL_VERBOSE}
     * logtargets is one of the LOG_TARGET_* constants
     *
     * @param string $message The message to log
     * @param int    $level   The level at which to log this error
     */
    public function trace($message, $level=self::LOG_LEVEL_STANDARD) {
        if ($level <= $this->loglevel) {
            // Use our logging system temporarily, which provides us with 
            // access to its nice features. We use log_message instead of
            // log_debug because that will retain the the line/file where 
            // trace() was called, rather than saying all of the messages came 
            // from trace() itself
            global $CFG;
609
610
            $oldtargets = $CFG->log_dbg_targets;
            $oldfile    = $CFG->log_file;
611
            $CFG->log_dbg_targets = $this->logtargets;
612
            $CFG->log_file = $this->logfile;
613
            $file = $line = $trace = null;
614
615
616
            log_message($message, LOG_LEVEL_DBG, true, true, $file, $line, $trace);
            $CFG->log_dbg_targets = $oldtargets;
            $CFG->log_file = $oldfile;
617
618
619
620
621
622
623
624
625
626
627
628
        }
    }

    private function snapshot($identifier) {
        if ($this->profile) {
            $this->snapshots[$identifier] = array(
                'time' => microtime(true),
                'ram'  => memory_get_usage(), // TODO: http://php.net/memory_get_usage suggests this isn't available everywhere
            );
        }
    }

Nigel McNie's avatar
Nigel McNie committed
629
630
631
632
633
634
635
636
637
638
639
640
641
    /**
     * Given an entry, should return a list of the possible ways that it could 
     * be imported by the core.
     *
     * The core handles View importing, so this method looks for entries that 
     * could be converted into Views.
     *
     * For more information about this method, see 
     * {LeapImportArtefactPlugin::get_import_strategies_for_entry}
     *
     * @param SimpleXMLElement $entry
     */
    public function get_import_strategies_for_entry(SimpleXMLElement $entry) {
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
        if (self::is_rdf_type($entry, $this, 'selection')) {
            if (self::is_correct_category_scheme($entry, $this, 'selection_type', 'Webpage')) {
                return array(array(
                    'strategy' => self::STRATEGY_IMPORT_AS_VIEW,
                    'score'    => 100,
                    'other_required_entries' => array(),
                ));
            }
            if (self::is_correct_category_scheme($entry, $this, 'selection_type', 'Website')) {
                return array(array(
                    'strategy' => self::STRATEGY_IMPORT_AS_COLLECTION,
                    'score'    => 100,
                    'other_required_entries' => array(),
                ));
            }
Nigel McNie's avatar
Nigel McNie committed
657
658
659
660
661
662
663
664
665
666
667
        }
        return array();
    }

    /**
     */
    public function import_using_strategy(SimpleXMLElement $entry, $strategy, array $otherentries) {
        switch ($strategy) {
        case self::STRATEGY_IMPORT_AS_VIEW:
            require_once('view.php');

668
            if (!$this->import_entry_as_mahara_view($entry)) {
669
670
671
                // Not a Mahara view, just do basic import
                $this->trace('Not a Mahara view, doing basic import', self::LOG_LEVEL_VERBOSE);

672
673
674
675
676
                $viewdata = array(
                    'title'       => (string)$entry->title,
                    'description' => (string)$entry->summary,
                    'type'        => 'portfolio', // TODO
                    'layout'      => null, // TODO
Nigel McNie's avatar
Nigel McNie committed
677
                    'tags'        => self::get_entry_tags($entry),
678
679
680
681
682
683
684
685
686
687
688
689
                    'numcolumns'  => 1,
                    'ownerformat' => FORMAT_NAME_DISPLAYNAME, // TODO
                    'owner'       => $this->get('usr'),
                );
                if ($published = strtotime((string)$entry->published)) {
                    $viewdata['ctime'] = $published;
                }
                if ($updated = strtotime((string)$entry->updated)) {
                    $viewdata['mtime'] = $updated;
                }

                $view = View::create($viewdata, $this->get('usr'));
690
691
692
693
694
695
696
697
698
699
700
701
702
703

                safe_require('blocktype', 'textbox');
                $bi = new BlockInstance(0,
                    array(
                        'blocktype'  => 'textbox',
                        'title'      => '',
                        'column'     => 1,
                        'order'      => 1,
                        'configdata' => array(
                            'text' => self::get_entry_content($entry, $this),
                        ),
                    )
                );
                $view->addblockinstance($bi);
704
                $this->viewids[(string)$entry->id] = $view->get('id');
705
            }
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
            break;
        case self::STRATEGY_IMPORT_AS_COLLECTION:
            require_once('collection.php');

            $collectiondata = array(
                'name'        => (string)$entry->title,
                'description' => (string)$entry->summary,
                'owner'       => $this->get('usr'),
            );
            if ($published = strtotime((string)$entry->published)) {
                $collectiondata['ctime'] = $published;
            }
            if ($updated = strtotime((string)$entry->updated)) {
                $collectiondata['mtime'] = $updated;
            }

            $collection = new Collection(0, $collectiondata);
            $collection->commit();
            $this->collectionids[(string)$entry->id] = $collection->get('id');

            // Remember entry ids that form part of this entry, and use them later
            // to put views into collections.
            foreach ($entry->link as $link) {
                if ($this->curie_equals($link['rel'], '', 'has_part') && isset($link['href'])) {
                    $this->collectionviewentries[$collection->get('id')][] = (string) $link['href'];
                }
            }

Nigel McNie's avatar
Nigel McNie committed
734
735
            break;
        default:
736
            throw new ImportException($this, 'TODO: get_string: unknown strategy chosen for importing entry');
Nigel McNie's avatar
Nigel McNie committed
737
738
739
        }
    }

740
741
742
    /**
     * Attempts to import an entry as a mahara view
     *
743
744
745
     * We look for custom mahara namespaced tags that explain the View 
     * structure. If they're present, we use them to create a View using that 
     * structure.
746
     *
Francois Marier's avatar
Francois Marier committed
747
     * This differs a bit from the Leap2A specification, but we do so 
748
749
750
     * deliberately to get 100% compatibility with Mahara to Mahara exports. 
     * Other systems can also construct content in the right format to trigger 
     * Mahara to import things as a full view.
751
     *
752
     * If the mahara tags are not present, we give up.
753
754
     *
     * @param SimpleXMLElement $entry The entry to be imported
755
     * @return boolean Whether it could be imported.
756
     */
757
    private function import_entry_as_mahara_view(SimpleXMLElement $entry) {
758
        static $blocktypes_installed = null;
759
        static $viewlayouts = null;
760
        static $viewtypes = null;
761
        $viewelement = $entry->xpath('mahara:view[1]');
762

763
764
        if (count($viewelement) != 1) {
            // This isn't a Mahara view
765
766
767
            return false;
        }

768
769
770
        if (is_null($viewlayouts)) {
            $viewlayouts = get_records_assoc('view_layout', '', '', '', 'widths, id');
        }
771
772
773
        if (is_null($viewtypes)) {
            $viewtypes = get_column('view_type', 'type');
        }
774
775
776
777
778
779
780

        $maharaattributes = PluginImportLeap::get_attributes($viewelement[0], PluginImportLeap::NS_MAHARA);

        $layout = null;
        if (isset($viewlayouts[$maharaattributes['layout']])) {
            $layout = $viewlayouts[$maharaattributes['layout']]->id;
        }
781
782
783
784
        $type = 'portfolio';
        if (isset($maharaattributes['type']) && in_array($maharaattributes['type'], $viewtypes)) {
            $type = $maharaattributes['type'];
        }
785
786
787
788
789
        $ownerformat = intval($maharaattributes['ownerformat']);
        if (!$ownerformat) {
            $ownerformat = FORMAT_NAME_DISPLAYNAME;
        }

790
791
792
793
794
795
796
797
        $columns = $entry->xpath('mahara:view[1]/mahara:column');
        $columncount = count($columns);
        if ($columncount < 1 || $columncount > 5) {
            // Whoops, invalid number of columns
            $this->trace("Invalid number of columns specified for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
            return false;
        }

798
799
800
        $config = array(
            'title'       => (string)$entry->title,
            'description' => (string)$entry->summary,
801
            'type'        => $type,
802
            'layout'      => $layout,
Nigel McNie's avatar
Nigel McNie committed
803
            'tags'        => self::get_entry_tags($entry),
804
            'numcolumns'  => $columncount,
805
            'owner'       => $this->get('usr'),
806
            'ownerformat' => $ownerformat,
807
        );
808
809
810
811
812

        $col = 1;
        foreach ($columns as $column) {
            $blockinstances = $column->xpath('mahara:blockinstance');
            $row = 1;
813
            $config['columns'][$col] = array();
814
815
816
817
818
819
820
821
822
823
824
825
826
827
            foreach ($blockinstances as $blockinstance) {
                $attrs = self::get_attributes($blockinstance, PluginImportLeap::NS_MAHARA);
                if (!isset($attrs['blocktype'])) {
                    $this->trace("  No mahara:blocktype attribute set for blockinstance at col $col, row $row: skipping");
                    continue;
                }
                $this->trace("  Found block with type {$attrs['blocktype']} at [$col][$row]", self::LOG_LEVEL_VERBOSE);

                if ($blocktypes_installed === null) {
                    $blocktypes_installed = array_map(create_function('$a', 'return $a->name;'), plugins_installed('blocktype'));
                }

                if (in_array($attrs['blocktype'], $blocktypes_installed)) {
                    $configelements = $blockinstance->xpath('mahara:*');
828
829
830
831
832
                    $config['columns'][$col][$row] = array(
                        'type'   => $attrs['blocktype'],
                        'title'  => $attrs['blocktitle'],
                        'config' => array()
                    );
833
                    foreach ($configelements as $element) {
834
835
836
837
838
839
840
841
                        $value = json_decode((string)$element);
                        if (is_array($value) && isset($value[0])) {
                            $config['columns'][$col][$row]['config'][$element->getName()] = $value[0];
                        }
                        else {
                            $this->trace("  Value for {$element->getName()} is not an array, ignoring (value follows below)");
                            $this->trace($value);
                        }
842
843
                    }

844
                    $row++;
845
846
847
                }
                else {
                    $this->trace("  Ignoring unknown blocktype {$attrs['blocktype']}");
848
849
                }
            }
850
            $col++;
851
852
        }

853
        $view = View::import_from_config($this->rewrite_artefact_ids($config), $this->get('usr'), 'leap');
854
855
856
857
858
859
860
861
862
863

        if ($published = strtotime((string)$entry->published)) {
            $view->set('ctime', $published);
        }
        if ($updated = strtotime((string)$entry->updated)) {
            $view->set('mtime', $updated);
        }
        $view->set('owner', $this->get('usr'));

        $view->commit();
864
        $this->viewids[(string)$entry->id] = $view->get('id');
865
        return true;
866
867
    }

868
869
870
871
872
873
874
875
876
877
878
879
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
906
907
908
909
910
911
912
913
914
915
916
    /**
     * Given the view config that we have built from the export, rewrite all
     * the entry references in blockinstance artefactid fields to be actual
     * artefact IDs.
     */
    private function rewrite_artefact_ids($config) {
        foreach ($config['columns'] as &$column) {
            foreach ($column as &$blockinstance) {
                if (isset($blockinstance['config']['artefactid'])) {
                    $artefactid = $blockinstance['config']['artefactid'];
                    if (isset($this->artefactids[$artefactid])) {
                        if (count($this->artefactids[$artefactid]) == 1) {
                            $blockinstance['config']['artefactid'] = intval($this->artefactids[$artefactid][0]);
                        }
                        else {
                            $this->trace('WARNING: View config specified one artefact, but loadmapping says more than one artefact was loaded for ' . $artefactid);
                            $this->trace($this->artefactids[$artefactid]);
                            unset($blockinstance['config']['artefactid']);
                        }
                    }
                    else {
                        $this->trace('WARNING: View config specified an artefact, but loadmapping does not say one was loaded for '. $artefactid);
                        unset($blockinstance['config']['artefactid']);
                    }
                }
                else if (isset($blockinstance['config']['artefactids'])) {
                    $ids = $blockinstance['config']['artefactids'];
                    foreach ($blockinstance['config']['artefactids'] as $key => $artefactid) {
                        if (isset($this->artefactids[$artefactid])) {
                            if (count($this->artefactids[$artefactid]) == 1) {
                                $blockinstance['config']['artefactids'][$key] = intval($this->artefactids[$artefactid][0]);
                            }
                            else {
                                $this->trace('WARNING: View config specified one artefact, but loadmapping says more than one artefact was loaded for ' . $artefactid);
                                $this->trace($this->artefactids[$artefactid]);
                                unset($blockinstance['config']['artefactids'][$key]);
                            }
                        }
                        else {
                            $this->trace('WARNING: View config specified an artefact, but loadmapping does not say one was loaded for '. $artefactid);
                            unset($blockinstance['config']['artefactids'][$key]);
                        }
                    }
                }
            }
        }
        return $config;
    }

917
    /**
Francois Marier's avatar
Francois Marier committed
918
     * Given an artefact record, looks through it for any Leap2A style
919
920
921
     * references to other artefacts, and rewrite those to point at the created
     * ones.
     *
Nigel McNie's avatar
Nigel McNie committed
922
     * @param object $artefact A record from the artefact table (only id, title,
923
924
     *                        description fields required)
     */
Nigel McNie's avatar
Nigel McNie committed
925
    private function fix_artefact_references($artefact) {
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
        $changed = false;

        if ($this->artefact_reference_quickcheck($artefact->title)) {
            if ($title = $this->fix_artefact_reference($artefact->title)) {
                $changed = true;
                $artefact->title = $title;
            }
        }

        if ($this->artefact_reference_quickcheck($artefact->description)) {
            if ($description = $this->fix_artefact_reference($artefact->description)) {
                $changed = true;
                $artefact->description = $description;
            }
        }

        if ($changed) {
            update_record('artefact', $artefact);
        }

    }

    /**
     * Detect whether it's worth running the potentially costly regex
     * replacements and content updates when fixing artefact references
     *
     * @param string   The field to check
     * @return boolean Whether it's worth checking in more detail
     */
    private function artefact_reference_quickcheck($field) {
956
957

        return (false !== strpos($field, 'rel="'.$this->leap2anamespace.':has_part"')
958
                || false !== strpos($field, 'rel="enclosure"'))
959
960
961
962
963
964
965
966
967
968
969
970
971
            && (
                (false !== strpos($field, '<img'))
                || (false !== strpos($field, '<a'))
               );
    }

    /**
     * Fix up references to artefacts in a field
     *
     * @param string $field The field to fix
     * @return string The fixed field
     */
    private function fix_artefact_reference($field) {
972
        $match = '#<((img)|a)([^>]+)rel="(?:'.$this->leap2anamespace.':has_part|enclosure)" (?:src|href)="([^"]+)"([^>]*)>#';
973
974
975
976
977
978
979
980
981
982
983
984
        $field = preg_replace_callback($match,
            array($this, '_fixref'),
            $field);
        return $field;
    }

    private function _fixref($matches) {
        static $basepath;
        if (!$basepath) {
            $basepath = get_mahara_install_subdirectory();
        }

985
        $artefacts = $this->get_artefactids_imported_by_entryid($matches[4]);
986
        if (is_null($artefacts) || count($artefacts) != 1) {
Francois Marier's avatar
Francois Marier committed
987
            // This can happen if a Leap2A xml file is uploaded that refers to
988
            // files that (naturally) weren't uploaded with it.
989
            log_debug("Warning: fixref was expecting one artefact to have been imported by entry {$matches[4]} but seems to have gotten " . count($artefacts));
990
991
992
993
994
995
            return $matches[0];
        }
        return '<' . $matches[1] . $matches[3] . ($matches[1] == 'img' ? 'src' : 'href') . '="'
            . $basepath . 'artefact/file/download.php?file=' . $artefacts[0] . '"' . $matches[5] . '>';
    }

996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
    /**
     * Register all namespaces on an element that have been declared on the 
     * document
     *
     * TODO: we should probably do this by examining $this->namespaces
     */
    public function registerXpathNamespaces(SimpleXMLElement $element) {
        $element->registerXpathNamespace('a', PluginImportLeap::NS_ATOM);
        $element->registerXpathNamespace('rdf', PluginImportLeap::NS_RDF);
        $element->registerXpathNamespace('mahara', PluginImportLeap::NS_MAHARA);
    }

    public function get_entry_by_id($entryid) {
        static $cache = array();
        if (isset($cache[$entryid])) {
            return $cache[$entryid];
        }
        // TODO: entryid injection? Probably not worth worrying about
        $matches = $this->xml->xpath("//a:feed/a:entry/a:id[.='$entryid']/..");
        // TODO: there had better be only one...
        $entry = $matches[0];
        if ($entry) {
            $this->registerXpathNamespaces($entry);
        }
        return ($cache[$entryid] = $entry);
    }

    public function get_artefactids_imported_by_entryid($entryid) {
        if (!isset($this->artefactids[$entryid])) {
            return null;
        }
        return $this->artefactids[$entryid];
    }

1030
1031
1032
1033
1034
1035
1036
    public function get_viewid_imported_by_entryid($entryid) {
        if (!isset($this->viewids[$entryid])) {
            return null;
        }
        return $this->viewids[$entryid];
    }

1037
1038
1039
    /**
     * Returns xpath for an attribute matching a given curie
     *
Francois Marier's avatar
Francois Marier committed
1040
     * See http://wiki.cetis.ac.uk/2009-03/Leap2A_elements#Use_of_CURIEs
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
     *
     * @param string $attribute The attribute to match
     * @param string $namespace The namespace for the attribute value
     * @param string $term      The term for the attribute value
     * @return string
     */
    public function curie_xpath($attribute, $namespace, $term) {
        $xpath = '';
        if (isset($this->namespaces[$namespace])) {
            $abbreviation = $this->namespaces[$namespace];

            // Simple case
            $xpath .= $attribute . '="' . $abbreviation . ':' . $term . '" or ';
            // "correct" curie syntax has them surrounded by [ ]
            $xpath .= $attribute . '="[' . $abbreviation . ':' . $term . ']" or ';
        }

        // The full URL for the curie
        $xpath .= $attribute . '="' . $namespace . $term . '"';

        return $xpath;
    }

    /**
     * Returns whether a curie matches a given namespace/term, checking all 
     * allowed forms of the curie
     *
     * @param string $curie     The curie to check
     * @param string $namespace The namespace to check the curie against
     * @param string $term      The term to check the curie against
     * @return boolean
     */
    public function curie_equals($curie, $namespace, $term) {
        if (isset($this->namespaces[$namespace])) {
            $abbreviation = $this->namespaces[$namespace];
            return
                $curie == "$abbreviation:$term"
                || $curie == "[$abbreviation:$term]"
                || $curie == $namespace . $term;
        }

        return $curie == $namespace . $term;
    }

1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
    /**
     * Returns whether an entry has the given RDF type
     *
     * This helper method should probably be replaced by the as yet unwritten 
     * get_rdf_type at some point, as it would be faster to get the type and do 
     * comparisons than call this multiple times.
     *
     * @param SimpleXMLElement $entry    The entry to check
     * $param PluginImportLeap $importer The importer
     * @param string $rdftype            The type to check for
     * @return boolean Whether the entry has the given RDF type
     */
1097
    public static function is_rdf_type(SimpleXMLElement $entry, PluginImportLeap $importer, $rdftype) {
1098
        $result = $entry->xpath('rdf:type['
1099
            . $importer->curie_xpath('@rdf:resource', $importer->get_leaptype_namespace(), $rdftype) . ']');
1100
1101
1102
        return isset($result[0]) && $result[0] instanceof SimpleXMLElement;
    }

1103
1104
1105
1106
1107
    /**
     * Returns if the entry has the given term in the given category
     *
     * @param SimpleXMLElement $entry    The entry to check
     * $param PluginImportLeap $importer The importer
Francois Marier's avatar
Francois Marier committed
1108
     * @param string $category           The category to look in. See http://wiki.cetis.ac.uk/2009-03/Leap2A_categories
1109
1110
1111
1112
1113
     * @param string $term               The term to look for (see the docs for the appropriate category)
     * @return boolean Whether the entry has the term in the category
     */
    public static function is_correct_category_scheme(SimpleXMLElement $entry, PluginImportLeap $importer, $category, $term) {
        $result = $entry->xpath('a:category[('
1114
            . $importer->curie_xpath('@scheme', $importer->get_categories_namespace(), $category . '#') . ') and @term="' . $term . '"]');
1115
1116
1117
        return isset($result[0]) && $result[0] instanceof SimpleXMLElement;
    }

1118
    /**
Nigel McNie's avatar
Nigel McNie committed
1119
1120
1121
     * Returns the <content> for a given entry, stripping off any transport 
     * encoding and respecting the content type.
     *
1122
     * TODO: make sure we are rawurlencoding our file paths in our export
Nigel McNie's avatar
Nigel McNie committed
1123
1124
1125
1126
     *
     * @param SimpleXMLElement $entry   The entry to get the content for
     * @param PlugimImporLeap $importer The importer
     * @return string The content
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
     */
    public static function get_entry_content(SimpleXMLElement $entry, PluginImportLeap $importer) {
        // Entries have content, and that content can be of different types. So we want to make sure we grab it in the right type
        // - if it's xhtml, we need asXML(), plus removing the <content> tags
        // - if it's text, what do we need???
        $type = isset($entry->content['type']) ? (string)$entry->content['type'] : 'text';
        switch ($type) {
        case 'xhtml':
            if (isset($entry->content->div)) {
                // TODO: using asXML() gives us the content, but does things 
                // like squashing the space between <br and />. This might need 
                // to be "fixed" (turned back into browser-happy xhtml) if it 
                // causes problems.
                $content = (string)$entry->content->div->asXML();
1141
                if (substr($content, 0, 42) == self::XHTML_DIV) {
1142
1143
1144
                    $content = substr($content, 42, -6);
                    return $content;
                }
1145
1146
1147
                else if (substr($content, 0, 43) == self::XHTML_DIV_EMPTY) {
                    return '';
                }
1148
            }
1149
            log_debug("ERROR: <content> tag for entry {$entry->id} declared to be type xhtml but didn't wrap its content in a div with xmlns=http://www.w3.org/1999/xhtml");
1150
1151
1152
1153

            $starttaglength = strlen('<content type="xhtml">');
            $endtaglength   = strlen('</content>');
            return substr((string)$entry->content->asXML(), $starttaglength, -$endtaglength);
1154
        case 'html':
1155
1156
        case 'text':
            return (string)$entry->content;
1157
1158
        case '':
            return ''; // empty entry
1159
        default:
1160
            throw new SystemException("Unrecognised content type for entry '$entry->id' ($type)");
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
        }
    }

    public static function get_entry_tags(SimpleXMLElement $entry) {
        $tags = array();
        foreach ($entry->category as $category) {
            if (!isset($category['scheme'])) {
                if (isset($category['label'])) {
                    $tags[] = (string)$category['label'];
                }
                else {
                    $tags[] = (string)$category['term'];
                }
            }
        }
        return array_unique($tags);
    }

1179
    /**
1180
     * Look for leap2:date elements that are part of an entry (if any) and 
1181
1182
     * return the values we parse from them
     *
1183
1184
1185
1186
1187
     *
     * @param SimpleXMLElement $entry The element containing the date
     * @param array $namespaces array of namespaces @see PluginImportLeap::namespaces
     * @param string $ns namespace URL which is used as a key in the $namespaces array
     *
1188
1189
1190
     * Returned in a structure like so:
     * array(
     *     'start' => array(
Francois Marier's avatar
Francois Marier committed
1191
     *         'value' => 'w3c compliant date/time format, as allowed by Leap2A',
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
     *         'label' => 'label attribute, which is a plaintext version of the date',
     *     ),
     *     'end' => array(
     *         'value' => 'maybe only the value is set on some elements',
     *     ),
     *     'target' => array(
     *         'label' => 'sometimes, only the label will be set'
     *     )
     * )
     *
Francois Marier's avatar
Francois Marier committed
1202
     * The only keys in the return value are those allowed by the Leap2A spec, 
1203
1204
1205
1206
1207
1208
1209
1210
     * and only if they exist on the entry.
     *
     * The values may have the 'value', 'label' or both keys, depending on what 
     * each element has.
     *
     * Try and use the 'value' first, if you have a choice. Quite a few places 
     * in Mahara currently just store dates as plaintext though.
     *
Francois Marier's avatar
Francois Marier committed
1211
     * Spec reference: http://wiki.cetis.ac.uk/2009-03/Leap2A_literals#date
1212
     */
1213
    public static function get_leap_dates(SimpleXMLElement $entry, $namespaces, $ns) {
1214
1215
        $dates = array();
        foreach (array('start', 'end', 'target') as $point) {
1216
            $dateelement = $entry->xpath($namespaces[$ns].':date[@'.$namespaces[$ns].':point="' . $point . '"]');
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
            if (count($dateelement) == 1) {
                $dateelement = $dateelement[0];
            }

            if ($dateelement instanceof SimpleXMLElement) {
                $date = (string)$dateelement;
                if ($date) {
                    $dates[$point]['value'] = $date;
                }

1227
                // Parse for leap2:label
1228
                $leapattributes = array();
1229
                foreach ($dateelement->attributes($ns) as $key => $value) {
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
                    $leapattributes[$key] = (string)$value;
                }
                if (isset($leapattributes['label'])) {
                    $dates[$point]['label'] = $leapattributes['label'];
                }
            }
        }
        return $dates;
    }

1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
    /**
     * Look for a leap2:myrole element that is part of an entry (if any) and
     * return the value
     *
     *
     * @param SimpleXMLElement $entry The element containing the date
     * @param array $namespaces array of namespaces @see PluginImportLeap::namespaces
     * @param string $ns namespace URL which is used as a key in the $namespaces array
     *
     * @return string
     *
     * Spec reference: http://wiki.leapspecs.org/2A/literals#myrole
     */
    public static function get_leap_myrole(SimpleXMLElement $entry, $namespaces, $ns) {
        $myrole = $entry->xpath($namespaces[$ns].':myrole');
        // we only expect one role
        if($myrole[0]) {
            return $myrole[0];
        }
        return '';
    }

1262
1263
1264
1265
1266
1267
    /**
     * Waffer thin helper to grab all attributes in a namespace.
     *
     * It's often much easier to work with them in this form. SimpleXML doesn't 
     * provide a nice property to get at them with.
     *
1268
1269
1270
     * @param SimpleXMLElement $element The element to get attributes from
     * @param string $ns                The namespace to get the attributes for
     * @return array                    The attributes in the namespace
1271
1272
1273
1274
1275
1276
1277
1278
1279
     */
    public static function get_attributes(SimpleXMLElement $item, $ns) {
        $attributes = array();
        foreach ($item->attributes($ns) as $key => $value) {
            $attributes[$key] = (string)$value;
        }
        return $attributes;
    }

1280
1281
1282
1283
1284
1285
1286
1287
1288
    /**
     * getter to return the leap2typeanamespace property
     *
     * @return string namespace URL
     */
    public function get_leaptype_namespace() {
        return $this->leap2atypenamespace;
    }

1289
1290
1291
1292
1293
    /**
     * getter to return the leap2anamespace property
     *
     * @return string namespace URL
     */
1294
1295
1296
1297
    public function get_leap2a_namespace() {
        return $this->leap2anamespace;
    }

1298
1299
1300
1301
1302
    /**
     * getter to return the namespace property
     *
     * @return array
     */
1303
1304
1305
    public function get_namespaces() {
        return $this->namespaces;
    }
1306

1307
1308
1309
1310
1311
1312
1313
1314
1315
    /**
     * getter to return the leap2 categories namespace
     *
     * @return string namespace URL
     */
    public function get_categories_namespace() {
        return $this->leap2acategories;
    }

1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
    /**
     * helper function to create attachments between entries.
     * The 2010-07 version of leap2a says that linked *entries* should use related relation,
     * and directly linked files (attachments) should use enclosures.
     * However, for BC we should support both.
     * This function supports both and additionally creates the File artefacts for attachments, then links them.
     *
     * @param SimpleXMLElement $entry    the entry we want to attach things *to*
     * @param SimpleXMLElement $link     the link to inspect
     * @param ArtefactType     $artefact the artefact that has been created from the entry.
     *
     * @return void|int the id of a *newly created* attached artefact
     */
    public function create_attachment(SimpleXMLElement $entry, SimpleXMLElement $link, ArtefactType $artefact) {
        if (($this->curie_equals($link['rel'], '', 'enclosure') || $this->curie_equals($link['rel'], '', 'related')) && isset($link['href'])) {
            $this->trace("Attaching file $link[href] to comment $entry->id", PluginImportLeap::LOG_LEVEL_VERBOSE);
            $artefactids = $this->get_artefactids_imported_by_entryid((string)$link['href']);
            if (isset($artefactids[0])) {
                $artefact->attach($artefactids[0]);
            } else { // it may be just an attached file, with no Leap2A element in its own right ....
                if ($id = $this->create_linked_file($entry, $link)) {
                    $artefact->attach($id);
                    $newartefactmapping[(string)$link['href']][] = $id;
                    return $id;
                }
            }
        }
    }

    /**
     * Attaches a file to a blogpost entry that was just linked directly, rather than having a Leap2a entry
     * See http://wiki.leapspecs.org/2A/files
     *
     * @param SimpleXMLElement $entry
     * @param SimpleXMLElement $link
     */
    private function create_linked_file(SimpleXMLElement $entry, SimpleXMLElement $link) {
        $this->trace($link);
        $pathname = urldecode((string)$link['href']);
        $dir = dirname($this->get('filename'));
        $pathname = $dir . DIRECTORY_SEPARATOR . $pathname;
        if (!file_exists($pathname)) {
            return false;
        }
        // Note: this data is passed (eventually) to ArtefactType->__construct,
        // which calls strtotime on the dates for us
        require_once('file.php');
        $data = (object)array(
            'title' => (string)$entry->title . ' ' . get_string('attachment'),
            'owner' => $this->get('usr'),
            'filetype' => file_mime_type($pathname),
        );
        return ArtefactTypeFile::save_file($pathname, $data, $this->get('usrobj'), true);
    }

    public function entry_exists($entryid) {
        return array_key_exists($entryid, $this->strategylisting);
    }
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
}


/**
 * Base class for artefact plugin implementations of LEAP import
 *
 * Any artefact plugin wanting to implement import needs to extend this class 
 * in the file artefact/<plugin>/import/leap/lib.php.
 *
 * TODO: link to wiki docs for more info
 */
abstract class LeapImportArtefactPlugin {

1387
1388
1389
1390
1391
1392
1393
1394
1395
    /**
     * Runs as the importer is starting up, giving the plugin a chance to do
     * some initialisation.
     *
     * @param PluginImportLeap $importer The importer
     */
    public static function setup(PluginImportLeap $importer) {
    }

1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
    /**
     * Given an entry, should return a list of the possible ways that it could 
     * be imported by this plugin.
     *
     * The return result is in the form:
     * array(
     *     array(
     *         strategy => [strategy:int],
     *         score    => [score:int],
     *         other_required_entries => array(
     *             [entryid:string],
     *             [entryid:string],
     *             ...
     *         ),
     *     ),
     *     [...],
     * )
     *
     * This can be described as a list of strategies. Each strategy has a 
     * unique (to this class) identifier ([strategy:int]), a score, and a list 
     * of IDs of other entries required to implement this strategy.
     *
     * The strategy is just an identifier for the internal use of the class, to 
     * distinguish between strategies. Most implementors should define class 
     * constants for them, e.g.:
     *
     *     const STRATEGY_IMPORT_AS_FILE = 1;
     *     const STRATEGY_IMPORT_AS_FOLDER = 1;
     *
     * The score represents how well this strategy applies to this entry. 100 
     * is considered an extremely high score (use this for 'I think this is a 
     * perfect match' type strategies).
     *
     * The other required entries is a list of entries this strategy will 
     * require to be implemented. It's a list of entry IDs - a.k.a the contents 
     * of the <id> element of an <entry>.
     *
     * The return result is a list of strategies, which means that you can 
     * provide more than one if you think you have two possible matches. This 
     * method should return everything that is _possible_, even if it's not the 
     * best match, as the user may choose the less obvious method of importing 
     * for some reason.
     *
1439
1440
     * @param SimpleXMLElement $entry    The entry to find import strategies for
     * @param PluginImportLeap $importer The importer
1441
1442
     * @return array A list of strategies that could be used to import this entry
     */
1443
    abstract public static function get_import_strategies_for_entry(SimpleXMLElement $entry, PluginImportLeap $importer);
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484

    /**
     * Converts an entry into the appropriate artefacts using the given 
     * strategy.
     *
     * The strategy will be one of ones this plugin previously said would be
     * possible for this entry. This method may throw an ImportException if it 
     * is not.
     *
     * This method is quite tied to get_import_strategies_for_entry: if that 
     * method exports a certain strategy (with a certain list of other required 
     * entries), then if that strategy is chosen, this method will be invoked 
     * with that strategy and that list of other required entries. HOWEVER, you 
     * cannot assume that both method calls will happen in the same request - a 
     * UI may be presented to the user to make them choose strategies in 
     * between these steps, for example. So don't store state between them!
     *
     * Regarding other entries: based on the previous statement, this class 
     * said it required them to import this entry, so they should be necessary 
     * to complete the import of the entry. Alternatively, perhaps you 
     * recognise that importing them makes no sense when you import this entry. 
     * But be aware that your class is denying these entries to other classes 
     * if you do this!
     *
     * This method should return a list of entry ID => (list of artefact IDs):
     *
     * array(
     *     [entryid:string] => array([artefactid:int], [artefactid:int], ...),
     *     [entryid:string] => array([artefactid:int], [artefactid:int], ...),
     *     ...
     * )
     *
     * This list informs the importer of how each entry was converted into 
     * artefact(s). Often, an entry will be converted into just one artefact, 
     * but there's no reason why it might not be convereted into more.
     *
     * This information is used by setup_relationships() hooks to work out how 
     * entries were converted to artefacts, so for example, files can be 
     * attached to blog posts even though the files and blog posts were 
     * imported by different plugins.
     *
1485
1486
1487
1488
1489
1490
1491
1492
1493
     * @param SimpleXMLElement $entry    The entry to import
     * @param PluginImportLeap $importer The importer
     * @param int $strategy              The strategy to use (should be a class 
     *                                   constant on your class, see the documentation
     *                                   of get_import_strategies_for_entry for more
     *                                   information)
     * @param array $otherentries        A list of entry IDs that this class 
     *                                   previously said were required to import 
     *                                   the entry
1494
1495
1496
1497
     * @throws ImportException If the strategy is unrecognised
     * @return array A list describing what artefacts were created by the 
     *               import of each entry
     */
1498
    abstract public static function import_using_strategy(SimpleXMLElement $entry, PluginImportLeap $importer, $strategy, array $otherentries);
1499

1500
1501
    /**
     * Gives plugins a chance to import author data
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
     *
     * This gets passed the entry ID for the entry that represents the person
     * who is being imported, should there be such an entry. This method can
     * then dig through it to create artefacts. Contrast this with exporting
     * persondata in the plugin's export implementation. A plugin might export
     * a persondata field there, and then look for it again here.
     *
     * @param PluginImportLeap $importer The importer
     * @param string $persondataid       The entry ID for the persondata entry.
     *                                   May be empty if no such entry was
     *                                   found in the import.
1513
     */
1514
    public static function import_author_data(PluginImportLeap $importer, $persondataid) {
1515
1516
    }

1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
    /**
     * Gives plugins a chance to construct relationships between the newly 
     * created artefacts.
     *
     * This hook is optional. If implemented, plugins get access to the entries 
     * they imported, and the strategy they used to import them. It is 
     * guaranteed that all other plugins have created the artefacts they wanted 
     * to create, and implementors of this hook can use 
     * $importer->get_artefactids_imported_by_entryid to get access to the 
     * artefacts they need.
     *
     * This method has no return value.
     *
1530
1531
1532
1533
1534
1535
     * @param SimpleXMLElement $entry    The entry previously imported
     * @param PluginImportLeap $importer The importer
     * @param int $strategy              The strategy to use (should be a class 
     *                                   constant on your class, see the documentation
     *                                   of get_import_strategies_for_entry for more
     *                                   information)
1536
1537
1538
1539
1540
     * @param array $otherentries     A list of entry IDs that this class 
     *                                previously said were required to import 
     *                                the entry
     * @throws ImportException If the strategy is unrecognised
     */
1541
    public static function setup_relationships(SimpleXMLElement $entry, PluginImportLeap $importer, $strategy, array $otherentries) {
1542
1543
    }

1544
1545
1546
1547
1548
1549
1550
    /**
     * Gives plugins a chance to construct relationships between the newly
     * created artefacts and newly created views.
     */
    public static function setup_view_relationships(SimpleXMLElement $entry, PluginImportLeap $importer, $strategy, array $otherentries) {
    }

1551
1552
1553
1554
1555
1556
1557
1558
1559
    /**
     * Runs after the importer has finished, to allow the plugin to perform any
     * cleanup operations.