phpBB
Statistics
| Revision:

root / trunk / phpBB / includes / functions_user.php

History | View | Annotate | Download (94.3 kB)

1
<?php
2
/**
3
*
4
* @package phpBB3
5
* @copyright (c) 2005 phpBB Group
6
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
7
*
8
*/
9
10
/**
11
* @ignore
12
*/
13
if (!defined('IN_PHPBB'))
14
{
15
        exit;
16
}
17
18
/**
19
* Obtain user_ids from usernames or vice versa. Returns false on
20
* success else the error string
21
*
22
* @param array &$user_id_ary The user ids to check or empty if usernames used
23
* @param array &$username_ary The usernames to check or empty if user ids used
24
* @param mixed $user_type Array of user types to check, false if not restricting by user type
25
*/
26
function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
27
{
28
        global $db;
29
30
        // Are both arrays already filled? Yep, return else
31
        // are neither array filled?
32
        if ($user_id_ary && $username_ary)
33
        {
34
                return false;
35
        }
36
        else if (!$user_id_ary && !$username_ary)
37
        {
38
                return 'NO_USERS';
39
        }
40
41
        $which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
42
43
        if ($$which_ary && !is_array($$which_ary))
44
        {
45
                $$which_ary = array($$which_ary);
46
        }
47
48
        $sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
49
        unset($$which_ary);
50
51
        $user_id_ary = $username_ary = array();
52
53
        // Grab the user id/username records
54
        $sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
55
        $sql = 'SELECT user_id, username
56
                FROM ' . USERS_TABLE . '
57
                WHERE ' . $db->sql_in_set($sql_where, $sql_in);
58
59
        if ($user_type !== false && !empty($user_type))
60
        {
61
                $sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
62
        }
63
64
        $result = $db->sql_query($sql);
65
66
        if (!($row = $db->sql_fetchrow($result)))
67
        {
68
                $db->sql_freeresult($result);
69
                return 'NO_USERS';
70
        }
71
72
        do
73
        {
74
                $username_ary[$row['user_id']] = $row['username'];
75
                $user_id_ary[] = $row['user_id'];
76
        }
77
        while ($row = $db->sql_fetchrow($result));
78
        $db->sql_freeresult($result);
79
80
        return false;
81
}
82
83
/**
84
* Get latest registered username and update database to reflect it
85
*/
86
function update_last_username()
87
{
88
        global $db;
89
90
        // Get latest username
91
        $sql = 'SELECT user_id, username, user_colour
92
                FROM ' . USERS_TABLE . '
93
                WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
94
                ORDER BY user_id DESC';
95
        $result = $db->sql_query_limit($sql, 1);
96
        $row = $db->sql_fetchrow($result);
97
        $db->sql_freeresult($result);
98
99
        if ($row)
100
        {
101
                set_config('newest_user_id', $row['user_id'], true);
102
                set_config('newest_username', $row['username'], true);
103
                set_config('newest_user_colour', $row['user_colour'], true);
104
        }
105
}
106
107
/**
108
* Updates a username across all relevant tables/fields
109
*
110
* @param string $old_name the old/current username
111
* @param string $new_name the new username
112
*/
113
function user_update_name($old_name, $new_name)
114
{
115
        global $config, $db, $cache;
116
117
        $update_ary = array(
118
                FORUMS_TABLE                        => array('forum_last_poster_name'),
119
                MODERATOR_CACHE_TABLE        => array('username'),
120
                POSTS_TABLE                                => array('post_username'),
121
                TOPICS_TABLE                        => array('topic_first_poster_name', 'topic_last_poster_name'),
122
        );
123
124
        foreach ($update_ary as $table => $field_ary)
125
        {
126
                foreach ($field_ary as $field)
127
                {
128
                        $sql = "UPDATE $table
129
                                SET $field = '" . $db->sql_escape($new_name) . "'
130
                                WHERE $field = '" . $db->sql_escape($old_name) . "'";
131
                        $db->sql_query($sql);
132
                }
133
        }
134
135
        if ($config['newest_username'] == $old_name)
136
        {
137
                set_config('newest_username', $new_name, true);
138
        }
139
140
        // Because some tables/caches use username-specific data we need to purge this here.
141
        $cache->destroy('sql', MODERATOR_CACHE_TABLE);
142
}
143
144
/**
145
* Adds an user
146
*
147
* @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
148
* @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
149
* @return the new user's ID.
150
*/
151
function user_add($user_row, $cp_data = false)
152
{
153
        global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
154
155
        if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
156
        {
157
                return false;
158
        }
159
160
        $username_clean = utf8_clean_string($user_row['username']);
161
162
        if (empty($username_clean))
163
        {
164
                return false;
165
        }
166
167
        $sql_ary = array(
168
                'username'                        => $user_row['username'],
169
                'username_clean'        => $username_clean,
170
                'user_password'                => (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
171
                'user_pass_convert'        => 0,
172
                'user_email'                => strtolower($user_row['user_email']),
173
                'user_email_hash'        => phpbb_email_hash($user_row['user_email']),
174
                'group_id'                        => $user_row['group_id'],
175
                'user_type'                        => $user_row['user_type'],
176
        );
177
178
        // These are the additional vars able to be specified
179
        $additional_vars = array(
180
                'user_permissions'        => '',
181
                'user_timezone'                => $config['board_timezone'],
182
                'user_dateformat'        => $config['default_dateformat'],
183
                'user_lang'                        => $config['default_lang'],
184
                'user_style'                => (int) $config['default_style'],
185
                'user_actkey'                => '',
186
                'user_ip'                        => '',
187
                'user_regdate'                => time(),
188
                'user_passchg'                => time(),
189
                'user_options'                => 230271,
190
                // We do not set the new flag here - registration scripts need to specify it
191
                'user_new'                        => 0,
192
193
                'user_inactive_reason'        => 0,
194
                'user_inactive_time'        => 0,
195
                'user_lastmark'                        => time(),
196
                'user_lastvisit'                => 0,
197
                'user_lastpost_time'        => 0,
198
                'user_lastpage'                        => '',
199
                'user_posts'                        => 0,
200
                'user_dst'                                => (int) $config['board_dst'],
201
                'user_colour'                        => '',
202
                'user_occ'                                => '',
203
                'user_interests'                => '',
204
                'user_avatar'                        => '',
205
                'user_avatar_type'                => 0,
206
                'user_avatar_width'                => 0,
207
                'user_avatar_height'        => 0,
208
                'user_new_privmsg'                => 0,
209
                'user_unread_privmsg'        => 0,
210
                'user_last_privmsg'                => 0,
211
                'user_message_rules'        => 0,
212
                'user_full_folder'                => PRIVMSGS_NO_BOX,
213
                'user_emailtime'                => 0,
214
215
                'user_notify'                        => 0,
216
                'user_notify_pm'                => 1,
217
                'user_notify_type'                => NOTIFY_EMAIL,
218
                'user_allow_pm'                        => 1,
219
                'user_allow_viewonline'        => 1,
220
                'user_allow_viewemail'        => 1,
221
                'user_allow_massemail'        => 1,
222
223
                'user_sig'                                        => '',
224
                'user_sig_bbcode_uid'                => '',
225
                'user_sig_bbcode_bitfield'        => '',
226
227
                'user_form_salt'                        => unique_id(),
228
        );
229
230
        // Now fill the sql array with not required variables
231
        foreach ($additional_vars as $key => $default_value)
232
        {
233
                $sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
234
        }
235
236
        // Any additional variables in $user_row not covered above?
237
        $remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
238
239
        // Now fill our sql array with the remaining vars
240
        if (sizeof($remaining_vars))
241
        {
242
                foreach ($remaining_vars as $key)
243
                {
244
                        $sql_ary[$key] = $user_row[$key];
245
                }
246
        }
247
248
        $sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
249
        $db->sql_query($sql);
250
251
        $user_id = $db->sql_nextid();
252
253
        // Insert Custom Profile Fields
254
        if ($cp_data !== false && sizeof($cp_data))
255
        {
256
                $cp_data['user_id'] = (int) $user_id;
257
258
                if (!class_exists('custom_profile'))
259
                {
260
                        include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
261
                }
262
263
                $sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
264
                        $db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
265
                $db->sql_query($sql);
266
        }
267
268
        // Place into appropriate group...
269
        $sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
270
                'user_id'                => (int) $user_id,
271
                'group_id'                => (int) $user_row['group_id'],
272
                'user_pending'        => 0)
273
        );
274
        $db->sql_query($sql);
275
276
        // Now make it the users default group...
277
        group_set_user_default($user_row['group_id'], array($user_id), false);
278
279
        // Add to newly registered users group if user_new is 1
280
        if ($config['new_member_post_limit'] && $sql_ary['user_new'])
281
        {
282
                $sql = 'SELECT group_id
283
                        FROM ' . GROUPS_TABLE . "
284
                        WHERE group_name = 'NEWLY_REGISTERED'
285
                                AND group_type = " . GROUP_SPECIAL;
286
                $result = $db->sql_query($sql);
287
                $add_group_id = (int) $db->sql_fetchfield('group_id');
288
                $db->sql_freeresult($result);
289
290
                if ($add_group_id)
291
                {
292
                        // Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
293
                        $GLOBALS['skip_add_log'] = true;
294
295
                        // Add user to "newly registered users" group and set to default group if admin specified so.
296
                        if ($config['new_member_group_default'])
297
                        {
298
                                group_user_add($add_group_id, $user_id, false, false, true);
299
                                $user_row['group_id'] = $add_group_id;
300
                        }
301
                        else
302
                        {
303
                                group_user_add($add_group_id, $user_id);
304
                        }
305
306
                        unset($GLOBALS['skip_add_log']);
307
                }
308
        }
309
310
        // set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
311
        if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
312
        {
313
                set_config('newest_user_id', $user_id, true);
314
                set_config('newest_username', $user_row['username'], true);
315
                set_config_count('num_users', 1, true);
316
317
                $sql = 'SELECT group_colour
318
                        FROM ' . GROUPS_TABLE . '
319
                        WHERE group_id = ' . (int) $user_row['group_id'];
320
                $result = $db->sql_query_limit($sql, 1);
321
                $row = $db->sql_fetchrow($result);
322
                $db->sql_freeresult($result);
323
324
                set_config('newest_user_colour', $row['group_colour'], true);
325
        }
326
327
        return $user_id;
328
}
329
330
/**
331
* Remove User
332
*/
333
function user_delete($mode, $user_id, $post_username = false)
334
{
335
        global $cache, $config, $db, $user, $auth;
336
        global $phpbb_root_path, $phpEx;
337
338
        $sql = 'SELECT *
339
                FROM ' . USERS_TABLE . '
340
                WHERE user_id = ' . $user_id;
341
        $result = $db->sql_query($sql);
342
        $user_row = $db->sql_fetchrow($result);
343
        $db->sql_freeresult($result);
344
345
        if (!$user_row)
346
        {
347
                return false;
348
        }
349
350
        // Before we begin, we will remove the reports the user issued.
351
        $sql = 'SELECT r.post_id, p.topic_id
352
                FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
353
                WHERE r.user_id = ' . $user_id . '
354
                        AND p.post_id = r.post_id';
355
        $result = $db->sql_query($sql);
356
357
        $report_posts = $report_topics = array();
358
        while ($row = $db->sql_fetchrow($result))
359
        {
360
                $report_posts[] = $row['post_id'];
361
                $report_topics[] = $row['topic_id'];
362
        }
363
        $db->sql_freeresult($result);
364
365
        if (sizeof($report_posts))
366
        {
367
                $report_posts = array_unique($report_posts);
368
                $report_topics = array_unique($report_topics);
369
370
                // Get a list of topics that still contain reported posts
371
                $sql = 'SELECT DISTINCT topic_id
372
                        FROM ' . POSTS_TABLE . '
373
                        WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
374
                                AND post_reported = 1
375
                                AND ' . $db->sql_in_set('post_id', $report_posts, true);
376
                $result = $db->sql_query($sql);
377
378
                $keep_report_topics = array();
379
                while ($row = $db->sql_fetchrow($result))
380
                {
381
                        $keep_report_topics[] = $row['topic_id'];
382
                }
383
                $db->sql_freeresult($result);
384
385
                if (sizeof($keep_report_topics))
386
                {
387
                        $report_topics = array_diff($report_topics, $keep_report_topics);
388
                }
389
                unset($keep_report_topics);
390
391
                // Now set the flags back
392
                $sql = 'UPDATE ' . POSTS_TABLE . '
393
                        SET post_reported = 0
394
                        WHERE ' . $db->sql_in_set('post_id', $report_posts);
395
                $db->sql_query($sql);
396
397
                if (sizeof($report_topics))
398
                {
399
                        $sql = 'UPDATE ' . TOPICS_TABLE . '
400
                                SET topic_reported = 0
401
                                WHERE ' . $db->sql_in_set('topic_id', $report_topics);
402
                        $db->sql_query($sql);
403
                }
404
        }
405
406
        // Remove reports
407
        $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
408
409
        if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
410
        {
411
                avatar_delete('user', $user_row);
412
        }
413
414
        switch ($mode)
415
        {
416
                case 'retain':
417
418
                        $db->sql_transaction('begin');
419
420
                        if ($post_username === false)
421
                        {
422
                                $post_username = $user->lang['GUEST'];
423
                        }
424
425
                        // If the user is inactive and newly registered we assume no posts from this user being there...
426
                        if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
427
                        {
428
                        }
429
                        else
430
                        {
431
                                $sql = 'UPDATE ' . FORUMS_TABLE . '
432
                                        SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
433
                                        WHERE forum_last_poster_id = $user_id";
434
                                $db->sql_query($sql);
435
436
                                $sql = 'UPDATE ' . POSTS_TABLE . '
437
                                        SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
438
                                        WHERE poster_id = $user_id";
439
                                $db->sql_query($sql);
440
441
                                $sql = 'UPDATE ' . POSTS_TABLE . '
442
                                        SET post_edit_user = ' . ANONYMOUS . "
443
                                        WHERE post_edit_user = $user_id";
444
                                $db->sql_query($sql);
445
446
                                $sql = 'UPDATE ' . TOPICS_TABLE . '
447
                                        SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
448
                                        WHERE topic_poster = $user_id";
449
                                $db->sql_query($sql);
450
451
                                $sql = 'UPDATE ' . TOPICS_TABLE . '
452
                                        SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
453
                                        WHERE topic_last_poster_id = $user_id";
454
                                $db->sql_query($sql);
455
456
                                $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
457
                                        SET poster_id = ' . ANONYMOUS . "
458
                                        WHERE poster_id = $user_id";
459
                                $db->sql_query($sql);
460
461
                                // Since we change every post by this author, we need to count this amount towards the anonymous user
462
463
                                // Update the post count for the anonymous user
464
                                if ($user_row['user_posts'])
465
                                {
466
                                        $sql = 'UPDATE ' . USERS_TABLE . '
467
                                                SET user_posts = user_posts + ' . $user_row['user_posts'] . '
468
                                                WHERE user_id = ' . ANONYMOUS;
469
                                        $db->sql_query($sql);
470
                                }
471
                        }
472
473
                        $db->sql_transaction('commit');
474
475
                break;
476
477
                case 'remove':
478
479
                        if (!function_exists('delete_posts'))
480
                        {
481
                                include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
482
                        }
483
484
                        // Delete posts, attachments, etc.
485
                        delete_posts('poster_id', $user_id);
486
487
                break;
488
        }
489
490
        $db->sql_transaction('begin');
491
492
        $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE, SESSIONS_KEYS_TABLE, PRIVMSGS_FOLDER_TABLE, PRIVMSGS_RULES_TABLE);
493
494
        foreach ($table_ary as $table)
495
        {
496
                $sql = "DELETE FROM $table
497
                        WHERE user_id = $user_id";
498
                $db->sql_query($sql);
499
        }
500
501
        $cache->destroy('sql', MODERATOR_CACHE_TABLE);
502
503
        // Delete user log entries about this user
504
        $sql = 'DELETE FROM ' . LOG_TABLE . '
505
                WHERE reportee_id = ' . $user_id;
506
        $db->sql_query($sql);
507
508
        // Change user_id to anonymous for this users triggered events
509
        $sql = 'UPDATE ' . LOG_TABLE . '
510
                SET user_id = ' . ANONYMOUS . '
511
                WHERE user_id = ' . $user_id;
512
        $db->sql_query($sql);
513
514
        // Delete the user_id from the zebra table
515
        $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
516
                WHERE user_id = ' . $user_id . '
517
                        OR zebra_id = ' . $user_id;
518
        $db->sql_query($sql);
519
520
        // Delete the user_id from the banlist
521
        $sql = 'DELETE FROM ' . BANLIST_TABLE . '
522
                WHERE ban_userid = ' . $user_id;
523
        $db->sql_query($sql);
524
525
        // Delete the user_id from the session table
526
        $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
527
                WHERE session_user_id = ' . $user_id;
528
        $db->sql_query($sql);
529
530
        // Remove any undelivered mails...
531
        $sql = 'SELECT msg_id, user_id
532
                FROM ' . PRIVMSGS_TO_TABLE . '
533
                WHERE author_id = ' . $user_id . '
534
                        AND folder_id = ' . PRIVMSGS_NO_BOX;
535
        $result = $db->sql_query($sql);
536
537
        $undelivered_msg = $undelivered_user = array();
538
        while ($row = $db->sql_fetchrow($result))
539
        {
540
                $undelivered_msg[] = $row['msg_id'];
541
                $undelivered_user[$row['user_id']][] = true;
542
        }
543
        $db->sql_freeresult($result);
544
545
        if (sizeof($undelivered_msg))
546
        {
547
                $sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
548
                        WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
549
                $db->sql_query($sql);
550
        }
551
552
        $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
553
                WHERE author_id = ' . $user_id . '
554
                        AND folder_id = ' . PRIVMSGS_NO_BOX;
555
        $db->sql_query($sql);
556
557
        // Delete all to-information
558
        $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
559
                WHERE user_id = ' . $user_id;
560
        $db->sql_query($sql);
561
562
        // Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
563
        $sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
564
                SET author_id = ' . ANONYMOUS . '
565
                WHERE author_id = ' . $user_id;
566
        $db->sql_query($sql);
567
568
        $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
569
                SET author_id = ' . ANONYMOUS . '
570
                WHERE author_id = ' . $user_id;
571
        $db->sql_query($sql);
572
573
        foreach ($undelivered_user as $_user_id => $ary)
574
        {
575
                if ($_user_id == $user_id)
576
                {
577
                        continue;
578
                }
579
580
                $sql = 'UPDATE ' . USERS_TABLE . '
581
                        SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
582
                                user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
583
                        WHERE user_id = ' . $_user_id;
584
                $db->sql_query($sql);
585
        }
586
587
        $db->sql_transaction('commit');
588
589
        // Reset newest user info if appropriate
590
        if ($config['newest_user_id'] == $user_id)
591
        {
592
                update_last_username();
593
        }
594
595
        // Decrement number of users if this user is active
596
        if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
597
        {
598
                set_config_count('num_users', -1, true);
599
        }
600
601
        return false;
602
}
603
604
/**
605
* Flips user_type from active to inactive and vice versa, handles group membership updates
606
*
607
* @param string $mode can be flip for flipping from active/inactive, activate or deactivate
608
*/
609
function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
610
{
611
        global $config, $db, $user, $auth;
612
613
        $deactivated = $activated = 0;
614
        $sql_statements = array();
615
616
        if (!is_array($user_id_ary))
617
        {
618
                $user_id_ary = array($user_id_ary);
619
        }
620
621
        if (!sizeof($user_id_ary))
622
        {
623
                return;
624
        }
625
626
        $sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
627
                FROM ' . USERS_TABLE . '
628
                WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
629
        $result = $db->sql_query($sql);
630
631
        while ($row = $db->sql_fetchrow($result))
632
        {
633
                $sql_ary = array();
634
635
                if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
636
                        ($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
637
                        ($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
638
                {
639
                        continue;
640
                }
641
642
                if ($row['user_type'] == USER_INACTIVE)
643
                {
644
                        $activated++;
645
                }
646
                else
647
                {
648
                        $deactivated++;
649
650
                        // Remove the users session key...
651
                        $user->reset_login_keys($row['user_id']);
652
                }
653
654
                $sql_ary += array(
655
                        'user_type'                                => ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
656
                        'user_inactive_time'        => ($row['user_type'] == USER_NORMAL) ? time() : 0,
657
                        'user_inactive_reason'        => ($row['user_type'] == USER_NORMAL) ? $reason : 0,
658
                );
659
660
                $sql_statements[$row['user_id']] = $sql_ary;
661
        }
662
        $db->sql_freeresult($result);
663
664
        if (sizeof($sql_statements))
665
        {
666
                foreach ($sql_statements as $user_id => $sql_ary)
667
                {
668
                        $sql = 'UPDATE ' . USERS_TABLE . '
669
                                SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
670
                                WHERE user_id = ' . $user_id;
671
                        $db->sql_query($sql);
672
                }
673
674
                $auth->acl_clear_prefetch(array_keys($sql_statements));
675
        }
676
677
        if ($deactivated)
678
        {
679
                set_config_count('num_users', $deactivated * (-1), true);
680
        }
681
682
        if ($activated)
683
        {
684
                set_config_count('num_users', $activated, true);
685
        }
686
687
        // Update latest username
688
        update_last_username();
689
}
690
691
/**
692
* Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
693
*
694
* @param string $mode Type of ban. One of the following: user, ip, email
695
* @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
696
* @param int $ban_len Ban length in minutes
697
* @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
698
* @param boolean $ban_exclude Exclude these entities from banning?
699
* @param string $ban_reason String describing the reason for this ban
700
* @return boolean
701
*/
702
function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
703
{
704
        global $db, $user, $auth, $cache;
705
706
        // Delete stale bans
707
        $sql = 'DELETE FROM ' . BANLIST_TABLE . '
708
                WHERE ban_end < ' . time() . '
709
                        AND ban_end <> 0';
710
        $db->sql_query($sql);
711
712
        $ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
713
        $ban_list_log = implode(', ', $ban_list);
714
715
        $current_time = time();
716
717
        // Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
718
        if ($ban_len)
719
        {
720
                if ($ban_len != -1 || !$ban_len_other)
721
                {
722
                        $ban_end = max($current_time, $current_time + ($ban_len) * 60);
723
                }
724
                else
725
                {
726
                        $ban_other = explode('-', $ban_len_other);
727
                        if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
728
                                (strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
729
                        {
730
                                $time_offset = (isset($user->timezone) && isset($user->dst)) ? (int) $user->timezone + (int) $user->dst : 0;
731
                                $ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]) - $time_offset);
732
                        }
733
                        else
734
                        {
735
                                trigger_error('LENGTH_BAN_INVALID', E_USER_WARNING);
736
                        }
737
                }
738
        }
739
        else
740
        {
741
                $ban_end = 0;
742
        }
743
744
        $founder = $founder_names = array();
745
746
        if (!$ban_exclude)
747
        {
748
                // Create a list of founder...
749
                $sql = 'SELECT user_id, user_email, username_clean
750
                        FROM ' . USERS_TABLE . '
751
                        WHERE user_type = ' . USER_FOUNDER;
752
                $result = $db->sql_query($sql);
753
754
                while ($row = $db->sql_fetchrow($result))
755
                {
756
                        $founder[$row['user_id']] = $row['user_email'];
757
                        $founder_names[$row['user_id']] = $row['username_clean'];
758
                }
759
                $db->sql_freeresult($result);
760
        }
761
762
        $banlist_ary = array();
763
764
        switch ($mode)
765
        {
766
                case 'user':
767
                        $type = 'ban_userid';
768
769
                        // At the moment we do not support wildcard username banning
770
771
                        // Select the relevant user_ids.
772
                        $sql_usernames = array();
773
774
                        foreach ($ban_list as $username)
775
                        {
776
                                $username = trim($username);
777
                                if ($username != '')
778
                                {
779
                                        $clean_name = utf8_clean_string($username);
780
                                        if ($clean_name == $user->data['username_clean'])
781
                                        {
782
                                                trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
783
                                        }
784
                                        if (in_array($clean_name, $founder_names))
785
                                        {
786
                                                trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
787
                                        }
788
                                        $sql_usernames[] = $clean_name;
789
                                }
790
                        }
791
792
                        // Make sure we have been given someone to ban
793
                        if (!sizeof($sql_usernames))
794
                        {
795
                                trigger_error('NO_USER_SPECIFIED', E_USER_WARNING);
796
                        }
797
798
                        $sql = 'SELECT user_id
799
                                FROM ' . USERS_TABLE . '
800
                                WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
801
802
                        // Do not allow banning yourself, the guest account, or founders.
803
                        $non_bannable = array($user->data['user_id'], ANONYMOUS);
804
                        if (sizeof($founder))
805
                        {
806
                                $sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), $non_bannable), true);
807
                        }
808
                        else
809
                        {
810
                                $sql .= ' AND ' . $db->sql_in_set('user_id', $non_bannable, true);
811
                        }
812
813
                        $result = $db->sql_query($sql);
814
815
                        if ($row = $db->sql_fetchrow($result))
816
                        {
817
                                do
818
                                {
819
                                        $banlist_ary[] = (int) $row['user_id'];
820
                                }
821
                                while ($row = $db->sql_fetchrow($result));
822
                        }
823
                        else
824
                        {
825
                                $db->sql_freeresult($result);
826
                                trigger_error('NO_USERS', E_USER_WARNING);
827
                        }
828
                        $db->sql_freeresult($result);
829
                break;
830
831
                case 'ip':
832
                        $type = 'ban_ip';
833
834
                        foreach ($ban_list as $ban_item)
835
                        {
836
                                if (preg_match('#^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$#', trim($ban_item), $ip_range_explode))
837
                                {
838
                                        // This is an IP range
839
                                        // Don't ask about all this, just don't ask ... !
840
                                        $ip_1_counter = $ip_range_explode[1];
841
                                        $ip_1_end = $ip_range_explode[5];
842
843
                                        while ($ip_1_counter <= $ip_1_end)
844
                                        {
845
                                                $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
846
                                                $ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
847
848
                                                if ($ip_2_counter == 0 && $ip_2_end == 254)
849
                                                {
850
                                                        $ip_2_counter = 256;
851
                                                        $ip_2_fragment = 256;
852
853
                                                        $banlist_ary[] = "$ip_1_counter.*";
854
                                                }
855
856
                                                while ($ip_2_counter <= $ip_2_end)
857
                                                {
858
                                                        $ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
859
                                                        $ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
860
861
                                                        if ($ip_3_counter == 0 && $ip_3_end == 254)
862
                                                        {
863
                                                                $ip_3_counter = 256;
864
                                                                $ip_3_fragment = 256;
865
866
                                                                $banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
867
                                                        }
868
869
                                                        while ($ip_3_counter <= $ip_3_end)
870
                                                        {
871
                                                                $ip_4_counter = ($ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[4] : 0;
872
                                                                $ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
873
874
                                                                if ($ip_4_counter == 0 && $ip_4_end == 254)
875
                                                                {
876
                                                                        $ip_4_counter = 256;
877
                                                                        $ip_4_fragment = 256;
878
879
                                                                        $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
880
                                                                }
881
882
                                                                while ($ip_4_counter <= $ip_4_end)
883
                                                                {
884
                                                                        $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
885
                                                                        $ip_4_counter++;
886
                                                                }
887
                                                                $ip_3_counter++;
888
                                                        }
889
                                                        $ip_2_counter++;
890
                                                }
891
                                                $ip_1_counter++;
892
                                        }
893
                                }
894
                                else if (preg_match('#^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$#', trim($ban_item)) || preg_match('#^[a-f0-9:]+\*?$#i', trim($ban_item)))
895
                                {
896
                                        // Normal IP address
897
                                        $banlist_ary[] = trim($ban_item);
898
                                }
899
                                else if (preg_match('#^\*$#', trim($ban_item)))
900
                                {
901
                                        // Ban all IPs
902
                                        $banlist_ary[] = '*';
903
                                }
904
                                else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
905
                                {
906
                                        // hostname
907
                                        $ip_ary = gethostbynamel(trim($ban_item));
908
909
                                        if (!empty($ip_ary))
910
                                        {
911
                                                foreach ($ip_ary as $ip)
912
                                                {
913
                                                        if ($ip)
914
                                                        {
915
                                                                if (strlen($ip) > 40)
916
                                                                {
917
                                                                        continue;
918
                                                                }
919
920
                                                                $banlist_ary[] = $ip;
921
                                                        }
922
                                                }
923
                                        }
924
                                }
925
926
                                if (empty($banlist_ary))
927
                                {
928
                                        trigger_error('NO_IPS_DEFINED', E_USER_WARNING);
929
                                }
930
                        }
931
                break;
932
933
                case 'email':
934
                        $type = 'ban_email';
935
936
                        foreach ($ban_list as $ban_item)
937
                        {
938
                                $ban_item = trim($ban_item);
939
940
                                if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
941
                                {
942
                                        if (strlen($ban_item) > 100)
943
                                        {
944
                                                continue;
945
                                        }
946
947
                                        if (!sizeof($founder) || !in_array($ban_item, $founder))
948
                                        {
949
                                                $banlist_ary[] = $ban_item;
950
                                        }
951
                                }
952
                        }
953
954
                        if (sizeof($ban_list) == 0)
955
                        {
956
                                trigger_error('NO_EMAILS_DEFINED', E_USER_WARNING);
957
                        }
958
                break;
959
960
                default:
961
                        trigger_error('NO_MODE', E_USER_WARNING);
962
                break;
963
        }
964
965
        // Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
966
        $sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
967
968
        $sql = "SELECT $type
969
                FROM " . BANLIST_TABLE . "
970
                WHERE $sql_where
971
                        AND ban_exclude = " . (int) $ban_exclude;
972
        $result = $db->sql_query($sql);
973
974
        // Reset $sql_where, because we use it later...
975
        $sql_where = '';
976
977
        if ($row = $db->sql_fetchrow($result))
978
        {
979
                $banlist_ary_tmp = array();
980
                do
981
                {
982
                        switch ($mode)
983
                        {
984
                                case 'user':
985
                                        $banlist_ary_tmp[] = $row['ban_userid'];
986
                                break;
987
988
                                case 'ip':
989
                                        $banlist_ary_tmp[] = $row['ban_ip'];
990
                                break;
991
992
                                case 'email':
993
                                        $banlist_ary_tmp[] = $row['ban_email'];
994
                                break;
995
                        }
996
                }
997
                while ($row = $db->sql_fetchrow($result));
998
999
                $banlist_ary_tmp = array_intersect($banlist_ary, $banlist_ary_tmp);
1000
1001
                if (sizeof($banlist_ary_tmp))
1002
                {
1003
                        // One or more entities are already banned/excluded, delete the existing bans, so they can be re-inserted with the given new length
1004
                        $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1005
                                WHERE ' . $db->sql_in_set($type, $banlist_ary_tmp) . '
1006
                                        AND ban_exclude = ' . (int) $ban_exclude;
1007
                        $db->sql_query($sql);
1008
                }
1009
1010
                unset($banlist_ary_tmp);
1011
        }
1012
        $db->sql_freeresult($result);
1013
1014
        // We have some entities to ban
1015
        if (sizeof($banlist_ary))
1016
        {
1017
                $sql_ary = array();
1018
1019
                foreach ($banlist_ary as $ban_entry)
1020
                {
1021
                        $sql_ary[] = array(
1022
                                $type                                => $ban_entry,
1023
                                'ban_start'                        => (int) $current_time,
1024
                                'ban_end'                        => (int) $ban_end,
1025
                                'ban_exclude'                => (int) $ban_exclude,
1026
                                'ban_reason'                => (string) $ban_reason,
1027
                                'ban_give_reason'        => (string) $ban_give_reason,
1028
                        );
1029
                }
1030
1031
                $db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
1032
1033
                // If we are banning we want to logout anyone matching the ban
1034
                if (!$ban_exclude)
1035
                {
1036
                        switch ($mode)
1037
                        {
1038
                                case 'user':
1039
                                        $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
1040
                                break;
1041
1042
                                case 'ip':
1043
                                        $sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
1044
                                break;
1045
1046
                                case 'email':
1047
                                        $banlist_ary_sql = array();
1048
1049
                                        foreach ($banlist_ary as $ban_entry)
1050
                                        {
1051
                                                $banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
1052
                                        }
1053
1054
                                        $sql = 'SELECT user_id
1055
                                                FROM ' . USERS_TABLE . '
1056
                                                WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
1057
                                        $result = $db->sql_query($sql);
1058
1059
                                        $sql_in = array();
1060
1061
                                        if ($row = $db->sql_fetchrow($result))
1062
                                        {
1063
                                                do
1064
                                                {
1065
                                                        $sql_in[] = $row['user_id'];
1066
                                                }
1067
                                                while ($row = $db->sql_fetchrow($result));
1068
1069
                                                $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
1070
                                        }
1071
                                        $db->sql_freeresult($result);
1072
                                break;
1073
                        }
1074
1075
                        if (isset($sql_where) && $sql_where)
1076
                        {
1077
                                $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
1078
                                        $sql_where";
1079
                                $db->sql_query($sql);
1080
1081
                                if ($mode == 'user')
1082
                                {
1083
                                        $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
1084
                                        $db->sql_query($sql);
1085
                                }
1086
                        }
1087
                }
1088
1089
                // Update log
1090
                $log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
1091
1092
                // Add to moderator log, admin log and user notes
1093
                add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1094
                add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1095
                if ($mode == 'user')
1096
                {
1097
                        foreach ($banlist_ary as $user_id)
1098
                        {
1099
                                add_log('user', $user_id, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
1100
                        }
1101
                }
1102
1103
                $cache->destroy('sql', BANLIST_TABLE);
1104
1105
                return true;
1106
        }
1107
1108
        // There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
1109
        $cache->destroy('sql', BANLIST_TABLE);
1110
1111
        return false;
1112
}
1113
1114
/**
1115
* Unban User
1116
*/
1117
function user_unban($mode, $ban)
1118
{
1119
        global $db, $user, $auth, $cache;
1120
1121
        // Delete stale bans
1122
        $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1123
                WHERE ban_end < ' . time() . '
1124
                        AND ban_end <> 0';
1125
        $db->sql_query($sql);
1126
1127
        if (!is_array($ban))
1128
        {
1129
                $ban = array($ban);
1130
        }
1131
1132
        $unban_sql = array_map('intval', $ban);
1133
1134
        if (sizeof($unban_sql))
1135
        {
1136
                // Grab details of bans for logging information later
1137
                switch ($mode)
1138
                {
1139
                        case 'user':
1140
                                $sql = 'SELECT u.username AS unban_info, u.user_id
1141
                                        FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
1142
                                        WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
1143
                                                AND u.user_id = b.ban_userid';
1144
                        break;
1145
1146
                        case 'email':
1147
                                $sql = 'SELECT ban_email AS unban_info
1148
                                        FROM ' . BANLIST_TABLE . '
1149
                                        WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
1150
                        break;
1151
1152
                        case 'ip':
1153
                                $sql = 'SELECT ban_ip AS unban_info
1154
                                        FROM ' . BANLIST_TABLE . '
1155
                                        WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
1156
                        break;
1157
                }
1158
                $result = $db->sql_query($sql);
1159
1160
                $l_unban_list = '';
1161
                $user_ids_ary = array();
1162
                while ($row = $db->sql_fetchrow($result))
1163
                {
1164
                        $l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
1165
                        if ($mode == 'user')
1166
                        {
1167
                                $user_ids_ary[] = $row['user_id'];
1168
                        }
1169
                }
1170
                $db->sql_freeresult($result);
1171
1172
                $sql = 'DELETE FROM ' . BANLIST_TABLE . '
1173
                        WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
1174
                $db->sql_query($sql);
1175
1176
                // Add to moderator log, admin log and user notes
1177
                add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1178
                add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1179
                if ($mode == 'user')
1180
                {
1181
                        foreach ($user_ids_ary as $user_id)
1182
                        {
1183
                                add_log('user', $user_id, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
1184
                        }
1185
                }
1186
        }
1187
1188
        $cache->destroy('sql', BANLIST_TABLE);
1189
1190
        return false;
1191
}
1192
1193
/**
1194
* Internet Protocol Address Whois
1195
* RFC3912: WHOIS Protocol Specification
1196
*
1197
* @param string $ip                Ip address, either IPv4 or IPv6.
1198
*
1199
* @return string                Empty string if not a valid ip address.
1200
*                                                Otherwise make_clickable()'ed whois result.
1201
*/
1202
function user_ipwhois($ip)
1203
{
1204
        if (empty($ip))
1205
        {
1206
                return '';
1207
        }
1208
1209
        if (preg_match(get_preg_expression('ipv4'), $ip))
1210
        {
1211
                // IPv4 address
1212
                $whois_host = 'whois.arin.net.';
1213
        }
1214
        else if (preg_match(get_preg_expression('ipv6'), $ip))
1215
        {
1216
                // IPv6 address
1217
                $whois_host = 'whois.sixxs.net.';
1218
        }
1219
        else
1220
        {
1221
                return '';
1222
        }
1223
1224
        $ipwhois = '';
1225
1226
        if (($fsk = @fsockopen($whois_host, 43)))
1227
        {
1228
                // CRLF as per RFC3912
1229
                fputs($fsk, "$ip\r\n");
1230
                while (!feof($fsk))
1231
                {
1232
                        $ipwhois .= fgets($fsk, 1024);
1233
                }
1234
                @fclose($fsk);
1235
        }
1236
1237
        $match = array();
1238
1239
        // Test for referrals from $whois_host to other whois databases, roll on rwhois
1240
        if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
1241
        {
1242
                if (strpos($match[1], ':') !== false)
1243
                {
1244
                        $pos        = strrpos($match[1], ':');
1245
                        $server        = substr($match[1], 0, $pos);
1246
                        $port        = (int) substr($match[1], $pos + 1);
1247
                        unset($pos);
1248
                }
1249
                else
1250
                {
1251
                        $server        = $match[1];
1252
                        $port        = 43;
1253
                }
1254
1255
                $buffer = '';
1256
1257
                if (($fsk = @fsockopen($server, $port)))
1258
                {
1259
                        fputs($fsk, "$ip\r\n");
1260
                        while (!feof($fsk))
1261
                        {
1262
                                $buffer .= fgets($fsk, 1024);
1263
                        }
1264
                        @fclose($fsk);
1265
                }
1266
1267
                // Use the result from $whois_host if we don't get any result here
1268
                $ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
1269
        }
1270
1271
        $ipwhois = htmlspecialchars($ipwhois);
1272
1273
        // Magic URL ;)
1274
        return trim(make_clickable($ipwhois, false, ''));
1275
}
1276
1277
/**
1278
* Data validation ... used primarily but not exclusively by ucp modules
1279
*
1280
* "Master" function for validating a range of data types
1281
*/
1282
function validate_data($data, $val_ary)
1283
{
1284
        global $user;
1285
1286
        $error = array();
1287
1288
        foreach ($val_ary as $var => $val_seq)
1289
        {
1290
                if (!is_array($val_seq[0]))
1291
                {
1292
                        $val_seq = array($val_seq);
1293
                }
1294
1295
                foreach ($val_seq as $validate)
1296
                {
1297
                        $function = array_shift($validate);
1298
                        array_unshift($validate, $data[$var]);
1299
1300
                        if ($result = call_user_func_array('validate_' . $function, $validate))
1301
                        {
1302
                                // Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
1303
                                $error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
1304
                        }
1305
                }
1306
        }
1307
1308
        return $error;
1309
}
1310
1311
/**
1312
* Validate String
1313
*
1314
* @return        boolean|string        Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1315
*/
1316
function validate_string($string, $optional = false, $min = 0, $max = 0)
1317
{
1318
        if (empty($string) && $optional)
1319
        {
1320
                return false;
1321
        }
1322
1323
        if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
1324
        {
1325
                return 'TOO_SHORT';
1326
        }
1327
        else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
1328
        {
1329
                return 'TOO_LONG';
1330
        }
1331
1332
        return false;
1333
}
1334
1335
/**
1336
* Validate Number
1337
*
1338
* @return        boolean|string        Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1339
*/
1340
function validate_num($num, $optional = false, $min = 0, $max = 1E99)
1341
{
1342
        if (empty($num) && $optional)
1343
        {
1344
                return false;
1345
        }
1346
1347
        if ($num < $min)
1348
        {
1349
                return 'TOO_SMALL';
1350
        }
1351
        else if ($num > $max)
1352
        {
1353
                return 'TOO_LARGE';
1354
        }
1355
1356
        return false;
1357
}
1358
1359
/**
1360
* Validate Date
1361
* @param String $string a date in the dd-mm-yyyy format
1362
* @return        boolean
1363
*/
1364
function validate_date($date_string, $optional = false)
1365
{
1366
        $date = explode('-', $date_string);
1367
        if ((empty($date) || sizeof($date) != 3) && $optional)
1368
        {
1369
                return false;
1370
        }
1371
        else if ($optional)
1372
        {
1373
                for ($field = 0; $field <= 1; $field++)
1374
                {
1375
                        $date[$field] = (int) $date[$field];
1376
                        if (empty($date[$field]))
1377
                        {
1378
                                $date[$field] = 1;
1379
                        }
1380
                }
1381
                $date[2] = (int) $date[2];
1382
                // assume an arbitrary leap year
1383
                if (empty($date[2]))
1384
                {
1385
                        $date[2] = 1980;
1386
                }
1387
        }
1388
1389
        if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
1390
        {
1391
                return 'INVALID';
1392
        }
1393
1394
        return false;
1395
}
1396
1397
1398
/**
1399
* Validate Match
1400
*
1401
* @return        boolean|string        Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1402
*/
1403
function validate_match($string, $optional = false, $match = '')
1404
{
1405
        if (empty($string) && $optional)
1406
        {
1407
                return false;
1408
        }
1409
1410
        if (empty($match))
1411
        {
1412
                return false;
1413
        }
1414
1415
        if (!preg_match($match, $string))
1416
        {
1417
                return 'WRONG_DATA';
1418
        }
1419
1420
        return false;
1421
}
1422
1423
/**
1424
* Validate Language Pack ISO Name
1425
*
1426
* Tests whether a language name is valid and installed
1427
*
1428
* @param string $lang_iso        The language string to test
1429
*
1430
* @return bool|string                Either false if validation succeeded or
1431
*                                                        a string which will be used as the error message
1432
*                                                        (with the variable name appended)
1433
*/
1434
function validate_language_iso_name($lang_iso)
1435
{
1436
        global $db;
1437
1438
        $sql = 'SELECT lang_id
1439
                FROM ' . LANG_TABLE . "
1440
                WHERE lang_iso = '" . $db->sql_escape($lang_iso) . "'";
1441
        $result = $db->sql_query($sql);
1442
        $lang_id = (int) $db->sql_fetchfield('lang_id');
1443
        $db->sql_freeresult($result);
1444
1445
        return ($lang_id) ? false : 'WRONG_DATA';
1446
}
1447
1448
/**
1449
* Check to see if the username has been taken, or if it is disallowed.
1450
* Also checks if it includes the " character, which we don't allow in usernames.
1451
* Used for registering, changing names, and posting anonymously with a username
1452
*
1453
* @param string $username The username to check
1454
* @param string $allowed_username An allowed username, default being $user->data['username']
1455
*
1456
* @return        mixed        Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1457
*/
1458
function validate_username($username, $allowed_username = false)
1459
{
1460
        global $config, $db, $user, $cache;
1461
1462
        $clean_username = utf8_clean_string($username);
1463
        $allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
1464
1465
        if ($allowed_username == $clean_username)
1466
        {
1467
                return false;
1468
        }
1469
1470
        // ... fast checks first.
1471
        if (strpos($username, '&quot;') !== false || strpos($username, '"') !== false || empty($clean_username))
1472
        {
1473
                return 'INVALID_CHARS';
1474
        }
1475
1476
        $mbstring = $pcre = false;
1477
1478
        // generic UTF-8 character types supported?
1479
        if (phpbb_pcre_utf8_support())
1480
        {
1481
                $pcre = true;
1482
        }
1483
        else if (function_exists('mb_ereg_match'))
1484
        {
1485
                mb_regex_encoding('UTF-8');
1486
                $mbstring = true;
1487
        }
1488
1489
        switch ($config['allow_name_chars'])
1490
        {
1491
                case 'USERNAME_CHARS_ANY':
1492
                        $pcre = true;
1493
                        $regex = '.+';
1494
                break;
1495
1496
                case 'USERNAME_ALPHA_ONLY':
1497
                        $pcre = true;
1498
                        $regex = '[A-Za-z0-9]+';
1499
                break;
1500
1501
                case 'USERNAME_ALPHA_SPACERS':
1502
                        $pcre = true;
1503
                        $regex = '[A-Za-z0-9-[\]_+ ]+';
1504
                break;
1505
1506
                case 'USERNAME_LETTER_NUM':
1507
                        if ($pcre)
1508
                        {
1509
                                $regex = '[\p{Lu}\p{Ll}\p{N}]+';
1510
                        }
1511
                        else if ($mbstring)
1512
                        {
1513
                                $regex = '[[:upper:][:lower:][:digit:]]+';
1514
                        }
1515
                        else
1516
                        {
1517
                                $pcre = true;
1518
                                $regex = '[a-zA-Z0-9]+';
1519
                        }
1520
                break;
1521
1522
                case 'USERNAME_LETTER_NUM_SPACERS':
1523
                        if ($pcre)
1524
                        {
1525
                                $regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
1526
                        }
1527
                        else if ($mbstring)
1528
                        {
1529
                                $regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
1530
                        }
1531
                        else
1532
                        {
1533
                                $pcre = true;
1534
                                $regex = '[-\]_+ [a-zA-Z0-9]+';
1535
                        }
1536
                break;
1537
1538
                case 'USERNAME_ASCII':
1539
                default:
1540
                        $pcre = true;
1541
                        $regex = '[\x01-\x7F]+';
1542
                break;
1543
        }
1544
1545
        if ($pcre)
1546
        {
1547
                if (!preg_match('#^' . $regex . '$#u', $username))
1548
                {
1549
                        return 'INVALID_CHARS';
1550
                }
1551
        }
1552
        else if ($mbstring)
1553
        {
1554
                mb_ereg_search_init($username, '^' . $regex . '$');
1555
                if (!mb_ereg_search())
1556
                {
1557
                        return 'INVALID_CHARS';
1558
                }
1559
        }
1560
1561
        $sql = 'SELECT username
1562
                FROM ' . USERS_TABLE . "
1563
                WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
1564
        $result = $db->sql_query($sql);
1565
        $row = $db->sql_fetchrow($result);
1566
        $db->sql_freeresult($result);
1567
1568
        if ($row)
1569
        {
1570
                return 'USERNAME_TAKEN';
1571
        }
1572
1573
        $sql = 'SELECT group_name
1574
                FROM ' . GROUPS_TABLE . "
1575
                WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
1576
        $result = $db->sql_query($sql);
1577
        $row = $db->sql_fetchrow($result);
1578
        $db->sql_freeresult($result);
1579
1580
        if ($row)
1581
        {
1582
                return 'USERNAME_TAKEN';
1583
        }
1584
1585
        $bad_usernames = $cache->obtain_disallowed_usernames();
1586
1587
        foreach ($bad_usernames as $bad_username)
1588
        {
1589
                if (preg_match('#^' . $bad_username . '$#', $clean_username))
1590
                {
1591
                        return 'USERNAME_DISALLOWED';
1592
                }
1593
        }
1594
1595
        return false;
1596
}
1597
1598
/**
1599
* Check to see if the password meets the complexity settings
1600
*
1601
* @return        boolean|string        Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1602
*/
1603
function validate_password($password)
1604
{
1605
        global $config, $db, $user;
1606
1607
        if ($password === '' || $config['pass_complex'] === 'PASS_TYPE_ANY')
1608
        {
1609
                // Password empty or no password complexity required.
1610
                return false;
1611
        }
1612
1613
        $pcre = $mbstring = false;
1614
1615
        // generic UTF-8 character types supported?
1616
        if (phpbb_pcre_utf8_support())
1617
        {
1618
                $upp = '\p{Lu}';
1619
                $low = '\p{Ll}';
1620
                $num = '\p{N}';
1621
                $sym = '[^\p{Lu}\p{Ll}\p{N}]';
1622
                $pcre = true;
1623
        }
1624
        else if (function_exists('mb_ereg_match'))
1625
        {
1626
                mb_regex_encoding('UTF-8');
1627
                $upp = '[[:upper:]]';
1628
                $low = '[[:lower:]]';
1629
                $num = '[[:digit:]]';
1630
                $sym = '[^[:upper:][:lower:][:digit:]]';
1631
                $mbstring = true;
1632
        }
1633
        else
1634
        {
1635
                $upp = '[A-Z]';
1636
                $low = '[a-z]';
1637
                $num = '[0-9]';
1638
                $sym = '[^A-Za-z0-9]';
1639
                $pcre = true;
1640
        }
1641
1642
        $chars = array();
1643
1644
        switch ($config['pass_complex'])
1645
        {
1646
                // No break statements below ...
1647
                // We require strong passwords in case pass_complex is not set or is invalid
1648
                default:
1649
1650
                // Require mixed case letters, numbers and symbols
1651
                case 'PASS_TYPE_SYMBOL':
1652
                        $chars[] = $sym;
1653
1654
                // Require mixed case letters and numbers
1655
                case 'PASS_TYPE_ALPHA':
1656
                        $chars[] = $num;
1657
1658
                // Require mixed case letters
1659
                case 'PASS_TYPE_CASE':
1660
                        $chars[] = $low;
1661
                        $chars[] = $upp;
1662
        }
1663
1664
        if ($pcre)
1665
        {
1666
                foreach ($chars as $char)
1667
                {
1668
                        if (!preg_match('#' . $char . '#u', $password))
1669
                        {
1670
                                return 'INVALID_CHARS';
1671
                        }
1672
                }
1673
        }
1674
        else if ($mbstring)
1675
        {
1676
                foreach ($chars as $char)
1677
                {
1678
                        if (mb_ereg($char, $password) === false)
1679
                        {
1680
                                return 'INVALID_CHARS';
1681
                        }
1682
                }
1683
        }
1684
1685
        return false;
1686
}
1687
1688
/**
1689
* Check to see if email address is banned or already present in the DB
1690
*
1691
* @param string $email The email to check
1692
* @param string $allowed_email An allowed email, default being $user->data['user_email']
1693
*
1694
* @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
1695
*/
1696
function validate_email($email, $allowed_email = false)
1697
{
1698
        global $config, $db, $user;
1699
1700
        $email = strtolower($email);
1701
        $allowed_email = ($allowed_email === false) ? strtolower($user->data['user_email']) : strtolower($allowed_email);
1702
1703
        if ($allowed_email == $email)
1704
        {
1705
                return false;
1706
        }
1707
1708
        if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
1709
        {
1710
                return 'EMAIL_INVALID';
1711
        }
1712
1713
        // Check MX record.
1714
        // The idea for this is from reading the UseBB blog/announcement. :)
1715
        if ($config['email_check_mx'])
1716
        {
1717
                list(, $domain) = explode('@', $email);
1718
1719
                if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
1720
                {
1721
                        return 'DOMAIN_NO_MX_RECORD';
1722
                }
1723
        }
1724
1725
        if (($ban_reason = $user->check_ban(false, false, $email, true)) !== false)
1726
        {
1727
                return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
1728
        }
1729
1730
        if (!$config['allow_emailreuse'])
1731
        {
1732
                $sql = 'SELECT user_email_hash
1733
                        FROM ' . USERS_TABLE . "
1734
                        WHERE user_email_hash = " . $db->sql_escape(phpbb_email_hash($email));
1735
                $result = $db->sql_query($sql);
1736
                $row = $db->sql_fetchrow($result);
1737
                $db->sql_freeresult($result);
1738
1739
                if ($row)
1740
                {
1741
                        return 'EMAIL_TAKEN';
1742
                }
1743
        }
1744
1745
        return false;
1746
}
1747
1748
/**
1749
* Validate jabber address
1750
* Taken from the jabber class within flyspray (see author notes)
1751
*
1752
* @author flyspray.org
1753
*/
1754
function validate_jabber($jid)
1755
{
1756
        if (!$jid)
1757
        {
1758
                return false;
1759
        }
1760
1761
        $separator_pos = strpos($jid, '@');
1762
1763
        if ($separator_pos === false)
1764
        {
1765
                return 'WRONG_DATA';
1766
        }
1767
1768
        $username = substr($jid, 0, $separator_pos);
1769
        $realm = substr($jid, $separator_pos + 1);
1770
1771
        if (strlen($username) == 0 || strlen($realm) < 3)
1772
        {
1773
                return 'WRONG_DATA';
1774
        }
1775
1776
        $arr = explode('.', $realm);
1777
1778
        if (sizeof($arr) == 0)
1779
        {
1780
                return 'WRONG_DATA';
1781
        }
1782
1783
        foreach ($arr as $part)
1784
        {
1785
                if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
1786
                {
1787
                        return 'WRONG_DATA';
1788
                }
1789
1790
                if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
1791
                {
1792
                        return 'WRONG_DATA';
1793
                }
1794
        }
1795
1796
        $boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
1797
1798
        // Prohibited Characters RFC3454 + RFC3920
1799
        $prohibited = array(
1800
                // Table C.1.1
1801
                array(0x0020, 0x0020),                // SPACE
1802
                // Table C.1.2
1803
                array(0x00A0, 0x00A0),                // NO-BREAK SPACE
1804
                array(0x1680, 0x1680),                // OGHAM SPACE MARK
1805
                array(0x2000, 0x2001),                // EN QUAD
1806
                array(0x2001, 0x2001),                // EM QUAD
1807
                array(0x2002, 0x2002),                // EN SPACE
1808
                array(0x2003, 0x2003),                // EM SPACE
1809
                array(0x2004, 0x2004),                // THREE-PER-EM SPACE
1810
                array(0x2005, 0x2005),                // FOUR-PER-EM SPACE
1811
                array(0x2006, 0x2006),                // SIX-PER-EM SPACE
1812
                array(0x2007, 0x2007),                // FIGURE SPACE
1813
                array(0x2008, 0x2008),                // PUNCTUATION SPACE
1814
                array(0x2009, 0x2009),                // THIN SPACE
1815
                array(0x200A, 0x200A),                // HAIR SPACE
1816
                array(0x200B, 0x200B),                // ZERO WIDTH SPACE
1817
                array(0x202F, 0x202F),                // NARROW NO-BREAK SPACE
1818
                array(0x205F, 0x205F),                // MEDIUM MATHEMATICAL SPACE
1819
                array(0x3000, 0x3000),                // IDEOGRAPHIC SPACE
1820
                // Table C.2.1
1821
                array(0x0000, 0x001F),                // [CONTROL CHARACTERS]
1822
                array(0x007F, 0x007F),                // DELETE
1823
                // Table C.2.2
1824
                array(0x0080, 0x009F),                // [CONTROL CHARACTERS]
1825
                array(0x06DD, 0x06DD),                // ARABIC END OF AYAH
1826
                array(0x070F, 0x070F),                // SYRIAC ABBREVIATION MARK
1827
                array(0x180E, 0x180E),                // MONGOLIAN VOWEL SEPARATOR
1828
                array(0x200C, 0x200C),                 // ZERO WIDTH NON-JOINER
1829
                array(0x200D, 0x200D),                // ZERO WIDTH JOINER
1830
                array(0x2028, 0x2028),                // LINE SEPARATOR
1831
                array(0x2029, 0x2029),                // PARAGRAPH SEPARATOR
1832
                array(0x2060, 0x2060),                // WORD JOINER
1833
                array(0x2061, 0x2061),                // FUNCTION APPLICATION
1834
                array(0x2062, 0x2062),                // INVISIBLE TIMES
1835
                array(0x2063, 0x2063),                // INVISIBLE SEPARATOR
1836
                array(0x206A, 0x206F),                // [CONTROL CHARACTERS]
1837
                array(0xFEFF, 0xFEFF),                // ZERO WIDTH NO-BREAK SPACE
1838
                array(0xFFF9, 0xFFFC),                // [CONTROL CHARACTERS]
1839
                array(0x1D173, 0x1D17A),        // [MUSICAL CONTROL CHARACTERS]
1840
                // Table C.3
1841
                array(0xE000, 0xF8FF),                // [PRIVATE USE, PLANE 0]
1842
                array(0xF0000, 0xFFFFD),        // [PRIVATE USE, PLANE 15]
1843
                array(0x100000, 0x10FFFD),        // [PRIVATE USE, PLANE 16]
1844
                // Table C.4
1845
                array(0xFDD0, 0xFDEF),                // [NONCHARACTER CODE POINTS]
1846
                array(0xFFFE, 0xFFFF),                // [NONCHARACTER CODE POINTS]
1847
                array(0x1FFFE, 0x1FFFF),        // [NONCHARACTER CODE POINTS]
1848
                array(0x2FFFE, 0x2FFFF),        // [NONCHARACTER CODE POINTS]
1849
                array(0x3FFFE, 0x3FFFF),        // [NONCHARACTER CODE POINTS]
1850
                array(0x4FFFE, 0x4FFFF),        // [NONCHARACTER CODE POINTS]
1851
                array(0x5FFFE, 0x5FFFF),        // [NONCHARACTER CODE POINTS]
1852
                array(0x6FFFE, 0x6FFFF),        // [NONCHARACTER CODE POINTS]
1853
                array(0x7FFFE, 0x7FFFF),        // [NONCHARACTER CODE POINTS]
1854
                array(0x8FFFE, 0x8FFFF),        // [NONCHARACTER CODE POINTS]
1855
                array(0x9FFFE, 0x9FFFF),        // [NONCHARACTER CODE POINTS]
1856
                array(0xAFFFE, 0xAFFFF),        // [NONCHARACTER CODE POINTS]
1857
                array(0xBFFFE, 0xBFFFF),        // [NONCHARACTER CODE POINTS]
1858
                array(0xCFFFE, 0xCFFFF),        // [NONCHARACTER CODE POINTS]
1859
                array(0xDFFFE, 0xDFFFF),        // [NONCHARACTER CODE POINTS]
1860
                array(0xEFFFE, 0xEFFFF),        // [NONCHARACTER CODE POINTS]
1861
                array(0xFFFFE, 0xFFFFF),        // [NONCHARACTER CODE POINTS]
1862
                array(0x10FFFE, 0x10FFFF),        // [NONCHARACTER CODE POINTS]
1863
                // Table C.5
1864
                array(0xD800, 0xDFFF),                // [SURROGATE CODES]
1865
                // Table C.6
1866
                array(0xFFF9, 0xFFF9),                // INTERLINEAR ANNOTATION ANCHOR
1867
                array(0xFFFA, 0xFFFA),                // INTERLINEAR ANNOTATION SEPARATOR
1868
                array(0xFFFB, 0xFFFB),                // INTERLINEAR ANNOTATION TERMINATOR
1869
                array(0xFFFC, 0xFFFC),                // OBJECT REPLACEMENT CHARACTER
1870
                array(0xFFFD, 0xFFFD),                // REPLACEMENT CHARACTER
1871
                // Table C.7
1872
                array(0x2FF0, 0x2FFB),                // [IDEOGRAPHIC DESCRIPTION CHARACTERS]
1873
                // Table C.8
1874
                array(0x0340, 0x0340),                // COMBINING GRAVE TONE MARK
1875
                array(0x0341, 0x0341),                // COMBINING ACUTE TONE MARK
1876
                array(0x200E, 0x200E),                // LEFT-TO-RIGHT MARK
1877
                array(0x200F, 0x200F),                // RIGHT-TO-LEFT MARK
1878
                array(0x202A, 0x202A),                // LEFT-TO-RIGHT EMBEDDING
1879
                array(0x202B, 0x202B),                // RIGHT-TO-LEFT EMBEDDING
1880
                array(0x202C, 0x202C),                // POP DIRECTIONAL FORMATTING
1881
                array(0x202D, 0x202D),                // LEFT-TO-RIGHT OVERRIDE
1882
                array(0x202E, 0x202E),                // RIGHT-TO-LEFT OVERRIDE
1883
                array(0x206A, 0x206A),                // INHIBIT SYMMETRIC SWAPPING
1884
                array(0x206B, 0x206B),                // ACTIVATE SYMMETRIC SWAPPING
1885
                array(0x206C, 0x206C),                // INHIBIT ARABIC FORM SHAPING
1886
                array(0x206D, 0x206D),                // ACTIVATE ARABIC FORM SHAPING
1887
                array(0x206E, 0x206E),                // NATIONAL DIGIT SHAPES
1888
                array(0x206F, 0x206F),                // NOMINAL DIGIT SHAPES
1889
                // Table C.9
1890
                array(0xE0001, 0xE0001),        // LANGUAGE TAG
1891
                array(0xE0020, 0xE007F),        // [TAGGING CHARACTERS]
1892
                // RFC3920
1893
                array(0x22, 0x22),                        // "
1894
                array(0x26, 0x26),                        // &
1895
                array(0x27, 0x27),                        // '
1896
                array(0x2F, 0x2F),                        // /
1897
                array(0x3A, 0x3A),                        // :
1898
                array(0x3C, 0x3C),                        // <
1899
                array(0x3E, 0x3E),                        // >
1900
                array(0x40, 0x40)                        // @
1901
        );
1902
1903
        $pos = 0;
1904
        $result = true;
1905
1906
        while ($pos < strlen($username))
1907
        {
1908
                $len = $uni = 0;
1909
                for ($i = 0; $i <= 5; $i++)
1910
                {
1911
                        if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
1912
                        {
1913
                                $len = $i + 1;
1914
                                $uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
1915
1916
                                for ($k = 1; $k < $len; $k++)
1917
                                {
1918
                                        $uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
1919
                                }
1920
1921
                                break;
1922
                        }
1923
                }
1924
1925
                if ($len == 0)
1926
                {
1927
                        return 'WRONG_DATA';
1928
                }
1929
1930
                foreach ($prohibited as $pval)
1931
                {
1932
                        if ($uni >= $pval[0] && $uni <= $pval[1])
1933
                        {
1934
                                $result = false;
1935
                                break 2;
1936
                        }
1937
                }
1938
1939
                $pos = $pos + $len;
1940
        }
1941
1942
        if (!$result)
1943
        {
1944
                return 'WRONG_DATA';
1945
        }
1946
1947
        return false;
1948
}
1949
1950
/**
1951
* Remove avatar
1952
*/
1953
function avatar_delete($mode, $row, $clean_db = false)
1954
{
1955
        global $phpbb_root_path, $config, $db, $user;
1956
1957
        // Check if the users avatar is actually *not* a group avatar
1958
        if ($mode == 'user')
1959
        {
1960
                if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_avatar'] !== (int)$row['user_id'])))
1961
                {
1962
                        return false;
1963
                }
1964
        }
1965
1966
        if ($clean_db)
1967
        {
1968
                avatar_remove_db($row[$mode . '_avatar']);
1969
        }
1970
        $filename = get_avatar_filename($row[$mode . '_avatar']);
1971
        if (file_exists($phpbb_root_path . $config['avatar_path'] . '/' . $filename))
1972
        {
1973
                @unlink($phpbb_root_path . $config['avatar_path'] . '/' . $filename);
1974
                return true;
1975
        }
1976
1977
        return false;
1978
}
1979
1980
/**
1981
* Remote avatar linkage
1982
*/
1983
function avatar_remote($data, &$error)
1984
{
1985
        global $config, $db, $user, $phpbb_root_path, $phpEx;
1986
1987
        if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
1988
        {
1989
                $data['remotelink'] = 'http://' . $data['remotelink'];
1990
        }
1991
        if (!preg_match('#^(http|https|ftp)://(?:(.*?\.)*?[a-z0-9\-]+?\.[a-z]{2,4}|(?:\d{1,3}\.){3,5}\d{1,3}):?([0-9]*?).*?\.(gif|jpg|jpeg|png)$#i', $data['remotelink']))
1992
        {
1993
                $error[] = $user->lang['AVATAR_URL_INVALID'];
1994
                return false;
1995
        }
1996
1997
        // Make sure getimagesize works...
1998
        if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
1999
        {
2000
                $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
2001
                return false;
2002
        }
2003
2004
        if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
2005
        {
2006
                $error[] = $user->lang['AVATAR_NO_SIZE'];
2007
                return false;
2008
        }
2009
2010
        $width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
2011
        $height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
2012
2013
        if ($width < 2 || $height < 2)
2014
        {
2015
                $error[] = $user->lang['AVATAR_NO_SIZE'];
2016
                return false;
2017
        }
2018
2019
        // Check image type
2020
        include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
2021
        $types = fileupload::image_types();
2022
        $extension = strtolower(filespec::get_extension($data['remotelink']));
2023
2024
        if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
2025
        {
2026
                if (!isset($types[$image_data[2]]))
2027
                {
2028
                        $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
2029
                }
2030
                else
2031
                {
2032
                        $error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
2033
                }
2034
                return false;
2035
        }
2036
2037
        if ($config['avatar_max_width'] || $config['avatar_max_height'])
2038
        {
2039
                if ($width > $config['avatar_max_width'] || $height > $config['avatar_max_height'])
2040
                {
2041
                        $error[] = phpbb_avatar_error_wrong_size($width, $height);
2042
                        return false;
2043
                }
2044
        }
2045
2046
        if ($config['avatar_min_width'] || $config['avatar_min_height'])
2047
        {
2048
                if ($width < $config['avatar_min_width'] || $height < $config['avatar_min_height'])
2049
                {
2050
                        $error[] = phpbb_avatar_error_wrong_size($width, $height);
2051
                        return false;
2052
                }
2053
        }
2054
2055
        return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
2056
}
2057
2058
/**
2059
* Avatar upload using the upload class
2060
*/
2061
function avatar_upload($data, &$error)
2062
{
2063
        global $phpbb_root_path, $config, $db, $user, $phpEx;
2064
2065
        // Init upload class
2066
        include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
2067
        $upload = new fileupload('AVATAR_', array('jpg', 'jpeg', 'gif', 'png'), $config['avatar_filesize'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], (isset($config['mime_triggers']) ? explode('|', $config['mime_triggers']) : false));
2068
2069
        if (!empty($_FILES['uploadfile']['name']))
2070
        {
2071
                $file = $upload->form_upload('uploadfile');
2072
        }
2073
        else
2074
        {
2075
                $file = $upload->remote_upload($data['uploadurl']);
2076
        }
2077
2078
        $prefix = $config['avatar_salt'] . '_';
2079
        $file->clean_filename('avatar', $prefix, $data['user_id']);
2080
2081
        $destination = $config['avatar_path'];
2082
2083
        // Adjust destination path (no trailing slash)
2084
        if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
2085
        {
2086
                $destination = substr($destination, 0, -1);
2087
        }
2088
2089
        $destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
2090
        if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
2091
        {
2092
                $destination = '';
2093
        }
2094
2095
        // Move file and overwrite any existing image
2096
        $file->move_file($destination, true);
2097
2098
        if (sizeof($file->error))
2099
        {
2100
                $file->remove();
2101
                $error = array_merge($error, $file->error);
2102
        }
2103
2104
        return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
2105
}
2106
2107
/**
2108
* Generates avatar filename from the database entry
2109
*/
2110
function get_avatar_filename($avatar_entry)
2111
{
2112
        global $config;
2113
2114
2115
        if ($avatar_entry[0] === 'g')
2116
        {
2117
                $avatar_group = true;
2118
                $avatar_entry = substr($avatar_entry, 1);
2119
        }
2120
        else
2121
        {
2122
                $avatar_group = false;
2123
        }
2124
        $ext                         = substr(strrchr($avatar_entry, '.'), 1);
2125
        $avatar_entry        = intval($avatar_entry);
2126
        return $config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
2127
}
2128
2129
/**
2130
* Avatar Gallery
2131
*/
2132
function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
2133
{
2134
        global $user, $cache, $template;
2135
        global $config, $phpbb_root_path;
2136
2137
        $avatar_list = array();
2138
2139
        $path = $phpbb_root_path . $config['avatar_gallery_path'];
2140
2141
        if (!file_exists($path) || !is_dir($path))
2142
        {
2143
                $avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
2144
        }
2145
        else
2146
        {
2147
                // Collect images
2148
                $dp = @opendir($path);
2149
2150
                if (!$dp)
2151
                {
2152
                        return array($user->lang['NO_AVATAR_CATEGORY'] => array());
2153
                }
2154
2155
                while (($file = readdir($dp)) !== false)
2156
                {
2157
                        if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
2158
                        {
2159
                                $avatar_row_count = $avatar_col_count = 0;
2160
2161
                                if ($dp2 = @opendir("$path/$file"))
2162
                                {
2163
                                        while (($sub_file = readdir($dp2)) !== false)
2164
                                        {
2165
                                                if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
2166
                                                {
2167
                                                        $avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
2168
                                                                'file'                => rawurlencode($file) . '/' . rawurlencode($sub_file),
2169
                                                                'filename'        => rawurlencode($sub_file),
2170
                                                                'name'                => ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
2171
                                                        );
2172
                                                        $avatar_col_count++;
2173
                                                        if ($avatar_col_count == $items_per_column)
2174
                                                        {
2175
                                                                $avatar_row_count++;
2176
                                                                $avatar_col_count = 0;
2177
                                                        }
2178
                                                }
2179
                                        }
2180
                                        closedir($dp2);
2181
                                }
2182
                        }
2183
                }
2184
                closedir($dp);
2185
        }
2186
2187
        if (!sizeof($avatar_list))
2188
        {
2189
                $avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
2190
        }
2191
2192
        @ksort($avatar_list);
2193
2194
        $category = (!$category) ? key($avatar_list) : $category;
2195
        $avatar_categories = array_keys($avatar_list);
2196
2197
        $s_category_options = '';
2198
        foreach ($avatar_categories as $cat)
2199
        {
2200
                $s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
2201
        }
2202
2203
        $template->assign_vars(array(
2204
                'S_AVATARS_ENABLED'                => true,
2205
                'S_IN_AVATAR_GALLERY'        => true,
2206
                'S_CAT_OPTIONS'                        => $s_category_options)
2207
        );
2208
2209
        $avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
2210
2211
        foreach ($avatar_list as $avatar_row_ary)
2212
        {
2213
                $template->assign_block_vars($block_var, array());
2214
2215
                foreach ($avatar_row_ary as $avatar_col_ary)
2216
                {
2217
                        $template->assign_block_vars($block_var . '.avatar_column', array(
2218
                                'AVATAR_IMAGE'        => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
2219
                                'AVATAR_NAME'        => $avatar_col_ary['name'],
2220
                                'AVATAR_FILE'        => $avatar_col_ary['filename'])
2221
                        );
2222
2223
                        $template->assign_block_vars($block_var . '.avatar_option_column', array(
2224
                                'AVATAR_IMAGE'        => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
2225
                                'S_OPTIONS_AVATAR'        => $avatar_col_ary['filename'])
2226
                        );
2227
                }
2228
        }
2229
2230
        return $avatar_list;
2231
}
2232
2233
2234
/**
2235
* Tries to (re-)establish avatar dimensions
2236
*/
2237
function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
2238
{
2239
        global $config, $phpbb_root_path, $user;
2240
2241
        switch ($avatar_type)
2242
        {
2243
                case AVATAR_REMOTE :
2244
                        break;
2245
2246
                case AVATAR_UPLOAD :
2247
                        $avatar = $phpbb_root_path . $config['avatar_path'] . '/' . get_avatar_filename($avatar);
2248
                        break;
2249
2250
                case AVATAR_GALLERY :
2251
                        $avatar = $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar ;
2252
                        break;
2253
        }
2254
2255
        // Make sure getimagesize works...
2256
        if (($image_data = @getimagesize($avatar)) === false)
2257
        {
2258
                $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
2259
                return false;
2260
        }
2261
2262
        if ($image_data[0] < 2 || $image_data[1] < 2)
2263
        {
2264
                $error[] = $user->lang['AVATAR_NO_SIZE'];
2265
                return false;
2266
        }
2267
2268
        // try to maintain ratio
2269
        if (!(empty($current_x) && empty($current_y)))
2270
        {
2271
                if ($current_x != 0)
2272
                {
2273
                        $image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
2274
                        $image_data[1] = min($config['avatar_max_height'], $image_data[1]);
2275
                        $image_data[1] = max($config['avatar_min_height'], $image_data[1]);
2276
                }
2277
                if ($current_y != 0)
2278
                {
2279
                        $image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
2280
                        $image_data[0] = min($config['avatar_max_width'], $image_data[1]);
2281
                        $image_data[0] = max($config['avatar_min_width'], $image_data[1]);
2282
                }
2283
        }
2284
        return array($image_data[0], $image_data[1]);
2285
}
2286
2287
/**
2288
* Uploading/Changing user avatar
2289
*/
2290
function avatar_process_user(&$error, $custom_userdata = false, $can_upload = null)
2291
{
2292
        global $config, $phpbb_root_path, $auth, $user, $db;
2293
2294
        $data = array(
2295
                'uploadurl'                => request_var('uploadurl', ''),
2296
                'remotelink'        => request_var('remotelink', ''),
2297
                'width'                        => request_var('width', 0),
2298
                'height'                => request_var('height', 0),
2299
        );
2300
2301
        $error = validate_data($data, array(
2302
                'uploadurl'                => array('string', true, 5, 255),
2303
                'remotelink'        => array('string', true, 5, 255),
2304
                'width'                        => array('string', true, 1, 3),
2305
                'height'                => array('string', true, 1, 3),
2306
        ));
2307
2308
        if (sizeof($error))
2309
        {
2310
                return false;
2311
        }
2312
2313
        $sql_ary = array();
2314
2315
        if ($custom_userdata === false)
2316
        {
2317
                $userdata = &$user->data;
2318
        }
2319
        else
2320
        {
2321
                $userdata = &$custom_userdata;
2322
        }
2323
2324
        $data['user_id'] = $userdata['user_id'];
2325
        $change_avatar = ($custom_userdata === false) ? $auth->acl_get('u_chgavatar') : true;
2326
        $avatar_select = basename(request_var('avatar_select', ''));
2327
2328
        // Can we upload?
2329
        if (is_null($can_upload))
2330
        {
2331
                $can_upload = ($config['allow_avatar_upload'] && file_exists($phpbb_root_path . $config['avatar_path']) && phpbb_is_writable($phpbb_root_path . $config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
2332
        }
2333
2334
        if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
2335
        {
2336
                list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
2337
        }
2338
        else if ($data['remotelink'] && $change_avatar && $config['allow_avatar_remote'])
2339
        {
2340
                list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
2341
        }
2342
        else if ($avatar_select && $change_avatar && $config['allow_avatar_local'])
2343
        {
2344
                $category = basename(request_var('category', ''));
2345
2346
                $sql_ary['user_avatar_type'] = AVATAR_GALLERY;
2347
                $sql_ary['user_avatar'] = $avatar_select;
2348
2349
                // check avatar gallery
2350
                if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category))
2351
                {
2352
                        $sql_ary['user_avatar'] = '';
2353
                        $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
2354
                }
2355
                else
2356
                {
2357
                        list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . urldecode($sql_ary['user_avatar']));
2358
                        $sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
2359
                }
2360
        }
2361
        else if (isset($_POST['delete']) && $change_avatar)
2362
        {
2363
                $sql_ary['user_avatar'] = '';
2364
                $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
2365
        }
2366
        else if (!empty($userdata['user_avatar']))
2367
        {
2368
                // Only update the dimensions
2369
2370
                if (empty($data['width']) || empty($data['height']))
2371
                {
2372
                        if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
2373
                        {
2374
                                list($guessed_x, $guessed_y) = $dims;
2375
                                if (empty($data['width']))
2376
                                {
2377
                                        $data['width'] = $guessed_x;
2378
                                }
2379
                                if (empty($data['height']))
2380
                                {
2381
                                        $data['height'] = $guessed_y;
2382
                                }
2383
                        }
2384
                }
2385
                if (($config['avatar_max_width'] || $config['avatar_max_height']) &&
2386
                        (($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
2387
                {
2388
                        if ($data['width'] > $config['avatar_max_width'] || $data['height'] > $config['avatar_max_height'])
2389
                        {
2390
                                $error[] = phpbb_avatar_error_wrong_size($data['width'], $data['height']);
2391
                        }
2392
                }
2393
2394
                if (!sizeof($error))
2395
                {
2396
                        if ($config['avatar_min_width'] || $config['avatar_min_height'])
2397
                        {
2398
                                if ($data['width'] < $config['avatar_min_width'] || $data['height'] < $config['avatar_min_height'])
2399
                                {
2400
                                        $error[] = phpbb_avatar_error_wrong_size($data['width'], $data['height']);
2401
                                }
2402
                        }
2403
                }
2404
2405
                if (!sizeof($error))
2406
                {
2407
                        $sql_ary['user_avatar_width'] = $data['width'];
2408
                        $sql_ary['user_avatar_height'] = $data['height'];
2409
                }
2410
        }
2411
2412
        if (!sizeof($error))
2413
        {
2414
                // Do we actually have any data to update?
2415
                if (sizeof($sql_ary))
2416
                {
2417
                        $ext_new = $ext_old = '';
2418
                        if (isset($sql_ary['user_avatar']))
2419
                        {
2420
                                $userdata = ($custom_userdata === false) ? $user->data : $custom_userdata;
2421
                                $ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
2422
                                $ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
2423
2424
                                if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
2425
                                {
2426
                                        // Delete old avatar if present
2427
                                        if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))
2428
                                           || ( !empty($userdata['user_avatar']) && !empty($sql_ary['user_avatar']) && $ext_new !== $ext_old))
2429
                                        {
2430
                                                avatar_delete('user', $userdata);
2431
                                        }
2432
                                }
2433
                        }
2434
2435
                        $sql = 'UPDATE ' . USERS_TABLE . '
2436
                                SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
2437
                                WHERE user_id = ' . (($custom_userdata === false) ? $user->data['user_id'] : $custom_userdata['user_id']);
2438
                        $db->sql_query($sql);
2439
2440
                }
2441
        }
2442
2443
        return (sizeof($error)) ? false : true;
2444
}
2445
2446
/**
2447
* Returns a language string with the avatar size of the new avatar and the allowed maximum and minimum
2448
*
2449
* @param $width                int                The width of the new uploaded/selected avatar
2450
* @param $height        int                The height of the new uploaded/selected avatar
2451
* @return string
2452
*/
2453
function phpbb_avatar_error_wrong_size($width, $height)
2454
{
2455
        global $config, $user;
2456
2457
        return $user->lang('AVATAR_WRONG_SIZE',
2458
                $user->lang('PIXELS', (int) $config['avatar_min_width']),
2459
                $user->lang('PIXELS', (int) $config['avatar_min_height']),
2460
                $user->lang('PIXELS', (int) $config['avatar_max_width']),
2461
                $user->lang('PIXELS', (int) $config['avatar_max_height']),
2462
                $user->lang('PIXELS', (int) $width),
2463
                $user->lang('PIXELS', (int) $height));
2464
}
2465
2466
/**
2467
* Returns an explanation string with maximum avatar settings
2468
*
2469
* @return string
2470
*/
2471
function phpbb_avatar_explanation_string()
2472
{
2473
        global $config, $user;
2474
2475
        return $user->lang('AVATAR_EXPLAIN',
2476
                $user->lang('PIXELS', (int) $config['avatar_max_width']),
2477
                $user->lang('PIXELS', (int) $config['avatar_max_height']),
2478
                round($config['avatar_filesize'] / 1024));
2479
}
2480
2481
//
2482
// Usergroup functions
2483
//
2484
2485
/**
2486
* Add or edit a group. If we're editing a group we only update user
2487
* parameters such as rank, etc. if they are changed
2488
*/
2489
function group_create(&$group_id, $type, $name, $desc, $group_attributes, $allow_desc_bbcode = false, $allow_desc_urls = false, $allow_desc_smilies = false)
2490
{
2491
        global $phpbb_root_path, $config, $db, $user, $file_upload;
2492
2493
        $error = array();
2494
2495
        // Attributes which also affect the users table
2496
        $user_attribute_ary = array('group_colour', 'group_rank', 'group_avatar', 'group_avatar_type', 'group_avatar_width', 'group_avatar_height');
2497
2498
        // Check data. Limit group name length.
2499
        if (!utf8_strlen($name) || utf8_strlen($name) > 60)
2500
        {
2501
                $error[] = (!utf8_strlen($name)) ? $user->lang['GROUP_ERR_USERNAME'] : $user->lang['GROUP_ERR_USER_LONG'];
2502
        }
2503
2504
        $err = group_validate_groupname($group_id, $name);
2505
        if (!empty($err))
2506
        {
2507
                $error[] = $user->lang[$err];
2508
        }
2509
2510
        if (!in_array($type, array(GROUP_OPEN, GROUP_CLOSED, GROUP_HIDDEN, GROUP_SPECIAL, GROUP_FREE)))
2511
        {
2512
                $error[] = $user->lang['GROUP_ERR_TYPE'];
2513
        }
2514
2515
        if (!sizeof($error))
2516
        {
2517
                $current_legend = phpbb_group_positions::GROUP_DISABLED;
2518
                $current_teampage = phpbb_group_positions::GROUP_DISABLED;
2519
2520
                $legend = new phpbb_group_positions($db, 'legend');
2521
                $teampage = new phpbb_group_positions($db, 'teampage');
2522
                if ($group_id)
2523
                {
2524
                        $current_legend = $legend->get_group_value($group_id);
2525
                        $current_teampage = $teampage->get_group_value($group_id);
2526
                }
2527
2528
                if (!empty($group_attributes['group_legend']))
2529
                {
2530
                        if (($group_id && ($current_legend == phpbb_group_positions::GROUP_DISABLED)) || !$group_id)
2531
                        {
2532
                                // Old group currently not in the legend or new group, add at the end.
2533
                                $group_attributes['group_legend'] = 1 + $legend->get_group_count();
2534
                        }
2535
                        else
2536
                        {
2537
                                // Group stayes in the legend
2538
                                $group_attributes['group_legend'] = $current_legend;
2539
                        }
2540
                }
2541
                else if ($group_id && ($current_legend > phpbb_group_positions::GROUP_DISABLED))
2542
                {
2543
                        // Group is removed from the legend
2544
                        $legend->delete_group($group_id, true);
2545
                        $group_attributes['group_legend'] = phpbb_group_positions::GROUP_DISABLED;
2546
                }
2547
                else
2548
                {
2549
                        $group_attributes['group_legend'] = phpbb_group_positions::GROUP_DISABLED;
2550
                }
2551
2552
                if (!empty($group_attributes['group_teampage']))
2553
                {
2554
                        if (($group_id && ($current_teampage == phpbb_group_positions::GROUP_DISABLED)) || !$group_id)
2555
                        {
2556
                                // Old group currently not on the teampage or new group, add at the end.
2557
                                $group_attributes['group_teampage'] = 1 + $teampage->get_group_count();
2558
                        }
2559
                        else
2560
                        {
2561
                                // Group stayes on the teampage
2562
                                $group_attributes['group_teampage'] = $current_teampage;
2563
                        }
2564
                }
2565
                else if ($group_id && ($current_teampage > phpbb_group_positions::GROUP_DISABLED))
2566
                {
2567
                        // Group is removed from the teampage
2568
                        $teampage->delete_group($group_id, true);
2569
                        $group_attributes['group_teampage'] = phpbb_group_positions::GROUP_DISABLED;
2570
                }
2571
                else
2572
                {
2573
                        $group_attributes['group_teampage'] = phpbb_group_positions::GROUP_DISABLED;
2574
                }
2575
2576
                // Unset the objects, we don't need them anymore.
2577
                unset($legend);
2578
                unset($teampage);
2579
2580
                $user_ary = array();
2581
                $sql_ary = array(
2582
                        'group_name'                        => (string) $name,
2583
                        'group_desc'                        => (string) $desc,
2584
                        'group_desc_uid'                => '',
2585
                        'group_desc_bitfield'        => '',
2586
                        'group_type'                        => (int) $type,
2587
                );
2588
2589
                // Parse description
2590
                if ($desc)
2591
                {
2592
                        generate_text_for_storage($sql_ary['group_desc'], $sql_ary['group_desc_uid'], $sql_ary['group_desc_bitfield'], $sql_ary['group_desc_options'], $allow_desc_bbcode, $allow_desc_urls, $allow_desc_smilies);
2593
                }
2594
2595
                if (sizeof($group_attributes))
2596
                {
2597
                        // Merge them with $sql_ary to properly update the group
2598
                        $sql_ary = array_merge($sql_ary, $group_attributes);
2599
                }
2600
2601
                // Setting the log message before we set the group id (if group gets added)
2602
                $log = ($group_id) ? 'LOG_GROUP_UPDATED' : 'LOG_GROUP_CREATED';
2603
2604
                $query = '';
2605
2606
                if ($group_id)
2607
                {
2608
                        $sql = 'SELECT user_id
2609
                                FROM ' . USERS_TABLE . '
2610
                                WHERE group_id = ' . $group_id;
2611
                        $result = $db->sql_query($sql);
2612
2613
                        while ($row = $db->sql_fetchrow($result))
2614
                        {
2615
                                $user_ary[] = $row['user_id'];
2616
                        }
2617
                        $db->sql_freeresult($result);
2618
2619
                        if (isset($sql_ary['group_avatar']) && !$sql_ary['group_avatar'])
2620
                        {
2621
                                remove_default_avatar($group_id, $user_ary);
2622
                        }
2623
2624
                        if (isset($sql_ary['group_rank']) && !$sql_ary['group_rank'])
2625
                        {
2626
                                remove_default_rank($group_id, $user_ary);
2627
                        }
2628
2629
                        $sql = 'UPDATE ' . GROUPS_TABLE . '
2630
                                SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
2631
                                WHERE group_id = $group_id";
2632
                        $db->sql_query($sql);
2633
2634
                        // Since we may update the name too, we need to do this on other tables too...
2635
                        $sql = 'UPDATE ' . MODERATOR_CACHE_TABLE . "
2636
                                SET group_name = '" . $db->sql_escape($sql_ary['group_name']) . "'
2637
                                WHERE group_id = $group_id";
2638
                        $db->sql_query($sql);
2639
2640
                        // One special case is the group skip auth setting. If this was changed we need to purge permissions for this group
2641
                        if (isset($group_attributes['group_skip_auth']))
2642
                        {
2643
                                // Get users within this group...
2644
                                $sql = 'SELECT user_id
2645
                                        FROM ' . USER_GROUP_TABLE . '
2646
                                        WHERE group_id = ' . $group_id . '
2647
                                                AND user_pending = 0';
2648
                                $result = $db->sql_query($sql);
2649
2650
                                $user_id_ary = array();
2651
                                while ($row = $db->sql_fetchrow($result))
2652
                                {
2653
                                        $user_id_ary[] = $row['user_id'];
2654
                                }
2655
                                $db->sql_freeresult($result);
2656
2657
                                if (!empty($user_id_ary))
2658
                                {
2659
                                        global $auth;
2660
2661
                                        // Clear permissions cache of relevant users
2662
                                        $auth->acl_clear_prefetch($user_id_ary);
2663
                                }
2664
                        }
2665
                }
2666
                else
2667
                {
2668
                        $sql = 'INSERT INTO ' . GROUPS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
2669
                        $db->sql_query($sql);
2670
                }
2671
2672
                if (!$group_id)
2673
                {
2674
                        $group_id = $db->sql_nextid();
2675
2676
                        if (isset($sql_ary['group_avatar_type']) && $sql_ary['group_avatar_type'] == AVATAR_UPLOAD)
2677
                        {
2678
                                group_correct_avatar($group_id, $sql_ary['group_avatar']);
2679
                        }
2680
                }
2681
2682
                // Set user attributes
2683
                $sql_ary = array();
2684
                if (sizeof($group_attributes))
2685
                {
2686
                        // Go through the user attributes array, check if a group attribute matches it and then set it. ;)
2687
                        foreach ($user_attribute_ary as $attribute)
2688
                        {
2689
                                if (!isset($group_attributes[$attribute]))
2690
                                {
2691
                                        continue;
2692
                                }
2693
2694
                                // If we are about to set an avatar, we will not overwrite user avatars if no group avatar is set...
2695
                                if (strpos($attribute, 'group_avatar') === 0 && !$group_attributes[$attribute])
2696
                                {
2697
                                        continue;
2698
                                }
2699
2700
                                $sql_ary[$attribute] = $group_attributes[$attribute];
2701
                        }
2702
                }
2703
2704
                if (sizeof($sql_ary) && sizeof($user_ary))
2705
                {
2706
                        group_set_user_default($group_id, $user_ary, $sql_ary);
2707
                }
2708
2709
                $name = ($type == GROUP_SPECIAL) ? $user->lang['G_' . $name] : $name;
2710
                add_log('admin', $log, $name);
2711
2712
                group_update_listings($group_id);
2713
        }
2714
2715
        return (sizeof($error)) ? $error : false;
2716
}
2717
2718
2719
/**
2720
* Changes a group avatar's filename to conform to the naming scheme
2721
*/
2722
function group_correct_avatar($group_id, $old_entry)
2723
{
2724
        global $config, $db, $phpbb_root_path;
2725
2726
        $group_id                = (int)$group_id;
2727
        $ext                         = substr(strrchr($old_entry, '.'), 1);
2728
        $old_filename         = get_avatar_filename($old_entry);
2729
        $new_filename         = $config['avatar_salt'] . "_g$group_id.$ext";
2730
        $new_entry                 = 'g' . $group_id . '_' . substr(time(), -5) . ".$ext";
2731
2732
        $avatar_path = $phpbb_root_path . $config['avatar_path'];
2733
        if (@rename($avatar_path . '/'. $old_filename, $avatar_path . '/' . $new_filename))
2734
        {
2735
                $sql = 'UPDATE ' . GROUPS_TABLE . '
2736
                        SET group_avatar = \'' . $db->sql_escape($new_entry) . "'
2737
                        WHERE group_id = $group_id";
2738
                $db->sql_query($sql);
2739
        }
2740
}
2741
2742
2743
/**
2744
* Remove avatar also for users not having the group as default
2745
*/
2746
function avatar_remove_db($avatar_name)
2747
{
2748
        global $config, $db;
2749
2750
        $sql = 'UPDATE ' . USERS_TABLE . "
2751
                SET user_avatar = '',
2752
                user_avatar_type = 0
2753
                WHERE user_avatar = '" . $db->sql_escape($avatar_name) . '\'';
2754
        $db->sql_query($sql);
2755
}
2756
2757
2758
/**
2759
* Group Delete
2760
*/
2761
function group_delete($group_id, $group_name = false)
2762
{
2763
        global $db, $phpbb_root_path, $phpEx;
2764
2765
        if (!$group_name)
2766
        {
2767
                $group_name = get_group_name($group_id);
2768
        }
2769
2770
        $start = 0;
2771
2772
        do
2773
        {
2774
                $user_id_ary = $username_ary = array();
2775
2776
                // Batch query for group members, call group_user_del
2777
                $sql = 'SELECT u.user_id, u.username
2778
                        FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . " u
2779
                        WHERE ug.group_id = $group_id
2780
                                AND u.user_id = ug.user_id";
2781
                $result = $db->sql_query_limit($sql, 200, $start);
2782
2783
                if ($row = $db->sql_fetchrow($result))
2784
                {
2785
                        do
2786
                        {
2787
                                $user_id_ary[] = $row['user_id'];
2788
                                $username_ary[] = $row['username'];
2789
2790
                                $start++;
2791
                        }
2792
                        while ($row = $db->sql_fetchrow($result));
2793
2794
                        group_user_del($group_id, $user_id_ary, $username_ary, $group_name);
2795
                }
2796
                else
2797
                {
2798
                        $start = 0;
2799
                }
2800
                $db->sql_freeresult($result);
2801
        }
2802
        while ($start);
2803
2804
        // Delete group from legend and teampage
2805
        $legend = new phpbb_group_positions($db, 'legend');
2806
        $legend->delete_group($group_id);
2807
        unset($legend);
2808
        $teampage = new phpbb_group_positions($db, 'teampage');
2809
        $teampage->delete_group($group_id);
2810
        unset($teampage);
2811
2812
        // Delete group
2813
        $sql = 'DELETE FROM ' . GROUPS_TABLE . "
2814
                WHERE group_id = $group_id";
2815
        $db->sql_query($sql);
2816
2817
        // Delete auth entries from the groups table
2818
        $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . "
2819
                WHERE group_id = $group_id";
2820
        $db->sql_query($sql);
2821
2822
        // Re-cache moderators
2823
        if (!function_exists('cache_moderators'))
2824
        {
2825
                include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
2826
        }
2827
2828
        cache_moderators();
2829
2830
        add_log('admin', 'LOG_GROUP_DELETE', $group_name);
2831
2832
        // Return false - no error
2833
        return false;
2834
}
2835
2836
/**
2837
* Add user(s) to group
2838
*
2839
* @return mixed false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
2840
*/
2841
function group_user_add($group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $default = false, $leader = 0, $pending = 0, $group_attributes = false)
2842
{
2843
        global $db, $auth;
2844
2845
        // We need both username and user_id info
2846
        $result = user_get_id_name($user_id_ary, $username_ary);
2847
2848
        if (!sizeof($user_id_ary) || $result !== false)
2849
        {
2850
                return 'NO_USER';
2851
        }
2852
2853
        // Remove users who are already members of this group
2854
        $sql = 'SELECT user_id, group_leader
2855
                FROM ' . USER_GROUP_TABLE . '
2856
                WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . "
2857
                        AND group_id = $group_id";
2858
        $result = $db->sql_query($sql);
2859
2860
        $add_id_ary = $update_id_ary = array();
2861
        while ($row = $db->sql_fetchrow($result))
2862
        {
2863
                $add_id_ary[] = (int) $row['user_id'];
2864
2865
                if ($leader && !$row['group_leader'])
2866
                {
2867
                        $update_id_ary[] = (int) $row['user_id'];
2868
                }
2869
        }
2870
        $db->sql_freeresult($result);
2871
2872
        // Do all the users exist in this group?
2873
        $add_id_ary = array_diff($user_id_ary, $add_id_ary);
2874
2875
        // If we have no users
2876
        if (!sizeof($add_id_ary) && !sizeof($update_id_ary))
2877
        {
2878
                return 'GROUP_USERS_EXIST';
2879
        }
2880
2881
        $db->sql_transaction('begin');
2882
2883
        // Insert the new users
2884
        if (sizeof($add_id_ary))
2885
        {
2886
                $sql_ary = array();
2887
2888
                foreach ($add_id_ary as $user_id)
2889
                {
2890
                        $sql_ary[] = array(
2891
                                'user_id'                => (int) $user_id,
2892
                                'group_id'                => (int) $group_id,
2893
                                'group_leader'        => (int) $leader,
2894
                                'user_pending'        => (int) $pending,
2895
                        );
2896
                }
2897
2898
                $db->sql_multi_insert(USER_GROUP_TABLE, $sql_ary);
2899
        }
2900
2901
        if (sizeof($update_id_ary))
2902
        {
2903
                $sql = 'UPDATE ' . USER_GROUP_TABLE . '
2904
                        SET group_leader = 1
2905
                        WHERE ' . $db->sql_in_set('user_id', $update_id_ary) . "
2906
                                AND group_id = $group_id";
2907
                $db->sql_query($sql);
2908
        }
2909
2910
        if ($default)
2911
        {
2912
                group_user_attributes('default', $group_id, $user_id_ary, false, $group_name, $group_attributes);
2913
        }
2914
2915
        $db->sql_transaction('commit');
2916
2917
        // Clear permissions cache of relevant users
2918
        $auth->acl_clear_prefetch($user_id_ary);
2919
2920
        if (!$group_name)
2921
        {
2922
                $group_name = get_group_name($group_id);
2923
        }
2924
2925
        $log = ($leader) ? 'LOG_MODS_ADDED' : (($pending) ? 'LOG_USERS_PENDING' : 'LOG_USERS_ADDED');
2926
2927
        add_log('admin', $log, $group_name, implode(', ', $username_ary));
2928
2929
        group_update_listings($group_id);
2930
2931
        // Return false - no error
2932
        return false;
2933
}
2934
2935
/**
2936
* Remove a user/s from a given group. When we remove users we update their
2937
* default group_id. We do this by examining which "special" groups they belong
2938
* to. The selection is made based on a reasonable priority system
2939
*
2940
* @return false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
2941
*/
2942
function group_user_del($group_id, $user_id_ary = false, $username_ary = false, $group_name = false)
2943
{
2944
        global $db, $auth, $config;
2945
2946
        if ($config['coppa_enable'])
2947
        {
2948
                $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED_COPPA', 'REGISTERED', 'BOTS', 'GUESTS');
2949
        }
2950
        else
2951
        {
2952
                $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED', 'BOTS', 'GUESTS');
2953
        }
2954
2955
        // We need both username and user_id info
2956
        $result = user_get_id_name($user_id_ary, $username_ary);
2957
2958
        if (!sizeof($user_id_ary) || $result !== false)
2959
        {
2960
                return 'NO_USER';
2961
        }
2962
2963
        $sql = 'SELECT *
2964
                FROM ' . GROUPS_TABLE . '
2965
                WHERE ' . $db->sql_in_set('group_name', $group_order);
2966
        $result = $db->sql_query($sql);
2967
2968
        $group_order_id = $special_group_data = array();
2969
        while ($row = $db->sql_fetchrow($result))
2970
        {
2971
                $group_order_id[$row['group_name']] = $row['group_id'];
2972
2973
                $special_group_data[$row['group_id']] = array(
2974
                        'group_colour'                        => $row['group_colour'],
2975
                        'group_rank'                                => $row['group_rank'],
2976
                );
2977
2978
                // Only set the group avatar if one is defined...
2979
                if ($row['group_avatar'])
2980
                {
2981
                        $special_group_data[$row['group_id']] = array_merge($special_group_data[$row['group_id']], array(
2982
                                'group_avatar'                        => $row['group_avatar'],
2983
                                'group_avatar_type'                => $row['group_avatar_type'],
2984
                                'group_avatar_width'                => $row['group_avatar_width'],
2985
                                'group_avatar_height'        => $row['group_avatar_height'])
2986
                        );
2987
                }
2988
        }
2989
        $db->sql_freeresult($result);
2990
2991
        // Get users default groups - we only need to reset default group membership if the group from which the user gets removed is set as default
2992
        $sql = 'SELECT user_id, group_id
2993
                FROM ' . USERS_TABLE . '
2994
                WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
2995
        $result = $db->sql_query($sql);
2996
2997
        $default_groups = array();
2998
        while ($row = $db->sql_fetchrow($result))
2999
        {
3000
                $default_groups[$row['user_id']] = $row['group_id'];
3001
        }
3002
        $db->sql_freeresult($result);
3003
3004
        // What special group memberships exist for these users?
3005
        $sql = 'SELECT g.group_id, g.group_name, ug.user_id
3006
                FROM ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g
3007
                WHERE ' . $db->sql_in_set('ug.user_id', $user_id_ary) . "
3008
                        AND g.group_id = ug.group_id
3009
                        AND g.group_id <> $group_id
3010
                        AND g.group_type = " . GROUP_SPECIAL . '
3011
                ORDER BY ug.user_id, g.group_id';
3012
        $result = $db->sql_query($sql);
3013
3014
        $temp_ary = array();
3015
        while ($row = $db->sql_fetchrow($result))
3016
        {
3017
                if ($default_groups[$row['user_id']] == $group_id && (!isset($temp_ary[$row['user_id']]) || $group_order_id[$row['group_name']] < $temp_ary[$row['user_id']]))
3018
                {
3019
                        $temp_ary[$row['user_id']] = $row['group_id'];
3020
                }
3021
        }
3022
        $db->sql_freeresult($result);
3023
3024
        // sql_where_ary holds the new default groups and their users
3025
        $sql_where_ary = array();
3026
        foreach ($temp_ary as $uid => $gid)
3027
        {
3028
                $sql_where_ary[$gid][] = $uid;
3029
        }
3030
        unset($temp_ary);
3031
3032
        foreach ($special_group_data as $gid => $default_data_ary)
3033
        {
3034
                if (isset($sql_where_ary[$gid]) && sizeof($sql_where_ary[$gid]))
3035
                {
3036
                        remove_default_rank($group_id, $sql_where_ary[$gid]);
3037
                        remove_default_avatar($group_id, $sql_where_ary[$gid]);
3038
                        group_set_user_default($gid, $sql_where_ary[$gid], $default_data_ary);
3039
                }
3040
        }
3041
        unset($special_group_data);
3042
3043
        $sql = 'DELETE FROM ' . USER_GROUP_TABLE . "
3044
                WHERE group_id = $group_id
3045
                        AND " . $db->sql_in_set('user_id', $user_id_ary);
3046
        $db->sql_query($sql);
3047
3048
        // Clear permissions cache of relevant users
3049
        $auth->acl_clear_prefetch($user_id_ary);
3050
3051
        if (!$group_name)
3052
        {
3053
                $group_name = get_group_name($group_id);
3054
        }
3055
3056
        $log = 'LOG_GROUP_REMOVE';
3057
3058
        if ($group_name)
3059
        {
3060
                add_log('admin', $log, $group_name, implode(', ', $username_ary));
3061
        }
3062
3063
        group_update_listings($group_id);
3064
3065
        // Return false - no error
3066
        return false;
3067
}
3068
3069
3070
/**
3071
* Removes the group avatar of the default group from the users in user_ids who have that group as default.
3072
*/
3073
function remove_default_avatar($group_id, $user_ids)
3074
{
3075
        global $db;
3076
3077
        if (!is_array($user_ids))
3078
        {
3079
                $user_ids = array($user_ids);
3080
        }
3081
        if (empty($user_ids))
3082
        {
3083
                return false;
3084
        }
3085
3086
        $user_ids = array_map('intval', $user_ids);
3087
3088
        $sql = 'SELECT *
3089
                FROM ' . GROUPS_TABLE . '
3090
                WHERE group_id = ' . (int)$group_id;
3091
        $result = $db->sql_query($sql);
3092
        if (!$row = $db->sql_fetchrow($result))
3093
        {
3094
                $db->sql_freeresult($result);
3095
                return false;
3096
        }
3097
        $db->sql_freeresult($result);
3098
3099
        $sql = 'UPDATE ' . USERS_TABLE . "
3100
                SET user_avatar = '',
3101
                        user_avatar_type = 0,
3102
                        user_avatar_width = 0,
3103
                        user_avatar_height = 0
3104
                WHERE group_id = " . (int) $group_id . "
3105
                AND user_avatar = '" . $db->sql_escape($row['group_avatar']) . "'
3106
                AND " . $db->sql_in_set('user_id', $user_ids);
3107
3108
        $db->sql_query($sql);
3109
}
3110
3111
/**
3112
* Removes the group rank of the default group from the users in user_ids who have that group as default.
3113
*/
3114
function remove_default_rank($group_id, $user_ids)
3115
{
3116
        global $db;
3117
3118
        if (!is_array($user_ids))
3119
        {
3120
                $user_ids = array($user_ids);
3121
        }
3122
        if (empty($user_ids))
3123
        {
3124
                return false;
3125
        }
3126
3127
        $user_ids = array_map('intval', $user_ids);
3128
3129
        $sql = 'SELECT *
3130
                FROM ' . GROUPS_TABLE . '
3131
                WHERE group_id = ' . (int)$group_id;
3132
        $result = $db->sql_query($sql);
3133
        if (!$row = $db->sql_fetchrow($result))
3134
        {
3135
                $db->sql_freeresult($result);
3136
                return false;
3137
        }
3138
        $db->sql_freeresult($result);
3139
3140
        $sql = 'UPDATE ' . USERS_TABLE . '
3141
                SET user_rank = 0
3142
                WHERE group_id = ' . (int)$group_id . '
3143
                AND user_rank <> 0
3144
                AND user_rank = ' . (int)$row['group_rank'] . '
3145
                AND ' . $db->sql_in_set('user_id', $user_ids);
3146
        $db->sql_query($sql);
3147
}
3148
3149
/**
3150
* This is used to promote (to leader), demote or set as default a member/s
3151
*/
3152
function group_user_attributes($action, $group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $group_attributes = false)
3153
{
3154
        global $db, $auth, $phpbb_root_path, $phpEx, $config;
3155
3156
        // We need both username and user_id info
3157
        $result = user_get_id_name($user_id_ary, $username_ary);
3158
3159
        if (!sizeof($user_id_ary) || $result !== false)
3160
        {
3161
                return 'NO_USERS';
3162
        }
3163
3164
        if (!$group_name)
3165
        {
3166
                $group_name = get_group_name($group_id);
3167
        }
3168
3169
        switch ($action)
3170
        {
3171
                case 'demote':
3172
                case 'promote':
3173
3174
                        $sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . "
3175
                                WHERE group_id = $group_id
3176
                                        AND user_pending = 1
3177
                                        AND " . $db->sql_in_set('user_id', $user_id_ary);
3178
                        $result = $db->sql_query_limit($sql, 1);
3179
                        $not_empty = ($db->sql_fetchrow($result));
3180
                        $db->sql_freeresult($result);
3181
                        if ($not_empty)
3182
                        {
3183
                                return 'NO_VALID_USERS';
3184
                        }
3185
3186
                        $sql = 'UPDATE ' . USER_GROUP_TABLE . '
3187
                                SET group_leader = ' . (($action == 'promote') ? 1 : 0) . "
3188
                                WHERE group_id = $group_id
3189
                                        AND user_pending = 0
3190
                                        AND " . $db->sql_in_set('user_id', $user_id_ary);
3191
                        $db->sql_query($sql);
3192
3193
                        $log = ($action == 'promote') ? 'LOG_GROUP_PROMOTED' : 'LOG_GROUP_DEMOTED';
3194
                break;
3195
3196
                case 'approve':
3197
                        // Make sure we only approve those which are pending ;)
3198
                        $sql = 'SELECT u.user_id, u.user_email, u.username, u.username_clean, u.user_notify_type, u.user_jabber, u.user_lang
3199
                                FROM ' . USERS_TABLE . ' u, ' . USER_GROUP_TABLE . ' ug
3200
                                WHERE ug.group_id = ' . $group_id . '
3201
                                        AND ug.user_pending = 1
3202
                                        AND ug.user_id = u.user_id
3203
                                        AND ' . $db->sql_in_set('ug.user_id', $user_id_ary);
3204
                        $result = $db->sql_query($sql);
3205
3206
                        $user_id_ary = $email_users = array();
3207
                        while ($row = $db->sql_fetchrow($result))
3208
                        {
3209
                                $user_id_ary[] = $row['user_id'];
3210
                                $email_users[] = $row;
3211
                        }
3212
                        $db->sql_freeresult($result);
3213
3214
                        if (!sizeof($user_id_ary))
3215
                        {
3216
                                return false;
3217
                        }
3218
3219
                        $sql = 'UPDATE ' . USER_GROUP_TABLE . "
3220
                                SET user_pending = 0
3221
                                WHERE group_id = $group_id
3222
                                        AND " . $db->sql_in_set('user_id', $user_id_ary);
3223
                        $db->sql_query($sql);
3224
3225
                        // Send approved email to users...
3226
                        include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
3227
                        $messenger = new messenger();
3228
3229
                        foreach ($email_users as $row)
3230
                        {
3231
                                $messenger->template('group_approved', $row['user_lang']);
3232
3233
                                $messenger->to($row['user_email'], $row['username']);
3234
                                $messenger->im($row['user_jabber'], $row['username']);
3235
3236
                                $messenger->assign_vars(array(
3237
                                        'USERNAME'                => htmlspecialchars_decode($row['username']),
3238
                                        'GROUP_NAME'        => htmlspecialchars_decode($group_name),
3239
                                        'U_GROUP'                => generate_board_url() . "/ucp.$phpEx?i=groups&mode=membership")
3240
                                );
3241
3242
                                $messenger->send($row['user_notify_type']);
3243
                        }
3244
3245
                        $messenger->save_queue();
3246
3247
                        $log = 'LOG_USERS_APPROVED';
3248
                break;
3249
3250
                case 'default':
3251
                        // We only set default group for approved members of the group
3252
                        $sql = 'SELECT user_id
3253
                                FROM ' . USER_GROUP_TABLE . "
3254
                                WHERE group_id = $group_id
3255
                                        AND user_pending = 0
3256
                                        AND " . $db->sql_in_set('user_id', $user_id_ary);
3257
                        $result = $db->sql_query($sql);
3258
3259
                        $user_id_ary = $username_ary = array();
3260
                        while ($row = $db->sql_fetchrow($result))
3261
                        {
3262
                                $user_id_ary[] = $row['user_id'];
3263
                        }
3264
                        $db->sql_freeresult($result);
3265
3266
                        $result = user_get_id_name($user_id_ary, $username_ary);
3267
                        if (!sizeof($user_id_ary) || $result !== false)
3268
                        {
3269
                                return 'NO_USERS';
3270
                        }
3271
3272
                        $sql = 'SELECT user_id, group_id FROM ' . USERS_TABLE . '
3273
                                WHERE ' . $db->sql_in_set('user_id', $user_id_ary, false, true);
3274
                        $result = $db->sql_query($sql);
3275
3276
                        $groups = array();
3277
                        while ($row = $db->sql_fetchrow($result))
3278
                        {
3279
                                if (!isset($groups[$row['group_id']]))
3280
                                {
3281
                                        $groups[$row['group_id']] = array();
3282
                                }
3283
                                $groups[$row['group_id']][] = $row['user_id'];
3284
                        }
3285
                        $db->sql_freeresult($result);
3286
3287
                        foreach ($groups as $gid => $uids)
3288
                        {
3289
                                remove_default_rank($gid, $uids);
3290
                                remove_default_avatar($gid, $uids);
3291
                        }
3292
                        group_set_user_default($group_id, $user_id_ary, $group_attributes);
3293
                        $log = 'LOG_GROUP_DEFAULTS';
3294
                break;
3295
        }
3296
3297
        // Clear permissions cache of relevant users
3298
        $auth->acl_clear_prefetch($user_id_ary);
3299
3300
        add_log('admin', $log, $group_name, implode(', ', $username_ary));
3301
3302
        group_update_listings($group_id);
3303
3304
        return false;
3305
}
3306
3307
/**
3308
* A small version of validate_username to check for a group name's existence. To be called directly.
3309
*/
3310
function group_validate_groupname($group_id, $group_name)
3311
{
3312
        global $config, $db;
3313
3314
        $group_name =  utf8_clean_string($group_name);
3315
3316
        if (!empty($group_id))
3317
        {
3318
                $sql = 'SELECT group_name
3319
                        FROM ' . GROUPS_TABLE . '
3320
                        WHERE group_id = ' . (int) $group_id;
3321
                $result = $db->sql_query($sql);
3322
                $row = $db->sql_fetchrow($result);
3323
                $db->sql_freeresult($result);
3324
3325
                if (!$row)
3326
                {
3327
                        return false;
3328
                }
3329
3330
                $allowed_groupname = utf8_clean_string($row['group_name']);
3331
3332
                if ($allowed_groupname == $group_name)
3333
                {
3334
                        return false;
3335
                }
3336
        }
3337
3338
        $sql = 'SELECT group_name
3339
                FROM ' . GROUPS_TABLE . "
3340
                WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($group_name)) . "'";
3341
        $result = $db->sql_query($sql);
3342
        $row = $db->sql_fetchrow($result);
3343
        $db->sql_freeresult($result);
3344
3345
        if ($row)
3346
        {
3347
                return 'GROUP_NAME_TAKEN';
3348
        }
3349
3350
        return false;
3351
}
3352
3353
/**
3354
* Set users default group
3355
*
3356
* @access private
3357
*/
3358
function group_set_user_default($group_id, $user_id_ary, $group_attributes = false, $update_listing = false)
3359
{
3360
        global $cache, $db;
3361
3362
        if (empty($user_id_ary))
3363
        {
3364
                return;
3365
        }
3366
3367
        $attribute_ary = array(
3368
                'group_colour'                        => 'string',
3369
                'group_rank'                        => 'int',
3370
                'group_avatar'                        => 'string',
3371
                'group_avatar_type'                => 'int',
3372
                'group_avatar_width'        => 'int',
3373
                'group_avatar_height'        => 'int',
3374
        );
3375
3376
        $sql_ary = array(
3377
                'group_id'                => $group_id
3378
        );
3379
3380
        // Were group attributes passed to the function? If not we need to obtain them
3381
        if ($group_attributes === false)
3382
        {
3383
                $sql = 'SELECT ' . implode(', ', array_keys($attribute_ary)) . '
3384
                        FROM ' . GROUPS_TABLE . "
3385
                        WHERE group_id = $group_id";
3386
                $result = $db->sql_query($sql);
3387
                $group_attributes = $db->sql_fetchrow($result);
3388
                $db->sql_freeresult($result);
3389
        }
3390
3391
        foreach ($attribute_ary as $attribute => $type)
3392
        {
3393
                if (isset($group_attributes[$attribute]))
3394
                {
3395
                        // If we are about to set an avatar or rank, we will not overwrite with empty, unless we are not actually changing the default group
3396
                        if ((strpos($attribute, 'group_avatar') === 0 || strpos($attribute, 'group_rank') === 0) && !$group_attributes[$attribute])
3397
                        {
3398
                                continue;
3399
                        }
3400
3401
                        settype($group_attributes[$attribute], $type);
3402
                        $sql_ary[str_replace('group_', 'user_', $attribute)] = $group_attributes[$attribute];
3403
                }
3404
        }
3405
3406
        // Before we update the user attributes, we will make a list of those having now the group avatar assigned
3407
        if (isset($sql_ary['user_avatar']))
3408
        {
3409
                // Ok, get the original avatar data from users having an uploaded one (we need to remove these from the filesystem)
3410
                $sql = 'SELECT user_id, group_id, user_avatar
3411
                        FROM ' . USERS_TABLE . '
3412
                        WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . '
3413
                                AND user_avatar_type = ' . AVATAR_UPLOAD;
3414
                $result = $db->sql_query($sql);
3415
3416
                while ($row = $db->sql_fetchrow($result))
3417
                {
3418
                        avatar_delete('user', $row);
3419
                }
3420
                $db->sql_freeresult($result);
3421
        }
3422
        else
3423
        {
3424
                unset($sql_ary['user_avatar_type']);
3425
                unset($sql_ary['user_avatar_height']);
3426
                unset($sql_ary['user_avatar_width']);
3427
        }
3428
3429
        $sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
3430
                WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
3431
        $db->sql_query($sql);
3432
3433
        if (isset($sql_ary['user_colour']))
3434
        {
3435
                // Update any cached colour information for these users
3436
                $sql = 'UPDATE ' . FORUMS_TABLE . " SET forum_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
3437
                        WHERE " . $db->sql_in_set('forum_last_poster_id', $user_id_ary);
3438
                $db->sql_query($sql);
3439
3440
                $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_first_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
3441
                        WHERE " . $db->sql_in_set('topic_poster', $user_id_ary);
3442
                $db->sql_query($sql);
3443
3444
                $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
3445
                        WHERE " . $db->sql_in_set('topic_last_poster_id', $user_id_ary);
3446
                $db->sql_query($sql);
3447
3448
                global $config;
3449
3450
                if (in_array($config['newest_user_id'], $user_id_ary))
3451
                {
3452
                        set_config('newest_user_colour', $sql_ary['user_colour'], true);
3453
                }
3454
        }
3455
3456
        if ($update_listing)
3457
        {
3458
                group_update_listings($group_id);
3459
        }
3460
3461
        // Because some tables/caches use usercolour-specific data we need to purge this here.
3462
        $cache->destroy('sql', MODERATOR_CACHE_TABLE);
3463
}
3464
3465
/**
3466
* Get group name
3467
*/
3468
function get_group_name($group_id)
3469
{
3470
        global $db, $user;
3471
3472
        $sql = 'SELECT group_name, group_type
3473
                FROM ' . GROUPS_TABLE . '
3474
                WHERE group_id = ' . (int) $group_id;
3475
        $result = $db->sql_query($sql);
3476
        $row = $db->sql_fetchrow($result);
3477
        $db->sql_freeresult($result);
3478
3479
        if (!$row || ($row['group_type'] == GROUP_SPECIAL && empty($user->lang)))
3480
        {
3481
                return '';
3482
        }
3483
3484
        return ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
3485
}
3486
3487
/**
3488
* Obtain either the members of a specified group, the groups the specified user is subscribed to
3489
* or checking if a specified user is in a specified group. This function does not return pending memberships.
3490
*
3491
* Note: Never use this more than once... first group your users/groups
3492
*/
3493
function group_memberships($group_id_ary = false, $user_id_ary = false, $return_bool = false)
3494
{
3495
        global $db;
3496
3497
        if (!$group_id_ary && !$user_id_ary)
3498
        {
3499
                return true;
3500
        }
3501
3502
        if ($user_id_ary)
3503
        {
3504
                $user_id_ary = (!is_array($user_id_ary)) ? array($user_id_ary) : $user_id_ary;
3505
        }
3506
3507
        if ($group_id_ary)
3508
        {
3509
                $group_id_ary = (!is_array($group_id_ary)) ? array($group_id_ary) : $group_id_ary;
3510
        }
3511
3512
        $sql = 'SELECT ug.*, u.username, u.username_clean, u.user_email
3513
                FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u
3514
                WHERE ug.user_id = u.user_id
3515
                        AND ug.user_pending = 0 AND ';
3516
3517
        if ($group_id_ary)
3518
        {
3519
                $sql .= ' ' . $db->sql_in_set('ug.group_id', $group_id_ary);
3520
        }
3521
3522
        if ($user_id_ary)
3523
        {
3524
                $sql .= ($group_id_ary) ? ' AND ' : ' ';
3525
                $sql .= $db->sql_in_set('ug.user_id', $user_id_ary);
3526
        }
3527
3528
        $result = ($return_bool) ? $db->sql_query_limit($sql, 1) : $db->sql_query($sql);
3529
3530
        $row = $db->sql_fetchrow($result);
3531
3532
        if ($return_bool)
3533
        {
3534
                $db->sql_freeresult($result);
3535
                return ($row) ? true : false;
3536
        }
3537
3538
        if (!$row)
3539
        {
3540
                return false;
3541
        }
3542
3543
        $return = array();
3544
3545
        do
3546
        {
3547
                $return[] = $row;
3548
        }
3549
        while ($row = $db->sql_fetchrow($result));
3550
3551
        $db->sql_freeresult($result);
3552
3553
        return $return;
3554
}
3555
3556
/**
3557
* Re-cache moderators and foes if group has a_ or m_ permissions
3558
*/
3559
function group_update_listings($group_id)
3560
{
3561
        global $auth;
3562
3563
        $hold_ary = $auth->acl_group_raw_data($group_id, array('a_', 'm_'));
3564
3565
        if (!sizeof($hold_ary))
3566
        {
3567
                return;
3568
        }
3569
3570
        $mod_permissions = $admin_permissions = false;
3571
3572
        foreach ($hold_ary as $g_id => $forum_ary)
3573
        {
3574
                foreach ($forum_ary as $forum_id => $auth_ary)
3575
                {
3576
                        foreach ($auth_ary as $auth_option => $setting)
3577
                        {
3578
                                if ($mod_permissions && $admin_permissions)
3579
                                {
3580
                                        break 3;
3581
                                }
3582
3583
                                if ($setting != ACL_YES)
3584
                                {
3585
                                        continue;
3586
                                }
3587
3588
                                if ($auth_option == 'm_')
3589
                                {
3590
                                        $mod_permissions = true;
3591
                                }
3592
3593
                                if ($auth_option == 'a_')
3594
                                {
3595
                                        $admin_permissions = true;
3596
                                }
3597
                        }
3598
                }
3599
        }
3600
3601
        if ($mod_permissions)
3602
        {
3603
                if (!function_exists('cache_moderators'))
3604
                {
3605
                        global $phpbb_root_path, $phpEx;
3606
                        include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
3607
                }
3608
                cache_moderators();
3609
        }
3610
3611
        if ($mod_permissions || $admin_permissions)
3612
        {
3613
                if (!function_exists('update_foes'))
3614
                {
3615
                        global $phpbb_root_path, $phpEx;
3616
                        include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
3617
                }
3618
                update_foes(array($group_id));
3619
        }
3620
}
3621
3622
3623
3624
/**
3625
* Funtion to make a user leave the NEWLY_REGISTERED system group.
3626
* @access public
3627
* @param $user_id The id of the user to remove from the group
3628
*/
3629
function remove_newly_registered($user_id, $user_data = false)
3630
{
3631
        global $db;
3632
3633
        if ($user_data === false)
3634
        {
3635
                $sql = 'SELECT *
3636
                        FROM ' . USERS_TABLE . '
3637
                        WHERE user_id = ' . $user_id;
3638
                $result = $db->sql_query($sql);
3639
                $user_row = $db->sql_fetchrow($result);
3640
                $db->sql_freeresult($result);
3641
3642
                if (!$user_row)
3643
                {
3644
                        return false;
3645
                }
3646
                else
3647
                {
3648
                        $user_data  = $user_row;
3649
                }
3650
        }
3651
3652
        if (empty($user_data['user_new']))
3653
        {
3654
                return false;
3655
        }
3656
3657
        $sql = 'SELECT group_id
3658
                FROM ' . GROUPS_TABLE . "
3659
                WHERE group_name = 'NEWLY_REGISTERED'
3660
                        AND group_type = " . GROUP_SPECIAL;
3661
        $result = $db->sql_query($sql);
3662
        $group_id = (int) $db->sql_fetchfield('group_id');
3663
        $db->sql_freeresult($result);
3664
3665
        if (!$group_id)
3666
        {
3667
                return false;
3668
        }
3669
3670
        // We need to call group_user_del here, because this function makes sure everything is correctly changed.
3671
        // A downside for a call within the session handler is that the language is not set up yet - so no log entry
3672
        group_user_del($group_id, $user_id);
3673
3674
        // Set user_new to 0 to let this not be triggered again
3675
        $sql = 'UPDATE ' . USERS_TABLE . '
3676
                SET user_new = 0
3677
                WHERE user_id = ' . $user_id;
3678
        $db->sql_query($sql);
3679
3680
        // The new users group was the users default group?
3681
        if ($user_data['group_id'] == $group_id)
3682
        {
3683
                // Which group is now the users default one?
3684
                $sql = 'SELECT group_id
3685
                        FROM ' . USERS_TABLE . '
3686
                        WHERE user_id = ' . $user_id;
3687
                $result = $db->sql_query($sql);
3688
                $user_data['group_id'] = $db->sql_fetchfield('group_id');
3689
                $db->sql_freeresult($result);
3690
        }
3691
3692
        return $user_data['group_id'];
3693
}