user.php 88.9 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
Penny Leach's avatar
Penny Leach committed
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
Penny Leach's avatar
Penny Leach committed
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
Penny Leach's avatar
Penny Leach committed
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Penny Leach's avatar
Penny Leach committed
19
20
21
 *
 * @package    mahara
 * @subpackage core
22
 * @author     Catalyst IT Ltd
Penny Leach's avatar
Penny Leach committed
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
Penny Leach's avatar
Penny Leach committed
25
26
27
28
29
 *
 */

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

30
31
define('MAX_USERNAME_DISPLAY', 30);

Penny Leach's avatar
Penny Leach committed
32
33
34
35
36
37
38
39
40
41
42
/** 
 * loads up activity preferences for a given user
 *
 * @param int $userid to load preferences for 
 * @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
43
    if ($prefs = get_records_assoc('usr_activity_preference', 'usr', $userid, '', 'activity,method')) {
Penny Leach's avatar
Penny Leach committed
44
        foreach ($prefs as $p) {
45
            $prefs[$p->activity] = $p->method;
Penny Leach's avatar
Penny Leach committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
        }
    }
    return $prefs;
}

/** 
 * loads up account preferences for a given user
 * if you want them for the current user
 * use $SESSION->accountprefs
 *
 * @param int $userid to load preferences for 
 * @todo caching
 * @todo defaults? 
 */
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");
    }
66
    if ($prefs = get_records_array('usr_account_preference', 'usr', $userid)) {
Penny Leach's avatar
Penny Leach committed
67
        foreach ($prefs as $p) {
68
            $prefs[$p->field] = $p->value;
Penny Leach's avatar
Penny Leach committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        }
    }
    foreach ($expectedprefs as $field => $default) {
        if (!isset($prefs[$field])) {
            $prefs[$field] = $default;
        }
    }
    return $prefs;
}


/** 
 * sets a user preference in the database
 * if you want to set it in the session as well
 * use SESSION->set_account_preference 
 *
 * @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) {
90
91
92
93
94
95
96
97
98
99
    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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    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");
        }
    }
}

118
119
120

/** 
 * Change language-specific stuff in the db for a user.  Currently
121
122
 * 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
123
 * sideblock
124
125
126
127
128
129
 *
 * @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) {
130
131
132
133
    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
134
135
    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));
136
137
}

Penny Leach's avatar
Penny Leach committed
138
139
140
141
142
143
/** 
 * sets an activity preference in the database
 * if you want to set it in the session as well
 * use $SESSION->set_activity_preference 
 *
 * @param int $userid user id to set preference for
144
 * @param int $activity activity type to set
Penny Leach's avatar
Penny Leach committed
145
146
147
 * @param string $method notification method to set.
 */
function set_activity_preference($userid, $activity, $method) {
148
149
150
    if (empty($method)) {
        return delete_records('usr_activity_preference', 'activity', $activity, 'usr', $userid);
    }
Penny Leach's avatar
Penny Leach committed
151
152
153
154
155
156
157
158
159
160
161
162
163
    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 "
164
                ." $method for $activity for user $userid");
Penny Leach's avatar
Penny Leach committed
165
166
167
168
        }
    }
}

169
170
171
172
173
174
175
176
177
/**
 * gets an account preference for the user, 
 * 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) {
178
    if ($pref = get_record('usr_account_preference', 'usr', $userid, 'field', $field)) {
179
180
181
182
183
184
        return $pref->value;
    }
    $expected = expected_account_preferences();
    return $expected[$field];
}

185
186
187
188
189
190
191
192
193
194

function get_user_language($userid) {
    $langpref = get_account_preference($userid, 'lang');
    if (empty($langpref) || $langpref == 'default') {
        return get_config('lang');
    }
    return $langpref;
}


195
196
197
198
199
/**
 * default account settings
 * 
 * @returns array of fields => values
 */
Penny Leach's avatar
Penny Leach committed
200
201
202
203
function expected_account_preferences() {
    return array('friendscontrol' => 'auth',
                 'wysiwyg'        =>  1,
                 'messages'       => 'allow',
204
                 'lang'           => 'default',
205
                 'addremovecolumns' => 0,
206
                 'maildisabled'   => 0,
207
                 'tagssideblockmaxtags' => get_config('tagssideblockmaxtags'),
208
                 'hiderealname'   => 0,
209
                 'multipleblogs' => 0,
210
                 'showhomeinfo' => 1,
211
                 'mobileuploadtoken' => '',
Penny Leach's avatar
Penny Leach committed
212
213
214
                 );
}

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
function general_account_prefs_form_elements($prefs) {
    $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'),
    );
    $elements['maildisabled'] = array(
        'type' => 'checkbox',
        'defaultvalue' => $prefs->maildisabled,
        'title' => get_string('email'),
        '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();
    $elements['lang'] = array(
        'type' => 'select',
        'defaultvalue' => $prefs->lang,
        'title' => get_string('language', 'account'),
        'options' => array_merge(array('default' => get_string('sitedefault', 'admin') . ' (' . $languages[get_config('lang')] . ')'), $languages),
        'help' => true,
        'ignore' => count($languages) < 2,
    );
    $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',
        'title'=> get_string('enablemultipleblogs' ,'account'),
        '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),
        );
    }
    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,
            'title' => get_string('showhomeinfo', 'account'),
            'help' => 'true'
        );
    }
    if (get_config('allowmobileuploads')) {
        $elements['mobileuploadtoken'] = array(
            'type'         => 'text',
            'title'        => get_string('mobileuploadtoken', 'account'),
            'description'  => get_string('mobileuploadtokendescription', 'account'),
            'defaultvalue' => isset($prefs->mobileuploadtoken) ? $prefs->mobileuploadtoken : get_config('mobileuploadtoken')
        );
    }

    return $elements;
}

314
315
function set_profile_field($userid, $field, $value) {
    safe_require('artefact', 'internal');
316
317
318
319
320

    // this is a special case that replaces the primary email address with the
    // specified one
    if ($field == 'email') {
        try {
321
            $email = artefact_instance_from_type('email', $userid);
322
323
324
325
326
327
328
329
330
331
332
333
334
335
        }
        catch (ArtefactNotFoundException $e) {
            $email = new ArtefactTypeEmail();
            $email->set('owner', $userid);
        }
        $email->set('title', $value);
        $email->commit();
    }
    else {
        $classname = generate_artefact_class_name($field);
        $profile = new $classname(0, array('owner' => $userid));
        $profile->set('title', $value);
        $profile->commit();
    }
336
337
338
339
340
341
342
343
344
345
346
347
}

/**
 * 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
 * @returns string the value of the profile field (null if it doesn't exist)
 *
 * @todo, this needs to be better (fix email behaviour)
 */
function get_profile_field($userid, $field) {
348
349
350
351
352
353
354
355
356
357
    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));
    }
    else {
        $value = get_field('artefact', 'title', 'owner', $userid, 'artefacttype', $field);
    }
358
359
360
361

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

363
    return null;
364
365
}

366
367
368
369
370
371
372
373
/** 
 * Always use this function for all emails to users
 * 
 * @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)
374
 * @param array  $customheaders email headers
375
 * @throws EmailException
376
 * @throws EmailDisabledException
377
 */ 
378
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml='', $customheaders=null) {
379
380
381
    global $IDPJUMPURL;
    static $mnetjumps = array();

382
383
384
385
386
    if (!get_config('sendemail')) {
        // You can entirely disable Mahara from sending any e-mail via the 
        // 'sendemail' configuration variable
        return true;
    }
387
388
389
390

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

392
    if (isset($userto->id) && empty($userto->ignoredisabled)) {
393
394
395
396
        $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");
        }
397
398
    }

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
    // 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);
    }


422
423
    require_once('phpmailer/class.phpmailer.php');

424
    $mail = new phpmailer(true);
425

426
427
    // Leaving this commented out - there's no reason for people to know this
    //$mail->Version = 'Mahara ' . get_config('release');
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
    $mail->PluginDir = get_config('libroot')  . 'phpmailer/';
    
    $mail->CharSet = 'UTF-8';

    $smtphosts = get_config('smtphosts');
    if ($smtphosts == 'qmail') {
        // use Qmail system
        $mail->IsQmail();
    } 
    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
447
448
449
450
451
            $mail->SMTPAuth   = true;
            $mail->Username   = get_config('smtpuser');
            $mail->Password   = get_config('smtppass');
            $mail->SMTPSecure = get_config('smtpsecure');
            $mail->Port       = get_config('smtpport');
452
453
454
455
456
457
458
459
460
            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;
                }
            }
461
462
463
        }
    }

464
465
    if (get_config('bounces_handle') && !empty($userto->id) && empty($maildisabled)) {
        $mail->Sender = generate_email_processing_address($userto->id, $userto);
466
    }
467
    if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) {
468
469
470
471
        if (empty($mail->Sender)) {
            $mail->Sender = get_config('noreplyaddress');
        }
        $mail->From = get_config('noreplyaddress');
472
        $mail->FromName = (isset($userfrom->id)) ? display_name($userfrom, $userto) : get_config('sitename');
473
        $customheaders[] = 'Precedence: Bulk'; // Try to avoid pesky out of office responses
Richard Mansfield's avatar
Richard Mansfield committed
474
        $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n";
475
        if ($messagehtml) {
Richard Mansfield's avatar
Richard Mansfield committed
476
            $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n";
477
        }
478
479
    }
    else {
480
481
482
483
        if (empty($mail->Sender)) {
            $mail->Sender = $userfrom->email;
        }
        $mail->From = $userfrom->email;
484
485
        $mail->FromName = display_name($userfrom, $userto);
    }
486
    $replytoset = false;
487
488
489
    if (!empty($customheaders) && is_array($customheaders)) {
        foreach ($customheaders as $customheader) {
            $mail->AddCustomHeader($customheader);
490
491
492
            if (0 === stripos($customheader, 'reply-to')) {
                $replytoset = true;
            }
493
494
        }
    }
495

496
    $mail->Subject = substr(stripslashes($subject), 0, 900);
497

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    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);
517
518
        }
    }
519
    catch (phpmailerException $e) {
520
521
522
523
        // 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);
    }

524
525
526
527
528
529
    $mail->WordWrap = 79;   

    if ($messagehtml) { 
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body    =  $messagehtml;
530
        $mail->AltBody =  $messagetext;
531
532
533
    } 
    else {
        $mail->IsHTML(false);
534
        $mail->Body =  $messagetext;
535
536
    }

537
538
539
540
541
542
543
544
    try {
        $sent = $mail->Send();
    }
    catch (phpmailerException $e) {
        $sent = false;
    }

    if ($sent) {
545
546
547
548
549
550
551
        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));
            }
552
            $line = "$to <- $mail->From - " . str_shorten_text($mail->Subject, 200);
553
554
555
            @error_log('[' . date("Y-m-d h:i:s") . "] [$client] [$script] $line\n", 3, $logfile);
        }

556
557
558
559
        if (get_config('bounces_handle')) {
            // Update the count of sent mail
            update_send_count($userto);
        }
560

561
562
563
564
565
566
        return true;
    } 
    throw new EmailException("Couldn't send email to $usertoname with subject $subject. "
                        . "Error from phpmailer was: " . $mail->ErrorInfo );
}

567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/**
 * 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');
    $args = $type . base64_encode(pack('V', $userid)) . substr(md5($userto->email), 0, 16);
    return $mailprefix . $args . substr(md5($mailprefix . $userto->email . $installation_key), 0, 16) . '@' . $maildomain;
}

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
633
634
635
636
637
638
/**
 * 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;
    }

    if ((! $minbounces = get_config('bounces_min')) || (! $bounceratio = get_config('bounces_ratio'))) {
        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;
}

639
640
641
642
643
644
645
646
647
648
649
650
/**
 * 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
651
    if ($mailinfo = get_record_select('artefact_internal_profile_email', '"owner" = ? AND email = ? AND principal = 1', array($userto->id, $userto->email))) {
652
653
654
655
656
        $mailinfo->mailssent = (!empty($reset)) ? 0 : $mailinfo->mailssent+1;
        update_record('artefact_internal_profile_email', $mailinfo, array('email' => $userto->email, 'owner' => $userto->id));
    }
}

657
658
659
660
661
662
663
664
665
666
667
668
/**
 * 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
669
    if ($mailinfo = get_record_select('artefact_internal_profile_email', '"owner" = ? AND email = ? AND principal = 1', array($userto->id, $userto->email))) {
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
        $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;
    }

    list($email->localpart,$email->domain) = explode('@',$address);
    // The prefix is stored in the first four characters
    $email->prefix        = substr($email->localpart,0,4);
    // The type of message received is a one letter code
    $email->type          = substr($email->localpart,4,1);
    // The userid should be available immediately afterwards
    list(,$email->userid) = unpack('V',base64_decode(substr($email->localpart,5,8)));
    // Any additional arguments
    $email->args          = substr($email->localpart,13,-16);
    // 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
713
        if ($user = get_record_select('artefact_internal_profile_email', '"owner" = ? AND principal = 1', array($email->userid))) {
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
            $mailprefix = get_config('bounceprefix');
            $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;
}

732
733
734
735
736
737
738
/**
 * 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
 *
739
740
 * @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
741
 * blank, will default to the currently logged in user).
742
 * @param boolean $nameonly do not append the user's username even if $userto can see it.
743
 * @param boolean $realname show the user's real name even if preferredname exists
744
 * @param boolean $username show the user's username even if the viewer is not an admin
745
746
747
 *
 * @returns string name to display
 */
748
function display_name($user, $userto=null, $nameonly=false, $realname=false, $username=false) {
749
    global $USER;
750
    static $tutorcache  = array();
Nigel McNie's avatar
Nigel McNie committed
751
752
    static $usercache   = array();

753
754
755
756
    if ($nameonly) {
        return display_default_name($user);
    }

757
758
759
    if (empty($userto)) {
        $userto = new StdClass;
        $userto->id            = $USER->get('id');
760
        $userto->username      = $USER->get('username');
761
762
763
        $userto->preferredname = $USER->get('preferredname');
        $userto->firstname     = $USER->get('firstname');
        $userto->lastname      = $USER->get('lastname');
764
        $userto->admin         = $USER->get('admin') || $USER->is_institutional_admin();
765
        $userto->staff         = $USER->get('staff') || $USER->is_institutional_staff();
766
    }
Nigel McNie's avatar
Nigel McNie committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
    else if (is_numeric($userto)) {
        if (isset($usercache[$userto])) {
            $userto = $usercache[$userto];
        }
        else if ($userto == $USER->get('id')) {
            $userto = new StdClass;
            $userto->id            = $USER->get('id');
            $userto->username      = $USER->get('username');
            $userto->preferredname = $USER->get('preferredname');
            $userto->firstname     = $USER->get('firstname');
            $userto->lastname      = $USER->get('lastname');
            $userto->admin         = $USER->get('admin') || $USER->is_institutional_admin();
            $userto->staff         = $USER->get('staff') || $USER->is_institutional_staff();
            $usercache[$userto->id] = $userto;
        }
        else {
            $userto = $usercache[$userto] = get_record('usr', 'id', $userto);
        }
    }

787
788
789
790
    if (is_array($user)) {
        $user = (object)$user;
    }
    else if (is_numeric($user)) {
Nigel McNie's avatar
Nigel McNie committed
791
792
793
794
795
796
797
798
799
800
801
802
        if (isset($usercache[$user])) {
            $user = $usercache[$user];
        }
        else if ($user == $USER->get('id')) {
            $user = new StdClass;
            $user->id            = $USER->get('id');
            $user->username      = $USER->get('username');
            $user->preferredname = $USER->get('preferredname');
            $user->firstname     = $USER->get('firstname');
            $user->lastname      = $USER->get('lastname');
            $user->admin         = $USER->get('admin') || $USER->is_institutional_admin();
            $user->staff         = $USER->get('staff') || $USER->is_institutional_staff();
803
            $user->deleted       = 0;
Nigel McNie's avatar
Nigel McNie committed
804
805
806
807
808
            $usercache[$user->id] = $user;
        }
        else {
            $user = $usercache[$user] = get_record('usr', 'id', $user);
        }
809
810
811
812
813
    }
    if (!is_object($user)) {
        throw new InvalidArgumentException("Invalid user passed to display_name");
    }

Martyn Smith's avatar
Martyn Smith committed
814
815
816
817
    if ($user instanceof User) {
        $userObj = $user;
        $user = new StdClass;
        $user->id            = $userObj->get('id');
818
        $user->username      = $userObj->get('username');
Martyn Smith's avatar
Martyn Smith committed
819
820
821
822
        $user->preferredname = $userObj->get('preferredname');
        $user->firstname     = $userObj->get('firstname');
        $user->lastname      = $userObj->get('lastname');
        $user->admin         = $userObj->get('admin');
823
        $user->staff         = $userObj->get('staff');
824
        $user->deleted       = $userObj->get('deleted');
Martyn Smith's avatar
Martyn Smith committed
825
826
    }

827
828
829
    $user->id   = (isset($user->id)) ? $user->id : null;
    $userto->id = (isset($userto->id)) ? $userto->id : null;

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

832
833
    // if they don't have a preferred name set, just return here
    if (empty($user->preferredname)) {
834
835
        $firstlast = full_name($user);
        if ($addusername) {
836
            return $firstlast . ' (' . display_username($user) . ')';
837
        }
838
        return $firstlast;
839
    }
840
841
    else if ($user->id == $userto->id) {
        // If viewing our own name, show it how we like it
842
        return $user->preferredname;
843
    }
844

845
846
847
848
849
850
851
852
853
854
855
    // 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
856
                JOIN {group} g ON (g.id = s.group AND g.deleted = 0 AND g.submittableto = 1)
857
858
859
860
861
862
863
                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];
864
865
    }

866
867
868
    if ($addrealname) {
        $firstlast = full_name($user);
        if ($addusername) {
869
            return $user->preferredname . ' (' . $firstlast . ' - ' . display_username($user) . ')';
870
871
        }
        return $user->preferredname . ' (' . $firstlast . ')';
872
    }
873
    if ($addusername) {
874
        return $user->preferredname . ' (' . display_username($user) . ')';
875
876
    }
    return $user->preferredname;
877
878
}

Penny Leach's avatar
Penny Leach committed
879
880
881
/**
 * function to format a users name when there is no user to look at them
 * ie when display_name is not going to work..
882
 */
Penny Leach's avatar
Penny Leach committed
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
function display_default_name($user) {
    if (is_array($user)) {
        $user = (object)$user;
    }
    else if (is_numeric($user)) {
        $user = get_record('usr', 'id', $user);
    }
    if (!is_object($user)) {
        throw new InvalidArgumentException("Invalid user passed to display_name");
    }

    if ($user instanceof User) {
        $userObj = $user;
        $user = new StdClass;
        $user->id            = $userObj->get('id');
        $user->preferredname = $userObj->get('preferredname');
        $user->firstname     = $userObj->get('firstname');
        $user->lastname      = $userObj->get('lastname');
901
        $user->deleted       = $userObj->get('deleted');
Penny Leach's avatar
Penny Leach committed
902
903
    }

904
    return empty($user->preferredname) ? full_name($user) : $user->preferredname;
Penny Leach's avatar
Penny Leach committed
905
906
907
908
}



909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
/**
 * 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');
924
        $user->deleted   = $USER->get('deleted');
925
926
    }

927
    return isset($user->deleted) && $user->deleted ? get_string('deleteduser') : $user->firstname . ' ' . $user->lastname;
928
}
929

930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
/**
 * Creates a string containing a displayable username.
 *
 * If the username is longer than 30 characters (bug #548165), then print
 * the first 30 characters followed by '...'
 *
 * @param object $user The user object to display the username of. If empty,
 *                     the global $USER object is used
 */
function display_username($user=null) {
    global $USER;

    if ($user === null) {
        $user = new StdClass;
        $user->username = $USER->get('username');
    }

    if (strlen($user->username) > MAX_USERNAME_DISPLAY) {
        return substr($user->username, 0, MAX_USERNAME_DISPLAY).'...';
    }
    else {
        return $user->username;
    }
}
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973

/**
 * helper function to default to currently
 * logged in user if there isn't an id specified
 * @throws InvalidArgumentException if there is no user and no $USER
 */
function optional_userid($userid) {

    if (!empty($userid)) {
        return $userid;
    }

    if (!is_logged_in()) {
        throw new InvalidArgumentException("optional_userid no userid and no logged in user");
    }
    
    global $USER;
    return $USER->get('id');
}

974
975
976
977
978
979
980
981
982
983
984
985
986


/**
 * helper function to default to currently
 * logged in user if there isn't an id specified
 * @throws InvalidArgumentException if there is no user and no $USER
 */
function optional_userobj($user) {

    if (!empty($user) && is_object($user)) {
        return $user;
    }

987
    if (!empty($user) && is_numeric($user)) {
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
        if ($user = get_record('usr', 'id', $user)) {
            return $user;
        }
        throw new InvalidArgumentException("optional_userobj given id $id no db match found");
    }

    if (!is_logged_in()) {
        throw new InvalidArgumentException("optional_userobj no userid and no logged in user");
    }
    
    global $USER;
    return $USER->to_stdclass();
}




1005
1006
1007
/**
 * helper function for testing logins
 */
1008
1009
function is_logged_in() {
    global $USER;
Martyn Smith's avatar
Martyn Smith committed
1010
1011
1012
1013
1014
    if (empty($USER)) {
        return false;
    }

    return $USER->is_logged_in();
1015
1016
}

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
/**
 * is there a friend relationship between these two users?
 *
 * @param int $userid1 
 * @param int $userid2
 */

function is_friend($userid1, $userid2) {
    return record_exists_select('usr_friend', '(usr1 = ? AND usr2 = ?) OR (usr2 = ? AND usr1 = ?)', 
                                array($userid1, $userid2, $userid1, $userid2));
}

/**
 * has there been a request between these two users?
 *
 * @param int $userid1
 * @param int $userid2
 */
function get_friend_request($userid1, $userid2) {
Francois Marier's avatar
Francois Marier committed
1036
    return get_record_select('usr_friend_request', '("owner" = ? AND requester = ?) OR (requester = ? AND "owner" = ?)',
1037
1038
1039
1040
                             array($userid1, $userid2, $userid1, $userid2));
        
} 

1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
/**
 * Returns an object containing information about a user, including account
 * and activity preferences
 *
 * @param int $userid The ID of the user to retrieve information about
 * @return object     The user object. Note this is not in the same form as
 *                    the $USER object used to denote the current user -
 *                    the object returned by this method is a simple object.
 */
function get_user($userid) {
    if (!$user = get_record('usr', 'id', $userid, null, null, null, null,
        '*, ' . db_format_tsfield('expiry') . ', ' . db_format_tsfield('lastlogin'))) {
        throw new InvalidArgumentException('Unknown user ' . $userid);
    }

    $user->activityprefs = load_activity_preferences($userid);
    $user->accountprefs  = load_account_preferences($userid);
    return $user;
}

1061

Nigel McNie's avatar
Nigel McNie committed
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
/**
 * Suspends a user
 *
 * @param int $suspendeduserid  The ID of the user to suspend
 * @param string $reason        The reason why the user is being suspended
 * @param int $suspendinguserid The ID of the user who is performing the suspension
 */
function suspend_user($suspendeduserid, $reason, $suspendinguserid=null) {
    if ($suspendinguserid === null) {
        global $USER;
        $suspendinguserid = $USER->get('id');
    }
1074

Nigel McNie's avatar
Nigel McNie committed
1075
1076
1077
1078
1079
1080
    $suspendrec = new StdClass;
    $suspendrec->id              = $suspendeduserid;
    $suspendrec->suspendedcusr   = $suspendinguserid;
    $suspendrec->suspendedreason = $reason;
    $suspendrec->suspendedctime  = db_format_timestamp(time());
    update_record('usr', $suspendrec, 'id');
1081

1082
1083
1084
1085
    // Try to kick the user from any active login session.
    require_once(get_config('docroot') . 'auth/session.php');
    remove_user_sessions($suspendeduserid);

1086
    $lang = get_user_language($suspendeduserid);
1087
1088
    $message = new StdClass;
    $message->users = array($suspendeduserid);
1089
    $message->subject = get_string_from_language($lang, 'youraccounthasbeensuspended');
1090
1091
1092
1093
1094
1095
1096
1097
    if ($reason == '') {
        $message->message = get_string_from_language($lang, 'youraccounthasbeensuspendedtext2', 'mahara',
            get_config('sitename'), display_name($suspendinguserid, $suspendeduserid));
    }
    else {
        $message->message = get_string_from_language($lang, 'youraccounthasbeensuspendedreasontext', 'mahara',
            get_config('sitename'), display_name($suspendinguserid, $suspendeduserid), $reason);
    }
1098
    require_once('activity.php');
1099
1100
    activity_occurred('maharamessage', $message);

Nigel McNie's avatar
Nigel McNie committed
1101
1102
    handle_event('suspenduser', $suspendeduserid);
}
1103

1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
/**
 * Unsuspends a user
 *
 * @param int $userid The ID of the user to unsuspend
 */
function unsuspend_user($userid) {
    $suspendedrec = new StdClass;
    $suspendedrec->id = $userid;
    $suspendedrec->suspendedcusr = null;
    $suspendedrec->suspendedreason = null;
    $suspendedrec->suspendedctime  = null;
    update_record('usr', $suspendedrec);

1117
    $lang = get_user_language($userid);
1118
1119
    $message = new StdClass;
    $message->users = array($userid);
1120
    $message->subject = get_string_from_language($lang, 'youraccounthasbeenunsuspended');
1121
    $message->message = get_string_from_language($lang, 'youraccounthasbeenunsuspendedtext2', 'mahara', get_config('sitename'));
1122
    require_once('activity.php');
1123
1124
1125
1126
1127
1128
1129
1130
    activity_occurred('maharamessage', $message);

    handle_event('unsuspenduser', $userid);
}

/**
 * Deletes a user
 *
1131
1132
1133
1134
 * This function ensures that a user is deleted according to how Mahara wants a 
 * deleted user to be. You can call it multiple times on the same user without 
 * harm.
 *
1135
1136
1137
 * @param int $userid The ID of the user to delete
 */
function delete_user($userid) {
1138
1139
    db_begin();

1140
1141
1142
    // We want to append 'deleted.timestamp' to some unique fields in the usr 
    // table, so they can be reused by new accounts
    $fieldstomunge = array('username', 'email');
1143
    $datasuffix = '.deleted.' . time();
1144

1145
1146
    $user = get_record('usr', 'id', $userid, null, null, null, null, implode(', ', $fieldstomunge));

1147
1148
1149
    $deleterec = new StdClass;
    $deleterec->id = $userid;
    $deleterec->deleted = 1;
1150
1151
1152
1153
1154
    foreach ($fieldstomunge as $field) {
        if (!preg_match('/\.deleted\.\d+$/', $user->$field)) {
            $deleterec->$field = $user->$field . $datasuffix;
        }
    }
1155
1156
1157

    // Set authinstance to default internal, otherwise the old authinstance can be blocked from deletion
    // by deleted users.
1158
    $authinst = get_field('auth_instance', 'id', 'institution', 'mahara', 'authname', 'internal');
1159
    if ($authinst) {
1160
        $deleterec->authinstance = $authinst;
1161
1162
    }

1163
1164
    update_record('usr', $deleterec);

1165
    // Remove user from any groups they're in, invited to or want to be in
1166
1167
1168
1169
1170
1171
1172
    $groupids = get_column('group_member', '"group"', 'member', $userid);
    if ($groupids) {
        require_once(get_config('libroot') . 'group.php');
        foreach ($groupids as $groupid) {
            group_remove_user($groupid, $userid, true);
        }
    }
1173
1174
    delete_records('group_member_request', 'member', $userid);
    delete_records('group_member_invite', 'member', $userid);
1175

1176
1177
1178
1179
1180
1181
1182
1183
    // Remove any friend relationships the user is in
    execute_sql('DELETE FROM {usr_friend}
        WHERE usr1 = ?
        OR usr2 = ?', array($userid, $userid));
    execute_sql('DELETE FROM {usr_friend_request}
        WHERE owner = ?
        OR requester = ?', array($userid, $userid));

1184
1185
1186
1187
1188
1189
    // Delete the user from others' favourites lists
    delete_records('favorite_usr', 'usr', $userid);
    // Delete favourites lists owned by the user
    execute_sql('DELETE FROM {favorite_usr} WHERE favorite IN (SELECT id FROM {favorite} WHERE owner = ?)', array($userid));
    delete_records('favorite', 'owner', $userid);

1190
    delete_records('artefact_access_usr', 'usr', $userid);
1191
    delete_records('auth_remote_user', 'localusr', $userid);
1192
1193
1194
1195
1196
1197
1198
1199
    delete_records('import_queue', 'usr', $userid);
    delete_records('usr_account_preference', 'usr', $userid);
    delete_records('usr_activity_preference', 'usr', $userid);
    delete_records('usr_infectedupload', 'usr', $userid);
    delete_records('usr_institution', 'usr', $userid);
    delete_records('usr_institution_request', 'usr', $userid);
    delete_records('usr_password_request', 'usr', $userid);
    delete_records('usr_watchlist_view', 'usr', $userid);
1200
    delete_records('view_access', 'usr', $userid);
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

    // Remove the user's views & artefacts
    $viewids = get_column('view', 'id', 'owner', $userid);
    if ($viewids) {
        require_once(get_config('libroot') . 'view.php');
        foreach ($viewids as $viewid) {
            $view = new View($viewid);
            $view->delete();
        }
    }
1211

1212
    $artefactids = get_column('artefact', 'id', 'owner', $userid);
1213
1214
    // @todo: test all artefact bulk_delete stuff, then replace the one-by-one
    // artefact deletion below with ArtefactType::delete_by_artefacttype($artefactids);
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
    if ($artefactids) {
        foreach ($artefactids as $artefactid) {
            try {
                $a = artefact_instance_from_id($artefactid);
                $a->delete();
            }
            catch (ArtefactNotFoundException $e) {
                // Awesome, it's already gone.
            }
        }
    }
1226

1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
    // Remove the user's collections
    $collectionids = get_column('collection', 'id', 'owner', $userid);
    if ($collectionids) {
        require_once(get_config('libroot') . 'collection.php');
        foreach ($collectionids as $collectionid) {
            $collection = new Collection($collectionid);
            $collection->delete();
        }
    }

1237
1238
    db_commit();

1239
1240
1241
1242
1243
1244
    handle_event('deleteuser', $userid);
}

/**
 * Undeletes a user
 *
1245
1246
1247
1248
1249
1250
 * NOTE: changing their email addresses to remove the .deleted.timestamp part 
 * has not been implemented yet! This function is not actually used anywhere in 
 * Mahara, so hasn't really been tested because of this. It's a simple enough 
 * job for the first person who gets there - see how delete_user works to see 
 * what you must undo.
 *
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
 * @param int $userid The ID of the user to undelete
 */
function undelete_user($userid) {
    $deleterec = new StdClass;
    $deleterec->id = $userid;
    $deleterec->deleted = 0;
    update_record('usr', $deleterec);

    handle_event('undeleteuser', $userid);
}

/**
 * Expires a user
 *
 * Nothing amazing needs to happen here, but this function is here for
 * consistency.
 *
 * This function is called when a user account is detected to be expired.
 * It is assumed that the account actually is expired.
 *
 * @param int $userid The ID of user to expire
 */
function expire_user($userid) {
    handle_event('expireuser', $userid);
}

/**
 * Unexpires a user
 *
 * @param int $userid The ID of user to unexpire
 */
function unexpire_user($userid) {
    handle_event('unexpireuser', $userid);
}

/**
 * Marks a user as inactive
 *
 * Nothing amazing needs to happen here, but this function is here for
 * consistency.
 *
 * This function is called when a user account is detected to be inactive.
 * It is assumed that the account actually is inactive.
 *
 * @param int $userid The ID of user to mark inactive
 */
function deactivate_user($userid) {
    handle_event('deactivateuser', $userid);
}

/**
 * Activates a user
 *
 * @param int $userid The ID of user to reactivate
 */
function activate_user($userid) {
    handle_event('activateuser', $userid);
}

Evan Goldenberg's avatar
Evan Goldenberg committed
1310
1311
1312
1313
1314
1315
/**
 * Get the thread of message up to this point, given the id of
 * the message being replied to.
 */
function get_message_thread($replyto) {
    $message = get_record('notification_internal_activity', 'id', $replyto);
1316
    if (empty($message->parent)) {
Evan Goldenberg's avatar
Evan Goldenberg committed
1317
1318
1319
1320
1321
        return array($message);
    }
    return array_merge(get_message_thread($message->parent), array($message));
}

1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
/**
 * Sends a message from one user to another
 *
 * @param object $to User to send the message to
 * @param string $message The message to send
 * @param object $from Who to send the message from. If not set, defaults to 
 * the currently logged in user
 * @throws AccessDeniedException if the message is not allowed to be sent (as 
 * configured by the 'to' user's settings)
 */
Evan Goldenberg's avatar
Evan Goldenberg committed
1332
function send_user_message($to, $message, $parent, $from=null) {
1333
1334
1335
1336
1337
1338
1339
    // FIXME: permission checking!
    if ($from === null) {
        global $USER;
        $from = $USER;
    }

    $messagepref = get_account_preference($to->id, 'messages');
1340
    if ($messagepref == 'allow' || ($messagepref == 'friends' && is_friend($from->id, $to->id)) || $from->get('admin')) {
1341
        require_once('activity.php');
1342
1343
1344
1345
1346
        activity_occurred('usermessage', 
            array(
                'userto'   => $to->id, 
                'userfrom' => $from->id, 
                'message'  => $message,
Evan Goldenberg's avatar
Evan Goldenberg committed
1347
                'parent'   => $parent,
1348
1349
1350
1351
1352
1353
1354
            )
        );
    }
    else {
        throw new AccessDeniedException('Cannot send messages between ' . display_name($from) . ' and ' . display_name($to));
    }
}
1355
1356
1357
/**
 * can a user send a message to another?
 *
1358
1359
 * @param int/object from the user to send the message
 * @param int/object to the user to receive the message
1360
1361
1362
 * @return boolean whether userfrom is allowed to send messages to userto
 */
function can_send_message($from, $to) {
1363
1364
1365
    if (empty($from)) {
        return false; // not logged in
    }
1366
1367
1368
1369
1370
1371
	if (!is_object($from)) {
	    $from = get_record('usr', 'id', $from);
	}
	if (is_object($to)) {
	    $to = $to->id;
	}
1372
    $messagepref = get_account_preference($to, 'messages');
1373
    return (is_friend($from->id, $to) && $messagepref == 'friends') || $messagepref == 'allow' || $from->admin;
1374
}
1375
1376

function load_user_institutions($userid) {
1377
    if (!is_numeric($userid) || $userid < 0) {
1378
1379
        throw new InvalidArgumentException("couldn't load institutions, no user id specified");
    }
1380
    if ($institutions = get_records_sql_assoc('
1381
        SELECT u.institution,'.db_format_tsfield('ctime').','.db_format_tsfield('u.expiry', 'membership_expiry').',u.studentid,u.staff,u.admin,i.displayname,i.theme,i.registerallowed, i.showonlineusers,i.allowinstitutionpublicviews, i.logo, i.style
1382
        FROM {usr_institution} u INNER JOIN {institution} i ON u.institution = i.name
1383
        WHERE u.usr = ? ORDER BY i.priority DESC', array($userid))) {
1384
1385
1386
1387
1388
        return $institutions;
    }
    return array();
}

1389
1390
1391
1392
1393
1394
1395
1396

/**
 * Return a username which isn't taken and which is similar to a desired username
 * 
 * @param string $desired
 */
function get_new_username($desired) {
    $maxlen = 30;
1397
    $desired = strtolower(substr($desired, 0, $maxlen));
1398
    $taken = get_column_sql('
1399
        SELECT LOWER(username) FROM {usr}
1400
1401
        WHERE username ' . db_ilike() . " ?",
        array(substr($desired, 0, $maxlen - 6) . '%'));
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
    if (!$taken) {
        return $desired;
    }
    $taken = array_flip($taken);
    $i = '';
    $newname = substr($desired, 0, $maxlen - 1) . $i;
    while (isset($taken[$newname])) {
        $i++;
        $newname = substr($desired, 0, $maxlen - strlen($i)) . $i;
    }
    return $newname;
}

1415
1416
/**
 * used by user/myfriends.php and user/find.php to get the data (including pieforms etc) for display
1417
1418
 * @param array $userids
 * @return array containing the users in the order from $userids
1419
 */
1420
function get_users_data($userids, $getviews=true) {
1421
	global $USER;
1422
1423
    // $userids is only used by build_userlist_html() in this file and is sanitised there
    $userlist = join(',', $userids);
1424
    $sql = 'SELECT u.id, u.username, u.preferredname, u.firstname, u.lastname, u.admin, u.staff, u.deleted,
1425
                u.profileicon, u.email,
1426
                0 AS pending, ap.value AS hidenamepref,
1427
1428
1429
1430
1431
                COALESCE((SELECT ap.value FROM {usr_account_preference} ap WHERE ap.usr = u.id AND ap.field = \'messages\'), \'allow\') AS messages,
                COALESCE((SELECT ap.value FROM {usr_account_preference} ap WHERE ap.usr = u.id AND ap.field = \'friendscontrol\'), \'auth\') AS friendscontrol,
                (SELECT 1 FROM {usr_friend} WHERE ((usr1 = ? AND usr2 = u.id) OR (usr2 = ? AND usr1 = u.id))) AS friend,
                (SELECT 1 FROM {usr_friend_request} fr WHERE fr.requester = ? AND fr.owner = u.id) AS requestedfriendship,
                (SELECT title FROM {artefact} WHERE artefacttype = \'introduction\' AND owner = u.id) AS introduction,
1432
                NULL AS message
1433
                FROM {usr} u
1434
                LEFT JOIN {usr_account_preference} ap ON (u.id = ap.usr AND ap.field = \'hiderealname\')
1435
                WHERE u.id IN (' . $userlist . ')
1436
            UNION
1437
            SELECT u.id, u.username, u.preferredname, u.firstname, u.lastname, u.admin, u.staff, u.deleted,
1438
                u.profileicon, u.email,
1439
                1 AS pending, ap.value AS hidenamepref,
1440
1441
1442
1443
1444
                COALESCE((SELECT ap.value FROM {usr_account_preference} ap WHERE ap.usr = u.id AND ap.field = \'messages\'), \'allow\') AS messages,
                NULL AS friendscontrol,
                NULL AS friend,
                NULL AS requestedfriendship,
                (SELECT title FROM {artefact} WHERE artefacttype = \'introduction\' AND owner = u.id) AS introduction,
1445
                message
1446
                FROM {usr} u