user.php 127 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @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.
Penny Leach's avatar
Penny Leach committed
9
10
11
12
13
 *
 */

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

14
15
define('MAX_USERNAME_DISPLAY', 30);

16
17
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/Exception.php';
18
require 'phpmailer/src/SMTP.php';
19
20
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as phpmailerException;
21
use PHPMailer\PHPMailer\SMTP;
Aaron Wells's avatar
Aaron Wells committed
22
/**
Penny Leach's avatar
Penny Leach committed
23
24
 * loads up activity preferences for a given user
 *
Aaron Wells's avatar
Aaron Wells committed
25
 * @param int $userid to load preferences for
Penny Leach's avatar
Penny Leach committed
26
27
28
29
30
31
32
 * @todo caching
 */
function load_activity_preferences($userid) {
    $prefs = array();
    if (empty($userid)) {
        throw new InvalidArgumentException("couldn't load activity preferences, no user id specified");
    }
Richard Mansfield's avatar
Richard Mansfield committed
33
    if ($prefs = get_records_assoc('usr_activity_preference', 'usr', $userid, '', 'activity,method')) {
Penny Leach's avatar
Penny Leach committed
34
        foreach ($prefs as $p) {
35
            $prefs[$p->activity] = $p->method;
Penny Leach's avatar
Penny Leach committed
36
37
38
39
40
        }
    }
    return $prefs;
}

Aaron Wells's avatar
Aaron Wells committed
41
/**
Penny Leach's avatar
Penny Leach committed
42
43
44
45
 * loads up account preferences for a given user
 * if you want them for the current user
 * use $SESSION->accountprefs
 *
Aaron Wells's avatar
Aaron Wells committed
46
 * @param int $userid to load preferences for
Penny Leach's avatar
Penny Leach committed
47
 * @todo caching
Aaron Wells's avatar
Aaron Wells committed
48
 * @todo defaults?
Penny Leach's avatar
Penny Leach committed
49
50
51
52
53
54
55
 */
function load_account_preferences($userid) {
    $prefs = array();
    $expectedprefs = expected_account_preferences();
    if (empty($userid)) {
        throw new InvalidArgumentException("couldn't load account preferences, no user id specified");
    }
56
    if ($prefs = get_records_array('usr_account_preference', 'usr', $userid)) {
Penny Leach's avatar
Penny Leach committed
57
        foreach ($prefs as $p) {
58
            $prefs[$p->field] = $p->value;
Penny Leach's avatar
Penny Leach committed
59
60
61
62
63
64
65
66
67
68
69
        }
    }
    foreach ($expectedprefs as $field => $default) {
        if (!isset($prefs[$field])) {
            $prefs[$field] = $default;
        }
    }
    return $prefs;
}


Aaron Wells's avatar
Aaron Wells committed
70
/**
Penny Leach's avatar
Penny Leach committed
71
72
 * sets a user preference in the database
 * if you want to set it in the session as well
Aaron Wells's avatar
Aaron Wells committed
73
 * use SESSION->set_account_preference
Penny Leach's avatar
Penny Leach committed
74
75
76
77
78
79
 *
 * @param int $userid user id to set preference for
 * @param string $field preference field to set
 * @param string $value preference value to set.
 */
function set_account_preference($userid, $field, $value) {
80
81
82
83
84
85
86
87
88
89
    if ($field == 'lang') {
        $oldlang = get_field('usr_account_preference', 'value', 'usr', $userid, 'field', 'lang');
        if (empty($oldlang) || $oldlang == 'default') {
            $oldlang = get_config('lang');
        }
        $newlang = (empty($value) || $value == 'default') ? get_config('lang') : $value;
        if ($newlang != $oldlang) {
            change_language($userid, $oldlang, $newlang);
        }
    }
Penny Leach's avatar
Penny Leach committed
90
91
92
93
94
    if (record_exists('usr_account_preference', 'usr', $userid, 'field', $field)) {
        set_field('usr_account_preference', 'value', $value, 'usr', $userid, 'field', $field);
    }
    else {
        try {
95
            $pref = new stdClass();
Penny Leach's avatar
Penny Leach committed
96
97
98
99
100
101
102
103
104
105
106
107
            $pref->usr = $userid;
            $pref->field = $field;
            $pref->value = $value;
            insert_record('usr_account_preference', $pref);
        }
        catch (Exception $e) {
            throw new InvalidArgumentException("Failed to insert account preference "
                ." $value for $field for user $userid");
        }
    }
}

108

Aaron Wells's avatar
Aaron Wells committed
109
/**
110
 * Change language-specific stuff in the db for a user.  Currently
111
112
 * changes the name of the 'assessmentfiles' folder in the user's
 * files area and the views and artefacts tagged for the profile
Clare Lenihan's avatar
Clare Lenihan committed
113
 * sideblock
114
115
116
117
118
119
 *
 * @param int $userid user id to set preference for
 * @param string $oldlang old language
 * @param string $newlang new language
 */
function change_language($userid, $oldlang, $newlang) {
120
121
122
123
    if (get_field('artefact_installed', 'active', 'name', 'file')) {
        safe_require('artefact', 'file');
        ArtefactTypeFolder::change_language($userid, $oldlang, $newlang);
    }
124
125
126
127
    $typecast = is_postgres() ? '::varchar' : '';
    set_field_select('tag', 'tag', get_string_from_language($newlang, 'profile'), "WHERE tag = ? AND resourcetype = 'artefact' AND resourceid IN (SELECT id" . $typecast . " FROM {artefact} WHERE \"owner\" = ?)", array(get_string_from_language($oldlang, 'profile'), $userid));
    set_field_select('tag', 'tag', get_string_from_language($newlang, 'profile'), "WHERE tag = ? AND resourcetype = 'view' AND resourceid IN (SELECT id" . $typecast . " FROM {view} WHERE \"owner\" = ?)", array(get_string_from_language($oldlang, 'profile'), $userid));
    set_field_select('tag', 'tag', get_string_from_language($newlang, 'profile'), "WHERE tag = ? AND resourcetype = 'collection' AND resourceid IN (SELECT id" . $typecast . " FROM {collection} WHERE \"owner\" = ?)", array(get_string_from_language($oldlang, 'profile'), $userid));
128
129
}

Aaron Wells's avatar
Aaron Wells committed
130
/**
Penny Leach's avatar
Penny Leach committed
131
132
 * sets an activity preference in the database
 * if you want to set it in the session as well
Aaron Wells's avatar
Aaron Wells committed
133
 * use $SESSION->set_activity_preference
Penny Leach's avatar
Penny Leach committed
134
135
 *
 * @param int $userid user id to set preference for
136
 * @param int $activity activity type to set
Penny Leach's avatar
Penny Leach committed
137
138
139
140
141
142
143
144
 * @param string $method notification method to set.
 */
function set_activity_preference($userid, $activity, $method) {
    if (record_exists('usr_activity_preference', 'usr', $userid, 'activity', $activity)) {
        set_field('usr_activity_preference', 'method', $method, 'usr', $userid, 'activity', $activity);
    }
    else {
        try {
145
            $pref = new stdClass();
Penny Leach's avatar
Penny Leach committed
146
147
148
149
150
151
152
            $pref->usr = $userid;
            $pref->activity = $activity;
            $pref->method = $method;
            insert_record('usr_activity_preference', $pref);
        }
        catch (Exception $e) {
            throw new InvalidArgumentException("Failed to insert activity preference "
153
                ." $method for $activity for user $userid");
Penny Leach's avatar
Penny Leach committed
154
155
156
157
        }
    }
}

158
/**
Aaron Wells's avatar
Aaron Wells committed
159
 * gets an account preference for the user,
160
161
162
163
164
165
166
 * or the default if not set for that user,
 * as specified in {@link expected_account_preferences}
 *
 * @param int $userid id of user
 * @param string $field preference to get
 */
function get_account_preference($userid, $field) {
167
    if ($pref = get_record('usr_account_preference', 'usr', $userid, 'field', $field)) {
168
169
170
171
172
173
        return $pref->value;
    }
    $expected = expected_account_preferences();
    return $expected[$field];
}

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
/**
 * Returns the user preferred limit if there is one
 *
 * @param int    $limit
 * @param string $field   The account preference to check. To allow for having more than one limit
 *                        for different parts of the system.
 * @param mixed  $userid  Can be user object or id. If left blank then current $USER id will be used
 *
 * @return int $limit
 */
function user_preferred_limit($limit, $field = 'viewsperpage', $userid = null) {
    global $USER;

    if ($userid instanceof User) {
        $userid = $userid->id;
    }
    else if ($userid === null) {
        $userid = $USER->get('id');
    }

    $userlimit = get_account_preference($userid, $field);
    if ($limit > 0 && $limit != $userlimit) {
        set_account_preference($userid, $field, $limit);
    }
    else {
        $limit = $userlimit;
    }
    return $limit;
}
203
204
205
206

function get_user_language($userid) {
    $langpref = get_account_preference($userid, 'lang');
    if (empty($langpref) || $langpref == 'default') {
207
208

        // Check for an institution language
209
210
211
        $instlang = get_user_institution_language($userid);
        if (!empty($instlang) && $instlang != 'default') {
            return $instlang;
212
213
214
        }

        // Use the site language
215
216
217
218
219
220
        return get_config('lang');
    }
    return $langpref;
}


221
222
/**
 * default account settings
Aaron Wells's avatar
Aaron Wells committed
223
 *
224
225
 * @returns array of fields => values
 */
Penny Leach's avatar
Penny Leach committed
226
227
228
function expected_account_preferences() {
    return array('friendscontrol' => 'auth',
                 'wysiwyg'        =>  1,
229
                 'licensedefault' => '',
Penny Leach's avatar
Penny Leach committed
230
                 'messages'       => 'allow',
231
                 'lang'           => 'default',
232
                 'addremovecolumns' => 0,
233
                 'maildisabled'   => 0,
234
                 'tagssideblockmaxtags' => get_config('tagssideblockmaxtags'),
235
                 'groupsideblockmaxgroups' => '',
236
                 'groupsideblocksortby' => 'alphabetical',
237
                 'hiderealname'   => 0,
238
                 'multipleblogs' => get_config('defaultmultipleblogs'),
239
                 'showhomeinfo' => 1,
240
                 'showprogressbar' => 1,
241
                 'theme' => '',
242
                 'resizeonuploaduserdefault' => 1,
243
                 'devicedetection' => 1,
244
                 'licensedefault' => '',
245
                 'viewsperpage' => 20,
246
                 'itemsperpage' => 10,
247
                 'orderpagesby' => 'latestmodified',
248
                 'searchinfields' => 'titleanddescriptionandtags'
Penny Leach's avatar
Penny Leach committed
249
250
251
                 );
}

252
function general_account_prefs_form_elements($prefs) {
253
254
    global $USER;
    require_once('license.php');
255
    $elements = array();
256
257
258
259
260
261
262
263
264
265
266
267
268
    if (!get_config('friendsnotallowed')) {
        $elements['friendscontrol'] = array(
            'type' => 'radio',
            'defaultvalue' => $prefs->friendscontrol,
            'title'  => get_string('friendsdescr', 'account'),
            'options' => array(
                'nobody' => get_string('friendsnobody', 'account'),
                'auth'   => get_string('friendsauth', 'account'),
                'auto'   => get_string('friendsauto', 'account')
            ),
            'help' => true
        );
    }
269
    $elements['wysiwyg'] = array(
270
        'type' => 'switchbox',
271
272
273
274
275
        'defaultvalue' => (get_config('wysiwyg')) ? get_config('wysiwyg') == 'enable' : $prefs->wysiwyg,
        'title' => get_string('wysiwygdescr', 'account'),
        'help' => true,
        'disabled' => get_config('wysiwyg'),
    );
276
277
278
279
    if (get_config('licensemetadata')) {
        $elements['licensedefault'] = license_form_el_basic(null);
        $elements['licensedefault']['title'] = get_string('licensedefault','account');
        if ($USER->get('institutions')) {
280
            $elements['licensedefault']['options'][LICENSE_INSTITUTION_DEFAULT] = get_string('licensedefaultinherit','account');
281
282
        }
        $elements['licensedefault']['description'] = get_string('licensedefaultdescription','account');
283
        if (isset($prefs->licensedefault)) {
284
285
286
            $elements['licensedefault']['defaultvalue'] = $prefs->licensedefault;
        }
    }
287
    $elements['maildisabled'] = array(
288
        'type' => 'switchbox',
289
        'defaultvalue' => $prefs->maildisabled,
290
        'title' => get_string('disableemail', 'account'),
291
292
        'help' => true,
    );
293
294
295
296
297
298
299
300
301
302
303
304
305
    if (!get_config('friendsnotallowed')) {
        $elements['messages'] = array(
            'type' => 'radio',
            'defaultvalue' => $prefs->messages,
            'title' => get_string('messagesdescr', 'account'),
            'options' => array(
                'nobody' => get_string('messagesnobody', 'account'),
                'friends' => get_string('messagesfriends', 'account'),
                'allow' => get_string('messagesallow', 'account'),
            ),
            'help' => true,
        );
    }
306
    $languages = get_languages();
307
308
309
310
311
312
313
314
    // Determine default language.
    $instlang = get_user_institution_language($USER->id, $instlanginstname);
    if (!empty($instlang) && $instlang != 'default') {
        $sitedefaultlabel = get_string('defaultlangforinstitution', 'admin', get_config_institution($instlanginstname, 'displayname')) . ' (' . $languages[$instlang] . ')';
    }
    else {
        $sitedefaultlabel = get_string('sitedefault', 'admin') . ' (' . $languages[get_config('lang')] . ')';
    }
315

Liam Sharpe's avatar
Liam Sharpe committed
316
317
318
319
320
321
322
323
324
325
326
327
    $elements['lang'] = array(
        'type' => 'select',
        'defaultvalue' => $prefs->lang,
        'title' => get_string('language', 'account'),
        'options' => array_merge(array('default' => $sitedefaultlabel), $languages),
        'help' => true,
        'ignore' => count($languages) < 2,
    );
    $sitethemes = array();
    // Get all available standard site themes
    if (get_config('sitethemeprefs') && !in_admin_section()) {
        // get_user_accessible_themes() returns 'sitedefault' to mean fall back to the site or
328
        // institution theme. On save it sets user_account_preference to '' to allow the use of higher up theme.
Liam Sharpe's avatar
Liam Sharpe committed
329
330
331
332
        $sitethemes = array_reverse(get_user_accessible_themes());
        $sitethemes = array_reverse($sitethemes);
    }
    // Get all user's institution themes
333
    $lostthemes = array();
Liam Sharpe's avatar
Liam Sharpe committed
334
335
336
337
338
339
340
    $institutionthemes = array();
    if ($institutions = $USER->get('institutions')) {
        $allthemes = get_all_theme_objects();
        foreach ($institutions as $i) {
            if (empty($i->theme)) {
                $institutionthemes['sitedefault' . '/' . $i->institution] = $i->displayname . ' - ' . get_string('sitedefault', 'admin');
            }
341
            else if (isset($allthemes[$i->theme])) {
Liam Sharpe's avatar
Liam Sharpe committed
342
                $institutionthemes[$i->theme . '/' . $i->institution] = $i->displayname . ' - ' . $allthemes[$i->theme]->displayname;
343
            }
344
345
346
            else {
                $lostthemes[$i->theme] = 1;
            }
347
348
        }
    }
Liam Sharpe's avatar
Liam Sharpe committed
349
350
351
    $themes = array_merge($sitethemes, $institutionthemes);
    natcasesort($themes);
    $currenttheme = $USER->get_themedata();
352
353
354

    if (!isset($currenttheme->basename) || (isset($currenttheme->altname) && $currenttheme->altname == 'sitedefault')
        || !empty($lostthemes[$currenttheme->basename])) {
Liam Sharpe's avatar
Liam Sharpe committed
355
356
357
358
359
        $defaulttheme = 'sitedefault';
    }
    else {
        $defaulttheme = $currenttheme->basename;
    }
360
    if (isset($currenttheme->institutionname) && empty($lostthemes[$currenttheme->basename])) {
Liam Sharpe's avatar
Liam Sharpe committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
        $defaulttheme = $defaulttheme . '/' . $currenttheme->institutionname;
    }
    if (!array_key_exists($defaulttheme, $themes)) {
        reset($themes);
        $defaulttheme = key($themes);
    }
    $elements['theme'] = array(
        'type' => 'select',
        'defaultvalue' => $defaulttheme,
        'title' => get_string('theme'),
        'options' => $themes,
        'ignore' => count($themes) < 2,
        'help' => true,
    );
375

376
    $elements['addremovecolumns'] = array(
377
        'type' => 'switchbox',
378
379
380
381
382
383
        'defaultvalue' => $prefs->addremovecolumns,
        'title' => get_string('showviewcolumns', 'account'),
        'help' => 'true'
    );
    // TODO: add a way for plugins (like blog!) to have account preferences
    $elements['multipleblogs'] = array(
384
        'type' => 'switchbox',
385
        'title'=> get_string('enablemultipleblogs1' ,'account'),
386
        'description' => get_string('enablemultipleblogsdescription1', 'account'),
387
388
389
390
391
392
393
394
395
396
397
398
        'defaultvalue' => $prefs->multipleblogs,
    );
    if (get_config('showtagssideblock')) {
        $elements['tagssideblockmaxtags'] = array(
            'type'         => 'text',
            'size'         => 4,
            'title'        => get_string('tagssideblockmaxtags', 'account'),
            'description'  => get_string('tagssideblockmaxtagsdescription', 'account'),
            'defaultvalue' => isset($prefs->tagssideblockmaxtags) ? $prefs->tagssideblockmaxtags : get_config('tagssideblockmaxtags'),
            'rules'        => array('integer' => true, 'minvalue' => 0, 'maxvalue' => 1000),
        );
    }
399
400
401
    $elements['groupsideblockmaxgroups'] = array(
        'type'         => 'text',
        'size'         => 4,
402
403
        'title'        => get_string('limitto1', 'blocktype.mygroups'),
        'description'  => get_string('limittodescsideblock1', 'blocktype.mygroups'),
404
        'defaultvalue' => isset($prefs->groupsideblockmaxgroups) ? $prefs->groupsideblockmaxgroups : '',
405
406
407
408
409
        'rules'        => array('regex' => '/^[0-9]*$/', 'minvalue' => 0, 'maxvalue' => 1000),
    );
    $elements['groupsideblocksortby'] = array(
        'type'         => 'select',
        'defaultvalue' => isset($prefs->groupsideblocksortby) ? $prefs->groupsideblocksortby : 'alphabetical',
410
        'title' => get_string('sortgroups', 'blocktype.mygroups'),
411
412
413
414
415
416
        'options' =>  array(
            'latest' => get_string('latest', 'blocktype.mygroups'),
            'earliest' => get_string('earliest', 'blocktype.mygroups'),
            'alphabetical'  => get_string('alphabetical', 'blocktype.mygroups'),
        ),
    );
417
418
    if (get_config('userscanhiderealnames')) {
        $elements['hiderealname'] = array(
419
            'type'         => 'switchbox',
420
421
422
423
424
425
426
            'title'        => get_string('hiderealname', 'account'),
            'description'  => get_string('hiderealnamedescription', 'account'),
            'defaultvalue' => $prefs->hiderealname,
        );
    }
    if (get_config('homepageinfo')) {
        $elements['showhomeinfo'] = array(
427
            'type' => 'switchbox',
428
            'defaultvalue' => $prefs->showhomeinfo,
429
430
            'title' => get_string('showhomeinfo2', 'account'),
            'description' => get_string('showhomeinfodescription1', 'account', hsc(get_config('sitename'))),
431
432
433
            'help' => 'true'
        );
    }
434
435
    if (get_config('showprogressbar')) {
        $elements['showprogressbar'] = array(
436
            'type' => 'switchbox',
437
438
439
440
441
            'defaultvalue' => $prefs->showprogressbar,
            'title' => get_string('showprogressbar', 'account'),
            'description' => get_string('showprogressbardescription', 'account', hsc(get_config('sitename'))),
        );
    }
442
443
    if (get_config_plugin('artefact', 'file', 'resizeonuploadenable')) {
        $elements['resizeonuploaduserdefault'] = array(
444
            'type'         => 'switchbox',
445
            'title'        => get_string('resizeonuploaduserdefault1', 'account'),
446
            'description'  => get_string('resizeonuploaduserdefaultdescription2', 'account'),
447
448
449
            'defaultvalue' => $prefs->resizeonuploaduserdefault,
        );
    }
450

451
452
    if (get_config('userscandisabledevicedetection')) {
        $elements['devicedetection'] = array(
453
            'type'         => 'switchbox',
454
455
456
457
458
459
            'title'        => get_string('devicedetection', 'account'),
            'description'  => get_string('devicedetectiondescription', 'account'),
            'defaultvalue' => $prefs->devicedetection,
        );
    }

460
461
462
    return $elements;
}

463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
515
516
517
518
/**
 * Get account settings elements from plugins.
 *
 * @param stdClass $prefs
 * @return array
 */
function plugin_account_prefs_form_elements(stdClass $prefs) {
    $elements = array();
    $installed = plugin_all_installed();
    foreach ($installed as $i) {
        if (!safe_require_plugin($i->plugintype, $i->name)) {
            continue;
        }
        $elements = array_merge($elements, call_static_method(generate_class_name($i->plugintype, $i->name),
                'get_accountprefs_elements', $prefs));
    }
    return $elements;
}

/**
 * Validate plugin account form values.
 *
 * @param Pieform $form
 * @param array $values
 */
function plugin_account_prefs_validate(Pieform $form, $values) {
    $elements = array();
    $installed = plugin_all_installed();
    foreach ($installed as $i) {
        if (!safe_require_plugin($i->plugintype, $i->name)) {
            continue;
        }
        call_static_method(generate_class_name($i->plugintype, $i->name), 'accountprefs_validate', $form, $values);
    }
}

/**
 * Submit plugin account form values.
 *
 * @param Pieform $form
 * @param array $values
 * @return bool is page need to be refreshed
 */
function plugin_account_prefs_submit(Pieform $form, $values) {
    $reload = false;
    $elements = array();
    $installed = plugin_all_installed();
    foreach ($installed as $i) {
        if (!safe_require_plugin($i->plugintype, $i->name)) {
            continue;
        }
        $reload = call_static_method(generate_class_name($i->plugintype, $i->name), 'accountprefs_submit', $form, $values) || $reload;
    }
    return $reload;
}

519
520
/**
 * Save a profile field.
521
 * Exception is 'socialprofile' field. It is made up of 2 fields:
522
523
524
525
526
 * socialprofile_profileurl,
 * socialprofile_profiletype
 * @param int $userid
 * @param string $field
 * @param string (or array for socialprofile) $value
527
 * @param int $new - Whether the user is new (avoid unnecessary queries)
528
 */
529
function set_profile_field($userid, $field, $value, $new = FALSE) {
530
    safe_require('artefact', 'internal');
531
532
533
534

    // this is a special case that replaces the primary email address with the
    // specified one
    if ($field == 'email') {
535
536
537
538
539
540
541
        if (!$new) {
            try {
                $email = artefact_instance_from_type('email', $userid);
            }
            catch (ArtefactNotFoundException $e) {
                // We'll create a new artefact then.
            }
542
        }
543
544
        if (!isset($email)) {
            $email = new ArtefactTypeEmail(0, null, TRUE);
545
546
547
548
549
            $email->set('owner', $userid);
        }
        $email->set('title', $value);
        $email->commit();
    }
550
    else if ($field == 'socialprofile') {
551
552
553
554
555
556
557
558
        if (in_array($value['socialprofile_profiletype'], ArtefactTypeSocialprofile::$socialnetworks)) {
            $desc = get_string($value['socialprofile_profiletype'], 'artefact.internal');
            $type = $value['socialprofile_profiletype'];
        }
        else {
            $desc = $value['socialprofile_profiletype'];
            $type = 'website';
        }
559
        $classname = generate_artefact_class_name($field);
560
        $profile = new $classname(0, array('owner' => $userid), $new);
561
        $profile->set('title',       $value['socialprofile_profileurl']);
562
563
        $profile->set('description', $desc);
        $profile->set('note',        $type);
564
565
        $profile->commit();
    }
566
567
    else {
        $classname = generate_artefact_class_name($field);
568
        $profile = new $classname(0, array('owner' => $userid), $new);
569
570
571
        $profile->set('title', $value);
        $profile->commit();
    }
572
573
}

574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/**
 * Update the primary email to an user
 * Add new if not exists
 *
 * @param int $userid The user ID
 * @param string $newemail The new valid email address
 */
function set_user_primary_email($userid, $newemail) {
    safe_require('artefact', 'internal');

    $user = new User();
    $user->find_by_id($userid);

    db_begin();
    // Update user's primary email address
    if ($newemail !== $user->email) {
        // Set the current email address to be secondary
        update_record(
            'artefact_internal_profile_email',
            (object)array(
                'principal' => 0,
            ),
            (object)array(
                'owner' => $user->id,
                'email' => $user->email,
            )
        );
        // If the new primary email address is to be verified, remove it
        delete_records(
            'artefact_internal_profile_email',
            'owner', $user->id,
            'email', $newemail,
            'verified', '0'
        );
        // If the new address is one of the user's email addresses, set it as principal
        if (record_exists(
            'artefact_internal_profile_email',
            'owner', $user->id,
            'email', $newemail)) {
            update_record(
                'artefact_internal_profile_email',
                (object)array(
                    'principal' => 1,
                ),
                (object)array(
                    'owner' => $user->id,
                    'email' => $newemail,
                )
            );
        }
        else {
            // Add new user profile email address
            set_profile_field($user->id, 'email', $newemail, TRUE);
        }
        $user->email = $newemail;
        $user->commit();
    }
    db_commit();
}
633
634
635
636
637
/**
 * Return the value of a profile field for a given user
 *
 * @param integer user id to find the profile field for
 * @param field what profile field you want the value for
638
639
640
 * @returns string for non-socialprofile fields - the value of the profile field.
 *          array for socialprofile fields - array of the values of the profile fields ('id-<id>'|'<description>|'<title>').
 *          null if it doesn't exist
641
642
643
644
 *
 * @todo, this needs to be better (fix email behaviour)
 */
function get_profile_field($userid, $field) {
645
646
647
648
649
650
651
    if ($field == 'email') {
        $value = get_field_sql("
            SELECT a.title
            FROM {usr} u
            JOIN {artefact} a ON (a.title = u.email AND a.owner = u.id)
            WHERE a.artefacttype = 'email' AND u.id = ?", array($userid));
    }
652
653
654
655
656
657
658
659
    else if ($field == 'socialprofile') {
        // First check if the block is enabled.
        if (get_record('blocktype_installed', 'active', 1, 'name', 'socialprofile')) {
            // The user can have more than one social profiles. Will need to return an array.
            safe_require('artefact', 'internal');
            $value = ArtefactTypeSocialprofile::get_social_profiles();
        }
    }
660
661
662
    else if ($field == 'introduction') {
        $value = get_field('artefact', 'description', 'owner', $userid, 'artefacttype', $field);
    }
663
664
665
    else {
        $value = get_field('artefact', 'title', 'owner', $userid, 'artefacttype', $field);
    }
666
667
668
669

    if ($value) {
        return $value;
    }
670

671
    return null;
672
673
}

Aaron Wells's avatar
Aaron Wells committed
674
/**
675
 * Always use this function for all emails to users
Aaron Wells's avatar
Aaron Wells committed
676
 *
677
678
679
680
681
 * @param object $userto user object to send email to. must contain firstname,lastname,preferredname,email
 * @param object $userfrom user object to send email from. If null, email will come from mahara
 * @param string $subject email subject
 * @param string $messagetext text version of email
 * @param string $messagehtml html version of email (will send both html and text)
682
 * @param array  $customheaders email headers
683
 * @throws EmailException
684
 * @throws EmailDisabledException
Aaron Wells's avatar
Aaron Wells committed
685
 */
686
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml='', $customheaders=null) {
687
688
689
    global $IDPJUMPURL;
    static $mnetjumps = array();

690
    if (!get_config('sendemail')) {
Aaron Wells's avatar
Aaron Wells committed
691
        // You can entirely disable Mahara from sending any e-mail via the
692
693
694
        // 'sendemail' configuration variable
        return true;
    }
695
696
697
698

    if (empty($userto)) {
        throw new InvalidArgumentException("empty user given to email_user");
    }
699

700
    if (isset($userto->id) && empty($userto->ignoredisabled)) {
701
702
703
704
        $maildisabled = property_exists($userto, 'maildisabled') ? $userto->maildisabled : get_account_preference($userto->id, 'maildisabled') == 1;
        if ($maildisabled) {
            throw new EmailDisabledException("email for this user has been disabled");
        }
705
706
    }

707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
    // If the user is a remote xmlrpc user, trawl through the email text for URLs
    // to our wwwroot and modify the url to direct the user's browser to login at
    // their home site before hitting the link on this site
    if (!empty($userto->mnethostwwwroot) && !empty($userto->mnethostapp)) {
        require_once(get_config('docroot') . 'auth/xmlrpc/lib.php');

        // Form the request url to hit the idp's jump.php
        if (isset($mnetjumps[$userto->mnethostwwwroot])) {
            $IDPJUMPURL = $mnetjumps[$userto->mnethostwwwroot];
        } else {
            $mnetjumps[$userto->mnethostwwwroot] = $IDPJUMPURL = PluginAuthXmlrpc::get_jump_url_prefix($userto->mnethostwwwroot, $userto->mnethostapp);
        }

        $wwwroot = get_config('wwwroot');
        $messagetext = preg_replace_callback('%(' . $wwwroot . '([\w_:\?=#&@/;.~-]*))%',
            'localurl_to_jumpurl',
            $messagetext);
        $messagehtml = preg_replace_callback('%href=["\'`](' . $wwwroot . '([\w_:\?=#&@/;.~-]*))["\'`]%',
            'localurl_to_jumpurl',
            $messagehtml);
    }

729
    $mail = new PHPMailer(true);
Aaron Wells's avatar
Aaron Wells committed
730

731
732
733
734
735
736
    $mail->CharSet = 'UTF-8';

    $smtphosts = get_config('smtphosts');
    if ($smtphosts == 'qmail') {
        // use Qmail system
        $mail->IsQmail();
Aaron Wells's avatar
Aaron Wells committed
737
    }
738
739
740
741
742
743
744
745
    else if (empty($smtphosts)) {
        // use PHP mail() = sendmail
        $mail->IsMail();
    }
    else {
        $mail->IsSMTP();
        // use SMTP directly
        $mail->Host = get_config('smtphosts');
746
        $mail->Port = is_numeric(get_config('smtpport')) ? get_config('smtpport') : 25;
747
748
        if (get_config('smtpuser')) {
            // Use SMTP authentication
749
750
751
752
            $mail->SMTPAuth   = true;
            $mail->Username   = get_config('smtpuser');
            $mail->Password   = get_config('smtppass');
            $mail->SMTPSecure = get_config('smtpsecure');
753
754
755
756
757
758
759
760
761
            if (get_config('smtpsecure') && !get_config('smtpport')) {
                // Encrypted connection with no port. Use default one.
                if (get_config('smtpsecure') == 'ssl') {
                    $mail->Port = 465;
                }
                elseif (get_config('smtpsecure') == 'tls') {
                    $mail->Port = 587;
                }
            }
762
763
764
        }
    }

765
766
    if (get_config('bounces_handle') && !empty($userto->id) && empty($maildisabled)) {
        $mail->Sender = generate_email_processing_address($userto->id, $userto);
767
    }
768
    if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) {
769
770
771
772
        if (empty($mail->Sender)) {
            $mail->Sender = get_config('noreplyaddress');
        }
        $mail->From = get_config('noreplyaddress');
773
        $mail->FromName = (isset($userfrom->id)) ? display_name($userfrom, $userto) : get_config('sitename');
774
        $customheaders[] = 'Precedence: Bulk'; // Try to avoid pesky out of office responses
Richard Mansfield's avatar
Richard Mansfield committed
775
        $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n";
776
        if ($messagehtml) {
Richard Mansfield's avatar
Richard Mansfield committed
777
            $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n";
778
        }
779
780
    }
    else {
781
782
783
784
        if (empty($mail->Sender)) {
            $mail->Sender = $userfrom->email;
        }
        $mail->From = $userfrom->email;
785
786
        $mail->FromName = display_name($userfrom, $userto);
    }
787
    $replytoset = false;
788
789
    if (!empty($customheaders) && is_array($customheaders)) {
        foreach ($customheaders as $customheader) {
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
            // To prevent duplicated declaration of the field "Message-ID",
            // don't add it into the $mail->CustomHeader[].
            if (false === stripos($customheader, 'message-id')) {
                // Hack the fields "In-Reply-To" and "References":
                // add touser<userID>
                if ((0 === stripos($customheader, 'in-reply-to')) ||
                    (0 === stripos($customheader, 'references'))) {
                    $customheader = preg_replace('/<forumpost(\d+)/', '<forumpost${1}touser' . $userto->id, $customheader);
                }
                $mail->AddCustomHeader($customheader);
            }
            else {
                list($h, $msgid) = explode(':', $customheader, 2);
                // Hack the "Message-ID": add touser<userID> to make sure
                // the "Message-ID" is unique
                $msgid = preg_replace('/<forumpost(\d+)/', '<forumpost${1}touser' . $userto->id, $msgid);
                $mail->MessageID = trim($msgid);
            }
808
809
810
            if (0 === stripos($customheader, 'reply-to')) {
                $replytoset = true;
            }
811
812
        }
    }
813

814
    $mail->Subject = substr(stripslashes($subject), 0, 900);
815

816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
    try {
        if ($to = get_config('sendallemailto')) {
            // Admins can configure the system to send all email to a given address
            // instead of whoever would receive it, useful for debugging.
            $usertoname = display_name($userto, $userto, true) . ' (' . get_string('divertingemailto', 'mahara', $to) . ')';
            $mail->addAddress($to);
            $notice = get_string('debugemail', 'mahara', display_name($userto, $userto), $userto->email);
            $messagetext =  $notice . "\n\n" . $messagetext;
            if ($messagehtml) {
                $messagehtml = '<p>' . hsc($notice) . '</p>' . $messagehtml;
            }
        }
        else {
            $usertoname = display_name($userto, $userto);
            $mail->AddAddress($userto->email, $usertoname );
            $to = $userto->email;
        }
        if (!$replytoset) {
            $mail->AddReplyTo($mail->From, $mail->FromName);
835
836
        }
    }
837
    catch (phpmailerException $e) {
838
839
840
841
        // If there's a phpmailer error already, assume it's an invalid address
        throw new InvalidEmailException("Cannot send email to $usertoname with subject $subject. Error from phpmailer was: " . $mail->ErrorInfo);
    }

Aaron Wells's avatar
Aaron Wells committed
842
    $mail->WordWrap = 79;
843

Aaron Wells's avatar
Aaron Wells committed
844
    if ($messagehtml) {
845
846
847
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body    =  $messagehtml;
848
        $mail->AltBody =  $messagetext;
Aaron Wells's avatar
Aaron Wells committed
849
    }
850
851
    else {
        $mail->IsHTML(false);
852
        $mail->Body =  $messagetext;
853
854
    }

855
856
857
858
859
860
861
862
    try {
        $sent = $mail->Send();
    }
    catch (phpmailerException $e) {
        $sent = false;
    }

    if ($sent) {
863
864
865
866
867
868
869
        if ($logfile = get_config('emaillog')) {
            $docroot = get_config('docroot');
            @$client = (string) $_SERVER['REMOTE_ADDR'];
            @$script = (string) $_SERVER['SCRIPT_FILENAME'];
            if (strpos($script, $docroot) === 0) {
                $script = substr($script, strlen($docroot));
            }
870
            $line = "$to <- $mail->From - " . str_shorten_text($mail->Subject, 200);
871
872
873
            @error_log('[' . date("Y-m-d h:i:s") . "] [$client] [$script] $line\n", 3, $logfile);
        }

874
875
876
877
        if (get_config('bounces_handle')) {
            // Update the count of sent mail
            update_send_count($userto);
        }
878

879
        return true;
Aaron Wells's avatar
Aaron Wells committed
880
    }
881
882
883
884
    throw new EmailException("Couldn't send email to $usertoname with subject $subject. "
                        . "Error from phpmailer was: " . $mail->ErrorInfo );
}

885
886
887
888
889
890
891
892
893
894
895
896
897
898
/**
 * Generate an email processing address for VERP handling of email
 *
 * @param int $userid the ID of the user sending the mail
 * @param object $userto an object containing the email address
 * @param char $type The type of address to generate
 *
 * The type of address is typically a Bounce. These are processed by the
 * process_email function.
 */
function generate_email_processing_address($userid, $userto, $type='B') {
    $mailprefix = get_config('bounceprefix');
    $maildomain = get_config('bouncedomain');
    $installation_key = get_config('installation_key');
899
900
901
    // Postfix and other smtp servers don't like the use of / in the extension part of an email
    // Replace it with another valid email character that isn't in base64, like '-'
    $args = $type . preg_replace('/\//', '-', base64_encode(pack('V', $userid))) . substr(md5($userto->email), 0, 16);
902
903
904
    return $mailprefix . $args . substr(md5($mailprefix . $userto->email . $installation_key), 0, 16) . '@' . $maildomain;
}

905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
/**
 * Check whether an email account is over the site-wide bounce threshold.
 * If the user is over threshold, then e-mail is disabled for their
 * account, and they are sent a notification to notify them of the change.
 *
 * @param object $mailinfo The row from artefact_internal_profile_email for
 * the user being processed.
 * @return boolean false if the user is not over threshold, true if they
 * are.
 */
function check_overcount($mailinfo) {
    // if we don't handle bounce e-mails, then we can't be over threshold
    if (!get_config('bounces_handle')) {
        return false;
    }

Aaron Wells's avatar
Aaron Wells committed
921
922
923
924
    $minbounces = get_config('bounces_min');
    $bounceratio = get_config('bounces_ratio');
    // If they haven't set a minbounces value, then we can't proceed
    if (!$minbounces) {
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
        return false;
    }

    if ($mailinfo->mailssent == 0) {
        return false;
    }

    // If the bouncecount is larger than the allowed amount
    // and the bounce count ratio (bounces/total sent) is larger than the
    // bounceratio, then disable email
    $overlimit = ($mailinfo->mailsbounced >= $minbounces) && ($mailinfo->mailsbounced/$mailinfo->mailssent >= $bounceratio);

    if ($overlimit) {
        if (get_account_preference($mailinfo->owner,'maildisabled') != 1) {
            // Disable the e-mail account
            db_begin();
            set_account_preference($mailinfo->owner, 'maildisabled', 1);

            $lang = get_user_language($mailinfo->owner);

            // Send a notification that e-mail has been disabled
946
            $message = new stdClass();
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
            $message->users = array($mailinfo->owner);

            $message->subject = get_string_from_language($lang, 'maildisabled', 'account');
            $message->message = get_string_from_language($lang, 'maildisabledbounce', 'account', get_config('wwwroot') . 'account/');

            require_once('activity.php');
            activity_occurred('maharamessage', $message);

            db_commit();
        }
        return true;
    }
    return false;
}

962
963
964
965
966
967
968
969
970
971
972
973
/**
 * Update the send count for the specified e-mail address
 *
 * @param object $userto object to update count for. Must contain email and
 * user id
 * @param boolean reset Reset the sent mail count to 0 (optional).
 */
function update_send_count($userto, $reset=false) {
    if (!$userto->id) {
        // We need a user id to update the send count.
        return false;
    }
Francois Marier's avatar
Francois Marier committed
974
    if ($mailinfo = get_record_select('artefact_internal_profile_email', '"owner" = ? AND email = ? AND principal = 1', array($userto->id, $userto->email))) {
975
976
977
978
979
        $mailinfo->mailssent = (!empty($reset)) ? 0 : $mailinfo->mailssent+1;
        update_record('artefact_internal_profile_email', $mailinfo, array('email' => $userto->email, 'owner' => $userto->id));
    }
}

980
981
982
983
984
985
986
987
988
989
990
991
/**
 * Update the bounce count for the specified e-mail address
 *
 * @param object $userto object to update count for. Must contain email and
 * user id
 * @param boolean reset Reset the sent mail count to 0 (optional).
 */
function update_bounce_count($userto, $reset=false) {
    if (!$userto->id) {
        // We need a user id to update the bounce count.
        return false;
    }
Francois Marier's avatar
Francois Marier committed
992
    if ($mailinfo = get_record_select('artefact_internal_profile_email', '"owner" = ? AND email = ? AND principal = 1', array($userto->id, $userto->email))) {
993
994
995
996
997
998
999
1000
        $mailinfo->mailsbounced = (!empty($reset)) ? 0 : $mailinfo->mailsbounced+1;
        update_record('artefact_internal_profile_email', $mailinfo, array('email' => $userto->email, 'owner' => $userto->id));
    }
}

/**
 * Process an incoming email
 *
For faster browsing, not all history is shown. View entire blame