lib.php 18.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/**
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
 * Copyright (C) 2006-2011 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
 *
 * 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 blocktype-openbadgedisplayer
 * @author     Discendum Oy
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2012 Discedum Oy http://discendum.com
 * @copyright  (C) 2011 Catalyst IT Ltd http://catalyst.net.nz
 *
 */


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

class PluginBlocktypeOpenbadgedisplayer extends SystemBlocktype {

    private static $source = null;

    public static function single_only() {
        return false;
    }

    public static function get_title() {
        return get_string('title', 'blocktype.openbadgedisplayer');
    }

    public static function get_description() {
        return get_string('description', 'blocktype.openbadgedisplayer');
    }

    public static function get_categories() {
        return array('external');
    }

52
    public static function get_css_icon($blocktypename) {
53
54
55
        return 'shield';
    }

56
57
58
59
60
61
62
63
    public static function get_viewtypes() {
        return array('portfolio', 'profile');
    }

    public static function get_backpack_source() {
        if (is_null(self::$source)) {
            $source = get_config('openbadgedisplayer_source');

64
65
66
67
68
            if (!empty($source)) {
                $source = (array) $source;
            }
            else {
                return false;
69
70
71
72
73
74
75
76
77
78
            }

            self::$source = $source;
        }

        return self::$source;
    }

    public static function render_instance(BlockInstance $instance, $editing=false) {
        $configdata = $instance->get('configdata');
79
        if (empty($configdata) || !isset($configdata['badgegroup']) || !get_config('openbadgedisplayer_source')) {
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
            return;
        }

        $host = 'backpack';
        $badgegroups = $configdata['badgegroup'];
        $html = '';

        // Support the legacy format (a string, not an array).
        if (is_string($badgegroups)) {
            $badgegroups = array($badgegroups);
        }

        if ($editing) {
            $items = array();

95
96
97
98
99
100
101
102
            foreach ($badgegroups as $selectedbadgegroup) {
                list($host, $uid, $selectedgroupid) = explode(':', $selectedbadgegroup);

                $allbadgegroups = self::get_badgegroupnames($host, $uid);
                if (!empty($allbadgegroups)) {
                    foreach ($allbadgegroups as $badgegroupid => $name) {
                        if ((int) $selectedgroupid === (int) $badgegroupid) {
                            $items[] = $name;
103
104
105
106
107
108
109
110
                        }
                    }
                }
            }

            if (count($items) > 0) {
                $html .= '<ul>' . implode('', array_map(function ($item) { return "<li>{$item}</li>"; }, $items)) . '</ul>';
            }
111
112
113
            else {
                $html .= get_string('nobadgegroups', 'blocktype.openbadgedisplayer');
            }
114
115
116
117
118

            return $html;
        }
        else {
            $smarty = smarty_core();
119
120
            $smarty->left_delimiter = '{{';
            $smarty->right_delimiter = '}}';
121
            $smarty->assign('id', $instance->get('id'));
122
            $smarty->assign('badgehtml', self::get_badges_html($badgegroups));
123
124
125
126
127
128
129

            $html = $smarty->fetch('blocktype:openbadgedisplayer:openbadgedisplayer.tpl');
        }

        return $html;
    }

130
131
132
133
134
135
136
137
138
139
    /**
     * Returns html code for badge in a group
     * @param string $group in format <host>:<uid>:<badgegroupid>
     * @param bool $fromcache if true the info will be fetched from database first
     * @return string HTML code
     */
    private static function get_badge_html($group, $fromcache=false) {
        if (!isset($group) && !is_string($group)) {
            return '';
        }
140

141
        $parts = explode(':', $group);
142

143
144
145
        if (count($parts) < 3) {
            return '';
        }
146

147
148
149
150
151
152
153
154
155
156
157
158
        $host = $parts[0];
        $uid = $parts[1];
        $badgegroupid = $parts[2];

        // Try to get the badge html from database first
        // Get badge group html using uid (backpackid)
        if ($fromcache && $badgegroup = get_record_select('blocktype_openbadgedisplayer_data',
                'host = ? AND uid = ? AND badgegroupid = ? AND lastupdate > ?',
                array($host, $uid, $badgegroupid, db_format_timestamp(strtotime('-1 day'))),
                'html')) {
            if (isset($badgegroup->html)) {
                return $badgegroup->html;
159
            }
160
        }
161

162
163
        $html = '';
        $existing = array();
164

165
166
167
        $backpack_url = self::get_backpack_url($host);
        $url = $backpack_url . 'displayer/' . $uid . '/group/' . $badgegroupid . '.json';
        $res = mahara_http_request(array(CURLOPT_URL => $url));
168

169
170
171
        if ($res->info['http_code'] != 200) {
            return '';
        }
172

173
        $json = json_decode($res->data);
174

175
176
177
178
        if (isset($json->badges) && is_array($json->badges)) {

            foreach ($json->badges as $badge) {
                $b = $badge->assertion->badge;
179

180
181
182
183
                // TODO: Simple check for unique badges, improve me!
                if (array_key_exists($b->name, $existing) && strcmp($existing[$b->name], $b->description) === 0) {
                    continue;
                }
184

185
186
                if (self::assertion_has_expired($badge->assertion)) {
                    continue;
187
                }
188
189

                $html .= '<img '
190
191
192
                            . 'src="' . $b->image . '" '
                            . 'title="' . $b->name . '" '
                            . 'data-assertion="' . htmlentities(json_encode($badge->assertion)) . '" />';
193
194

                $existing[$b->name] = $b->description;
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
        // Caching badge info into database for better performance
        if ($fromcache) {
            ensure_record_exists('blocktype_openbadgedisplayer_data',
                (object) array(
                    'host' => $host,
                    'uid' => $uid,
                    'badgegroupid' => $badgegroupid,
                ),
                (object) array(
                    'host' => $host,
                    'uid' => $uid,
                    'badgegroupid' => $badgegroupid,
                    'html' => $html,
                    'lastupdate' => db_format_timestamp(time())
                )
            );
        }

        return $html;
    }

    private static function get_badges_html($groups) {
        $html = '';

        foreach ($groups as $group) {
            $html .= self::get_badge_html($group);
224
225
        }

226
227
228
        if (empty($html)) {
            $html = get_string('nobadgegroups', 'blocktype.openbadgedisplayer');
        }
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        return $html;
    }

    private static function assertion_has_expired($assertion) {
        if (!isset($assertion->expires)) {
            return false;
        }

        // Unix timestamp
        if (preg_match('/^[0-9]+$/', $assertion->expires)) {
            return ($assertion->expires * 1000) < time();
        }

        // Formatted date
        return strtotime($assertion->expires) < time();
    }

    public static function has_instance_config() {
        return true;
    }

250
    public static function instance_config_form(BlockInstance $instance) {
251
252
253
        global $USER;

        $sources = self::get_backpack_source();
254
255
256
257
258
259
260
261
262
263
264
        if ($sources === false) {
            $fields = array(
                'message' => array(
                    'type' => 'html',
                    'class' => '',
                    'value' => '<div class="alert alert-warning" role="alert"><span class="icon icon-lg icon-exclamation-triangle left" aria-hidden="true" role="presentation"></span>' . get_string('missingbadgesources', 'blocktype.openbadgedisplayer') . '</div>'
                ),
            );
            return $fields;
        }

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
        $configdata = $instance->get('configdata');
        $addresses = get_column('artefact_internal_profile_email', 'email', 'owner', $USER->id, 'verified', 1);
        $current_values = array();

        if (isset($configdata['badgegroup'])) {
            $current_values = $configdata['badgegroup'];

            // Support the legacy format (a string, not an array).
            if (is_string($current_values)) {
                $current_values = array($current_values);
            }

            foreach ($current_values as &$current_value) {
                if (substr_count($current_value, ':') == 1) {
                    // Legacy value, prepend host
                    $current_value = 'backpack:' . $current_value;
                }
            }
        }

        $sourcelinks = array();

        foreach ($sources as $source => $url) {
            if (!empty($url)) {
                $title = get_string('title_' . $source, 'blocktype.openbadgedisplayer');
290
                $sourcelinks[] = '<a href="' . $url . '">' . $title . '</a>';
291
292
293
294
295
296
297
298
299
300
301
302
            }
        }

        $fields = array(
            'message' => array(
                'type' => 'html',
                'class' => '',
                'value' => '<p class="message">'. get_string('confighelp', 'blocktype.openbadgedisplayer', implode(', ', $sourcelinks)) .'</p>'
            ),
            'badgegroups' => array(
                'type' => 'container',
                'class' => '',
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
                'elements' => array(
                    'loadinginfo' => array(
                        'type' => 'html',
                        'class' => '',
                        'value' => '<p class="loading-box alert alert-info">'. get_string('fetchingbadges', 'blocktype.openbadgedisplayer') .'</p>' .
                                    '<div></div>',
                    ),
                    'hosts' => array(
                        'type' => 'hidden',
                        'value' => json_encode(array_keys($sources)),
                    ),
                    'emails' => array(
                        'type' => 'hidden',
                        'value' => json_encode($addresses),
                    ),
                    'selectedbadgegroups' => array(
                        'type' => 'hidden',
                        'value' => json_encode($current_values),
                    ),
                )
323
324
325
326
327
328
            )
        );

        return $fields;
    }

329
330
331
332
    public static function get_instance_config_javascript(BlockInstance $instance) {
        return array(
            'js/configform.js',
        );
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    }

    private static function get_form_fields($host, $addresses) {
        if ( ! $host) {
            return array();
        }

        $backpackid = array();
        foreach ($addresses AS $email) {
            $backpackid[] = self::get_backpack_id($host, $email);
        }
        $backpackid = array_filter($backpackid);

        $opt = array();
        foreach ($backpackid AS $uid) {
            $opt += self::get_group_opt($host, $uid);
        }

        return $opt;

    }


356
357
    public static function get_backpack_id($host, $email) {
        static $backpackids = array();
358
359
        $backpack_url = self::get_backpack_url($host);

360
361
362
363
        if (isset($backpackids[$host][$email])) {
            return $backpackids[$host][$email];
        }

364
365
366
367
368
369
370
371
372
373
        if ($backpack_url !== false) {
            $res = mahara_http_request(
                array(
                    CURLOPT_URL        => $backpack_url . 'displayer/convert/email',
                    CURLOPT_POST       => 1,
                    CURLOPT_POSTFIELDS => 'email=' . urlencode($email)
                )
            );
            $res = json_decode($res->data);
            if (isset($res->userId)) {
374
                $backpackids[$host][$email] = $res->userId;
375
376
377
378
379
380
                return $res->userId;
            }
        }
        return null;
    }

381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
    /**
     * Returns all backpack IDs of current logged-in user
     *
     * @return array of backpack IDs:
     *      array(
     *          <host> => array (
     *              <email> => <backpackid>
     *          )
     *      )
     */
    public static function get_user_backpack_ids() {
        global $USER;

        if (!$USER->is_logged_in()) {
            return array();
        }

        $sources = self::get_backpack_source();
        $addresses = get_column('artefact_internal_profile_email', 'email', 'owner', $USER->get('id'), 'verified', 1);
        $userbackpackids = array();

        if (!empty($sources) && !empty($addresses)) {
            foreach ($sources as $h => $url) {
                $userbackpackids[$h] = array();
                foreach ($addresses as $e) {
                    $userbackpackids[$h][$e] = self::get_backpack_id($h, $e);
                }
            }
        }

        return $userbackpackids;
    }

    /**
     * Return name of badge groups for a given host and backpackid
     * @param $host
     * @param $uid backpack ID attached to an email on the host
     * @param $usedbcache if true, the badge groups will be fetched from database first
     * @return array
     *      <badgegroupid> => <badgegroupname>
     * )
     */
    public static function get_badgegroupnames($host, $uid, $usedbcache=false) {
        static $badgegroupnames = array();

        if (!isset($host) || !isset($uid)) {
            return array();
        }

        if (isset($badgegroupnames[$host][$uid])) {
            return $badgegroupnames[$host][$uid];
        }

        // Get badge group names using uid (backpackid) from database
        if ($usedbcache && $badgegroups = get_records_select_array('blocktype_openbadgedisplayer_data',
            'host = ? AND uid = ? AND lastupdate > ?', array($host, $uid, db_format_timestamp(strtotime('-1 day'))),
            '', 'badgegroupid, name')) {
            foreach ($badgegroups as $badgegroup) {
                $badgegroupnames[$host][$uid][$badgegroup->badgegroupid] = $badgegroup->name;
            }
            return $badgegroupnames[$host][$uid];
        }

        $badgegroupnames[$host][$uid] = array();
        $backpack_url = self::get_backpack_url($host);
        $res = mahara_http_request(array(CURLOPT_URL => $backpack_url . "displayer/{$uid}/groups.json"));
        $res = json_decode($res->data);

        if (!empty($res->groups)) {
            foreach ($res->groups AS $g) {
                if ($g->name == 'Public badges' && $g->groupId == 0) {
                    $name = get_string('obppublicbadges', 'blocktype.openbadgedisplayer');
                }
                else {
                    $name = hsc($g->name);
                }

                $name .= ' (' . get_string('nbadges', 'blocktype.openbadgedisplayer', $g->badges) . ')';
                $badgegroupnames[$host][$uid][$g->groupId] = $name;

                // Caching badge info into database for better performance
                ensure_record_exists('blocktype_openbadgedisplayer_data',
                    (object) array(
                        'host' => $host,
                        'uid' => $uid,
                        'badgegroupid' => $g->groupId,
                    ),
                    (object) array(
                        'host' => $host,
                        'uid' => $uid,
                        'badgegroupid' => $g->groupId,
                        'name' => $name,
                        'lastupdate' => db_format_timestamp(time())
                    )
                );
            }
        }
        return $badgegroupnames[$host][$uid];
    }
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514

    private static function get_group_opt($host, $uid) {
        $opt = array();
        $backpack_url = self::get_backpack_url($host);
        $res = mahara_http_request(array(CURLOPT_URL => $backpack_url . "displayer/{$uid}/groups.json"));
        $res = json_decode($res->data);

        if (!empty($res->groups)) {
            foreach ($res->groups AS $g) {
                if ($g->name == 'Public badges' && $g->groupId == 0) {
                    $name = get_string('obppublicbadges', 'blocktype.openbadgedisplayer');
                }
                else {
                    $name = hsc($g->name);
                }

                $name .= ' (' . get_string('nbadges', 'blocktype.openbadgedisplayer', $g->badges) . ')';
                $cb_id = $host . ':' . $uid . ':' . $g->groupId;
                $cb_name = self::_sanitize_name($cb_id);
                $opt[$cb_name] = array(
                    'type' => 'checkbox',
                    'title' => $name,
                    'value' => $cb_id
                );
            }
        }
        return $opt;
    }

    public static function get_backpack_url($host) {
        $sources = self::get_backpack_source();

        return isset($sources[$host]) ? $sources[$host] : false;
    }

515
    public static function _sanitize_name($name) {
516
517
518
519
520
521
522
523
        return preg_replace('/[^a-zA-Z0-9_]/', '_', $name);
    }

    public static function instance_config_save($values) {
        unset($values['message']);
        // Support old save format.
        $sources = array_keys(self::get_backpack_source());
        $values['badgegroup'] = array();
524
        $validbackpackids = self::get_user_backpack_ids();
525
526
527
528
529
530

        foreach ($sources as $source) {
            if (isset($values[$source])) {
                $values['badgegroup'] = array_merge($values['badgegroup'], $values[$source]);
                unset($values[$source]);
            }
531
532
533
534
535
536
537
538
539
540
541
542
            else if (isset($_POST[$source])) {
                $values['badgegroup'] = array_merge($values['badgegroup'], $_POST[$source]);
            }
        }
        // check that what has been entered is allowed
        if (!empty($values['badgegroup'])) {
            foreach ($values['badgegroup'] as $key => $badgegroup) {
                list($host, $uid, $group) = explode(':', $badgegroup);
                if (!isset($uid) || !in_array($uid, array_values($validbackpackids[$host]))) {
                    unset($values['badgegroup'][$key]);
                }
            }
543
544
545
546
547
548
549
550
551
552
553
554
        }
        return $values;
    }

    public static function default_copy_type() {
        return 'shallow';
    }

    public static function allowed_in_view(View $view) {
        return $view->get('owner') != null;
    }

555
    public static function get_instance_javascript(BlockInstance $bi) {
556
        return array('js/showdetails.js');
557
558
    }

559
560
561
562
    public static function should_ajaxify() {
        return true;
    }

563
}