user.php 35.3 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
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
Penny Leach's avatar
Penny Leach committed
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * 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
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * 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
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * 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
18
19
20
 *
 * @package    mahara
 * @subpackage core
21
 * @author     Catalyst IT Ltd
Penny Leach's avatar
Penny Leach committed
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
Penny Leach's avatar
Penny Leach committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 *
 */

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

/** 
 * 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
40
    if ($prefs = get_records_assoc('usr_activity_preference', 'usr', $userid, '', 'activity,method')) {
Penny Leach's avatar
Penny Leach committed
41
        foreach ($prefs as $p) {
42
            $prefs[$p->activity] = $p->method;
Penny Leach's avatar
Penny Leach committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        }
    }
    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");
    }
63
    if ($prefs = get_records_array('usr_account_preference', 'usr', $userid)) {
Penny Leach's avatar
Penny Leach committed
64
        foreach ($prefs as $p) {
65
            $prefs[$p->field] = $p->value;
Penny Leach's avatar
Penny Leach committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        }
    }
    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) {
87
88
89
90
91
92
93
94
95
96
    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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    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");
        }
    }
}

115
116
117

/** 
 * Change language-specific stuff in the db for a user.  Currently
Clare Lenihan's avatar
Clare Lenihan committed
118
119
120
 * changes the name of the 'blogfiles', 'assessmentfiles'
 * folders in the user's files area and the views and artefacts tagged for the profile
 * sideblock
121
122
123
124
125
126
127
128
129
130
 *
 * @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) {
    if (get_field('artefact_installed', 'active', 'name', 'blog')) {
        safe_require('artefact', 'blog');
        ArtefactTypeBlogPost::change_language($userid, $oldlang, $newlang);
    }
131
132
133
134
    if (get_field('artefact_installed', 'active', 'name', 'file')) {
        safe_require('artefact', 'file');
        ArtefactTypeFolder::change_language($userid, $oldlang, $newlang);
    }
Clare Lenihan's avatar
Clare Lenihan committed
135
136
    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));
137
138
}

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

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

186
187
188
189
190
191
192
193
194
195

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


196
197
198
199
200
/**
 * default account settings
 * 
 * @returns array of fields => values
 */
Penny Leach's avatar
Penny Leach committed
201
202
203
204
function expected_account_preferences() {
    return array('friendscontrol' => 'auth',
                 'wysiwyg'        =>  1,
                 'messages'       => 'allow',
205
                 'lang'           => 'default',
206
                 'addremovecolumns' => 0,
Penny Leach's avatar
Penny Leach committed
207
208
209
                 );
}

210
211
function set_profile_field($userid, $field, $value) {
    safe_require('artefact', 'internal');
212
213
214
215
216

    // this is a special case that replaces the primary email address with the
    // specified one
    if ($field == 'email') {
        try {
217
            $email = artefact_instance_from_type('email', $userid);
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        }
        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();
    }
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
}

/**
 * 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) {
    $value = get_field('artefact', 'title', 'owner', $userid, 'artefacttype', $field);

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

250
    return null;
251
252
}

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/** 
 * 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)
 * @throws EmailException
 */ 
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml='') {

    if (empty($userto)) {
        throw new InvalidArgumentException("empty user given to email_user");
    }
    
    require_once('phpmailer/class.phpmailer.php');

    $mail = new phpmailer();

273
274
    // Leaving this commented out - there's no reason for people to know this
    //$mail->Version = 'Mahara ' . get_config('release');
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    $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
            $mail->SMTPAuth = true;
            $mail->Username = get_config('smtpuser');
            $mail->Password = get_config('smtppass');
        }
    }

    if (empty($userfrom)) {
        $mail->Sender = get_config('noreplyaddress');
        $mail->From = $mail->Sender;
        $mail->FromName = get_string('emailname');
    }
    else {
        $mail->Sender = $userfrom->email;
        $mail->From = $mail->Sender;
        $mail->FromName = display_name($userfrom, $userto);
    }
           
    $mail->AddReplyTo($mail->From, $mail->FromName);

    $mail->Subject = substr(stripslashes($subject), 0, 78);

    $usertoname = display_name($userto, $userto);
    $mail->AddAddress($userto->email, $usertoname );

    $mail->WordWrap = 79;   

    if ($messagehtml) { 
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body    =  $messagehtml;
324
        $mail->AltBody =  $messagetext;
325
326
327
    } 
    else {
        $mail->IsHTML(false);
328
        $mail->Body =  $messagetext;
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
    }

    if ($mail->Send()) {
        return true;
    } 
    throw new EmailException("Couldn't send email to $usertoname with subject $subject. "
                        . "Error from phpmailer was: " . $mail->ErrorInfo );
}

/**
 * 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
 *
345
346
 * @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
347
 * blank, will default to the currently logged in user).
348
 * @param boolean $nameonly do not append the user's username even if $userto can see it.
349
350
351
 *
 * @returns string name to display
 */
352
function display_name($user, $userto=null, $nameonly=false) {
353
354
355
356
357
    global $USER;
    
    if (empty($userto)) {
        $userto = new StdClass;
        $userto->id            = $USER->get('id');
358
        $userto->username      = $USER->get('username');
359
360
361
        $userto->preferredname = $USER->get('preferredname');
        $userto->firstname     = $USER->get('firstname');
        $userto->lastname      = $USER->get('lastname');
362
        $userto->admin         = $USER->get('admin') || $USER->is_institutional_admin();
363
        $userto->staff         = $USER->get('staff') || $USER->is_institutional_staff();
364
365
366
367
368
369
370
371
372
373
374
    }
    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");
    }

Martyn Smith's avatar
Martyn Smith committed
375
376
377
378
    if ($user instanceof User) {
        $userObj = $user;
        $user = new StdClass;
        $user->id            = $userObj->get('id');
379
        $user->username      = $userObj->get('username');
Martyn Smith's avatar
Martyn Smith committed
380
381
382
383
        $user->preferredname = $userObj->get('preferredname');
        $user->firstname     = $userObj->get('firstname');
        $user->lastname      = $userObj->get('lastname');
        $user->admin         = $userObj->get('admin');
384
        $user->staff         = $userObj->get('staff');
Martyn Smith's avatar
Martyn Smith committed
385
386
    }

387
388
    // if they don't have a preferred name set, just return here
    if (empty($user->preferredname)) {
389
        if ((!empty($userto->admin) || !empty($userto->staff)) && !$nameonly) {
390
391
            return $user->firstname . ' ' . $user->lastname . ' (' . $user->username . ')';
        }
392
393
        return $user->firstname . ' ' . $user->lastname;
    }
394
395
396
397
    else if ($user->id == $userto->id) {
        // If viewing our own name, show it how we like it
        return $user->preferredname;
    }
398

399
    if ((!empty($userto->admin) || !empty($userto->staff)) && !$nameonly) {
400
        return $user->preferredname . ' (' . $user->firstname . ' ' . $user->lastname . ' - ' . $user->username . ')';
401
402
    }

403
    $sql = "SELECT g1.member
404
405
            FROM {group_member} g1 
            JOIN {group_member} g2
406
407
                ON g1.group = g2.group
            JOIN {group} g ON (g.id = g1.group AND g.deleted = 0)
408
409
            WHERE g1.member = ? AND g2.member = ? AND g2.role = 'tutor'";
    if (record_exists_sql($sql, array($user->id, $userto->id))) {
410
        return $user->preferredname . ($nameonly ? '' : ' (' . $user->firstname . ' ' . $user->lastname . ')');
411
412
413
414
    }
    return  $user->preferredname;
}

Penny Leach's avatar
Penny Leach committed
415
416
417
/**
 * function to format a users name when there is no user to look at them
 * ie when display_name is not going to work..
418
 */
Penny Leach's avatar
Penny Leach committed
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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');
        $user->admin         = $userObj->get('admin');
    }

    // if they don't have a preferred name set, just return here
    if (empty($user->preferredname)) {
        return $user->firstname . ' ' . $user->lastname;
    }
    else {
445
        return $user->preferredname;
Penny Leach's avatar
Penny Leach committed
446
447
448
449
450
    }
}



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/**
 * 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');
    }

    return $user->firstname . ' ' . $user->lastname;
}
470

471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490

/**
 * 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');
}

491
492
493
494
495
496
497
498
499
500
501
502
503


/**
 * 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;
    }

504
    if (!empty($user) && is_numeric($user)) {
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
        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();
}




522
523
524
/**
 * helper function for testing logins
 */
525
526
function is_logged_in() {
    global $USER;
Martyn Smith's avatar
Martyn Smith committed
527
528
529
530
531
    if (empty($USER)) {
        return false;
    }

    return $USER->is_logged_in();
532
533
}

534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/**
 * 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) {
    return get_record_select('usr_friend_request', '(owner = ? AND requester = ?) OR (requester = ? AND owner = ?)',
                             array($userid1, $userid2, $userid1, $userid2));
        
} 

558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/**
 * 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;
}

578

Nigel McNie's avatar
Nigel McNie committed
579
580
581
582
583
584
585
586
587
588
589
590
/**
 * 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');
    }
591

Nigel McNie's avatar
Nigel McNie committed
592
593
594
595
596
597
    $suspendrec = new StdClass;
    $suspendrec->id              = $suspendeduserid;
    $suspendrec->suspendedcusr   = $suspendinguserid;
    $suspendrec->suspendedreason = $reason;
    $suspendrec->suspendedctime  = db_format_timestamp(time());
    update_record('usr', $suspendrec, 'id');
598

599
    $lang = get_user_language($suspendeduserid);
600
601
    $message = new StdClass;
    $message->users = array($suspendeduserid);
602
603
    $message->subject = get_string_from_language($lang, 'youraccounthasbeensuspended');
    $message->message = get_string_from_language($lang, 'youraccounthasbeensuspendedtext');
604
605
    activity_occurred('maharamessage', $message);

Nigel McNie's avatar
Nigel McNie committed
606
607
    handle_event('suspenduser', $suspendeduserid);
}
608

609
610
611
612
613
614
615
616
617
618
619
620
621
/**
 * 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);

622
    $lang = get_user_language($userid);
623
624
    $message = new StdClass;
    $message->users = array($userid);
625
626
    $message->subject = get_string_from_language($lang, 'youraccounthasbeenunsuspended');
    $message->message = get_string_from_language($lang, 'youraccounthasbeenunsuspendedtext');
627
628
629
630
631
632
633
634
635
636
637
    activity_occurred('maharamessage', $message);

    handle_event('unsuspenduser', $userid);
}

/**
 * Deletes a user
 *
 * @param int $userid The ID of the user to delete
 */
function delete_user($userid) {
638
639
640
641
    db_begin();

    $emailsuffix = '.deleted.' . time();

642
643
644
    $deleterec = new StdClass;
    $deleterec->id = $userid;
    $deleterec->deleted = 1;
645
    $deleterec->email = get_field('usr', 'email', 'id', $userid) . $emailsuffix;
646
647
648
649
650

    // Set authinstance to default internal, otherwise the old authinstance can be blocked from deletion
    // by deleted users.
    $authinst = get_field('auth_instance', 'id', 'institution', 'mahara', 'instancename', 'internal');
    if ($authinst) {
651
        $deleterec->authinstance = $deleterec->lastauthinstance = $authinst;
652
653
    }

654
655
    update_record('usr', $deleterec);

656
657
658
659
660
661
662
    // Because the user is being deleted, but their email address may be wanted 
    // for a new user, we change their email addresses to add 
    // 'deleted.[timestamp]'
    execute_sql('UPDATE {artefact_internal_profile_email}
    SET email = email || ?
    WHERE owner = ?', array($emailsuffix, $userid));

663
664
665
    // mark all groups the user owns as deleted
    set_field('group', 'deleted', '1', 'owner', $userid);

666
667
    db_commit();

668
669
670
671
672
673
    handle_event('deleteuser', $userid);
}

/**
 * Undeletes a user
 *
674
675
676
677
678
679
 * 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.
 *
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
 * @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);
}

739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/**
 * 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)
 */
function send_user_message($to, $message, $from=null) {
    // FIXME: permission checking!
    if ($from === null) {
        global $USER;
        $from = $USER;
    }

    $messagepref = get_account_preference($to->id, 'messages');
    if ((is_friend($from->id, $to->id) && $messagepref == 'friends') || $messagepref == 'allow' || $from->get('admin')) {
        activity_occurred('usermessage', 
            array(
                'userto'   => $to->id, 
                'userfrom' => $from->id, 
                'message'  => $message,
            )
        );
    }
    else {
        throw new AccessDeniedException('Cannot send messages between ' . display_name($from) . ' and ' . display_name($to));
    }
}
770
771
772
/**
 * can a user send a message to another?
 *
773
774
 * @param int/object from the user to send the message
 * @param int/object to the user to receive the message
775
776
777
 * @return boolean whether userfrom is allowed to send messages to userto
 */
function can_send_message($from, $to) {
778
779
780
781
782
783
784
	if (!is_object($from)) {
	    $from = get_record('usr', 'id', $from);
	}
	if (is_object($to)) {
	    $to = $to->id;
	}
    if ($from->id == $to) {
785
786
        return false;
    }
787
    $messagepref = get_account_preference($to, 'messages');
788
    return (is_friend($from->id, $to) && $messagepref == 'friends') || $messagepref == 'allow' || $from->admin;
789
}
790
791
792
793
794

function load_user_institutions($userid) {
    if (empty($userid)) {
        throw new InvalidArgumentException("couldn't load institutions, no user id specified");
    }
795
    if ($institutions = get_records_sql_assoc('
796
        SELECT u.institution,'.db_format_tsfield('ctime').','.db_format_tsfield('expiry').',u.studentid,u.staff,u.admin,i.theme
797
798
        FROM {usr_institution} u INNER JOIN {institution} i ON u.institution = i.name
        WHERE u.usr = ?', array($userid))) {
799
800
801
802
803
        return $institutions;
    }
    return array();
}

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828

/**
 * 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;
    $desired = substr($desired, 0, $maxlen);
    $taken = get_column_sql('
        SELECT username FROM {usr}
        WHERE username ' . db_ilike() . " '" . substr($desired, 0, $maxlen - 6) . "%'");
    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;
}

829
830
/**
 * used by user/myfriends.php and user/find.php to get the data (including pieforms etc) for display
831
832
 * @param $userlist the ids separated by commas
 * @return array containing the users in the order from $userlist
833
834
835
836
837
838
839
840
841
842
843
 */
function get_users_data($userlist) {
	global $USER;
    $sql = 'SELECT u.id, 0 AS pending,
                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,
                NULL AS reason
                FROM {usr} u
844
                WHERE u.id IN (' . $userlist . ')
845
846
847
848
849
850
851
852
853
854
855
            UNION
            SELECT u.id, 1 AS pending,
                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,
                reason
                FROM {usr} u
                JOIN {usr_friend_request} fr ON fr.requester = u.id
                WHERE fr.owner = ?
856
                AND u.id IN (' . $userlist . ')';
857
858
859
860
861
    $userid = $USER->get('id');
    $data = get_records_sql_assoc($sql, array($userid, $userid, $userid, $userid));

    foreach ($data as &$record) {
        if (isset($record->introduction)) {
862
            $record->introduction = str_shorten($record->introduction, 100, true);
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
        }

        $record->messages = ($record->messages == 'allow' || $record->friend && $record->messages == 'friends' || $USER->get('admin')) ? 1 : 0;
    }

    if (!$data || !$views = get_views(array_keys($data), null, null)) {
        $views = array();
    }

   $viewcount = array_map('count', $views);
    // since php is so special and inconsistent, we can't use array_map for this because it breaks the top level indexes.
    $cleanviews = array();
    foreach ($views as $userindex => $viewarray) {
        $cleanviews[$userindex] = array_slice($viewarray, 0, 5);

        // Don't reveal any more about the view than necessary
        foreach ($cleanviews as $userviews) {
            foreach ($userviews as &$view) {
               foreach (array_keys(get_object_vars($view)) as $key) {
                    if ($key != 'id' && $key != 'title') {
                        unset($view->$key);
                    }
                }
            }
        }

    }

    foreach ($data as $friend) {
        if (isset($cleanviews[$friend->id])) {
            $friend->views = $cleanviews[$friend->id];
        }
        if ($friend->pending) {
            $friend->accept = pieform(array(
                'name' => 'acceptfriend' . $friend->id,
                'successcallback' => 'acceptfriend_submit',
                'renderer' => 'div',
                'autofocus' => 'false',
                'elements' => array(
                    'submit' => array(
                        'type' => 'submit',
                        'value' => get_string('approverequest', 'group')
                    ),
                    'id' => array(
                        'type' => 'hidden',
                        'value' => $friend->id
                    )
                )
            ));
        }
        if (!$friend->friend && !$friend->pending && !$friend->requestedfriendship && $friend->friendscontrol == 'auto') {
            $friend->makefriend = pieform(array(
915
916
                'name' => 'addfriend' . $friend->id,
                'successcallback' => 'addfriend_submit',
917
918
919
920
921
                'renderer' => 'div',
                'autofocus' => 'false',
                'elements' => array(
                    'submit' => array(
                        'type' => 'submit',
922
                        'value' => get_string('addtofriendslist', 'group'),
923
924
925
                    ),
                    'id' => array(
                        'type' => 'hidden',
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
                        'value' => $friend->id,
                    ),
                    // These two fields pass on any query that was running on a 
                    // user search screen. This is so when the form is 
                    // submitted, the correct user search is run again and so 
                    // this pieform will definitely be created and ready to be 
                    // submitted.
                    //
                    // A bit of a hack caused by having one form for each user. 
                    // It would be nice at some point to put the entire 'find 
                    // friends' page into one form and toggle on the submit 
                    // button to work out which friend to add.
                    'query' => array(
                        'type' => 'hidden',
                        'value' => param_variable('query', ''),
                    ),
                    'offset' => array(
                        'type' => 'hidden',
                        'value' => param_integer('offset', 0),
                    ),
946
947
948
949
                )
            ));
        }
    }
950
951
952
953
954
955
956
957
    $order = explode(',', $userlist);
    $ordereddata = array();
    foreach ($order as $id) {
        if (isset($data[$id])) {
            $ordereddata[] = $data[$id];
        }
    }
    return $ordereddata;
958
959
}

960
function friends_control_sideblock($returnto='myfriends') {
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
    global $USER;
    $form = array(
        'name' => 'friendscontrol',
        'plugintype'  => 'core',
        'pluginname'  => 'account',
        'autofocus'   => false,
        'elements' => array(
            'friendscontrol' => array(
                'type' => 'radio',
                'defaultvalue' => $USER->get_account_preference('friendscontrol'),
                'separator' => HTML_BR,
                'options' => array(
                    'nobody' => get_string('friendsnobody', 'account'),
                    'auth'   => get_string('friendsauth', 'account'),
                    'auto'   => get_string('friendsauto', 'account')
                ),
                'rules' => array(
                    'required' => true
                ),
            ),
            'submit' => array(
                'type' => 'submit',
                'value' => get_string('save')
            ),
985
986
987
988
            'returnto' => array(
                'type' => 'hidden',
                'value' => $returnto
            )
989
990
991
992
993
994
995
996
997
998
        )
    );
    // Make a sideblock to put the friendscontrol block in
    return array(
        'name' => 'friendscontrol',
        'weight' => -5,
        'data' => pieform($form)
    );
}

999
1000
1001
1002
function friendscontrol_submit(Pieform $form, $values) {
    global $USER, $SESSION;
    $USER->set_account_preference('friendscontrol', $values['friendscontrol']);
    $SESSION->add_ok_msg(get_string('updatedfriendcontrolsetting', 'account'));
1003
    redirect($values['returnto'] == 'find' ? '/user/find.php' : '/user/myfriends.php');
1004
1005
}

1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
function acceptfriend_submit(Pieform $form, $values) {
    global $USER, $SESSION;

    $user = get_record('usr', 'id', $values['id']);

    // friend db record
    $f = new StdClass;
    $f->ctime = db_format_timestamp(time());
    $f->usr1 = $user->id;
    $f->usr2 = $USER->get('id');

    // notification info
    $n = new StdClass;
    $n->url = get_config('wwwroot') . 'user/view.php?id=' . $USER->get('id');
    $n->users = array($user->id);
    $lang = get_user_language($user->id);
    $displayname = display_name($USER, $user);
    $n->message = get_string_from_language($lang, 'friendrequestacceptedmessage', 'group', $displayname, $displayname);
    $n->subject = get_string_from_language($lang, 'friendrequestacceptedsubject', 'group');

    db_begin();
    delete_records('usr_friend_request', 'owner', $USER->get('id'), 'requester', $user->id);
    insert_record('usr_friend', $f);

    db_commit();
    $SESSION->add_ok_msg(get_string('friendformacceptsuccess', 'group'));
    redirect('/user/view.php?id=' . $values['id']);
}

1035
function addfriend_submit(Pieform $form, $values) {
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
    global $USER, $SESSION;
    $user = get_record('usr', 'id', $values['id']);

    $loggedinid = $USER->get('id');
    $userid = $user->id;

    // friend db record
    $f = new StdClass;
    $f->ctime = db_format_timestamp(time());

    // notification info
    $n = new StdClass;
    $n->url = get_config('wwwroot') . 'user/view.php?id=' . $loggedinid;
    $n->users = array($user->id);
    $lang = get_user_language($user->id);
    $displayname = display_name($USER, $user);

    $f->usr1 = $values['id'];
    $f->usr2 = $loggedinid;
    insert_record('usr_friend', $f);
    $n->subject = get_string_from_language($lang, 'addedtofriendslistsubject', 'group');
    $n->message = get_string_from_language($lang, 'addedtofriendslistmessage', 'group', $displayname, $displayname);

    activity_occurred('maharamessage', $n);
1060
    $SESSION->add_ok_msg(get_string('friendformaddsuccess', 'group', display_name($user)));
Clare Lenihan's avatar
Clare Lenihan committed
1061
    redirect('/user/view.php?id=' . $values['id']);
1062
1063
}

Penny Leach's avatar
Penny Leach committed
1064
?>