lib.php 102 KB
Newer Older
1
2
3
4
5
6
<?php
/**
 *
 * @package    mahara
 * @subpackage import-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
 * Implements import of Leap2A files
16
17
18
19
20
21
22
23
24
25
 *
 * 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();
26
    private $coreloadmapping = array();
27
28
29
30
    public $artefactids = array();
    public $viewids = array();
    public $collectionids = array();
    public $collectionviewentries = array();
31
    protected $filename;
32

33
34
    protected $persondataid = null;

35
36
    protected $loglevel = 0;
    protected $logtargets = LOG_TARGET_ERRORLOG;
37
    protected $logfile = '';
38
    protected $profile = false;
39
40
    protected $leap2anamespace = null;
    protected $leap2atypenamespace = null;
41
    protected $leap2acategories = null;
42
43
44
    // 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/');
45
46
47
48
49
50
51
52

    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#';
53
54
55
56
    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/';
57
    const NS_CATEGORIES        = 'http://wiki.leapspecs.org/2A/categories/';
58
59
    const NS_MAHARA     = 'http://wiki.mahara.org/Developer_Area/Import%2F%2FExport/LEAP_Extensions#';

60
61
62
    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
63
    const STRATEGY_IMPORT_AS_VIEW = 1;
64
    const STRATEGY_IMPORT_AS_COLLECTION = 2;
Nigel McNie's avatar
Nigel McNie committed
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
    /**
     * Add the artefactmapping of an entry given by ID
     * @param string $entryid
     * @param string $artefactid
     */
    public function add_artefactmapping($entryid, $artefactid) {
        if (!isset($this->artefactids[$entryid])) {
            $this->artefactids[$entryid] = array();
        }
        if (!in_array($artefactid, $this->artefactids[$entryid])) {
            $this->artefactids[$entryid][] = $artefactid;
        }
    }

80
81
    public static function validate_transported_data(ImporterTransport $transport) {
        $importdata = $transport->files_info();
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
        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;
            }
        }
99
100
101
102
103
104
105
106
107
    }

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

108
109
110
111
112
    /**
     * Reads and parses the archive's "leap2a.xml" file
     * @throws ImportException
     */
    public function read_leap2a_xml_file() {
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
        ;
Hugh Davenport's avatar
Hugh Davenport committed
122
123
124
125
        if (function_exists('libxml_disable_entity_loader')) {
            // The LIBXML_NONET stops proper network based XXE attacks from happening
            libxml_disable_entity_loader(false);
        }
126
        if (!$this->xml = simplexml_load_file($this->filename, 'SimpleXMLElement', $options)) {
127
128
129
            // 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");
        }
Hugh Davenport's avatar
Hugh Davenport committed
130
131
132
        if (function_exists('libxml_disable_entity_loader')) {
            libxml_disable_entity_loader(true);
        }
133
134
135
136
137
        $this->namespaces = array_flip($this->xml->getDocNamespaces());
        $this->registerXpathNamespaces($this->xml);
        $this->trace("Document loaded, entries: " . count($this->xml->entry));
        $this->snapshot('loaded XML');

138
        $this->detect_leap2a_namespace();
139
        $this->ensure_document_valid();
140
    }
141

142
143
144
145
146
147
    /**
     * Create the default load mapping, usingthe highest-ranked strategy for each item in
     * the leap2a XML file
     */
    private function build_default_load_mapping() {
        $this->read_leap2a_xml_file();
148
149
150
151
        $this->create_strategy_listing();
        $this->snapshot('created strategy listing');
        $this->strategy_listing_to_load_mapping();
        $this->snapshot('converted strategy listing to load mapping');
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    }

    public function process($step = PluginImport::STEP_NON_INTERACTIVE) {
        db_begin();
        switch ($step) {
        case PluginImport::STEP_NON_INTERACTIVE:
            $this->build_default_load_mapping();
            $this->import_from_load_mapping();
            $this->snapshot('imported data based on load mapping');
            $this->import_completed();
            break;
        case PluginImport::STEP_INTERACTIVE_IMPORT_FORM:
            $this->build_default_load_mapping();
            $this->build_import_entry_requests();
            break;
        case PluginImport::STEP_INTERACTIVE_IMPORT_RESULT:
            // Load import requests from DB
            $this->load_import_entry_requests();
            // Import based on import requests
            $this->import_from_requests();
            $this->snapshot('imported data based on import requests');
            $this->import_completed();
            break;
        }
        db_commit();
    }

    /**
     * Builds import requests from load mapping and store them in DB for next steps
     */
    public function build_import_entry_requests() {
        $usedlist = $loadedentries = array();
        uasort($this->loadmapping, function ($a, $b) { return $a["score"] < $b["score"]; });
        // Find existing artefacts
        foreach ($this->loadmapping as $entryid => $strategydata) {
            if (in_array($entryid, $usedlist)) {
                continue;
            }
            if (isset($strategydata['other_required_entries'])) {
                foreach ($strategydata['other_required_entries'] as $otherentryid) {
                    if (in_array($otherentryid, $usedlist)) {
                        continue(2);
                    }
                }
            }
            $entry = $this->get_entry_by_id($entryid);
            $classname = 'LeapImport' . ucfirst($strategydata['artefactplugin']);
            call_static_method($classname, 'add_import_entry_request_using_strategy',
                            $entry, $this, $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;
        }
        // Find existing author's artefacts
        if (!is_array($this->data) || !array_key_exists('skippersondata', $this->data) || $this->data['skippersondata'] !== true) {
            foreach (plugins_installed('artefact') as $plugin) {
                $classname = 'LeapImport' . ucfirst($plugin->name);
                if (method_exists($classname, 'add_import_entry_request_author_data')) {
                    call_static_method($classname, 'add_import_entry_request_author_data', $this, $this->persondataid);
                }
            }
        }
        // Find existing views
        foreach ($this->coreloadmapping as $entryid => $strategydata) {
            if (in_array($entryid, $usedlist)) {
                continue;
            }
            if (isset($strategydata['other_required_entries'])) {
                foreach ($strategydata['other_required_entries'] as $otherentryid) {
                    if (in_array($otherentryid, $usedlist)) {
                        continue(2);
                    }
                }
            }

            $entry = $this->get_entry_by_id($entryid);
            $this->add_import_entry_request_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;
        }

    }

    /*
     * returns a list of import entries and their existing artefacts
     */
    public function build_import_entry_requests_form() {
        global $USER;

        $html = '<form name="ier" method="POST" action="">';
        $installedplugins = array_map(create_function('$a', 'return $a->name;'), plugins_installed('artefact'));
255
        $orderedimportplugins = array('internal', 'file', 'blog', 'resume', 'plans', 'annotation');
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        foreach ($orderedimportplugins as $plugin) {
            if (!in_array($plugin, $installedplugins)) {
                continue;
            }
            if (safe_require('import', 'leap/' . $plugin, 'lib.php', 'require_once', true)) {
                $classname = 'LeapImport' . ucfirst($plugin);
                if (method_exists($classname, 'render_import_entry_requests')) {
                    safe_require('artefact', $plugin);
                    $html .= call_static_method($classname, 'render_import_entry_requests', $this);
                }
            }
        }
        // core render for views
        $html .= self::render_import_entry_requests();
        $html .= '
            <input type="hidden" value="' . DOIMPORT_ACT . '" name="action">
            <input type="submit" value="' . get_string('Import', 'import') . '" name="import_submit" id="import_submit" class="submitcancel submit">
            <input type="submit" value="' . get_string('cancel') . '" name="cancel_import_submit" id="cancel_import_submit" class="submitcancel cancel">
        </form>';
        return $html;
    }

    /**
     * Call import method for plugins
     * @param $method    method name
     */
    public function call_import_method_plugins($method) {
        $installedplugins = array_map(create_function('$a', 'return $a->name;'), plugins_installed('artefact'));
284
        $orderedimportplugins = array('internal', 'file', 'blog', 'resume', 'plans', 'annotation');
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        foreach ($orderedimportplugins as $plugin) {
            if (!in_array($plugin, $installedplugins)) {
                continue;
            }
            if (safe_require('import', 'leap/' . $plugin, 'lib.php', 'require_once', true)) {
                $classname = 'LeapImport' . ucfirst($plugin);
                if (method_exists($classname, $method)) {
                    safe_require('artefact', $plugin);
                    call_static_method($classname, $method, $this);
                }
            }
        }
    }
    /*
     * do import from requests and returns the result
     */
    public function do_import_from_requests() {
        global $USER;

        db_begin();

        $this->read_leap2a_xml_file();
        // Allow each plugin imports its artefact from import entry requests
        $this->call_import_method_plugins('import_from_requests');
        $this->call_import_method_plugins('setup_relationships_from_requests');
        // Fix up any artefact references in the content of imported artefacts
        // TODO: restrict this to the ones that were imported right now
        if ($artefacts = get_records_array('artefact', 'owner', $this->get('usr'), '', 'id, title, description')) {
            foreach ($artefacts as $artefact) {
                $this->fix_artefact_references($artefact);
            }
        }
        // Now import views
        $this->import_from_requests();

        // Put views into collections

        // Keep track of which views have been placed in a collection, because
        // Mahara can't handle more one collection per view.
        $incollection = array();
        foreach ($this->collectionviewentries as $cid => $entryids) {
            $i = 0;
            foreach ($entryids as $entryid) {
                $viewid = self::get_viewid_imported_by_entryid($entryid);
                if ($viewid && !isset($incollection[$viewid])) {
                    insert_record('collection_view', (object) array(
                        'collection' => $cid,
                        'view' => $viewid,
                        'displayorder' => $i,
                    ));
                    $incollection[$viewid] = $cid;
                    $i++;
                }
            }
        }
340
        // Allow each artefact plugin to load relationships to views if they need to
341
        $this->call_import_method_plugins('setup_view_relationships_from_requests');
342
343
344
345

        // Allow each blocktype plugin to load relationships to views if they need to
        $this->rewrite_blockinstance_relationships();

346
        $this->import_completed();
347
        $this->delete_import_entry_requests();
348

349
        db_commit();
350
351
352
353

        $html = get_string('importsuccessfully', 'import');
        return $html;

354
355
    }

356
357
358
359
360
361
    /**
     * detect the leap2a namespace of the import document by looking for the 'version' element
     *
     *
     */
    private function detect_leap2a_namespace () {
362

363
        // check for the leap2a version used
364
365
366
367
368
369
370
371
372
373
374
        // 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");
375
        }
376
377

        if($version) {
378
379
            $this->leap2anamespace = self::NS_LEAP;
            $this->leap2atypenamespace = self::NS_LEAP;
380
381
382
383
384
385
386
387
388
            // this is a workaround for a bug that was introduced during the
            // update to LEAP2A 2010-07. Exports between the update and this
            // bugfix will contain a wrong namespace. This workaround will
            // allow those exports to still import properly. (bug #673434)
            if (isset($this->namespaces['http://wiki.leapspecs.org/2A/categories'])) {
                $this->leap2acategories = 'http://wiki.leapspecs.org/2A/categories';
            } else {
                $this->leap2acategories = self::NS_CATEGORIES;
            }
389
390
391
        } else {
            $this->leap2anamespace = self::NS_LEAP_200903;
            $this->leap2atypenamespace = self::NS_LEAPTYPE_200903;
392
            $this->leap2acategories = self::NS_CATEGORIES_200903;
393
394
395
        }
    }

396
397
398
    private function ensure_document_valid() {
        // TODO: http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/Import%3a_Implementation_Plan#beginning
        //
399
        // Do a bunch of checks that will ensure the feed is valid, and thus
400
401
402
403
404
        // 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
405
        // - feed element has correct namespaces (keep in mind we need to be
406
407
408
        // able to import raw ATOM feeds too)

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

410
        // Check all the namespaces we're gonna need are declared, and warn if
411
        // they're not there
412
413
414
415
416
417
        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) {
418
419
420
421
            if (!isset($this->namespaces[$ns])) {
                $this->trace("WARNING: Namespaces $ns wasn't declared - this will make importing data correctly difficult");
            }
        }
422
423
424
425
426
427
428
429
430
    }

    /**
     * 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()");
431
432
433
434
435
436
        // 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')) {
437
                    safe_require('artefact', $plugin);
438
439
440
441
                    call_static_method($classname, 'setup', $this);
                }
            }
        }
442

443
        // First, try to establish whether there is an element representing the
444
445
446
447
448
449
450
451
452
        // 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 {
453
                $persondata = $this->get('xml')->xpath('//a:feed/a:entry/a:category[('
454
                    . $this->curie_xpath('@scheme', $this->get_categories_namespace(), 'person_type#') . ') and @term="Self"]/../a:id');
455
456
457
458
459
460
                if (isset($persondata[0])) {
                    $this->persondataid = (string)$persondata[0][0];
                }
                else {
                    $this->persondataid = false;
                }
461
462
463
464
            }
        }

        // Generate strategy listing
465
466
467
468
469
        foreach ($this->xml->xpath('//a:feed/a:entry') as $entry) {
            $this->registerXpathNamespaces($entry);
            $entryid = (string)$entry->id;
            $this->trace(" * $entryid ({$entry->title})");

470
471
472
473
474
            if ($this->persondataid && $entryid == $this->persondataid) {
                // We don't offer this element to any plugin to be imported
                continue;
            }

475
            foreach (plugins_installed('artefact') as $plugin) {
476
                $plugin = $plugin->name;
477
478
                $classname = 'LeapImport' . ucfirst($plugin);
                if (class_exists($classname)) {
479
480
481
                    if (!is_subclass_of($classname, 'LeapImportArtefactPlugin')) {
                        throw new SystemException("Class $classname does not extend LeapImportArtefactPlugin as it should");
                    }
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
                    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
497
                            }
498
499
500
501
502
                        }
                    }
                }
            }

Nigel McNie's avatar
Nigel McNie committed
503
504
505
506
507
508
509
510
511
512
            $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;
                }
            }

513
514
515
516
517
518
519
            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
520
            usort($this->strategylisting[$entryid], function ($a, $b) { return $a["score"] < $b["score"]; });
521
522
523
524
525
526
        }
        $this->trace('*** Strategy listing: ***');
        $this->trace($this->strategylisting);
    }

    /**
527
     * Converts a strategy listing into the "best" load mapping that can be
528
529
     * gleaned from the strategy listing.
     *
530
531
     * 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
532
533
534
535
536
537
538
     * 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();

539
540
        // 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
541
542
543
544
545
        // 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);

546
547
548
        // 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,
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
        // 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]");
567
568
569
570
571
572
                if ($strategydata['artefactplugin']) {
                    $this->loadmapping[$entryid] = $strategydata;
                }
                else {
                    $this->coreloadmapping[$entryid] = $strategydata;
                }
573
574
575
576
577
578
579
580
581
582

                $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
583
584
                // 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
585
586
587
588
                // for debugging purposes
                break;
            }
        }
589
        $this->trace("*** Plugin load mapping: ***");
590
        $this->trace($this->loadmapping);
591
592
        $this->trace("*** Core load mapping: ***");
        $this->trace($this->coreloadmapping);
593
594
595
    }

    private function strategy_listing_sort($a, $b) {
596
597
        // NOTE: the strategy listing should already have the strategies for
        // each entry sorted from highest to lowest score. If it doesn't, these
598
599
600
601
602
603
604
605
        // 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:
606
     * https://wiki.mahara.org/index.php/Developer_Area/Import//Export/Import:_Implementation_Plan#second_pass:_load_all_entries_into_mahara_as_per_load_mapping
607
608
609
610
611
     */
    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();
612
        uasort($this->loadmapping, function ($a, $b) { return $a["score"] < $b["score"]; });
613
614
615
616
617
618
619
620
621
622
623
624
625
626
        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);
                    }
                }
            }

627
628
629
630
631
632
633
634
635
            $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']);
636
637
638
639
640

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

641
            $this->artefactids = array_merge_recursive($this->artefactids, $artefactmapping);
642
643
644
645
646
647
648
649
650
651
652

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

            $loadedentries[] = $entryid;
        }

653
        // Give plugins a chance to import stuff about the feed author from the
654
        // persondata entry
655
        // TODO: this should return an artefact mapping so things can create
656
        // links to profile fields, but nothing actually needs it yet
657
        if (!is_array($this->data) || !array_key_exists('skippersondata', $this->data) || $this->data['skippersondata'] !== true) {
658
659
660
661
662
            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);
                }
663
            }
664
        }
665

666
        // Now all artefacts are loaded, allow each plugin to load
667
668
669
        // relationships for them if they need to
        foreach ($loadedentries as $entryid) {
            $strategydata = $this->loadmapping[$entryid];
670
671
            $classname = 'LeapImport' . ucfirst($strategydata['artefactplugin']);
            $entry = $this->get_entry_by_id($entryid);
672
            $maybeartefacts = call_static_method($classname, 'setup_relationships',
673
                $entry, $this, $strategydata['strategy'], $strategydata['other_required_entries']);
674
675
676
            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);
            }
677
678
        }

679
        // Fix up any artefact references in the content of imported artefacts
680
        // TODO: restrict this to the ones that were imported right now
681
682
683
684
685
686
        if ($artefacts = get_records_array('artefact', 'owner', $this->get('usr'), '', 'id, title, description')) {
            foreach ($artefacts as $artefact) {
                $this->fix_artefact_references($artefact);
            }
        }

687
688
689
690
691
692
693
694
695
696
697
698
699
        // 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
700
            }
701
702
703
704
705
706
707
708
709
710
711
712
713

            $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;
714
        }
715

716
        // Put views into collections
717
718
719
720
721

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

722
723
724
        foreach ($this->collectionviewentries as $cid => $entryids) {
            $i = 0;
            foreach ($entryids as $entryid) {
725
726
                $viewid = self::get_viewid_imported_by_entryid($entryid);
                if ($viewid && !isset($incollection[$viewid])) {
727
728
729
730
731
732
                    $record = (object) array(
                        'collection' => $cid,
                        'view' => $viewid,
                        'displayorder' => $i,
                    );
                    insert_record('collection_view', $record);
733
                    $incollection[$viewid] = $cid;
734
735
736
737
738
                    $i++;
                }
            }
        }

739
740
741
742
743
744
745
746
747
748
        // 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']);
            }
        }
749
750
751

        // Allow each blocktype plugin to load relationships to views if they need to
        $this->rewrite_blockinstance_relationships();
752
753
    }

754
755
756
757
758
759
760
761
762
763
764
765
766
    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;
    }

767
    private function import_completed() {
768
769
770
771
772
773
774
        // 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);
            }
        }
775
776
777
        $this->trace("------------------\nimport_completed()");

        unset($this->loadmapping);
778
        unset($this->coreloadmapping);
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        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");
        }
    }

810
811
812
813
814
815
816
817
    /*
     * Delete all import entry requests
     */
    private function delete_import_entry_requests() {
        delete_records('import_entry_requests', 'importid', $this->get('importertransport')->get('importid'));
    }

        /**
818
819
     * Logs a message for debugging purposes
     *
820
     * The user can configure the amount of logging, and where it goes, by
821
822
823
824
825
826
827
828
829
830
     * 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) {
831
            // Use our logging system temporarily, which provides us with
832
            // access to its nice features. We use log_message instead of
833
834
            // log_debug because that will retain the the line/file where
            // trace() was called, rather than saying all of the messages came
835
836
            // from trace() itself
            global $CFG;
837
            $oldtargets = $CFG->log_dbg_targets;
838
            $oldfile = isset($CFG->log_file) ? $CFG->log_file : null;
839
            $CFG->log_dbg_targets = $this->logtargets;
840
            $CFG->log_file = $this->logfile;
841
            $file = $line = $trace = null;
842
843
844
            log_message($message, LOG_LEVEL_DBG, true, true, $file, $line, $trace);
            $CFG->log_dbg_targets = $oldtargets;
            $CFG->log_file = $oldfile;
845
846
847
848
849
850
851
852
853
854
855
856
        }
    }

    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
857
    /**
858
     * Given an entry, should return a list of the possible ways that it could
Nigel McNie's avatar
Nigel McNie committed
859
860
     * be imported by the core.
     *
861
     * The core handles View importing, so this method looks for entries that
Nigel McNie's avatar
Nigel McNie committed
862
863
     * could be converted into Views.
     *
864
     * For more information about this method, see
Nigel McNie's avatar
Nigel McNie committed
865
866
867
868
869
     * {LeapImportArtefactPlugin::get_import_strategies_for_entry}
     *
     * @param SimpleXMLElement $entry
     */
    public function get_import_strategies_for_entry(SimpleXMLElement $entry) {
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
        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
885
886
887
888
        }
        return array();
    }

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
917
918
919
920
921
922
923
924
925
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
    /**
     * Add import entry request for a view
     *
     * @param SimpleXMLElement $entry
     * @param  $strategy
     * @param array $otherentries
     * @return update DB table 'import_entry_requests'
     * @throws ImportException
     */
    public function add_import_entry_request_using_strategy(SimpleXMLElement $entry, $strategy, array $otherentries) {
        $importid = $this->get('importertransport')->get('importid');
        switch ($strategy) {
        case self::STRATEGY_IMPORT_AS_VIEW:
            require_once('view.php');

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

                $viewdata = array(
                    'title'       => (string)$entry->title,
                    'description' => (string)$entry->summary,
                    'type'        => 'portfolio', // TODO
                    'layout'      => null, // TODO
                    'tags'        => self::get_entry_tags($entry),
                    'numrows'     => 1,
                    '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;
                }
                $viewdata['columns'][1][1] = array(
                    'type'   => 'textbox',
                    'title'  => '',
                    'column' => 1,
                    'order'  => 1,
                    'config' => array('text' => self::get_entry_content($entry, $this))
                );
                PluginImportLeap::add_import_entry_request($importid, (string)$entry->id, self::STRATEGY_IMPORT_AS_VIEW, 'core', array(
                    'owner'   => $this->get('usr'),
                    'type'    => 'view',
                    'content' => $viewdata
                ));
            }
            break;
        case self::STRATEGY_IMPORT_AS_COLLECTION:
            $collectiondata = array(
                'title'       => (string)$entry->title,
                'name'        => (string)$entry->title,
                'description' => (string)$entry->summary,
                'tags'        => self::get_entry_tags($entry),
                'owner'       => $this->get('usr'),
            );
            if ($published = strtotime((string)$entry->published)) {
                $collectiondata['ctime'] = $published;
            }
            if ($updated = strtotime((string)$entry->updated)) {
                $collectiondata['mtime'] = $updated;
            }

            PluginImportLeap::add_import_entry_request($importid, (string)$entry->id, self::STRATEGY_IMPORT_AS_COLLECTION, 'core', array(
                'owner'   => $this->get('usr'),
                'type'    => 'collection',
                'content' => $collectiondata
            ));
            break;
        default:
            throw new ImportException($this, 'TODO: get_string: unknown strategy chosen for importing entry');
        }
    }

    /**
     * Import Mahara views and collections from requests
     * @throws ImportException
     */
    public function import_from_requests() {
        $importid = $this->get('importertransport')->get('importid');
        if ($entry_requests = get_records_select_array('import_entry_requests', 'importid = ? AND plugin = ? AND decision = ?', array($importid, 'core', PluginImport::DECISION_ADDNEW))) {
            foreach ($entry_requests as $entry_request) {
                switch ($entry_request->strategy) {
                case self::STRATEGY_IMPORT_AS_VIEW:
                    require_once('view.php');
                    $this->import_view_from_request($entry_request);
                    break;
                case self::STRATEGY_IMPORT_AS_COLLECTION:
                    require_once('collection.php');
                    $collectiondata = unserialize($entry_request->entrycontent);
                    $collection = new Collection(0, $collectiondata);
                    $collection->commit();
                    $this->collectionids[$entry_request->entryid] = $collection->get('id');

                    // Remember entry ids that form part of this entry, and use them later
                    // to put views into collections.
                    $entry = $this->get_entry_by_id($entry_request->entryid);
                    foreach ($entry->link as $link) {
                        if ($this->curie_equals($link['rel'], '', 'has_part') && isset($link['href'])) {
                            $this->collectionviewentries[$collection->get('id')][] = (string) $link['href'];
                        }
                    }
                    break;
                default:
                    throw new ImportException($this, 'TODO: get_string: unknown strategy chosen for importing entry');
                }
            }
        }
    }

    /**
     * Import an Mahara view from request
     * @throws ImportException
     */
    public function import_view_from_request($entry_request) {
        $viewdata = unserialize($entry_request->entrycontent);
1007
        $view = View::import_from_config($this->rewrite_blockinstance_config($viewdata), $this->get('usr'), 'leap');
1008

1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        // Rewrite embedded image urls in the view description
        // These links have been generated by export_leap_rewrite_links()
        require_once('embeddedimage.php');
        $newdescription = EmbeddedImage::rewrite_embedded_image_urls_from_import(
            $view->get('description'),
            $this->artefactids,
            'description',
            $view->get('id')
        );
        $view->set('description', $newdescription);

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
        if (isset($viewdata->ctime)) {
            $view->set('ctime', $viewdata->ctime);
        }
        if (isset($viewdata->mtime)) {
            $view->set('mtime', $viewdata->mtime);
        }
        $view->set('owner', $this->get('usr'));

        $view->commit();
        $this->viewids[$entry_request->entryid] = $view->get('id');
    }

Nigel McNie's avatar
Nigel McNie committed
1032
1033
1034
1035
1036
1037
1038
    /**
     */
    public function import_using_strategy(SimpleXMLElement $entry, $strategy, array $otherentries) {
        switch ($strategy) {
        case self::STRATEGY_IMPORT_AS_VIEW:
            require_once('view.php');

1039
            if (!$this->import_entry_as_mahara_view($entry)) {
1040
1041
1042
                // Not a Mahara view, just do basic import
                $this->trace('Not a Mahara view, doing basic import', self::LOG_LEVEL_VERBOSE);

1043
1044
1045
1046
1047
                $viewdata = array(
                    'title'       => (string)$entry->title,
                    'description' => (string)$entry->summary,
                    'type'        => 'portfolio', // TODO
                    'layout'      => null, // TODO
Nigel McNie's avatar
Nigel McNie committed
1048
                    'tags'        => self::get_entry_tags($entry),
1049
                    'numrows'     => 1,
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
                    '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'));
1061
1062
1063
1064
1065
1066

                safe_require('blocktype', 'textbox');
                $bi = new BlockInstance(0,
                    array(
                        'blocktype'  => 'textbox',
                        'title'      => '',
1067
                        'row'        => 1,
1068
1069
1070
1071
1072
1073
1074
1075
                        'column'     => 1,
                        'order'      => 1,
                        'configdata' => array(
                            'text' => self::get_entry_content($entry, $this),
                        ),
                    )
                );
                $view->addblockinstance($bi);
1076
                $this->viewids[(string)$entry->id] = $view->get('id');
1077
            }
1078
1079
1080
1081
1082
1083
1084
            break;
        case self::STRATEGY_IMPORT_AS_COLLECTION:
            require_once('collection.php');

            $collectiondata = array(
                'name'        => (string)$entry->title,
                'description' => (string)$entry->summary,
1085
                'tags'        => self::get_entry_tags($entry),
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
                '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
1107
1108
            break;
        default:
1109
            throw new ImportException($this, 'TODO: get_string: unknown strategy chosen for importing entry');
Nigel McNie's avatar
Nigel McNie committed
1110
1111
1112
        }
    }

1113
    /**
1114
1115
1116
     * Render import entry requests for Mahara views
     * @param PluginImportLeap $importer
     * @return HTML code for displaying views and choosing how to import them
1117
     */
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
    public function render_import_entry_requests() {
        $importid = $this->get('importertransport')->get('importid');
        // Get import entry requests for Mahara views
        $entryviews = array();
        if ($ierviews = get_records_select_array('import_entry_requests', 'importid = ? AND entrytype = ?', array($importid, 'view'))) {
            foreach ($ierviews as $ierview) {
                $view = unserialize($ierview->entrycontent);
                $view['id'] = $ierview->id;
                $view['decision'] = $ierview->decision;
                $view['disabled'][PluginImport::DECISION_IGNORE] = false;
                $view['disabled'][PluginImport::DECISION_ADDNEW] = false;
                $view['disabled'][PluginImport::DECISION_APPEND] = true;
                $view['disabled'][PluginImport::DECISION_REPLACE] = true;
                $entryviews[] = $view;
            }
        }
        $smarty = smarty_core();
        $smarty->assign_by_ref('displaydecisions', $this->get('displaydecisions'));
        $smarty->assign_by_ref('entryviews', $entryviews);
        return $smarty->fetch('import/views.tpl');
    }


    /**
     * Logic for processing an $entry into a Mahara view.
     * @param SimpleXMLElement $entry
     * @return array An array of data that can be used to create the view, or store it into an import_request
     */
    private function get_mahara_view_entry_data(SimpleXMLElement $entry) {
1147
        static $blocktypes_installed = null;
1148
        static $columnlayouts = null;
1149
        static $viewtypes = null;
1150
        $viewelement = $entry->xpath('mahara:view[1]');
1151

1152
1153
        if (count($viewelement) != 1) {
            // This isn't a Mahara view
1154
1155
1156
            return false;
        }

1157
1158
        if (is_null($columnlayouts)) {
            $columnlayouts = get_records_assoc('view_layout_columns');
1159
        }
1160
1161
1162
        if (is_null($viewtypes)) {
            $viewtypes = get_column('view_type', 'type');
        }
1163
1164
1165

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

1166
1167
1168
1169
        $type = 'portfolio';
        if (isset($maharaattributes['type']) && in_array($maharaattributes['type'], $viewtypes)) {
            $type = $maharaattributes['type'];
        }
1170
1171
1172
1173
1174
        $ownerformat = intval($maharaattributes['ownerformat']);
        if (!$ownerformat) {
            $ownerformat = FORMAT_NAME_DISPLAYNAME;
        }

1175
1176
        $rows = $entry->xpath('mahara:view[1]/mahara:row');
        $rowcount = count($rows);
1177
1178
        // A flag that indicates whether this is an old-style one-row layout, or a new-style multi-row layout
        $onerowlayout = false;
1179
        if ($rowcount < 1 || $rowcount > View::$maxlayoutrows) {
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
            // Check for a pre-1.8 (one-row) layout
            $columns = $entry->xpath('mahara:view[1]/mahara:column');
            $columncount = count($columns);
            if ($columncount < 1 || $columncount > 5) {
                // Whoops, invalid number of rows
                $this->trace("Invalid number of rows specified for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
                return false;
            }
            else {
                $onerowlayout = true;
                $rows = array($columns);
                $rowcount = 1;
            }
1193
1194
        }

1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
        $layout = null;
        if (isset($maharaattributes['layout'])) {
            $rowwidths = explode('-', $maharaattributes['layout']);
            if (count($rowwidths) != $rowcount) {
                $this->trace("Row widths and number of rows do not match for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
                return false;
            }
            $columnids = array();
            foreach ($columnlayouts as $columnlayout) {
                foreach ($rowwidths as $key => $widths) {
                    if ($columnlayout->widths == $widths) {
                        $columnids[$key+1] = $columnlayout->id;
                    }
                }
            }
            if (count($columnids) != $rowcount) {
                $this->trace("Invalid row widths were specified for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
                return false;
            }
1214
            $rowscolssql = '';
1215
1216
1217
1218
1219
1220
1221
1222
            for ($i=0; $i<count($columnids); $i++) {
                $rowscolssql .= '(row = ' . ($i+1) . ' AND columns = ' . $columnids[$i+1] . ')';
                if ($i != (count($columnids)-1)) {
                    $rowscolssql .= ' OR ';
                }
            }

            // search in default layout options for a match
1223
1224
1225
1226
1227
            // this will return first possible match with exact match (if any)
            // at front of possibles. More than one possible match can occur
            // if there are 3 or more rows in leap2a layout and 2 of those rows
            // match more than one possible view layout.
            $sql = 'SELECT vlrc.viewlayout AS id
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
                    FROM
                        {view_layout} vl
                        INNER JOIN {view_layout_rows_columns} vlrc
                            ON vl.id = vlrc.viewlayout
                        INNER JOIN (
                            SELECT
                                viewlayout, COUNT(*)
                            FROM {view_layout_rows_columns}
                            GROUP BY viewlayout
                            HAVING COUNT(*) = ?
                        ) vlrc2
                            ON vlrc.viewlayout = vlrc2.viewlayout
                        INNER JOIN {usr_custom_layout} ucl
                            ON ucl.layout = vl.id
                    WHERE (' . $rowscolssql . ')
                        AND (
                            vl.iscustom = 0
                            OR (
1246
                                vl.iscustom = 1 AND ucl.usr = ? AND ucl.group IS NULL AND ucl.institution IS NULL
1247
1248
                            )
                        )
1249
                    GROUP BY vlrc.viewlayout
1250
                    HAVING count(*) = ?
1251
                    LIMIT 1';
1252
            $layout = get_record_sql($sql, array($rowcount, $this->get('usr'), $rowcount));
1253
1254

            if (!$layout) {
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
                require_once(get_config('docroot') . 'lib/layoutpreviewimage.php');
                // No existing layout matches their page. This probably means they used a custom layout. So, create a new custom layout for them.

                // First check to see whether the custom layout they're using is acceptable in our system
                // TODO: A clever way to squeeze their page into one of the standard layouts if it isn't acceptable.
                // Maybe just put everything into a one-column layout and let them rearrange it?
                if (count ($rowwidths) < 1 || count($rowwidths) > View::$maxlayoutrows) {
                    $this->trace("Invalid layout specified for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
                    return false;
                }

                $i = 1;
                $layoutdata = array();
                $layoutdata['numrows'] = count($rowwidths);
                foreach ($rowwidths as $row) {
                    // First, check to see whether this row matches a valid row layout in the DB
                    $rowcolid = get_field('view_layout_columns', 'id', 'widths', $row);
                    if (!$rowcolid) {
                        $this->trace("Invalid layout specified for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
                        return false;
                    }

                    // Data to help us generate the layout
                    $layoutdata["row{$i}"] = $rowcolid;
                    $i++;
                }

                // Now that we know the layout is valid, generate a record and a thumbnail image for it.
                db_begin();
                // An empty view object, since this view isn't present in the DB yet. We need this in order to access the layout methods
                $viewobj = new View(0, array(
                    'owner' => $this->get('usr'),
                    'deleted' => true // To prevent it from being stored in the DB by the View destructor
                ));
                $layoutresult = $viewobj->addcustomlayout($layoutdata);
                if (empty($layoutresult['layoutid'])) {
                    $this->trace("Invalid layout specified for potential view {$entry->id}, falling back to standard import", self::LOG_LEVEL_VERBOSE);
                    db_rollback();
                    return false;
                }
1295
1296
                $layout = (object) array('id' => $layoutresult['layoutid']);
                db_commit();
1297
1298
1299
            }
        }

1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
        // Extract the view description in the entry 'summary'
        // A description may be wrapped in XHTML div
        // See more PluginExportLeap::parse_xhtmlish_content()
        $description = '';
        if ((string) $entry->summary['type'] === 'xhtml'
            || (string) $entry->summary['type'] === 'html'
            ) {
            $summaryelements =
                ((string) $entry->summary['type'] === 'xhtml'
                && $entry->summary->div->div) ?
                $entry->summary->div->div
                : $entry->summary;
            $summarychildren = $summaryelements->children();
            foreach ($summarychildren as $c) {
                $description .= $c->asXML();
            }
        }
        else {
            $description = (string)$entry->summary;
        }
1320
1321
        $config = array(
            'title'       => (string)$entry->title,
1322
            'description' => $description,
1323
            'type'        => $type,
1324
            'layout'      => $layout->id,
Nigel McNie's avatar
Nigel McNie committed
1325
            'tags'        => self::get_entry_tags($entry),
1326
            'numrows'     => $rowcount,
1327
            'owner'       => $this->get('usr'),
1328
            'ownerformat' => $ownerformat,
1329
        );
1330

1331
1332
        $rowindex = 1;
        foreach ($rows as $row) {
1333

1334
1335
1336
1337
1338
1339
1340
1341
1342
            // If this is the old one-row layout, we'll have handled that earlier, and have the one row's columns be in $columns
            if (!$onerowlayout) {
                $columns = $row->xpath('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;
                }
1343
            }
1344

1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
            $colindex = 1;
            foreach ($columns as $column) {
                $blockinstances = $column->xpath('mahara:blockinstance');
                $order = 1;
                $config['rows'][$rowindex]['columns'][$colindex] = array();
                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 row $rowindex col $colindex, order $order: skipping");
                        continue;
1355
                    }
1356
                    $this->trace("  Found block with type {$attrs['blocktype']} at [$rowindex][$colindex][$order]", self::LOG_LEVEL_VERBOSE);
1357

1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
                    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:*');
                        $config['rows'][$rowindex]['columns'][$colindex][$order] = array(
                            'type'   => $attrs['blocktype'],
                            'title'  => $attrs['blocktitle'],
                            'config' => array()
                        );
                        foreach ($configelements as $element) {
                            $value = json_decode((string)$element);
                            if (is_array($value) && isset($value[0])) {
                                $config['rows'][$rowindex]['columns'][$colindex][$order]['config'][$element->getName()] = $value[0];
                            }
                            else {
                                $this->trace("  Value for {$element->getName()} is not an array, ignoring (value follows below)");
                                $this->trace($value);
                            }
                        }

                        $order++;
                    }
                    else {
                        $this->trace("  Ignoring unknown blocktype {$attrs['blocktype']}");
                    }
1385
                }
1386
1387
1388
1389
                $colindex++;
            } // cols
            $rowindex++;
        } //rows
1390

1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
        return $config;
    }

    /**
     * Attempts to import an entry as a mahara view
     *
     * 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.
     *
     * This differs a bit from the Leap2A specification, but we do so
     * 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.
     *
     * If the mahara tags are not present, we give up.
     *
     * @param SimpleXMLElement $entry The entry to be imported
     * @return boolean Whether it could be imported.
     */
    private function import_entry_as_mahara_view(SimpleXMLElement $entry) {
        $config = $this->get_mahara_view_entry_data($entry);
        if (!$config) {
            return false;
        }

1417
        $view = View::import_from_config($this->rewrite_blockinstance_config($config), $this->get('usr'), 'leap');
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427

        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();
1428
        $this->viewids[(string)$entry->id] = $view->get('id');
1429
        return true;
1430
1431
    }

1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
    /**
     * Parse the import entry as mahara view from LEAP2A file and add the import entry request to DB
     *
     * @param SimpleXMLElement $entry
     * @return request ID if successful
     *     false if it is not Mahara view
     */
    private function add_import_entry_request_view(SimpleXMLElement $entry) {
        $config = $this->get_mahara_view_entry_data($entry);
        if (!$config) {
            return false;
        }

        if ($published = strtotime((string)$entry->published)) {
            $config['ctime'] = $published;
        }
        if ($updated = strtotime((string)$entry->updated)) {
            $config['mtime'] = $updated;
        }

        return PluginImportLeap::add_import_entry_request($this->get('importertransport')->get('importid'), (string)$entry->id, self::STRATEGY_IMPORT_AS_VIEW, 'core', array(
            'owner'   => $config['owner'],
            'type'    => 'view',
            'title'   => $config['title'],
            'content' => $config
        ));
    }

1460
1461
    /**
     * Given the view config that we have built from the export, rewrite all
1462
1463
1464
1465
1466
     * the entry references in the artefactid field of blockinstance config
     * and call PluginBlocktype::import_rewrite_blockinstance_extra_config() to
     * rewrite extra config
     * For example, the 'Text' blocktype will rewrite the embedded image urls
     * which is stored in $blockinstance['config']['text']
1467
     */
1468
    private function rewrite_blockinstance_config($config) {
1469
1470
1471
1472
1473
        foreach ($config['rows'] as &$row) {
            foreach ($row['columns'] as &$column) {
                foreach ($column as &$blockinstance) {
                    if (isset($blockinstance['config']['artefactid'])) {
                        $artefactid = $blockinstance['config']['artefactid'];
1474
1475
                        if (isset($this->artefactids[$artefactid])) {
                            if (count($this->artefactids[$artefactid]) == 1) {
1476
                                $blockinstance['config']['artefactid'] = intval($this->artefactids[$artefactid][0]);
1477
1478
1479
1480
                            }
                            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]);
1481
                                unset($blockinstance['config']['artefactid']);
1482
1483
1484
1485
                            }
                        }
                        else {
                            $this->trace('WARNING: View config specified an artefact, but loadmapping does not say one was loaded for '. $artefactid);
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
                            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'][