user.php 107 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);

Aaron Wells's avatar
Aaron Wells committed
16
/**
Penny Leach's avatar
Penny Leach committed
17 18
 * loads up activity preferences for a given user
 *
Aaron Wells's avatar
Aaron Wells committed
19
 * @param int $userid to load preferences for
Penny Leach's avatar
Penny Leach committed
20 21 22 23 24 25 26
 * @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
27
    if ($prefs = get_records_assoc('usr_activity_preference', 'usr', $userid, '', 'activity,method')) {
Penny Leach's avatar
Penny Leach committed
28
        foreach ($prefs as $p) {
29
            $prefs[$p->activity] = $p->method;
Penny Leach's avatar
Penny Leach committed
30 31 32 33 34
        }
    }
    return $prefs;
}

Aaron Wells's avatar
Aaron Wells committed
35
/**
Penny Leach's avatar
Penny Leach committed
36 37 38 39
 * 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
40
 * @param int $userid to load preferences for
Penny Leach's avatar
Penny Leach committed
41
 * @todo caching
Aaron Wells's avatar
Aaron Wells committed
42
 * @todo defaults?
Penny Leach's avatar
Penny Leach committed
43 44 45 46 47 48 49
 */
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");
    }
50
    if ($prefs = get_records_array('usr_account_preference', 'usr', $userid)) {
Penny Leach's avatar
Penny Leach committed
51
        foreach ($prefs as $p) {
52
            $prefs[$p->field] = $p->value;
Penny Leach's avatar
Penny Leach committed
53 54 55 56 57 58 59 60 61 62 63
        }
    }
    foreach ($expectedprefs as $field => $default) {
        if (!isset($prefs[$field])) {
            $prefs[$field] = $default;
        }
    }
    return $prefs;
}


Aaron Wells's avatar
Aaron Wells committed
64
/**
Penny Leach's avatar
Penny Leach committed
65 66
 * 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
67
 * use SESSION->set_account_preference
Penny Leach's avatar
Penny Leach committed
68 69 70 71 72 73
 *
 * @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) {
74 75 76
    if ($field == 'mobileuploadtoken'
        && ((!isset($value) || empty($value))
            || (is_array($value) && count($value) == 1 && (!isset($value[0]) || empty($value[0]))))) {
77 78
        $value = '';
    }
79 80 81 82 83 84 85 86 87 88
    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
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    if (record_exists('usr_account_preference', 'usr', $userid, 'field', $field)) {
        set_field('usr_account_preference', 'value', $value, 'usr', $userid, 'field', $field);
    }
    else {
        try {
            $pref = new StdClass;
            $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");
        }
    }
}

107

Aaron Wells's avatar
Aaron Wells committed
108
/**
109
 * Change language-specific stuff in the db for a user.  Currently
110 111
 * 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
112
 * sideblock
113 114 115 116 117 118
 *
 * @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) {
119 120 121 122
    if (get_field('artefact_installed', 'active', 'name', 'file')) {
        safe_require('artefact', 'file');
        ArtefactTypeFolder::change_language($userid, $oldlang, $newlang);
    }
Francois Marier's avatar
Francois Marier committed
123 124
    set_field_select('artefact_tag', 'tag', get_string_from_language($newlang, 'profile'), 'WHERE tag = ? AND artefact IN (SELECT id FROM {artefact} WHERE "owner" = ?)', array(get_string_from_language($oldlang, 'profile'), $userid));
    set_field_select('view_tag', 'tag', get_string_from_language($newlang, 'profile'), 'WHERE tag = ? AND "view" IN (SELECT id FROM {view} WHERE "owner" = ?)', array(get_string_from_language($oldlang, 'profile'), $userid));
125
    set_field_select('collection_tag', 'tag', get_string_from_language($newlang, 'profile'), 'WHERE tag = ? AND "collection" IN (SELECT id FROM {collection} WHERE "owner" = ?)', array(get_string_from_language($oldlang, 'profile'), $userid));
126 127
}

Aaron Wells's avatar
Aaron Wells committed
128
/**
Penny Leach's avatar
Penny Leach committed
129 130
 * 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
131
 * use $SESSION->set_activity_preference
Penny Leach's avatar
Penny Leach committed
132 133
 *
 * @param int $userid user id to set preference for
134
 * @param int $activity activity type to set
Penny Leach's avatar
Penny Leach committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
 * @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 {
            $pref = new StdClass;
            $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 "
151
                ." $method for $activity for user $userid");
Penny Leach's avatar
Penny Leach committed
152 153 154 155
        }
    }
}

156
/**
Aaron Wells's avatar
Aaron Wells committed
157
 * gets an account preference for the user,
158 159 160 161 162 163 164
 * 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) {
165
    if ($pref = get_record('usr_account_preference', 'usr', $userid, 'field', $field)) {
166 167 168 169 170 171
        return $pref->value;
    }
    $expected = expected_account_preferences();
    return $expected[$field];
}

172 173 174 175

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

        // Check for an institution language
178 179 180
        $instlang = get_user_institution_language($userid);
        if (!empty($instlang) && $instlang != 'default') {
            return $instlang;
181 182 183
        }

        // Use the site language
184 185 186 187 188 189
        return get_config('lang');
    }
    return $langpref;
}


190 191
/**
 * default account settings
Aaron Wells's avatar
Aaron Wells committed
192
 *
193 194
 * @returns array of fields => values
 */
Penny Leach's avatar
Penny Leach committed
195 196 197
function expected_account_preferences() {
    return array('friendscontrol' => 'auth',
                 'wysiwyg'        =>  1,
198
                 'licensedefault' => '',
Penny Leach's avatar
Penny Leach committed
199
                 'messages'       => 'allow',
200
                 'lang'           => 'default',
201
                 'addremovecolumns' => 0,
202
                 'maildisabled'   => 0,
203
                 'tagssideblockmaxtags' => get_config('tagssideblockmaxtags'),
204
                 'groupsideblockmaxgroups' => '',
205
                 'groupsideblocksortby' => 'alphabetical',
206
                 'hiderealname'   => 0,
207
                 'multipleblogs' => 0,
208
                 'showhomeinfo' => 1,
209
                 'showprogressbar' => 1,
210
                 'mobileuploadtoken' => '',
211
                 'theme' => '',
212
                 'resizeonuploaduserdefault' => 1,
213
                 'devicedetection' => 1,
214
                 'licensedefault' => '',
215
                 'viewsperpage' => 20,
Penny Leach's avatar
Penny Leach committed
216 217 218
                 );
}

219
function general_account_prefs_form_elements($prefs) {
220 221
    global $USER;
    require_once('license.php');
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    $elements = array();
    $elements['friendscontrol'] = array(
        'type' => 'radio',
        'defaultvalue' => $prefs->friendscontrol,
        'title'  => get_string('friendsdescr', 'account'),
        'separator' => '<br>',
        'options' => array(
            'nobody' => get_string('friendsnobody', 'account'),
            'auth'   => get_string('friendsauth', 'account'),
            'auto'   => get_string('friendsauto', 'account')
        ),
        'help' => true
    );
    $elements['wysiwyg'] = array(
        'type' => 'checkbox',
        'defaultvalue' => (get_config('wysiwyg')) ? get_config('wysiwyg') == 'enable' : $prefs->wysiwyg,
        'title' => get_string('wysiwygdescr', 'account'),
        'help' => true,
        'disabled' => get_config('wysiwyg'),
    );
242 243 244 245
    if (get_config('licensemetadata')) {
        $elements['licensedefault'] = license_form_el_basic(null);
        $elements['licensedefault']['title'] = get_string('licensedefault','account');
        if ($USER->get('institutions')) {
246
            $elements['licensedefault']['options'][LICENSE_INSTITUTION_DEFAULT] = get_string('licensedefaultinherit','account');
247 248
        }
        $elements['licensedefault']['description'] = get_string('licensedefaultdescription','account');
249
        if (isset($prefs->licensedefault)) {
250 251 252
            $elements['licensedefault']['defaultvalue'] = $prefs->licensedefault;
        }
    }
253 254 255
    $elements['maildisabled'] = array(
        'type' => 'checkbox',
        'defaultvalue' => $prefs->maildisabled,
256
        'title' => get_string('disableemail', 'account'),
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        'help' => true,
    );
    $elements['messages'] = array(
        'type' => 'radio',
        'defaultvalue' => $prefs->messages,
        'title' => get_string('messagesdescr', 'account'),
        'separator' => '<br>',
        'options' => array(
            'nobody' => get_string('messagesnobody', 'account'),
            'friends' => get_string('messagesfriends', 'account'),
            'allow' => get_string('messagesallow', 'account'),
        ),
        'help' => true,
    );
    $languages = get_languages();
272 273 274 275 276 277 278 279
    // 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')] . ')';
    }
280 281 282 283
    $elements['lang'] = array(
        'type' => 'select',
        'defaultvalue' => $prefs->lang,
        'title' => get_string('language', 'account'),
284
        'options' => array_merge(array('default' => $sitedefaultlabel), $languages),
285 286 287
        'help' => true,
        'ignore' => count($languages) < 2,
    );
288 289 290
    $sitethemes = array();
    // Get all available standard site themes
    if (get_config('sitethemeprefs') && !in_admin_section()) {
291 292 293 294
        // get_user_accessible_themes() returns 'sitedefault' to mean fall back to the site or
        // institution theme.  This won't work for account prefs, where 'sitedefault' is just
        // a theme that doesn't exist.  So change the 'sitedefault' key to '', and the empty
        // preference will be interpreted as "No theme selected".
295 296 297
        $sitethemes = array_reverse(get_user_accessible_themes());
        unset($sitethemes['sitedefault']);
        $sitethemes = array_reverse($sitethemes);
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
    // Get all user's institution themes
    $institutionthemes = array();
    global $USER;
    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');
            }
            else {
                $institutionthemes[$i->theme . '/' . $i->institution] = $i->displayname . ' - ' . $allthemes[$i->theme]->displayname;
            }
        }
    }
    $themes = array_merge($sitethemes, $institutionthemes);
    natcasesort($themes);
    $currenttheme = $USER->get_themedata();
    if (!isset($currenttheme->basename)) {
        $defaulttheme = 'sitedefault';
    }
    else {
        $defaulttheme = $currenttheme->basename;
    }
    if (isset($currenttheme->institutionname)) {
        $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,
    );

338 339 340 341 342 343 344 345 346
    $elements['addremovecolumns'] = array(
        'type' => 'checkbox',
        '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(
        'type' => 'checkbox',
347
        'title'=> get_string('enablemultipleblogs1' ,'account'),
348 349 350 351 352 353 354 355 356 357 358 359 360
        'description' => get_string('enablemultipleblogsdescription', 'account'),
        '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),
        );
    }
361 362 363
    $elements['groupsideblockmaxgroups'] = array(
        'type'         => 'text',
        'size'         => 4,
364 365
        'title'        => get_string('limitto1', 'blocktype.mygroups'),
        'description'  => get_string('limittodescsideblock1', 'blocktype.mygroups'),
366
        'defaultvalue' => isset($prefs->groupsideblockmaxgroups) ? $prefs->groupsideblockmaxgroups : '',
367 368 369 370 371
        'rules'        => array('regex' => '/^[0-9]*$/', 'minvalue' => 0, 'maxvalue' => 1000),
    );
    $elements['groupsideblocksortby'] = array(
        'type'         => 'select',
        'defaultvalue' => isset($prefs->groupsideblocksortby) ? $prefs->groupsideblocksortby : 'alphabetical',
372
        'title' => get_string('sortgroups', 'blocktype.mygroups'),
373 374 375 376 377 378
        'options' =>  array(
            'latest' => get_string('latest', 'blocktype.mygroups'),
            'earliest' => get_string('earliest', 'blocktype.mygroups'),
            'alphabetical'  => get_string('alphabetical', 'blocktype.mygroups'),
        ),
    );
379 380 381 382 383 384 385 386 387 388 389 390
    if (get_config('userscanhiderealnames')) {
        $elements['hiderealname'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('hiderealname', 'account'),
            'description'  => get_string('hiderealnamedescription', 'account'),
            'defaultvalue' => $prefs->hiderealname,
        );
    }
    if (get_config('homepageinfo')) {
        $elements['showhomeinfo'] = array(
            'type' => 'checkbox',
            'defaultvalue' => $prefs->showhomeinfo,
391 392
            'title' => get_string('showhomeinfo2', 'account'),
            'description' => get_string('showhomeinfodescription1', 'account', hsc(get_config('sitename'))),
393 394 395
            'help' => 'true'
        );
    }
396 397 398 399 400 401 402 403
    if (get_config('showprogressbar')) {
        $elements['showprogressbar'] = array(
            'type' => 'checkbox',
            'defaultvalue' => $prefs->showprogressbar,
            'title' => get_string('showprogressbar', 'account'),
            'description' => get_string('showprogressbardescription', 'account', hsc(get_config('sitename'))),
        );
    }
404
    if (get_config('allowmobileuploads')) {
405 406 407 408
        $defaultvalue = array();
        $mobileuploadtoken = isset($prefs->mobileuploadtoken) ? $prefs->mobileuploadtoken : get_config('mobileuploadtoken');
        $defaultvalue = explode('|', trim($mobileuploadtoken, '|'));

409
        $elements['mobileuploadtoken'] = array(
410
            'type'         => 'multitext',
411
            'title'        => get_string('mobileuploadtoken', 'account'),
412 413
            'defaultvalue' => $defaultvalue,
            'help'         => 'true'
414 415
        );
    }
416 417 418
    if (get_config_plugin('artefact', 'file', 'resizeonuploadenable')) {
        $elements['resizeonuploaduserdefault'] = array(
            'type'         => 'checkbox',
419 420
            'title'        => get_string('resizeonuploaduserdefault1', 'account'),
            'description'  => get_string('resizeonuploaduserdefaultdescription1', 'account'),
421 422 423
            'defaultvalue' => $prefs->resizeonuploaduserdefault,
        );
    }
424

425 426 427 428 429 430 431 432 433
    if (get_config('userscandisabledevicedetection')) {
        $elements['devicedetection'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('devicedetection', 'account'),
            'description'  => get_string('devicedetectiondescription', 'account'),
            'defaultvalue' => $prefs->devicedetection,
        );
    }

434 435 436
    return $elements;
}

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 480 481 482 483 484 485 486 487 488 489 490 491 492
/**
 * 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;
}

493 494
/**
 * Save a profile field.
495
 * Exception is 'socialprofile' field. It is made up of 2 fields:
496 497 498 499 500 501
 * socialprofile_profileurl,
 * socialprofile_profiletype
 * @param int $userid
 * @param string $field
 * @param string (or array for socialprofile) $value
 */
502 503
function set_profile_field($userid, $field, $value) {
    safe_require('artefact', 'internal');
504 505 506 507 508

    // this is a special case that replaces the primary email address with the
    // specified one
    if ($field == 'email') {
        try {
509
            $email = artefact_instance_from_type('email', $userid);
510 511 512 513 514 515 516 517
        }
        catch (ArtefactNotFoundException $e) {
            $email = new ArtefactTypeEmail();
            $email->set('owner', $userid);
        }
        $email->set('title', $value);
        $email->commit();
    }
518
    else if ($field == 'socialprofile') {
519 520 521 522 523 524 525 526
        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';
        }
527 528 529
        $classname = generate_artefact_class_name($field);
        $profile = new $classname(0, array('owner' => $userid));
        $profile->set('title',       $value['socialprofile_profileurl']);
530 531
        $profile->set('description', $desc);
        $profile->set('note',        $type);
532 533
        $profile->commit();
    }
534 535 536 537 538 539
    else {
        $classname = generate_artefact_class_name($field);
        $profile = new $classname(0, array('owner' => $userid));
        $profile->set('title', $value);
        $profile->commit();
    }
540 541 542 543 544 545 546
}

/**
 * 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
547 548 549
 * @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
550 551 552 553
 *
 * @todo, this needs to be better (fix email behaviour)
 */
function get_profile_field($userid, $field) {
554 555 556 557 558 559 560
    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));
    }
561 562 563 564 565 566 567 568
    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();
        }
    }
569 570 571
    else {
        $value = get_field('artefact', 'title', 'owner', $userid, 'artefacttype', $field);
    }
572 573 574 575

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

577
    return null;
578 579
}

Aaron Wells's avatar
Aaron Wells committed
580
/**
581
 * Always use this function for all emails to users
Aaron Wells's avatar
Aaron Wells committed
582
 *
583 584 585 586 587
 * @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)
588
 * @param array  $customheaders email headers
589
 * @throws EmailException
590
 * @throws EmailDisabledException
Aaron Wells's avatar
Aaron Wells committed
591
 */
592
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml='', $customheaders=null) {
593 594 595
    global $IDPJUMPURL;
    static $mnetjumps = array();

596
    if (!get_config('sendemail')) {
Aaron Wells's avatar
Aaron Wells committed
597
        // You can entirely disable Mahara from sending any e-mail via the
598 599 600
        // 'sendemail' configuration variable
        return true;
    }
601 602 603 604

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

606
    if (isset($userto->id) && empty($userto->ignoredisabled)) {
607 608 609 610
        $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");
        }
611 612
    }

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    // 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);
    }


636 637
    require_once('phpmailer/class.phpmailer.php');

638
    $mail = new phpmailer(true);
639

640 641
    // Leaving this commented out - there's no reason for people to know this
    //$mail->Version = 'Mahara ' . get_config('release');
642
    $mail->PluginDir = get_config('libroot')  . 'phpmailer/';
Aaron Wells's avatar
Aaron Wells committed
643

644 645 646 647 648 649
    $mail->CharSet = 'UTF-8';

    $smtphosts = get_config('smtphosts');
    if ($smtphosts == 'qmail') {
        // use Qmail system
        $mail->IsQmail();
Aaron Wells's avatar
Aaron Wells committed
650
    }
651 652 653 654 655 656 657 658 659 660
    else if (empty($smtphosts)) {
        // use PHP mail() = sendmail
        $mail->IsMail();
    }
    else {
        $mail->IsSMTP();
        // use SMTP directly
        $mail->Host = get_config('smtphosts');
        if (get_config('smtpuser')) {
            // Use SMTP authentication
661 662 663 664 665
            $mail->SMTPAuth   = true;
            $mail->Username   = get_config('smtpuser');
            $mail->Password   = get_config('smtppass');
            $mail->SMTPSecure = get_config('smtpsecure');
            $mail->Port       = get_config('smtpport');
666 667 668 669 670 671 672 673 674
            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;
                }
            }
675 676 677
        }
    }

678 679
    if (get_config('bounces_handle') && !empty($userto->id) && empty($maildisabled)) {
        $mail->Sender = generate_email_processing_address($userto->id, $userto);
680
    }
681
    if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) {
682 683 684 685
        if (empty($mail->Sender)) {
            $mail->Sender = get_config('noreplyaddress');
        }
        $mail->From = get_config('noreplyaddress');
686
        $mail->FromName = (isset($userfrom->id)) ? display_name($userfrom, $userto) : get_config('sitename');
687
        $customheaders[] = 'Precedence: Bulk'; // Try to avoid pesky out of office responses
Richard Mansfield's avatar
Richard Mansfield committed
688
        $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n";
689
        if ($messagehtml) {
Richard Mansfield's avatar
Richard Mansfield committed
690
            $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n";
691
        }
692 693
    }
    else {
694 695 696 697
        if (empty($mail->Sender)) {
            $mail->Sender = $userfrom->email;
        }
        $mail->From = $userfrom->email;
698 699
        $mail->FromName = display_name($userfrom, $userto);
    }
700
    $replytoset = false;
701 702
    if (!empty($customheaders) && is_array($customheaders)) {
        foreach ($customheaders as $customheader) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
            // 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);
            }
721 722 723
            if (0 === stripos($customheader, 'reply-to')) {
                $replytoset = true;
            }
724 725
        }
    }
726

727
    $mail->Subject = substr(stripslashes($subject), 0, 900);
728

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    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);
748 749
        }
    }
750
    catch (phpmailerException $e) {
751 752 753 754
        // 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
755
    $mail->WordWrap = 79;
756

Aaron Wells's avatar
Aaron Wells committed
757
    if ($messagehtml) {
758 759 760
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body    =  $messagehtml;
761
        $mail->AltBody =  $messagetext;
Aaron Wells's avatar
Aaron Wells committed
762
    }
763 764
    else {
        $mail->IsHTML(false);
765
        $mail->Body =  $messagetext;
766 767
    }

768 769 770 771 772 773 774 775
    try {
        $sent = $mail->Send();
    }
    catch (phpmailerException $e) {
        $sent = false;
    }

    if ($sent) {
776 777 778 779 780 781 782
        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));
            }
783
            $line = "$to <- $mail->From - " . str_shorten_text($mail->Subject, 200);
784 785 786
            @error_log('[' . date("Y-m-d h:i:s") . "] [$client] [$script] $line\n", 3, $logfile);
        }

787 788 789 790
        if (get_config('bounces_handle')) {
            // Update the count of sent mail
            update_send_count($userto);
        }
791

792
        return true;
Aaron Wells's avatar
Aaron Wells committed
793
    }
794 795 796 797
    throw new EmailException("Couldn't send email to $usertoname with subject $subject. "
                        . "Error from phpmailer was: " . $mail->ErrorInfo );
}

798 799 800 801 802 803 804 805 806 807 808 809 810 811
/**
 * 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');
812 813 814
    // 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);
815 816 817
    return $mailprefix . $args . substr(md5($mailprefix . $userto->email . $installation_key), 0, 16) . '@' . $maildomain;
}

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
/**
 * 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
834 835 836 837
    $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) {
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
        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
            $message = new StdClass;
            $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;
}

875 876 877 878 879 880 881 882 883 884 885 886
/**
 * 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
887
    if ($mailinfo = get_record_select('artefact_internal_profile_email', '"owner" = ? AND email = ? AND principal = 1', array($userto->id, $userto->email))) {
888 889 890 891 892
        $mailinfo->mailssent = (!empty($reset)) ? 0 : $mailinfo->mailssent+1;
        update_record('artefact_internal_profile_email', $mailinfo, array('email' => $userto->email, 'owner' => $userto->id));
    }
}

893 894 895 896 897 898 899 900 901 902 903 904
/**
 * 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
905
    if ($mailinfo = get_record_select('artefact_internal_profile_email', '"owner" = ? AND email = ? AND principal = 1', array($userto->id, $userto->email))) {
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
        $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
 *
 * @param string $address the email address to process
 */
function process_email($address) {

    $email = new StdClass;

    if (strlen($address) <= 30) {
        log_debug ('-- Email address not long enough to contain valid data.');
        return $email;
    }

    if (!strstr($address, '@')) {
        log_debug ('-- Email address does not contain @.');
        return $email;
    }

930 931 932
    $mailprefix = get_config('bounceprefix');
    $prefixlength = strlen($mailprefix);

933
    list($email->localpart,$email->domain) = explode('@',$address);
934 935
    // The prefix is stored in the first characters denoted by $prefixlength
    $email->prefix        = substr($email->localpart, 0, $prefixlength);
936
    // The type of message received is a one letter code
937
    $email->type          = substr($email->localpart, $prefixlength, 1);
938
    // The userid should be available immediately afterwards
939 940 941
    // Postfix and other smtp servers don't like the use of / in the extension part of an email
    // We may of replaced it with another valid email character which isn't in base64, namely '-'
    // If we didn't, then the preg_replace won't do anything
942
    list(,$email->userid) = unpack('V',base64_decode(preg_replace('/-/', '/', substr($email->localpart, $prefixlength + 1, 8))));
943
    // Any additional arguments
944
    $email->args          = substr($email->localpart, $prefixlength + 9,-16);
945 946 947 948 949 950 951 952 953 954
    // And a hash of the intended recipient for authentication
    $email->addresshash   = substr($email->localpart,-16);

    if (!$email->userid) {
        log_debug('-- no userid associated with this email address');
        return $email;
    }

    switch ($email->type) {
    case 'B': // E-mail bounces
Francois Marier's avatar
Francois Marier committed
955
        if ($user = get_record_select('artefact_internal_profile_email', '"owner" = ? AND principal = 1', array($email->userid))) {
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
            $maildomain = get_config('bouncedomain');
            $installation_key = get_config('installation_key');
            // check the half md5 of their email
            $md5check = substr(md5($mailprefix . $user->email . $installation_key), 0, 16);
            $user->id = $user->owner;
            if ($md5check == substr($email->addresshash, -16)) {
                update_bounce_count($user);
                check_overcount($user);
            }
            // else maybe they've already changed their email address
        }
        break;
        // No more cases yet
    }
    return $email;
}

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
/**
 * Check an imap mailbox for new mailbounces
 */
function check_imap_for_bounces() {
    $imapserver = get_config('imapserver');
    if (!$imapserver) {
        return;
    }
    if (!extension_loaded('imap')) {
        log_debug('php imap extension not loaded, can\'t continue');
        return;
    }
    $imapport = get_config('imapport');
    $imap = imap_open("{" . $imapserver . ($imapport ? ':' . $imapport : '') . get_config('imapflags') . '}' . get_config('imapmailbox'),
                        get_config('imapuser'), get_config('imappass'));
    $check = imap_check($imap);
    if ($check->Nmsgs == 0) {
        imap_close($imap);
        return;
    }
    $emails = imap_fetch_overview($imap, "1:" . $check->Nmsgs);
    foreach ($emails as $email) {
        if ($email->deleted) {
            continue;
        }
        $address = $email->to;
        log_debug('---------- started  processing email at ' . date('r', time()) . ' ----------');
        log_debug('-- mail from ' . $address . ' -- delivered ' . $email->date);

        $ret = process_email($address);

        log_debug('---------- finished processing email at ' . date('r', time()) . ' ----------');

        imap_delete($imap, $email->msgno);
    }
    imap_expunge($imap);
    imap_close($imap);
}

1012 1013 1014 1015 1016 1017 1018
/**
 * converts a user object to a string representation of the user suitable for
 * the current user (or specified user) to see
 *
 * Both parameters should be objects containing id, preferredname, firstname,
 * lastname, admin
 *
1019 1020
 * @param object $user the user that you're trying to format to a string
 * @param object $userto the user that is looking at the string representation (if left
1021
 * blank, will default to the currently logged in user).
1022
 * @param boolean $nameonly do not append the user's username even if $userto can see it.
1023
 * @param boolean $realname show the user's real name even if preferredname exists
1024
 * @param boolean $username show the user's username even if the viewer is not an admin
1025 1026 1027
 *
 * @returns string name to display
 */
1028
function display_name($user, $userto=null, $nameonly=false, $realname=false, $username=false) {
1029
    global $USER;
1030
    static $tutorcache  = array();
Nigel McNie's avatar
Nigel McNie committed
1031

1032 1033 1034 1035
    if ($nameonly) {
        return display_default_name($user);
    }

1036 1037
    $userto = get_user_for_display($userto);
    $user   = get_user_for_display($user);
1038

1039
    $addusername = $username || !empty($userto->admin) || !empty($userto->staff);
Nigel McNie's avatar
Nigel McNie committed
1040

1041 1042
    // if they don't have a preferred name set, just return here
    if (empty($user->preferredname)) {
1043 1044
        $firstlast = full_name($user);
        if ($addusername) {
1045
            return $firstlast . ' (' . display_username($user) . ')';
1046
        }
1047
        return $firstlast;
1048
    }
1049 1050
    else if ($user->id == $userto->id) {
        // If viewing our own name, show it how we like it
1051
        return $user->preferredname;
1052
    }
1053

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
    // Preferred name is set
    $addrealname = $realname || !empty($userto->admin) || !empty($userto->staff);

    if (!$addrealname) {
        // Tutors can always see the user's real name, so we need to check if the
        // viewer is a tutor of the user whose name is being displayed
        if (!isset($tutorcache[$user->id][$userto->id])) {
            $tutorcache[$user->id][$userto->id] = record_exists_sql('
                SELECT s.member
                FROM {group_member} s
                JOIN {group_member} t ON s.group = t.group
1065
                JOIN {group} g ON (g.id = s.group AND g.deleted = 0 AND g.submittableto = 1)
1066 1067 1068 1069 1070 1071 1072
                JOIN {grouptype_roles} gtr
                    ON (g.grouptype = gtr.grouptype AND gtr.role = t.role AND gtr.see_submitted_views = 1)
                WHERE s.member = ? AND t.member = ?',
                array($user->id, $userto->id)
            );
        }
        $addrealname = $tutorcache[$user->id][$userto->id];
1073 1074
    }

1075 1076 1077
    if ($addrealname) {
        $firstlast = full_name($user);
        if ($addusername) {
1078
            return $user->preferredname . ' (' . $firstlast . ' - ' . display_username($user) . ')';
1079 1080
        }
        return $user->preferredname . ' (' . $firstlast . ')';
1081
    }
1082
    if ($addusername) {
1083
        return $user->preferredname . ' (' . display_username($user) . ')';
1084 1085
    }
    return $user->preferredname;
1086 1087
}

Penny Leach's avatar
Penny Leach committed
1088 1089 1090
/**
 * function to format a users name when there is no user to look at them
 * ie when display_name is not going to work..
1091
 */
Penny Leach's avatar
Penny Leach committed
1092
function display_default_name($user) {
1093
    $user = get_user_for_display($user);
1094
    return empty($user->preferredname) ? full_name($user) : $user->preferredname;
Penny Leach's avatar
Penny Leach committed
1095 1096 1097 1098
}



1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
/**
 * Converts a user object to a full name representation, honouring the language
 * setting.
 *
 * Currently a stub, will need to be improved and completed as demand arises.
 *
 * @param object $user The user object to make a full name out of. If empty,
 *                     the global $USER object is used*/
function full_name($user=null) {
    global $USER;

    if ($user === null) {
        $user = new StdClass;
        $user->firstname = $USER->get('firstname');
        $user->lastname  = $USER->get('lastname');
1114
        $user->deleted   = $USER->get('deleted');
1115 1116
    }

1117
    return isset($user->deleted) && $user->deleted ? get_string('deleteduser') : $user->firstname . ' ' . $user->lastname;
1118
}
1119

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
/**
 * Takes an array, object or integer identifying a user and returns an object with
 * the properties needed for display_name, display_default_name, or profile_icon_url.
 */
function get_user_for_display($user=null) {
    global $USER;
    static $usercache = array();

    $fields = array(
        'id', 'username', 'preferredname', 'firstname', 'lastname', 'admin', 'staff',
1130
        'profileicon', 'email', 'deleted', 'urlid', 'suspendedctime',
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    );

    if (is_numeric($user) && isset($usercache[$user])) {
        return $usercache[$user];
    }

    if (is_array($user)) {
        $user = (object)$user;
    }
    else if (is_null($user) || (is_numeric($user) && $user == $USER->get('id'))) {
        $user = new StdClass;
        foreach ($fields as $f) {
            $user->$f = $USER->get($f);
        }
1145 1146
        $user->admin = $user->admin || $USER->is_institutional_admin();
        $user->staff = $user->staff || $USER->is_institutional_staff();
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181