lib.php 24.9 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 artefact-internal-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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 *
 */

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

/**
 * Implements LEAP2A import of profile related entries into Mahara
 *
 * For more information about LEAP profile importing, see:
 * http://wiki.mahara.org/Developer_Area/Import%2f%2fExport/LEAP_Import/Internal_Artefact_Plugin
 *
 * TODO:
 * - how do we want to handle potentially overwriting data?
 * - Address for person (leap:spatial) - our export might have to be modified 
 *   to output them in a more "correct" order for other systems
 * - Validate the values of profile fields coming in? Especially email
 *
 * - Refactor the bunches of duplicate code
 */
class LeapImportInternal extends LeapImportArtefactPlugin {

46
47
    private static $personcontentblank = null;

48
49
50
51
    /**
     * For grabbing entries representing profile data that can't be exported as 
     * persondata
     */
52
    const STRATEGY_IMPORT_AS_PROFILE_FIELD = 1;
53

54
55
56
57
58
    /**
     * Entries with common_item:Personalstatement are introductions
     */
    const STRATEGY_IMPORT_AS_INTRODUCTION = 2;

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    /**
     * Lookup table for some of the persondata fields.
     *
     * Info based on the table here:
     * http://wiki.cetis.ac.uk/2009-03/LEAP2A_personal_data#Persondata_fields
     *
     * The fields here that are not listed there are either not supported, or 
     * imported a different way by this plugin. For example, name related 
     * fields are handled by import_namedata().
     */
    private static $persondatafields = array(
        'country' => array(
            // TODO: we use leap:country inside leap:spatial, but should fall back to this
        ),
        'website' => array(
            'helper_method' => true,
        ),
        'id' => array(
            'helper_method' => true,
        ),
        'email' => array(
            // TODO: validation
81
            'helper_method' => true,
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        ),
        'homephone' => array(
            'mahara_fieldname' => 'homenumber',
        ),
        'workphone' => array(
            'mahara_fieldname' => 'businessnumber',
        ),
        'mobile' => array(
            'mahara_fieldname' => 'mobilenumber',
        ),
        'fax' => array(
            'mahara_fieldname' => 'faxnumber',
        ),
        'other' => array(
            'helper_method' => true,
        ),
    );

    /**
     * This list taken from 
     * http://wiki.cetis.ac.uk/2009-03/LEAP2A_personal_data#Service_abbreviations
     *
     * We are only including a list of the ones we can import, so some from the 
     * list will be missing
     */
    private static $services = array(
        array(
            'service' => 'icq',
            'uri'     => 'http://www.icq.com/',
            'artefact_type' => 'Icqnumber',
        ),
        array(
            'service' => 'msn',
            'uri'     => 'http://www.msn.com/',
            'artefact_type' => 'Msnnumber',
        ),
        array(
            'service' => 'aim',
            'uri'     => 'http://www.aim.com/',
            'artefact_type' => 'Aimscreenname',
        ),
        array(
            'service' => 'yahoo',
            'uri'     => 'http://www.yahoo.com/',
            'artefact_type' => 'Yahoochat',
        ),
        array(
            'service' => 'skype',
            'uri'     => 'http://www.skype.com/',
            'artefact_type' => 'Skypeusername',
        ),
        array(
            'service' => 'jabber',
            'uri'     => 'http://www.jabber.org/',
            'artefact_type' => 'Jabberusername',
        ),
    );

    /**
141
142
143
     * The profile importer tries to import raw profile fields using the 
     * strategy mechanism, but most of the useful profile information is stored 
     * in the person entry corresponding to the author.
144
145
146
     *
     * The persondata entry is not actually imported using a strategy, because 
     * we need to be able to import basic data from the <author> element if 
147
     * it's not present too. So all the person importing is handled in import_author_data()
148
     */
149
    public static function get_import_strategies_for_entry(SimpleXMLElement $entry, PluginImportLeap $importer) {
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        if (self::$personcontentblank === null) {
            self::$personcontentblank = true;
            if ($persondataid = $importer->get('persondataid')) {
                self::$personcontentblank = !(string)$importer->get_entry_by_id($persondataid)->content;
            }
        }

        $isentry = PluginImportLeap::is_rdf_type($entry, $importer, 'entry');

        if ($isentry && self::$personcontentblank
            && PluginImportLeap::is_correct_category_scheme($entry, $importer, 'common_item', 'Personalstatement')) {
            return array(array(
                'strategy' => self::STRATEGY_IMPORT_AS_INTRODUCTION,
                'score'    => 100,
                'other_required_entries' => array(),
            ));
        }
167

168
169
170
        // If it's a raw entry with the right mahara:plugin and mahara:type 
        // we should be able to import it
        $correctplugintype = count($entry->xpath('mahara:artefactplugin[@mahara:plugin="internal"]')) == 1;
171
172
        if ($isentry && $correctplugintype) {
            return array(array(
173
                'strategy' => self::STRATEGY_IMPORT_AS_PROFILE_FIELD,
174
175
                'score'    => 100,
                'other_required_entries' => array(),
176
            ));
177
178
        }

179
        return array();
180
181
    }

182
    public static function import_using_strategy(SimpleXMLElement $entry, PluginImportLeap $importer, $strategy, array $otherentries) {
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        $artefactmapping = array();
        switch ($strategy) {
        case self::STRATEGY_IMPORT_AS_PROFILE_FIELD:
            // Based on the mahara:type, we might be able to import it as 
            // something useful - otherwise, there is nothing we can do. The 
            // entry already claimed it was mahara:plugin="internal", so it's 
            // perfectly fine for us to not import it if we don't recognise it
            $types = array(
                'occupation',
                'industry',
            );
            $typexpath = join('" or @mahara:type="', $types);
            $artefactpluginelement = $entry->xpath('mahara:artefactplugin[@mahara:type="' . $typexpath . '"]');
            if (count($artefactpluginelement) == 1) {
                $artefactpluginelement = $artefactpluginelement[0];

199
                $maharaattributes = PluginImportLeap::get_attributes($artefactpluginelement, PluginImportLeap::NS_MAHARA);
200
                if (isset($maharaattributes['type']) && in_array($maharaattributes['type'], $types)) {
201
                    $artefactmapping[(string)$entry->id] = array(self::create_artefact($importer, $maharaattributes['type'], PluginImportLeap::get_entry_content($entry, $importer)));
202
203
204
                }
            }
            break;
205
206
207
208
209
210
        case self::STRATEGY_IMPORT_AS_INTRODUCTION:
            // The introduction comes from the entry content
            $introduction = new ArtefactTypeIntroduction(0, array('owner' => $importer->get('usr')));
            $introduction->set('title', PluginImportLeap::get_entry_content($entry, $importer));
            $introduction->commit();
            break;
211
212
213
214
215
216
217
        default:
            throw new ImportException($importer, 'TODO: get_string: unknown strategy chosen for importing entry');
        }
        return $artefactmapping;
    }

    /**
218
     * Import data about the feed author.
219
220
221
222
223
224
     *
     * If we have a persondata element for them, we can import lots of 
     * different information about them into Mahara's profile section. 
     * Otherwise, we can only import some very basic information from the 
     * <author> element.
     *
225
     * @param PluginImportLeap $importer The importer
226
227
     * @param string $persondataid       The ID of the person entry corresponding
     *                                   to the author, if there is one
228
     */
229
    public static function import_author_data(PluginImportLeap $importer, $persondataid) {
230
        if ($persondataid) {
231
            // Grab all the leap:persondata elements and import them
232
            $person = $importer->get_entry_by_id($persondataid);
233
234

            // The introduction comes from the entry content
235
236
237
238
239
            if (!self::$personcontentblank) {
                $introduction = new ArtefactTypeIntroduction(0, array('owner' => $importer->get('usr')));
                $introduction->set('title', PluginImportLeap::get_entry_content($person, $importer));
                $introduction->commit();
            }
240
241
242
243

            // Most of the rest of the profile data comes from leap:persondata elements
            $persondata = $person->xpath('leap:persondata');
            foreach ($persondata as $item) {
244
                $leapattributes = PluginImportLeap::get_attributes($item, PluginImportLeap::NS_LEAP);
245

246
247
248
249
                if (isset($leapattributes['field'])) {
                    self::import_persondata($importer, $item, $leapattributes);
                }
                else {
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
                    // 'Field' is required
                    // http://wiki.cetis.ac.uk/2009-03/LEAP2A_personal_data#field
                    $importer->trace('WARNING: persondata element did not have leap:field attribute');
                    continue;
                }
            }

            // The information about someone's name is much more comprehensive 
            // in LEAP than what Mahara has, so we have to piece it together
            self::import_namedata($importer, $persondata);

            // People can have address info associated with them
            $addressdata = $person->xpath('leap:spatial');
            if (count($addressdata) == 1) {
                self::import_addressdata($importer, $addressdata[0]);
            }
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

            // Set default profile icon. We look at rel="related" links on this 
            // element, and take the first one that we turned into a profile 
            // icon to be the default. In future versions of the spec, we may use
            // a "depicts" type relationship to explicitly identify them.
            foreach ($person->link as $link) {
                if ($importer->curie_equals($link['rel'], '', 'related') && isset($link['href'])) {
                    $artefactids = $importer->get_artefactids_imported_by_entryid((string)$link['href']);
                    if (count($artefactids) == 1 && $potentialicon = artefact_instance_from_id($artefactids[0])) {
                        if ($potentialicon->get('artefacttype') == 'profileicon') {
                            $importer->get('usrobj')->profileicon = $potentialicon->get('id');
                            $importer->get('usrobj')->commit();
                            // The first one we find in the export is the profile icon
                            break;
                        }
                    }
                }
            }
284
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
        }
        else {
            $author = $importer->get('xml')->xpath('//a:feed/a:author[1]');
            $author = $author[0];

            if (!isset($author->name)) {
                throw new ImportException($importer, 'TODO: get_string: <author> must include <name> - http://wiki.cetis.ac.uk/2009-03/LEAP2A_relationships#Author');
            }

            $name = (string)$author->name;
            if (false !== strpos($name, ' ')) {
                list($firstname, $lastname) = explode(' ', $name, 2);
                self::create_artefact($importer, 'firstname', trim($firstname));
                self::create_artefact($importer, 'lastname', trim($lastname));
            }
            else {
                // Blatant assumtion that the <name> is a first name
                self::create_artefact($importer, 'firstname', trim($name));
            }

            if (isset($author->email)) {
                self::create_artefact($importer, 'email', (string)$author->email);
            }

            if (isset($author->uri)) {
                $uri = (string)$author->uri;
                if (preg_match('#^https?://#', $uri)) {
                    self::create_artefact($importer, 'officialwebsite', (string)$author->uri);
                }
            }
        }
    }

    /**
     * Attempts to import a persondata element
     */
320
    private static function import_persondata(PluginImportLeap $importer, SimpleXMLElement $item, array $leapattributes) {
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
        $field = $leapattributes['field'];

        if (isset(self::$persondatafields[$field]['mahara_fieldname'])) {
            // Basic case - imports straight into a Mahara field. Mahara only 
            // allows you to keep one of each of these values, so we throw away 
            // any more if they're seen, on the assumption that they are 
            // ordered from most to least important: 
            // http://wiki.cetis.ac.uk/2009-03/LEAP2A_personal_data#Ordering
            static $seen = array();
            if (isset($seen[$field])) {
                return;
            }
            $seen[$field] = true;

            self::create_artefact($importer, self::$persondatafields[$field]['mahara_fieldname'], (string)$item);
            return;
        }

        if (!empty(self::$persondatafields[$field]['helper_method'])) {
            $method = 'import_persondata_' . $field;
            self::$method($importer, $item, $leapattributes);
        }
    }

    /**
     * Attempts to import a persondata field with leap:field="id"
     */
348
    private static function import_persondata_id(PluginImportLeap $importer, SimpleXMLElement $item, array $leapattributes) {
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
        if ($leapattributes['field'] == 'id' && !isset($leapattributes['service'])) {
            // 'id' must have a service set
            // http://wiki.cetis.ac.uk/2009-03/LEAP2A_personal_data#service
            throw new ImportException($importer, "TODO: get_string: persondata field was 'id' but had no service set");
        }

        // Lack of 'grep' and closures is annoying...
        foreach (self::$services as $service) {
            if ($service['service'] == $leapattributes['service'] || $service['uri']  == $leapattributes['service']) {
                self::create_artefact($importer, $service['artefact_type'], (string)$item);
                return;
            }
        }

        // TODO what do we do here?
        $importer->trace(" * Unrecognised service $attributes[service], ignored");
    }

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    /**
     * Attempts to import a persondata field with leap:field="email"
     */
    private static function import_persondata_email(PluginImportLeap $importer, SimpleXMLElement $item, array $leapattributes) {
        static $firstdone = false;
        static $seen = array();

        if (count($seen) >= 5) {
            $importer->trace("WARNING: users cannot have more than 5 e-mail addresses");
            return;
        }

        $email = (string)$item;

        if (!in_array($email, $seen)) {
            $id = self::create_artefact($importer, 'email', $email);
            if (!$firstdone) {
                update_record('artefact_internal_profile_email', (object)array(
                    'principal' => 1,
                ), (object)array(
                    'artefact'  => $id,
                ));
                $importer->get('usrobj')->email = $email;
                $importer->get('usrobj')->commit();
                $firstdone = true;
            }
        }
        else {
            $importer->trace("WARNING: export file had the same e-mail address listed more than once ($email)");
        }
    }

399
400
401
    /**
     * Attempts to import a persondata field with leap:field="website"
     */
402
    private static function import_persondata_website(PluginImportLeap $importer, SimpleXMLEntry $item, array $leapattributes) {
403
404
405
        // We've been given a 'website' field, but Mahara has three profile 
        // fields for website. So we need to examine it deeper to establish 
        // which field it should import into
406
        $maharaattributes = PluginImportLeap::get_attributes($item, PluginImportLeap::NS_MAHARA);
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433

        if (isset($maharaattributes['artefactplugin'])
            && isset($maharaattributes['artefacttype'])
            && $maharaattributes['artefactplugin'] == 'internal') {
            switch ($maharaattributes['artefacttype']) {
            case 'blogaddress':
            case 'personalwebsite':
            case 'officialwebsite':
                self::create_artefact($importer, $maharaattributes['artefacttype'], (string)$item);
                return;
            }
        }

        // No mahara: namespaced attributes to help us :(
        // For now, just import as officialwebsite. Later, we might import into 
        // the other fields as well based on the order we encounter them in the 
        // import file
        static $seen = false;
        if (!$seen) {
            $seen = true;
            self::create_artefact($importer, 'officialwebsite', (string)$item);
        }
    }

    /**
     * Attempts to import a persondata field with leap:field="other"
     */
434
    private static function import_persondata_other(PluginImportLeap $importer, SimpleXMLEntry $item, array $leapattributes) {
435
436
        // The only 'other' field we can actually import is one we recognise as 
        // 'student ID'
437
        $maharaattributes = PluginImportLeap::get_attributes($item, PluginImportLeap::NS_MAHARA);
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455

        if (isset($maharaattributes['artefactplugin'])
            && isset($maharaattributes['artefacttype'])
            && $maharaattributes['artefactplugin'] == 'internal') {
            switch ($maharaattributes['artefacttype']) {
            case 'studentid':
                self::create_artefact($importer, $maharaattributes['artefacttype'], (string)$item);
                return;
            }
        }

        $importer->trace("NOTICE: skipped persondata 'other' field");
    }

    /**
     * Imports info from a leap:spatial element as a user's address-related 
     * profile fields
     */
456
    private static function import_addressdata(PluginImportLeap $importer, SimpleXMLElement $addressdata) {
457
458
459
460
461
462
463
464
465
        // TODO: this xpath doesn't respect the namespace prefix - we should 
        // look it up from $importer->namespaces[NS_LEAP]
        $addresslines = $addressdata->xpath('leap:addressline');

        // We look for 'town' and 'city' deliberately, Mahara has 
        // separate fields for those. The rest get thrown in the 
        // 'address' field
        $personaddress = '';
        foreach ($addresslines as $addressline) {
466
            $maharaattributes = PluginImportLeap::get_attributes($addressline, PluginImportLeap::NS_MAHARA);
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489

            if (isset($maharaattributes['artefacttype'])) {
                switch ($maharaattributes['artefacttype']) {
                case 'address':
                case 'town':
                case 'city':
                    self::create_artefact($importer, $maharaattributes['artefacttype'], (string)$addressline);
                }
            }
            else {
                $personaddress .= (string)$addressline . "\n";
            }
        }

        if ($personaddress != '') {
            self::create_artefact($importer, 'address', substr($personaddress, 0, -1));
        }

        // Now deal with country
        $country = $addressdata->xpath('leap:country');

        if (count($country) == 1) {
            $country = $country[0];
490
            $leapattributes = PluginImportLeap::get_attributes($country, PluginImportLeap::NS_LEAP);
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509

            // Try using countrycode attribute first, but fall back to name if it's not present or 
            // doesn't represent a country
            require_once('country.php');
            $countrycode = null;
            if (isset($leapattributes['countrycode'])) {
                $countrycode = Country::iso3166_alpha3_to_iso3166_alpha2($leapattributes['countrycode']);
            }

            if (!$countrycode) {
                $countrycode = Country::countryname_to_iso3166_alpha2((string)$country);
            }

            if ($countrycode) {
                self::create_artefact($importer, 'country', $countrycode);
            }
        }
    }

510
    private static function import_namedata(PluginImportLeap $importer, array $persondata) {
511
512
513
514
515
516
517
518
519
520
521
522
        $namefields = array(
            'full_name' => false,
            'legal_family_name' => false,
            'legal_given_name' => false,
            'preferred_family_name' => false,
            'preferred_given_name' => false,
            'family_name_first' => false,
            'name_prefix' => false,
            'name_suffix' => false,
        );

        foreach ($persondata as $item) {
523
            $leapattributes = PluginImportLeap::get_attributes($item, PluginImportLeap::NS_LEAP);
524
525
526
527
528
529
530
531
532
533
            if (isset($leapattributes['field'])) {
                if (in_array($leapattributes['field'], array_keys($namefields))) {
                    // legal_given_name is allowed to occur any number of times
                    if ($leapattributes['field'] == 'legal_given_name'
                        && $namefields['legal_given_name'] != '') {
                        $namefields['legal_given_name'] .= ' ' . (string)$item;
                    }
                    else {
                        $namefields[$leapattributes['field']] = (string)$item;
                    }
534
535
                }
            }
536
537
538
539
540
541
            else {
                // 'Field' is required
                // http://wiki.cetis.ac.uk/2009-03/LEAP2A_personal_data#field
                $importer->trace('WARNING: persondata element did not have leap:field attribute');
                continue;
            }
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
        }

        $familynamefirst = $namefields['family_name_first'] == 'yes' ? true : false;

        // Try to guess reasonable values for first/last names if they're not set
        if ($namefields['legal_given_name'] === false && $namefields['preferred_given_name'] !== false) {
            $namefields['legal_given_name'] = $namefields['preferred_given_name'];
        }
        if ($namefields['legal_family_name'] === false && $namefields['preferred_family_name'] !== false) {
            $namefields['legal_family_name'] = $namefields['preferred_family_name'];
        }

        // This is _an_ algorithm for parsing this info, I'm not saying it's the _best_ one ;)
        if ($familynamefirst) {
            $firstname = (string)$namefields['legal_given_name'] . ' ' . (string)$namefields['name_suffix'];
            $lastname  = (string)$namefields['name_prefix'] . (string)$namefields['legal_family_name'];
            $preferredname = (string)$namefields['preferred_family_name'] . ' ' . (string)$namefields['preferred_given_name'];
        }
        else {
            $firstname = (string)$namefields['name_prefix'] . ' ' . (string)$namefields['legal_given_name'];
            $lastname  = (string)$namefields['legal_family_name'] . ' ' . (string)$namefields['name_suffix'];
            $preferredname = (string)$namefields['preferred_given_name'] . ' ' . (string)$namefields['preferred_family_name'];
        }
        $firstname = trim($firstname);
        $lastname  = trim($lastname);
        $preferredname = trim($preferredname);

        self::create_artefact($importer, 'firstname', $firstname);
        self::create_artefact($importer, 'lastname', $lastname);
        self::create_artefact($importer, 'preferredname', $preferredname);
572
573
574
575
        $importer->get('usrobj')->firstname = $firstname;
        $importer->get('usrobj')->lastname = $lastname;
        $importer->get('usrobj')->preferredname = $preferredname;
        $importer->get('usrobj')->commit();
576
577
578
579
580
581
    }

    /**
     * Creates an artefact in the manner required to overwrite existing profile 
     * artefacts
     *
582
583
584
585
     * @param PluginImportLeap $importer The importer
     * @param string $artefacttype        The type of artefact to create
     * @param string $title               The title for the artefact (with profile 
     *                                    fields, this is the main data)
586
587
     * @return int The ID of the artefact created
     */
588
    private static function create_artefact(PluginImportLeap $importer, $artefacttype, $title) {
589
        $classname = generate_artefact_class_name($artefacttype);
590
591
592
593
594
595
596
597
598
        $artefact = new $classname(0, array('owner' => $importer->get('usr')));
        $artefact->set('title', $title);
        $artefact->commit();
        return $artefact->get('id');
    }

}

?>