lib.php 16.6 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
141
142
143
144
145
146
147
148
149
150
151
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
255
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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
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
<?php
/**
 *
 * @package    mahara
 * @subpackage blocktype-courses
 * @author     Catalyst IT
 * @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.
 *
 */

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

class PluginBlocktypeCourseinfo extends MaharaCoreBlocktype {

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

    public static function get_instance_title(BlockInstance $instance) {
        $ownerid = $instance->get_view()->get('owner');
        if ($ownerid) {
            return get_string('blocktitleforowner', 'blocktype.courseinfo', display_name($ownerid, null, true));
        }
        return get_string('title', 'blocktype.courseinfo');
    }

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

    public static function single_only() {
        return true;
    }

    public static function get_categories() {
        return array('general' => 16500);
    }

    public static function get_viewtypes() {
        return array('portfolio');
    }

    public static function get_css_icon($blocktypename) {
        return 'book-reader';
    }

    private static function check_connection_for_user($id) {
        $user = new stdClass();
        $user->id = $id;
        if ($connections = Plugin::get_webservice_connections($user, 'fetch_userid')) {
            return true;
        }
        return false;
    }

    public static function render_instance(BlockInstance $instance, $editing=false, $versioning=false) {
        global $exporter;
        $owner = $instance->get_view()->get('owner');
        $configdata = $instance->get('configdata');
        $smarty = smarty_core();
        if (!array_key_exists('userid', $configdata) && !$owner) {
            // We are just displaying the default message as the page is not owned by a user
            $smarty->assign('message', get_string('placeholdermessage','blocktype.courseinfo'));
        }
        else if (!array_key_exists('userid', $configdata) && $owner) {
            if ($editing) {
                if (self::check_connection_for_user($owner)) {
                    // We display the complete configuration message if we are page owner
                    $smarty->assign('message', get_string('completeconfiguration', 'blocktype.courseinfo'));
                }
                else {
                    $smarty->assign('message', get_string('completeconfigurationnotpossible', 'blocktype.courseinfo'));
                }
            }
            else {
                $smarty->assign('message', get_string('nocourses','blocktype.courseinfo'));
            }
        }
        else if (is_null($configdata['userid'])) {
            // Unable to find external user related to page owner
            if ($editing) {
                if (self::check_connection_for_user($owner)) {
                    $smarty->assign('message', get_string('unabletofetchdata','blocktype.courseinfo'));
                }
                else {
                    $smarty->assign('message', get_string('completeconfigurationnotpossible','blocktype.courseinfo'));
                }
            }
            else {
                $smarty->assign('message', get_string('nocourses','blocktype.courseinfo'));
            }
        }
        else {
            $configdata['ownerid'] = $owner;
            if ($exporter) {
                $courses = self::get_data($configdata, 0, 0);
            }
            else {
                $courses = self::get_data($configdata, 0, 10);
            }
            $template = 'blocktype:courseinfo:courserows.tpl';
            $blockid = $instance->get('id');
            if ($exporter) {
                $pagination = false;
            }
            else {
                $baseurl = $instance->get_view()->get_url();
                $baseurl .= ((false === strpos($baseurl, '?')) ? '?' : '&') . 'block=' . $blockid;
                $pagination = array(
                    'baseurl'    => $baseurl,
                    'id'         => 'block' . $blockid . '_pagination',
                    'datatable'  => 'coursedata_' . $blockid,
                    'jsonscript' => 'blocktype/courseinfo/courses.json.php',
                );
            }
            $configdata['block'] = $blockid;
            self::render_courses($courses, $template, $configdata, $pagination, $editing, $versioning);
            $smarty->assign('blockid', $instance->get('id'));
            $from = !empty($configdata['from']) ? format_date($configdata['from'], 'strftimedate') : null;
            $to = !empty($configdata['to']) ? format_date($configdata['to'], 'strftimedate') : null;
            if ($from && $to) {
                $resultstr = get_string('coursesresultsfromto', 'blocktype.courseinfo', $from, $to);
            }
            else if ($from && !$to) {
                $resultstr = get_string('coursesresultsfrom', 'blocktype.courseinfo', $from);
            }
            else if (!$from && $to) {
                $resultstr = get_string('coursesresultsto', 'blocktype.courseinfo', $to);
            }
            else {
                $resultstr = '';
            }
            $smarty->assign('resultstr', $resultstr);
            $smarty->assign('course', $courses);
        }
        return $smarty->fetch('blocktype:courseinfo:courseinfo.tpl');
    }

    public static function has_instance_config() {
        return true;
    }

    public static function postinst($prevversion) {
        if ($prevversion == 0) {
            // do we need any post install stuff?
        }
    }

    public static function instance_config_form(BlockInstance $instance) {
        require_once('pieforms/pieform/elements/calendar.php');
        $configdata = $instance->get('configdata');
        $from = !empty($configdata['from']) ? $configdata['from'] : false;
        $to = !empty($configdata['to']) ? $configdata['to'] : false;
        $elements = array(
            'from' => array(
                'type'  => 'calendar',
                'title' => get_string('fromdate', 'blocktype.courseinfo'),
                'description' => get_string('fromdatedescription', 'blocktype.courseinfo', pieform_element_calendar_human_readable_dateformat()),
                'defaultvalue' => $from,
                'caloptions' => array(
                    'showsTime' => false,
                ),
            ),
            'to' => array(
                'type'  => 'calendar',
                'title' => get_string('todate', 'blocktype.courseinfo'),
                'description' => get_string('todatedescription', 'blocktype.courseinfo', pieform_element_calendar_human_readable_dateformat()),
                'defaultvalue' => $to,
                'caloptions' => array(
                    'showsTime' => false,
                ),
            )
        );
        $ownerid = $instance->get_view()->get('owner');
        if ($ownerid && !empty($configdata['userid'])) {
            $elements['externaluser'] = array('type' => 'html',
                                              'title' => get_string('externaluserid', 'blocktype.courseinfo'),
                                              'value' => $configdata['userid'],
                                              'class' => 'htmldescription');
        }

        return $elements;
    }

    public static function instance_config_validate(Pieform $form, $values) {
        $viewid = $form->get_element_option('id', 'value');
        $view = new View($viewid);
        if (!empty($values['from']) && !empty($values['to']) && $values['from'] > $values['to']) {
            $form->set_error('from', get_string('dateoutofsync', 'blocktype.courseinfo'));
        }
    }

    public static function instance_config_save($values, BlockInstance $instance) {
        $ownerid = $instance->get_view()->get('owner');
        if ($ownerid) {
            $username = get_field_sql("SELECT email FROM {artefact_internal_profile_email} WHERE owner = ? AND principal = ?", array($ownerid, 1)); // Check on primary email address
            $owner = new stdClass();
            $owner->id = $ownerid;
            $configdata['username'] = $username;
            if ($connections = Plugin::get_webservice_connections($owner, 'fetch_userid')) {
                foreach ($connections as $connection) {
                    $result = call_static_method($connection->connection->class, 'fetch_userid', $connection, $owner, $configdata);
                    $values['userid'] = $result;
                }
            }
        }
        return $values;
    }

    public static function has_config_info() {
        return true;
    }

    public static function get_config_info() {
        return array('header' => self::get_title(),
                     'body' => get_string('plugininfo', 'blocktype.courseinfo'));
    }

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

    public static function get_data($configdata, $offset=0, $limit=10) {
        $owner = new stdClass();
        $owner->id = $configdata['ownerid'];
        $content = false;
        $total = 0;
        if ($connections = Plugin::get_webservice_connections($owner, 'fetch_coursecompletion')) {
            foreach ($connections as $connection) {
                $content = call_static_method($connection->connection->class, 'fetch_coursecompletion', $connection, $owner, $configdata);
            }
        }

        $results = array();
        if ($content) {
            $total = count($content['courses']);
            foreach ($content['courses'] as $k => $course) {
                $data = new StdClass();
                $data->title = $course['name'];
                $data->rawdate = $course['completiondate'];
                $data->date = format_date($course['completiondate'], 'strftimedate');
                $data->courselength = floatval($course['courselength']) > 0 ? $course['courselength'] : '-';
                $data->hours = floatval($course['courselength']);
                $data->category = $course['coursecategory'];
                $data->cpdhours_display = floatval($course['cpdhours']) > 0 ? $course['cpdhours'] : '-';
                $data->cpdhours = floatval($course['cpdhours']);
                $data->type = $course['coursetype'];
                $data->historical = $course['historical'];
                $data->organisation = $course['courseorganisation'];
                $data->id = $course['courseid'];
                $data->uniqueid = $data->id . '_' . $data->rawdate;
                $results[] = $data;
            }
        }
        // Sort by latest course first
        usort($results, function ($a, $b) {
            if ($a->rawdate == $b->rawdate) { return 0; }
            if ($a->rawdate < $b->rawdate) { return 1; }
            if ($a->rawdate > $b->rawdate) { return -1; }
        });
        // calculate grand total of hours spent
        $grandtotalhours = 0;
        if (!empty($results)) {
            foreach ($results as $result) {
                $grandtotalhours = $grandtotalhours + $result->cpdhours;
            }
        }
        if ($limit > 0) {
            $results = array_slice($results, $offset, $limit);
        }
        $result = array(
            'grandtotalhours' => $grandtotalhours,
            'count'           => $total,
            'data'            => $results,
            'offset'          => $offset,
            'limit'           => $limit,
            'id'              => 'course',
        );
        return $result;
    }

    public static function render_courses(&$courses, $template, $options, $pagination, $editing = false, $versioning = false) {
        $smarty = smarty_core();
        $smarty->assign('courses', $courses);
        $smarty->assign('options', $options);
        $smarty->assign('block', (!empty($options['block']) ? $options['block'] : null));
        $smarty->assign('versioning', $versioning);
        $courses['tablerows'] = $smarty->fetch($template);
        if ($courses['limit'] && $pagination) {
            $pagination = build_pagination(array(
                'id'                      => $pagination['id'],
                'class'                   => 'center',
                'datatable'               => $pagination['datatable'],
                'url'                     => $pagination['baseurl'],
                'jsonscript'              => $pagination['jsonscript'],
                'count'                   => $courses['count'],
                'limit'                   => $courses['limit'],
                'offset'                  => $courses['offset'],
                'numbersincludefirstlast' => false,
                'resultcounttextsingular' => get_string('course', 'blocktype.courseinfo'),
                'resultcounttextplural'   => get_string('courses', 'blocktype.courseinfo'),
            ));
            $courses['pagination']    = $pagination['html'];
            $courses['pagination_js'] = $pagination['javascript'];
        }
    }

    public static function define_webservice_connections() {
        return array(
            array(
                'connection' => 'courseinfo',
                'name' => get_string('title', 'blocktype.courseinfo'),
                'notes' => get_string('description', 'blocktype.courseinfo'),
                'version' => '1.0',
                'type' => WEBSERVICE_TYPE_REST,
                'isfatal' => false,
                'config_fields' => array(
                    'userid_function' => array(
                        'type' => 'text',
                        'title' => get_string('userid_function_title', 'blocktype.courseinfo'),
                    ),
                    'coursecompletion_function' => array(
                        'type' => 'text',
                        'title' => get_string('coursecompletion_function_title', 'blocktype.courseinfo'),
                    ),
                ),
            ),
        );
    }

    public static function fetch_coursecompletion($connection, $user, $configdata) {
        $data = array('userid' => $configdata['userid']);
        if (!empty($configdata['from'])) {
            $data['datefrom'] = $configdata['from'];
        }
        if (!empty($configdata['to'])) {
            $data['dateto'] = $configdata['to'];
        }
        // check if we have any valid connection objects
        if ($function = get_field('client_connections_config', 'value', 'field', 'coursecompletion_function', 'connection', $connection->connection->id)) {
            $results = self::test_connection($connection, $user, $data, $function);
            if ($results['error'] === false && !empty($results['results']) && is_array($results['results'])) {
                return $results['results'];
            }
        }
        return false;
    }

    public static function fetch_userid($connection, $user, $configdata) {
        $data = array('field' => 'email',
                      'values' => array($configdata['username']));
        // check if we have any valid connection objects
        if ($function = get_field('client_connections_config', 'value', 'field', 'userid_function', 'connection', $connection->connection->id)) {
            $results = self::test_connection($connection, $user, $data, $function);
            if ($results['error'] === false && !empty($results['results']) && is_array($results['results'])) {
                return $results['results'][0]['id'];
            }
        }
        return null;
    }

    private function test_connection($connection, $user, $data, $functionname) {
        if (empty($connection)) {
            return array('error' => true,
                         'errormsg' => get_string('novalidconnections', 'blocktype.courseinfo'));
        }

        if ($connection->connection->type != 'rest' || ($connection->connection->authtype == 'rest' && $connection->connection->authtype != 'token')) {
            return array('error' => true,
                         'errormsg' => get_string('novalidconnectionauthtype', 'blocktype.courseinfo'));
        }
        try {
            $results = $connection->call($functionname, $data, 'GET');
            if (isset($results['errorcode'])) {
                return array('error' => true,
                             'errormsg' => get_string('connectionresultsinvalid', 'blocktype.courseinfo'),
                             'results' => $results,
                             );
            }
            else {
                return array('error' => false,
                             'results' => $results);
            }
        }
        catch (Exception $e) {
            return array('error' => true,
                         'errormsg' => get_string('novalidconnectionauthtype', 'blocktype.courseinfo') . ' - ' . $e->getMessage());
        }
    }
}