PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/forum/includes/functions_user.php

https://code.google.com/p/mwenhanced/
PHP | 3582 lines | 2696 code | 551 blank | 335 comment | 526 complexity | f48f3653e5c2b3b1412b15bc5a8b2af4 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, AGPL-1.0, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. *
  4. * @package phpBB3
  5. * @version $Id$
  6. * @copyright (c) 2005 phpBB Group
  7. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  8. *
  9. */
  10. /**
  11. * @ignore
  12. */
  13. if (!defined('IN_PHPBB'))
  14. {
  15. exit;
  16. }
  17. /**
  18. * Obtain user_ids from usernames or vice versa. Returns false on
  19. * success else the error string
  20. *
  21. * @param array &$user_id_ary The user ids to check or empty if usernames used
  22. * @param array &$username_ary The usernames to check or empty if user ids used
  23. * @param mixed $user_type Array of user types to check, false if not restricting by user type
  24. */
  25. function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
  26. {
  27. global $db;
  28. // Are both arrays already filled? Yep, return else
  29. // are neither array filled?
  30. if ($user_id_ary && $username_ary)
  31. {
  32. return false;
  33. }
  34. else if (!$user_id_ary && !$username_ary)
  35. {
  36. return 'NO_USERS';
  37. }
  38. $which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
  39. if ($$which_ary && !is_array($$which_ary))
  40. {
  41. $$which_ary = array($$which_ary);
  42. }
  43. $sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', $$which_ary) : array_map('utf8_clean_string', $$which_ary);
  44. unset($$which_ary);
  45. $user_id_ary = $username_ary = array();
  46. // Grab the user id/username records
  47. $sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
  48. $sql = 'SELECT user_id, username
  49. FROM ' . USERS_TABLE . '
  50. WHERE ' . $db->sql_in_set($sql_where, $sql_in);
  51. if ($user_type !== false && !empty($user_type))
  52. {
  53. $sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
  54. }
  55. $result = $db->sql_query($sql);
  56. if (!($row = $db->sql_fetchrow($result)))
  57. {
  58. $db->sql_freeresult($result);
  59. return 'NO_USERS';
  60. }
  61. do
  62. {
  63. $username_ary[$row['user_id']] = $row['username'];
  64. $user_id_ary[] = $row['user_id'];
  65. }
  66. while ($row = $db->sql_fetchrow($result));
  67. $db->sql_freeresult($result);
  68. return false;
  69. }
  70. /**
  71. * Get latest registered username and update database to reflect it
  72. */
  73. function update_last_username()
  74. {
  75. global $db;
  76. // Get latest username
  77. $sql = 'SELECT user_id, username, user_colour
  78. FROM ' . USERS_TABLE . '
  79. WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
  80. ORDER BY user_id DESC';
  81. $result = $db->sql_query_limit($sql, 1);
  82. $row = $db->sql_fetchrow($result);
  83. $db->sql_freeresult($result);
  84. if ($row)
  85. {
  86. set_config('newest_user_id', $row['user_id'], true);
  87. set_config('newest_username', $row['username'], true);
  88. set_config('newest_user_colour', $row['user_colour'], true);
  89. }
  90. }
  91. /**
  92. * Updates a username across all relevant tables/fields
  93. *
  94. * @param string $old_name the old/current username
  95. * @param string $new_name the new username
  96. */
  97. function user_update_name($old_name, $new_name)
  98. {
  99. global $config, $db, $cache;
  100. $update_ary = array(
  101. FORUMS_TABLE => array('forum_last_poster_name'),
  102. MODERATOR_CACHE_TABLE => array('username'),
  103. POSTS_TABLE => array('post_username'),
  104. TOPICS_TABLE => array('topic_first_poster_name', 'topic_last_poster_name'),
  105. );
  106. foreach ($update_ary as $table => $field_ary)
  107. {
  108. foreach ($field_ary as $field)
  109. {
  110. $sql = "UPDATE $table
  111. SET $field = '" . $db->sql_escape($new_name) . "'
  112. WHERE $field = '" . $db->sql_escape($old_name) . "'";
  113. $db->sql_query($sql);
  114. }
  115. }
  116. if ($config['newest_username'] == $old_name)
  117. {
  118. set_config('newest_username', $new_name, true);
  119. }
  120. // Because some tables/caches use username-specific data we need to purge this here.
  121. $cache->destroy('sql', MODERATOR_CACHE_TABLE);
  122. }
  123. /**
  124. * Adds an user
  125. *
  126. * @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.
  127. * @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
  128. * @return the new user's ID.
  129. */
  130. function user_add($user_row, $cp_data = false)
  131. {
  132. global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
  133. if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
  134. {
  135. return false;
  136. }
  137. $username_clean = utf8_clean_string($user_row['username']);
  138. if (empty($username_clean))
  139. {
  140. return false;
  141. }
  142. $sql_ary = array(
  143. 'username' => $user_row['username'],
  144. 'username_clean' => $username_clean,
  145. 'user_password' => (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
  146. 'user_pass_convert' => 0,
  147. 'user_email' => strtolower($user_row['user_email']),
  148. 'user_email_hash' => phpbb_email_hash($user_row['user_email']),
  149. 'group_id' => $user_row['group_id'],
  150. 'user_type' => $user_row['user_type'],
  151. );
  152. // These are the additional vars able to be specified
  153. $additional_vars = array(
  154. 'user_permissions' => '',
  155. 'user_timezone' => $config['board_timezone'],
  156. 'user_dateformat' => $config['default_dateformat'],
  157. 'user_lang' => $config['default_lang'],
  158. 'user_style' => (int) $config['default_style'],
  159. 'user_actkey' => '',
  160. 'user_ip' => '',
  161. 'user_regdate' => time(),
  162. 'user_passchg' => time(),
  163. 'user_options' => 230271,
  164. // We do not set the new flag here - registration scripts need to specify it
  165. 'user_new' => 0,
  166. 'user_inactive_reason' => 0,
  167. 'user_inactive_time' => 0,
  168. 'user_lastmark' => time(),
  169. 'user_lastvisit' => 0,
  170. 'user_lastpost_time' => 0,
  171. 'user_lastpage' => '',
  172. 'user_posts' => 0,
  173. 'user_dst' => (int) $config['board_dst'],
  174. 'user_colour' => '',
  175. 'user_occ' => '',
  176. 'user_interests' => '',
  177. 'user_avatar' => '',
  178. 'user_avatar_type' => 0,
  179. 'user_avatar_width' => 0,
  180. 'user_avatar_height' => 0,
  181. 'user_new_privmsg' => 0,
  182. 'user_unread_privmsg' => 0,
  183. 'user_last_privmsg' => 0,
  184. 'user_message_rules' => 0,
  185. 'user_full_folder' => PRIVMSGS_NO_BOX,
  186. 'user_emailtime' => 0,
  187. 'user_notify' => 0,
  188. 'user_notify_pm' => 1,
  189. 'user_notify_type' => NOTIFY_EMAIL,
  190. 'user_allow_pm' => 1,
  191. 'user_allow_viewonline' => 1,
  192. 'user_allow_viewemail' => 1,
  193. 'user_allow_massemail' => 1,
  194. 'user_sig' => '',
  195. 'user_sig_bbcode_uid' => '',
  196. 'user_sig_bbcode_bitfield' => '',
  197. 'user_form_salt' => unique_id(),
  198. );
  199. // Now fill the sql array with not required variables
  200. foreach ($additional_vars as $key => $default_value)
  201. {
  202. $sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
  203. }
  204. // Any additional variables in $user_row not covered above?
  205. $remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
  206. // Now fill our sql array with the remaining vars
  207. if (sizeof($remaining_vars))
  208. {
  209. foreach ($remaining_vars as $key)
  210. {
  211. $sql_ary[$key] = $user_row[$key];
  212. }
  213. }
  214. $sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
  215. $db->sql_query($sql);
  216. $user_id = $db->sql_nextid();
  217. // Insert Custom Profile Fields
  218. if ($cp_data !== false && sizeof($cp_data))
  219. {
  220. $cp_data['user_id'] = (int) $user_id;
  221. if (!class_exists('custom_profile'))
  222. {
  223. include_once($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
  224. }
  225. $sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
  226. $db->sql_build_array('INSERT', custom_profile::build_insert_sql_array($cp_data));
  227. $db->sql_query($sql);
  228. }
  229. // Place into appropriate group...
  230. $sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  231. 'user_id' => (int) $user_id,
  232. 'group_id' => (int) $user_row['group_id'],
  233. 'user_pending' => 0)
  234. );
  235. $db->sql_query($sql);
  236. // Now make it the users default group...
  237. group_set_user_default($user_row['group_id'], array($user_id), false);
  238. // Add to newly registered users group if user_new is 1
  239. if ($config['new_member_post_limit'] && $sql_ary['user_new'])
  240. {
  241. $sql = 'SELECT group_id
  242. FROM ' . GROUPS_TABLE . "
  243. WHERE group_name = 'NEWLY_REGISTERED'
  244. AND group_type = " . GROUP_SPECIAL;
  245. $result = $db->sql_query($sql);
  246. $add_group_id = (int) $db->sql_fetchfield('group_id');
  247. $db->sql_freeresult($result);
  248. if ($add_group_id)
  249. {
  250. // Because these actions only fill the log unneccessarily we skip the add_log() entry with a little hack. :/
  251. $GLOBALS['skip_add_log'] = true;
  252. // Add user to "newly registered users" group and set to default group if admin specified so.
  253. if ($config['new_member_group_default'])
  254. {
  255. group_user_add($add_group_id, $user_id, false, false, true);
  256. }
  257. else
  258. {
  259. group_user_add($add_group_id, $user_id);
  260. }
  261. unset($GLOBALS['skip_add_log']);
  262. }
  263. }
  264. // set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
  265. if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
  266. {
  267. set_config('newest_user_id', $user_id, true);
  268. set_config('newest_username', $user_row['username'], true);
  269. set_config_count('num_users', 1, true);
  270. $sql = 'SELECT group_colour
  271. FROM ' . GROUPS_TABLE . '
  272. WHERE group_id = ' . (int) $user_row['group_id'];
  273. $result = $db->sql_query_limit($sql, 1);
  274. $row = $db->sql_fetchrow($result);
  275. $db->sql_freeresult($result);
  276. set_config('newest_user_colour', $row['group_colour'], true);
  277. }
  278. return $user_id;
  279. }
  280. /**
  281. * Remove User
  282. */
  283. function user_delete($mode, $user_id, $post_username = false)
  284. {
  285. global $cache, $config, $db, $user, $auth;
  286. global $phpbb_root_path, $phpEx;
  287. $sql = 'SELECT *
  288. FROM ' . USERS_TABLE . '
  289. WHERE user_id = ' . $user_id;
  290. $result = $db->sql_query($sql);
  291. $user_row = $db->sql_fetchrow($result);
  292. $db->sql_freeresult($result);
  293. if (!$user_row)
  294. {
  295. return false;
  296. }
  297. // Before we begin, we will remove the reports the user issued.
  298. $sql = 'SELECT r.post_id, p.topic_id
  299. FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
  300. WHERE r.user_id = ' . $user_id . '
  301. AND p.post_id = r.post_id';
  302. $result = $db->sql_query($sql);
  303. $report_posts = $report_topics = array();
  304. while ($row = $db->sql_fetchrow($result))
  305. {
  306. $report_posts[] = $row['post_id'];
  307. $report_topics[] = $row['topic_id'];
  308. }
  309. $db->sql_freeresult($result);
  310. if (sizeof($report_posts))
  311. {
  312. $report_posts = array_unique($report_posts);
  313. $report_topics = array_unique($report_topics);
  314. // Get a list of topics that still contain reported posts
  315. $sql = 'SELECT DISTINCT topic_id
  316. FROM ' . POSTS_TABLE . '
  317. WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
  318. AND post_reported = 1
  319. AND ' . $db->sql_in_set('post_id', $report_posts, true);
  320. $result = $db->sql_query($sql);
  321. $keep_report_topics = array();
  322. while ($row = $db->sql_fetchrow($result))
  323. {
  324. $keep_report_topics[] = $row['topic_id'];
  325. }
  326. $db->sql_freeresult($result);
  327. if (sizeof($keep_report_topics))
  328. {
  329. $report_topics = array_diff($report_topics, $keep_report_topics);
  330. }
  331. unset($keep_report_topics);
  332. // Now set the flags back
  333. $sql = 'UPDATE ' . POSTS_TABLE . '
  334. SET post_reported = 0
  335. WHERE ' . $db->sql_in_set('post_id', $report_posts);
  336. $db->sql_query($sql);
  337. if (sizeof($report_topics))
  338. {
  339. $sql = 'UPDATE ' . TOPICS_TABLE . '
  340. SET topic_reported = 0
  341. WHERE ' . $db->sql_in_set('topic_id', $report_topics);
  342. $db->sql_query($sql);
  343. }
  344. }
  345. // Remove reports
  346. $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE user_id = ' . $user_id);
  347. if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == AVATAR_UPLOAD)
  348. {
  349. avatar_delete('user', $user_row);
  350. }
  351. switch ($mode)
  352. {
  353. case 'retain':
  354. $db->sql_transaction('begin');
  355. if ($post_username === false)
  356. {
  357. $post_username = $user->lang['GUEST'];
  358. }
  359. // If the user is inactive and newly registered we assume no posts from this user being there...
  360. if ($user_row['user_type'] == USER_INACTIVE && $user_row['user_inactive_reason'] == INACTIVE_REGISTER && !$user_row['user_posts'])
  361. {
  362. }
  363. else
  364. {
  365. $sql = 'UPDATE ' . FORUMS_TABLE . '
  366. SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
  367. WHERE forum_last_poster_id = $user_id";
  368. $db->sql_query($sql);
  369. $sql = 'UPDATE ' . POSTS_TABLE . '
  370. SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
  371. WHERE poster_id = $user_id";
  372. $db->sql_query($sql);
  373. $sql = 'UPDATE ' . POSTS_TABLE . '
  374. SET post_edit_user = ' . ANONYMOUS . "
  375. WHERE post_edit_user = $user_id";
  376. $db->sql_query($sql);
  377. $sql = 'UPDATE ' . TOPICS_TABLE . '
  378. SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
  379. WHERE topic_poster = $user_id";
  380. $db->sql_query($sql);
  381. $sql = 'UPDATE ' . TOPICS_TABLE . '
  382. SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
  383. WHERE topic_last_poster_id = $user_id";
  384. $db->sql_query($sql);
  385. $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
  386. SET poster_id = ' . ANONYMOUS . "
  387. WHERE poster_id = $user_id";
  388. $db->sql_query($sql);
  389. // Since we change every post by this author, we need to count this amount towards the anonymous user
  390. // Update the post count for the anonymous user
  391. if ($user_row['user_posts'])
  392. {
  393. $sql = 'UPDATE ' . USERS_TABLE . '
  394. SET user_posts = user_posts + ' . $user_row['user_posts'] . '
  395. WHERE user_id = ' . ANONYMOUS;
  396. $db->sql_query($sql);
  397. }
  398. }
  399. $db->sql_transaction('commit');
  400. break;
  401. case 'remove':
  402. if (!function_exists('delete_posts'))
  403. {
  404. include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
  405. }
  406. $sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
  407. FROM ' . POSTS_TABLE . "
  408. WHERE poster_id = $user_id
  409. GROUP BY topic_id";
  410. $result = $db->sql_query($sql);
  411. $topic_id_ary = array();
  412. while ($row = $db->sql_fetchrow($result))
  413. {
  414. $topic_id_ary[$row['topic_id']] = $row['total_posts'];
  415. }
  416. $db->sql_freeresult($result);
  417. if (sizeof($topic_id_ary))
  418. {
  419. $sql = 'SELECT topic_id, topic_replies, topic_replies_real
  420. FROM ' . TOPICS_TABLE . '
  421. WHERE ' . $db->sql_in_set('topic_id', array_keys($topic_id_ary));
  422. $result = $db->sql_query($sql);
  423. $del_topic_ary = array();
  424. while ($row = $db->sql_fetchrow($result))
  425. {
  426. if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
  427. {
  428. $del_topic_ary[] = $row['topic_id'];
  429. }
  430. }
  431. $db->sql_freeresult($result);
  432. if (sizeof($del_topic_ary))
  433. {
  434. $sql = 'DELETE FROM ' . TOPICS_TABLE . '
  435. WHERE ' . $db->sql_in_set('topic_id', $del_topic_ary);
  436. $db->sql_query($sql);
  437. }
  438. }
  439. // Delete posts, attachments, etc.
  440. delete_posts('poster_id', $user_id);
  441. break;
  442. }
  443. $db->sql_transaction('begin');
  444. $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);
  445. foreach ($table_ary as $table)
  446. {
  447. $sql = "DELETE FROM $table
  448. WHERE user_id = $user_id";
  449. $db->sql_query($sql);
  450. }
  451. $cache->destroy('sql', MODERATOR_CACHE_TABLE);
  452. // Delete user log entries about this user
  453. $sql = 'DELETE FROM ' . LOG_TABLE . '
  454. WHERE reportee_id = ' . $user_id;
  455. $db->sql_query($sql);
  456. // Change user_id to anonymous for this users triggered events
  457. $sql = 'UPDATE ' . LOG_TABLE . '
  458. SET user_id = ' . ANONYMOUS . '
  459. WHERE user_id = ' . $user_id;
  460. $db->sql_query($sql);
  461. // Delete the user_id from the zebra table
  462. $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
  463. WHERE user_id = ' . $user_id . '
  464. OR zebra_id = ' . $user_id;
  465. $db->sql_query($sql);
  466. // Delete the user_id from the banlist
  467. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  468. WHERE ban_userid = ' . $user_id;
  469. $db->sql_query($sql);
  470. // Delete the user_id from the session table
  471. $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
  472. WHERE session_user_id = ' . $user_id;
  473. $db->sql_query($sql);
  474. // Remove any undelivered mails...
  475. $sql = 'SELECT msg_id, user_id
  476. FROM ' . PRIVMSGS_TO_TABLE . '
  477. WHERE author_id = ' . $user_id . '
  478. AND folder_id = ' . PRIVMSGS_NO_BOX;
  479. $result = $db->sql_query($sql);
  480. $undelivered_msg = $undelivered_user = array();
  481. while ($row = $db->sql_fetchrow($result))
  482. {
  483. $undelivered_msg[] = $row['msg_id'];
  484. $undelivered_user[$row['user_id']][] = true;
  485. }
  486. $db->sql_freeresult($result);
  487. if (sizeof($undelivered_msg))
  488. {
  489. $sql = 'DELETE FROM ' . PRIVMSGS_TABLE . '
  490. WHERE ' . $db->sql_in_set('msg_id', $undelivered_msg);
  491. $db->sql_query($sql);
  492. }
  493. $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
  494. WHERE author_id = ' . $user_id . '
  495. AND folder_id = ' . PRIVMSGS_NO_BOX;
  496. $db->sql_query($sql);
  497. // Delete all to-information
  498. $sql = 'DELETE FROM ' . PRIVMSGS_TO_TABLE . '
  499. WHERE user_id = ' . $user_id;
  500. $db->sql_query($sql);
  501. // Set the remaining author id to anonymous - this way users are still able to read messages from users being removed
  502. $sql = 'UPDATE ' . PRIVMSGS_TO_TABLE . '
  503. SET author_id = ' . ANONYMOUS . '
  504. WHERE author_id = ' . $user_id;
  505. $db->sql_query($sql);
  506. $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
  507. SET author_id = ' . ANONYMOUS . '
  508. WHERE author_id = ' . $user_id;
  509. $db->sql_query($sql);
  510. foreach ($undelivered_user as $_user_id => $ary)
  511. {
  512. if ($_user_id == $user_id)
  513. {
  514. continue;
  515. }
  516. $sql = 'UPDATE ' . USERS_TABLE . '
  517. SET user_new_privmsg = user_new_privmsg - ' . sizeof($ary) . ',
  518. user_unread_privmsg = user_unread_privmsg - ' . sizeof($ary) . '
  519. WHERE user_id = ' . $_user_id;
  520. $db->sql_query($sql);
  521. }
  522. $db->sql_transaction('commit');
  523. // Reset newest user info if appropriate
  524. if ($config['newest_user_id'] == $user_id)
  525. {
  526. update_last_username();
  527. }
  528. // Decrement number of users if this user is active
  529. if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
  530. {
  531. set_config_count('num_users', -1, true);
  532. }
  533. return false;
  534. }
  535. /**
  536. * Flips user_type from active to inactive and vice versa, handles group membership updates
  537. *
  538. * @param string $mode can be flip for flipping from active/inactive, activate or deactivate
  539. */
  540. function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
  541. {
  542. global $config, $db, $user, $auth;
  543. $deactivated = $activated = 0;
  544. $sql_statements = array();
  545. if (!is_array($user_id_ary))
  546. {
  547. $user_id_ary = array($user_id_ary);
  548. }
  549. if (!sizeof($user_id_ary))
  550. {
  551. return;
  552. }
  553. $sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
  554. FROM ' . USERS_TABLE . '
  555. WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
  556. $result = $db->sql_query($sql);
  557. while ($row = $db->sql_fetchrow($result))
  558. {
  559. $sql_ary = array();
  560. if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
  561. ($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
  562. ($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
  563. {
  564. continue;
  565. }
  566. if ($row['user_type'] == USER_INACTIVE)
  567. {
  568. $activated++;
  569. }
  570. else
  571. {
  572. $deactivated++;
  573. // Remove the users session key...
  574. $user->reset_login_keys($row['user_id']);
  575. }
  576. $sql_ary += array(
  577. 'user_type' => ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
  578. 'user_inactive_time' => ($row['user_type'] == USER_NORMAL) ? time() : 0,
  579. 'user_inactive_reason' => ($row['user_type'] == USER_NORMAL) ? $reason : 0,
  580. );
  581. $sql_statements[$row['user_id']] = $sql_ary;
  582. }
  583. $db->sql_freeresult($result);
  584. if (sizeof($sql_statements))
  585. {
  586. foreach ($sql_statements as $user_id => $sql_ary)
  587. {
  588. $sql = 'UPDATE ' . USERS_TABLE . '
  589. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  590. WHERE user_id = ' . $user_id;
  591. $db->sql_query($sql);
  592. }
  593. $auth->acl_clear_prefetch(array_keys($sql_statements));
  594. }
  595. if ($deactivated)
  596. {
  597. set_config_count('num_users', $deactivated * (-1), true);
  598. }
  599. if ($activated)
  600. {
  601. set_config_count('num_users', $activated, true);
  602. }
  603. // Update latest username
  604. update_last_username();
  605. }
  606. /**
  607. * Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
  608. *
  609. * @param string $mode Type of ban. One of the following: user, ip, email
  610. * @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
  611. * @param int $ban_len Ban length in minutes
  612. * @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
  613. * @param boolean $ban_exclude Exclude these entities from banning?
  614. * @param string $ban_reason String describing the reason for this ban
  615. * @return boolean
  616. */
  617. function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
  618. {
  619. global $db, $user, $auth, $cache;
  620. // Delete stale bans
  621. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  622. WHERE ban_end < ' . time() . '
  623. AND ban_end <> 0';
  624. $db->sql_query($sql);
  625. $ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
  626. $ban_list_log = implode(', ', $ban_list);
  627. $current_time = time();
  628. // Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
  629. if ($ban_len)
  630. {
  631. if ($ban_len != -1 || !$ban_len_other)
  632. {
  633. $ban_end = max($current_time, $current_time + ($ban_len) * 60);
  634. }
  635. else
  636. {
  637. $ban_other = explode('-', $ban_len_other);
  638. if (sizeof($ban_other) == 3 && ((int)$ban_other[0] < 9999) &&
  639. (strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
  640. {
  641. $ban_end = max($current_time, gmmktime(0, 0, 0, (int)$ban_other[1], (int)$ban_other[2], (int)$ban_other[0]));
  642. }
  643. else
  644. {
  645. trigger_error('LENGTH_BAN_INVALID');
  646. }
  647. }
  648. }
  649. else
  650. {
  651. $ban_end = 0;
  652. }
  653. $founder = $founder_names = array();
  654. if (!$ban_exclude)
  655. {
  656. // Create a list of founder...
  657. $sql = 'SELECT user_id, user_email, username_clean
  658. FROM ' . USERS_TABLE . '
  659. WHERE user_type = ' . USER_FOUNDER;
  660. $result = $db->sql_query($sql);
  661. while ($row = $db->sql_fetchrow($result))
  662. {
  663. $founder[$row['user_id']] = $row['user_email'];
  664. $founder_names[$row['user_id']] = $row['username_clean'];
  665. }
  666. $db->sql_freeresult($result);
  667. }
  668. $banlist_ary = array();
  669. switch ($mode)
  670. {
  671. case 'user':
  672. $type = 'ban_userid';
  673. // At the moment we do not support wildcard username banning
  674. // Select the relevant user_ids.
  675. $sql_usernames = array();
  676. foreach ($ban_list as $username)
  677. {
  678. $username = trim($username);
  679. if ($username != '')
  680. {
  681. $clean_name = utf8_clean_string($username);
  682. if ($clean_name == $user->data['username_clean'])
  683. {
  684. trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
  685. }
  686. if (in_array($clean_name, $founder_names))
  687. {
  688. trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
  689. }
  690. $sql_usernames[] = $clean_name;
  691. }
  692. }
  693. // Make sure we have been given someone to ban
  694. if (!sizeof($sql_usernames))
  695. {
  696. trigger_error('NO_USER_SPECIFIED');
  697. }
  698. $sql = 'SELECT user_id
  699. FROM ' . USERS_TABLE . '
  700. WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
  701. // Do not allow banning yourself
  702. if (sizeof($founder))
  703. {
  704. $sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), array($user->data['user_id'])), true);
  705. }
  706. else
  707. {
  708. $sql .= ' AND user_id <> ' . $user->data['user_id'];
  709. }
  710. $result = $db->sql_query($sql);
  711. if ($row = $db->sql_fetchrow($result))
  712. {
  713. do
  714. {
  715. $banlist_ary[] = (int) $row['user_id'];
  716. }
  717. while ($row = $db->sql_fetchrow($result));
  718. }
  719. else
  720. {
  721. $db->sql_freeresult($result);
  722. trigger_error('NO_USERS');
  723. }
  724. $db->sql_freeresult($result);
  725. break;
  726. case 'ip':
  727. $type = 'ban_ip';
  728. foreach ($ban_list as $ban_item)
  729. {
  730. 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))
  731. {
  732. // This is an IP range
  733. // Don't ask about all this, just don't ask ... !
  734. $ip_1_counter = $ip_range_explode[1];
  735. $ip_1_end = $ip_range_explode[5];
  736. while ($ip_1_counter <= $ip_1_end)
  737. {
  738. $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
  739. $ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
  740. if ($ip_2_counter == 0 && $ip_2_end == 254)
  741. {
  742. $ip_2_counter = 256;
  743. $ip_2_fragment = 256;
  744. $banlist_ary[] = "$ip_1_counter.*";
  745. }
  746. while ($ip_2_counter <= $ip_2_end)
  747. {
  748. $ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
  749. $ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
  750. if ($ip_3_counter == 0 && $ip_3_end == 254)
  751. {
  752. $ip_3_counter = 256;
  753. $ip_3_fragment = 256;
  754. $banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
  755. }
  756. while ($ip_3_counter <= $ip_3_end)
  757. {
  758. $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;
  759. $ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
  760. if ($ip_4_counter == 0 && $ip_4_end == 254)
  761. {
  762. $ip_4_counter = 256;
  763. $ip_4_fragment = 256;
  764. $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
  765. }
  766. while ($ip_4_counter <= $ip_4_end)
  767. {
  768. $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
  769. $ip_4_counter++;
  770. }
  771. $ip_3_counter++;
  772. }
  773. $ip_2_counter++;
  774. }
  775. $ip_1_counter++;
  776. }
  777. }
  778. 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)))
  779. {
  780. // Normal IP address
  781. $banlist_ary[] = trim($ban_item);
  782. }
  783. else if (preg_match('#^\*$#', trim($ban_item)))
  784. {
  785. // Ban all IPs
  786. $banlist_ary[] = '*';
  787. }
  788. else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
  789. {
  790. // hostname
  791. $ip_ary = gethostbynamel(trim($ban_item));
  792. if (!empty($ip_ary))
  793. {
  794. foreach ($ip_ary as $ip)
  795. {
  796. if ($ip)
  797. {
  798. if (strlen($ip) > 40)
  799. {
  800. continue;
  801. }
  802. $banlist_ary[] = $ip;
  803. }
  804. }
  805. }
  806. }
  807. if (empty($banlist_ary))
  808. {
  809. trigger_error('NO_IPS_DEFINED');
  810. }
  811. }
  812. break;
  813. case 'email':
  814. $type = 'ban_email';
  815. foreach ($ban_list as $ban_item)
  816. {
  817. $ban_item = trim($ban_item);
  818. if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
  819. {
  820. if (strlen($ban_item) > 100)
  821. {
  822. continue;
  823. }
  824. if (!sizeof($founder) || !in_array($ban_item, $founder))
  825. {
  826. $banlist_ary[] = $ban_item;
  827. }
  828. }
  829. }
  830. if (sizeof($ban_list) == 0)
  831. {
  832. trigger_error('NO_EMAILS_DEFINED');
  833. }
  834. break;
  835. default:
  836. trigger_error('NO_MODE');
  837. break;
  838. }
  839. // Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
  840. $sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
  841. $sql = "SELECT $type
  842. FROM " . BANLIST_TABLE . "
  843. WHERE $sql_where
  844. AND ban_exclude = " . (int) $ban_exclude;
  845. $result = $db->sql_query($sql);
  846. // Reset $sql_where, because we use it later...
  847. $sql_where = '';
  848. if ($row = $db->sql_fetchrow($result))
  849. {
  850. $banlist_ary_tmp = array();
  851. do
  852. {
  853. switch ($mode)
  854. {
  855. case 'user':
  856. $banlist_ary_tmp[] = $row['ban_userid'];
  857. break;
  858. case 'ip':
  859. $banlist_ary_tmp[] = $row['ban_ip'];
  860. break;
  861. case 'email':
  862. $banlist_ary_tmp[] = $row['ban_email'];
  863. break;
  864. }
  865. }
  866. while ($row = $db->sql_fetchrow($result));
  867. $banlist_ary_tmp = array_intersect($banlist_ary, $banlist_ary_tmp);
  868. if (sizeof($banlist_ary_tmp))
  869. {
  870. // One or more entities are already banned/excluded, delete the existing bans, so they can be re-inserted with the given new length
  871. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  872. WHERE ' . $db->sql_in_set($type, $banlist_ary_tmp) . '
  873. AND ban_exclude = ' . (int) $ban_exclude;
  874. $db->sql_query($sql);
  875. }
  876. unset($banlist_ary_tmp);
  877. }
  878. $db->sql_freeresult($result);
  879. // We have some entities to ban
  880. if (sizeof($banlist_ary))
  881. {
  882. $sql_ary = array();
  883. foreach ($banlist_ary as $ban_entry)
  884. {
  885. $sql_ary[] = array(
  886. $type => $ban_entry,
  887. 'ban_start' => (int) $current_time,
  888. 'ban_end' => (int) $ban_end,
  889. 'ban_exclude' => (int) $ban_exclude,
  890. 'ban_reason' => (string) $ban_reason,
  891. 'ban_give_reason' => (string) $ban_give_reason,
  892. );
  893. }
  894. $db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
  895. // If we are banning we want to logout anyone matching the ban
  896. if (!$ban_exclude)
  897. {
  898. switch ($mode)
  899. {
  900. case 'user':
  901. $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
  902. break;
  903. case 'ip':
  904. $sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
  905. break;
  906. case 'email':
  907. $banlist_ary_sql = array();
  908. foreach ($banlist_ary as $ban_entry)
  909. {
  910. $banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
  911. }
  912. $sql = 'SELECT user_id
  913. FROM ' . USERS_TABLE . '
  914. WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
  915. $result = $db->sql_query($sql);
  916. $sql_in = array();
  917. if ($row = $db->sql_fetchrow($result))
  918. {
  919. do
  920. {
  921. $sql_in[] = $row['user_id'];
  922. }
  923. while ($row = $db->sql_fetchrow($result));
  924. $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
  925. }
  926. $db->sql_freeresult($result);
  927. break;
  928. }
  929. if (isset($sql_where) && $sql_where)
  930. {
  931. $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
  932. $sql_where";
  933. $db->sql_query($sql);
  934. if ($mode == 'user')
  935. {
  936. $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
  937. $db->sql_query($sql);
  938. }
  939. }
  940. }
  941. // Update log
  942. $log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
  943. // Add to moderator log, admin log and user notes
  944. add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
  945. add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
  946. if ($mode == 'user')
  947. {
  948. foreach ($banlist_ary as $user_id)
  949. {
  950. add_log('user', $user_id, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
  951. }
  952. }
  953. $cache->destroy('sql', BANLIST_TABLE);
  954. return true;
  955. }
  956. // There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
  957. $cache->destroy('sql', BANLIST_TABLE);
  958. return false;
  959. }
  960. /**
  961. * Unban User
  962. */
  963. function user_unban($mode, $ban)
  964. {
  965. global $db, $user, $auth, $cache;
  966. // Delete stale bans
  967. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  968. WHERE ban_end < ' . time() . '
  969. AND ban_end <> 0';
  970. $db->sql_query($sql);
  971. if (!is_array($ban))
  972. {
  973. $ban = array($ban);
  974. }
  975. $unban_sql = array_map('intval', $ban);
  976. if (sizeof($unban_sql))
  977. {
  978. // Grab details of bans for logging information later
  979. switch ($mode)
  980. {
  981. case 'user':
  982. $sql = 'SELECT u.username AS unban_info, u.user_id
  983. FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
  984. WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
  985. AND u.user_id = b.ban_userid';
  986. break;
  987. case 'email':
  988. $sql = 'SELECT ban_email AS unban_info
  989. FROM ' . BANLIST_TABLE . '
  990. WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
  991. break;
  992. case 'ip':
  993. $sql = 'SELECT ban_ip AS unban_info
  994. FROM ' . BANLIST_TABLE . '
  995. WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
  996. break;
  997. }
  998. $result = $db->sql_query($sql);
  999. $l_unban_list = '';
  1000. $user_ids_ary = array();
  1001. while ($row = $db->sql_fetchrow($result))
  1002. {
  1003. $l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
  1004. if ($mode == 'user')
  1005. {
  1006. $user_ids_ary[] = $row['user_id'];
  1007. }
  1008. }
  1009. $db->sql_freeresult($result);
  1010. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  1011. WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
  1012. $db->sql_query($sql);
  1013. // Add to moderator log, admin log and user notes
  1014. add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
  1015. add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
  1016. if ($mode == 'user')
  1017. {
  1018. foreach ($user_ids_ary as $user_id)
  1019. {
  1020. add_log('user', $user_id, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
  1021. }
  1022. }
  1023. }
  1024. $cache->destroy('sql', BANLIST_TABLE);
  1025. return false;
  1026. }
  1027. /**
  1028. * Whois facility
  1029. *
  1030. * @link http://tools.ietf.org/html/rfc3912 RFC3912: WHOIS Protocol Specification
  1031. */
  1032. function user_ipwhois($ip)
  1033. {
  1034. $ipwhois = '';
  1035. // Check IP
  1036. // Only supporting IPv4 at the moment...
  1037. if (empty($ip) || !preg_match(get_preg_expression('ipv4'), $ip))
  1038. {
  1039. return '';
  1040. }
  1041. if (($fsk = @fsockopen('whois.arin.net', 43)))
  1042. {
  1043. // CRLF as per RFC3912
  1044. fputs($fsk, "$ip\r\n");
  1045. while (!feof($fsk))
  1046. {
  1047. $ipwhois .= fgets($fsk, 1024);
  1048. }
  1049. @fclose($fsk);
  1050. }
  1051. $match = array();
  1052. // Test for referrals from ARIN to other whois databases, roll on rwhois
  1053. if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
  1054. {
  1055. if (strpos($match[1], ':') !== false)
  1056. {
  1057. $pos = strrpos($match[1], ':');
  1058. $server = substr($match[1], 0, $pos);
  1059. $port = (int) substr($match[1], $pos + 1);
  1060. unset($pos);
  1061. }
  1062. else
  1063. {
  1064. $server = $match[1];
  1065. $port = 43;
  1066. }
  1067. $buffer = '';
  1068. if (($fsk = @fsockopen($server, $port)))
  1069. {
  1070. fputs($fsk, "$ip\r\n");
  1071. while (!feof($fsk))
  1072. {
  1073. $buffer .= fgets($fsk, 1024);
  1074. }
  1075. @fclose($fsk);
  1076. }
  1077. // Use the result from ARIN if we don't get any result here
  1078. $ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
  1079. }
  1080. $ipwhois = htmlspecialchars($ipwhois);
  1081. // Magic URL ;)
  1082. return trim(make_clickable($ipwhois, false, ''));
  1083. }
  1084. /**
  1085. * Data validation ... used primarily but not exclusively by ucp modules
  1086. *
  1087. * "Master" function for validating a range of data types
  1088. */
  1089. function validate_data($data, $val_ary)
  1090. {
  1091. global $user;
  1092. $error = array();
  1093. foreach ($val_ary as $var => $val_seq)
  1094. {
  1095. if (!is_array($val_seq[0]))
  1096. {
  1097. $val_seq = array($val_seq);
  1098. }
  1099. foreach ($val_seq as $validate)
  1100. {
  1101. $function = array_shift($validate);
  1102. array_unshift($validate, $data[$var]);
  1103. if ($result = call_user_func_array('validate_' . $function, $validate))
  1104. {
  1105. // Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
  1106. $error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
  1107. }
  1108. }
  1109. }
  1110. return $error;
  1111. }
  1112. /**
  1113. * Validate String
  1114. *
  1115. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1116. */
  1117. function validate_string($string, $optional = false, $min = 0, $max = 0)
  1118. {
  1119. if (empty($string) && $optional)
  1120. {
  1121. return false;
  1122. }
  1123. if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
  1124. {
  1125. return 'TOO_SHORT';
  1126. }
  1127. else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
  1128. {
  1129. return 'TOO_LONG';
  1130. }
  1131. return false;
  1132. }
  1133. /**
  1134. * Validate Number
  1135. *
  1136. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1137. */
  1138. function validate_num($num, $optional = false, $min = 0, $max = 1E99)
  1139. {
  1140. if (empty($num) && $optional)
  1141. {
  1142. return false;
  1143. }
  1144. if ($num < $min)
  1145. {
  1146. return 'TOO_SMALL';
  1147. }
  1148. else if ($num > $max)
  1149. {
  1150. return 'TOO_LARGE';
  1151. }
  1152. return false;
  1153. }
  1154. /**
  1155. * Validate Date
  1156. * @param String $string a date in the dd-mm-yyyy format
  1157. * @return boolean
  1158. */
  1159. function validate_date($date_string, $optional = false)
  1160. {
  1161. $date = explode('-', $date_string);
  1162. if ((empty($date) || sizeof($date) != 3) && $optional)
  1163. {
  1164. return false;
  1165. }
  1166. else if ($optional)
  1167. {
  1168. for ($field = 0; $field <= 1; $field++)
  1169. {
  1170. $date[$field] = (int) $date[$field];
  1171. if (empty($date[$field]))
  1172. {
  1173. $date[$field] = 1;
  1174. }
  1175. }
  1176. $date[2] = (int) $date[2];
  1177. // assume an arbitrary leap year
  1178. if (empty($date[2]))
  1179. {
  1180. $date[2] = 1980;
  1181. }
  1182. }
  1183. if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
  1184. {
  1185. return 'INVALID';
  1186. }
  1187. return false;
  1188. }
  1189. /**
  1190. * Validate Match
  1191. *
  1192. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1193. */
  1194. function validate_match($string, $optional = false, $match = '')
  1195. {
  1196. if (empty($string) && $optional)
  1197. {
  1198. return false;
  1199. }
  1200. if (empty($match))
  1201. {
  1202. return false;
  1203. }
  1204. if (!preg_match($match, $string))
  1205. {
  1206. return 'WRONG_DATA';
  1207. }
  1208. return false;
  1209. }
  1210. /**
  1211. * Check to see if the username has been taken, or if it is disallowed.
  1212. * Also checks if it includes the " character, which we don't allow in usernames.
  1213. * Used for registering, changing names, and posting anonymously with a username
  1214. *
  1215. * @param string $username The username to check
  1216. * @param string $allowed_username An allowed username, default being $user->data['username']
  1217. *
  1218. * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1219. */
  1220. function validate_username($username, $allowed_username = false)
  1221. {
  1222. global $config, $db, $user, $cache;
  1223. $clean_username = utf8_clean_string($username);
  1224. $allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
  1225. if ($allowed_username == $clean_username)
  1226. {
  1227. return false;
  1228. }
  1229. // ... fast checks first.
  1230. if (strpos($username, '&quot;') !== false || strpos($username, '"') !== false || empty($clean_username))
  1231. {
  1232. return 'INVALID_CHARS';
  1233. }
  1234. $mbstring = $pcre = false;
  1235. // generic UTF-8 character types supported?
  1236. if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
  1237. {
  1238. $pcre = true;
  1239. }
  1240. else if (function_exists('mb_ereg_match'))
  1241. {
  1242. mb_regex_encoding('UTF-8');
  1243. $mbstring = true;
  1244. }
  1245. switch ($config['allow_name_chars'])
  1246. {
  1247. case 'USERNAME_CHARS_ANY':
  1248. $pcre = true;
  1249. $regex = '.+';
  1250. break;
  1251. case 'USERNAME_ALPHA_ONLY':
  1252. $pcre = true;
  1253. $regex = '[A-Za-z0-9]+';
  1254. break;
  1255. case 'USERNAME_ALPHA_SPACERS':
  1256. $pcre = true;
  1257. $regex = '[A-Za-z0-9-[\]_+ ]+';
  1258. break;
  1259. case 'USERNAME_LETTER_NUM':
  1260. if ($pcre)
  1261. {
  1262. $regex = '[\p{Lu}\p{Ll}\p{N}]+';
  1263. }
  1264. else if ($mbstring)
  1265. {
  1266. $regex = '[[:upper:][:lower:][:digit:]]+';
  1267. }
  1268. else
  1269. {
  1270. $pcre = true;
  1271. $regex = '[a-zA-Z0-9]+';
  1272. }
  1273. break;
  1274. case 'USERNAME_LETTER_NUM_SPACERS':
  1275. if ($pcre)
  1276. {
  1277. $regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
  1278. }
  1279. else if ($mbstring)
  1280. {
  1281. $regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
  1282. }
  1283. else
  1284. {
  1285. $pcre = true;
  1286. $regex = '[-\]_+ [a-zA-Z0-9]+';
  1287. }
  1288. break;
  1289. case 'USERNAME_ASCII':
  1290. default:
  1291. $pcre = true;
  1292. $regex = '[\x01-\x7F]+';
  1293. break;
  1294. }
  1295. if ($pcre)
  1296. {
  1297. if (!preg_match('#^' . $regex . '$#u', $username))
  1298. {
  1299. return 'INVALID_CHARS';
  1300. }
  1301. }
  1302. else if ($mbstring)
  1303. {
  1304. mb_ereg_search_init($username, '^' . $regex . '$');
  1305. if (!mb_ereg_search())
  1306. {
  1307. return 'INVALID_CHARS';
  1308. }
  1309. }
  1310. $sql = 'SELECT username
  1311. FROM ' . USERS_TABLE . "
  1312. WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
  1313. $result = $db->sql_query($sql);
  1314. $row = $db->sql_fetchrow($result);
  1315. $db->sql_freeresult($result);
  1316. if ($row)
  1317. {
  1318. return 'USERNAME_TAKEN';
  1319. }
  1320. $sql = 'SELECT group_name
  1321. FROM ' . GROUPS_TABLE . "
  1322. WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
  1323. $result = $db->sql_query($sql);
  1324. $row = $db->sql_fetchrow($result);
  1325. $db->sql_freeresult($result);
  1326. if ($row)
  1327. {
  1328. return 'USERNAME_TAKEN';
  1329. }
  1330. $bad_usernames = $cache->obtain_disallowed_usernames();
  1331. foreach ($bad_usernames as $bad_username)
  1332. {
  1333. if (preg_match('#^' . $bad_username . '$#', $clean_username))
  1334. {
  1335. return 'USERNAME_DISALLOWED';
  1336. }
  1337. }
  1338. return false;
  1339. }
  1340. /**
  1341. * Check to see if the password meets the complexity settings
  1342. *
  1343. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1344. */
  1345. function validate_password($password)
  1346. {
  1347. global $config, $db, $user;
  1348. if (!$password)
  1349. {
  1350. return false;
  1351. }
  1352. $pcre = $mbstring = false;
  1353. // generic UTF-8 character types supported?
  1354. if ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false)
  1355. {
  1356. $upp = '\p{Lu}';
  1357. $low = '\p{Ll}';
  1358. $let = '\p{L}';
  1359. $num = '\p{N}';
  1360. $sym = '[^\p{Lu}\p{Ll}\p{N}]';
  1361. $pcre = true;
  1362. }
  1363. else if (function_exists('mb_ereg_match'))
  1364. {
  1365. mb_regex_encoding('UTF-8');
  1366. $upp = '[[:upper:]]';
  1367. $low = '[[:lower:]]';
  1368. $let = '[[:lower:][:upper:]]';
  1369. $num = '[[:digit:]]';
  1370. $sym = '[^[:upper:][:lower:][:digit:]]';
  1371. $mbstring = true;
  1372. }
  1373. else
  1374. {
  1375. $upp = '[A-Z]';
  1376. $low = '[a-z]';
  1377. $let = '[a-zA-Z]';
  1378. $num = '[0-9]';
  1379. $sym = '[^A-Za-z0-9]';
  1380. $pcre = true;
  1381. }
  1382. $chars = array();
  1383. switch ($config['pass_complex'])
  1384. {
  1385. case 'PASS_TYPE_CASE':
  1386. $chars[] = $low;
  1387. $chars[] = $upp;
  1388. break;
  1389. case 'PASS_TYPE_ALPHA':
  1390. $chars[] = $let;
  1391. $chars[] = $num;
  1392. break;
  1393. case 'PASS_TYPE_SYMBOL':
  1394. $chars[] = $low;
  1395. $chars[] = $upp;
  1396. $chars[] = $num;
  1397. $chars[] = $sym;
  1398. break;
  1399. }
  1400. if ($pcre)
  1401. {
  1402. foreach ($chars as $char)
  1403. {
  1404. if (!preg_match('#' . $char . '#u', $password))
  1405. {
  1406. return 'INVALID_CHARS';
  1407. }
  1408. }
  1409. }
  1410. else if ($mbstring)
  1411. {
  1412. foreach ($chars as $char)
  1413. {
  1414. if (mb_ereg($char, $password) === false)
  1415. {
  1416. return 'INVALID_CHARS';
  1417. }
  1418. }
  1419. }
  1420. return false;
  1421. }
  1422. /**
  1423. * Check to see if email address is banned or already present in the DB
  1424. *
  1425. * @param string $email The email to check
  1426. * @param string $allowed_email An allowed email, default being $user->data['user_email']
  1427. *
  1428. * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1429. */
  1430. function validate_email($email, $allowed_email = false)
  1431. {
  1432. global $config, $db, $user;
  1433. $email = strtolower($email);
  1434. $allowed_email = ($allowed_email === false) ? strtolower($user->data['user_email']) : strtolower($allowed_email);
  1435. if ($allowed_email == $email)
  1436. {
  1437. return false;
  1438. }
  1439. if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
  1440. {
  1441. return 'EMAIL_INVALID';
  1442. }
  1443. // Check MX record.
  1444. // The idea for this is from reading the UseBB blog/announcement. :)
  1445. if ($config['email_check_mx'])
  1446. {
  1447. list(, $domain) = explode('@', $email);
  1448. if (phpbb_checkdnsrr($domain, 'A') === false && phpbb_checkdnsrr($domain, 'MX') === false)
  1449. {
  1450. return 'DOMAIN_NO_MX_RECORD';
  1451. }
  1452. }
  1453. if (($ban_reason = $user->check_ban(false, false, $email, true)) !== false)
  1454. {
  1455. return ($ban_reason === true) ? 'EMAIL_BANNED' : $ban_reason;
  1456. }
  1457. if (!$config['allow_emailreuse'])
  1458. {
  1459. $sql = 'SELECT user_email_hash
  1460. FROM ' . USERS_TABLE . "
  1461. WHERE user_email_hash = " . $db->sql_escape(phpbb_email_hash($email));
  1462. $result = $db->sql_query($sql);
  1463. $row = $db->sql_fetchrow($result);
  1464. $db->sql_freeresult($result);
  1465. if ($row)
  1466. {
  1467. return 'EMAIL_TAKEN';
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. /**
  1473. * Validate jabber address
  1474. * Taken from the jabber class within flyspray (see author notes)
  1475. *
  1476. * @author flyspray.org
  1477. */
  1478. function validate_jabber($jid)
  1479. {
  1480. if (!$jid)
  1481. {
  1482. return false;
  1483. }
  1484. $seperator_pos = strpos($jid, '@');
  1485. if ($seperator_pos === false)
  1486. {
  1487. return 'WRONG_DATA';
  1488. }
  1489. $username = substr($jid, 0, $seperator_pos);
  1490. $realm = substr($jid, $seperator_pos + 1);
  1491. if (strlen($username) == 0 || strlen($realm) < 3)
  1492. {
  1493. return 'WRONG_DATA';
  1494. }
  1495. $arr = explode('.', $realm);
  1496. if (sizeof($arr) == 0)
  1497. {
  1498. return 'WRONG_DATA';
  1499. }
  1500. foreach ($arr as $part)
  1501. {
  1502. if (substr($part, 0, 1) == '-' || substr($part, -1, 1) == '-')
  1503. {
  1504. return 'WRONG_DATA';
  1505. }
  1506. if (!preg_match("@^[a-zA-Z0-9-.]+$@", $part))
  1507. {
  1508. return 'WRONG_DATA';
  1509. }
  1510. }
  1511. $boundary = array(array(0, 127), array(192, 223), array(224, 239), array(240, 247), array(248, 251), array(252, 253));
  1512. // Prohibited Characters RFC3454 + RFC3920
  1513. $prohibited = array(
  1514. // Table C.1.1
  1515. array(0x0020, 0x0020), // SPACE
  1516. // Table C.1.2
  1517. array(0x00A0, 0x00A0), // NO-BREAK SPACE
  1518. array(0x1680, 0x1680), // OGHAM SPACE MARK
  1519. array(0x2000, 0x2001), // EN QUAD
  1520. array(0x2001, 0x2001), // EM QUAD
  1521. array(0x2002, 0x2002), // EN SPACE
  1522. array(0x2003, 0x2003), // EM SPACE
  1523. array(0x2004, 0x2004), // THREE-PER-EM SPACE
  1524. array(0x2005, 0x2005), // FOUR-PER-EM SPACE
  1525. array(0x2006, 0x2006), // SIX-PER-EM SPACE
  1526. array(0x2007, 0x2007), // FIGURE SPACE
  1527. array(0x2008, 0x2008), // PUNCTUATION SPACE
  1528. array(0x2009, 0x2009), // THIN SPACE
  1529. array(0x200A, 0x200A), // HAIR SPACE
  1530. array(0x200B, 0x200B), // ZERO WIDTH SPACE
  1531. array(0x202F, 0x202F), // NARROW NO-BREAK SPACE
  1532. array(0x205F, 0x205F), // MEDIUM MATHEMATICAL SPACE
  1533. array(0x3000, 0x3000), // IDEOGRAPHIC SPACE
  1534. // Table C.2.1
  1535. array(0x0000, 0x001F), // [CONTROL CHARACTERS]
  1536. array(0x007F, 0x007F), // DELETE
  1537. // Table C.2.2
  1538. array(0x0080, 0x009F), // [CONTROL CHARACTERS]
  1539. array(0x06DD, 0x06DD), // ARABIC END OF AYAH
  1540. array(0x070F, 0x070F), // SYRIAC ABBREVIATION MARK
  1541. array(0x180E, 0x180E), // MONGOLIAN VOWEL SEPARATOR
  1542. array(0x200C, 0x200C), // ZERO WIDTH NON-JOINER
  1543. array(0x200D, 0x200D), // ZERO WIDTH JOINER
  1544. array(0x2028, 0x2028), // LINE SEPARATOR
  1545. array(0x2029, 0x2029), // PARAGRAPH SEPARATOR
  1546. array(0x2060, 0x2060), // WORD JOINER
  1547. array(0x2061, 0x2061), // FUNCTION APPLICATION
  1548. array(0x2062, 0x2062), // INVISIBLE TIMES
  1549. array(0x2063, 0x2063), // INVISIBLE SEPARATOR
  1550. array(0x206A, 0x206F), // [CONTROL CHARACTERS]
  1551. array(0xFEFF, 0xFEFF), // ZERO WIDTH NO-BREAK SPACE
  1552. array(0xFFF9, 0xFFFC), // [CONTROL CHARACTERS]
  1553. array(0x1D173, 0x1D17A), // [MUSICAL CONTROL CHARACTERS]
  1554. // Table C.3
  1555. array(0xE000, 0xF8FF), // [PRIVATE USE, PLANE 0]
  1556. array(0xF0000, 0xFFFFD), // [PRIVATE USE, PLANE 15]
  1557. array(0x100000, 0x10FFFD), // [PRIVATE USE, PLANE 16]
  1558. // Table C.4
  1559. array(0xFDD0, 0xFDEF), // [NONCHARACTER CODE POINTS]
  1560. array(0xFFFE, 0xFFFF), // [NONCHARACTER CODE POINTS]
  1561. array(0x1FFFE, 0x1FFFF), // [NONCHARACTER CODE POINTS]
  1562. array(0x2FFFE, 0x2FFFF), // [NONCHARACTER CODE POINTS]
  1563. array(0x3FFFE, 0x3FFFF), // [NONCHARACTER CODE POINTS]
  1564. array(0x4FFFE, 0x4FFFF), // [NONCHARACTER CODE POINTS]
  1565. array(0x5FFFE, 0x5FFFF), // [NONCHARACTER CODE POINTS]
  1566. array(0x6FFFE, 0x6FFFF), // [NONCHARACTER CODE POINTS]
  1567. array(0x7FFFE, 0x7FFFF), // [NONCHARACTER CODE POINTS]
  1568. array(0x8FFFE, 0x8FFFF), // [NONCHARACTER CODE POINTS]
  1569. array(0x9FFFE, 0x9FFFF), // [NONCHARACTER CODE POINTS]
  1570. array(0xAFFFE, 0xAFFFF), // [NONCHARACTER CODE POINTS]
  1571. array(0xBFFFE, 0xBFFFF), // [NONCHARACTER CODE POINTS]
  1572. array(0xCFFFE, 0xCFFFF), // [NONCHARACTER CODE POINTS]
  1573. array(0xDFFFE, 0xDFFFF), // [NONCHARACTER CODE POINTS]
  1574. array(0xEFFFE, 0xEFFFF), // [NONCHARACTER CODE POINTS]
  1575. array(0xFFFFE, 0xFFFFF), // [NONCHARACTER CODE POINTS]
  1576. array(0x10FFFE, 0x10FFFF), // [NONCHARACTER CODE POINTS]
  1577. // Table C.5
  1578. array(0xD800, 0xDFFF), // [SURROGATE CODES]
  1579. // Table C.6
  1580. array(0xFFF9, 0xFFF9), // INTERLINEAR ANNOTATION ANCHOR
  1581. array(0xFFFA, 0xFFFA), // INTERLINEAR ANNOTATION SEPARATOR
  1582. array(0xFFFB, 0xFFFB), // INTERLINEAR ANNOTATION TERMINATOR
  1583. array(0xFFFC, 0xFFFC), // OBJECT REPLACEMENT CHARACTER
  1584. array(0xFFFD, 0xFFFD), // REPLACEMENT CHARACTER
  1585. // Table C.7
  1586. array(0x2FF0, 0x2FFB), // [IDEOGRAPHIC DESCRIPTION CHARACTERS]
  1587. // Table C.8
  1588. array(0x0340, 0x0340), // COMBINING GRAVE TONE MARK
  1589. array(0x0341, 0x0341), // COMBINING ACUTE TONE MARK
  1590. array(0x200E, 0x200E), // LEFT-TO-RIGHT MARK
  1591. array(0x200F, 0x200F), // RIGHT-TO-LEFT MARK
  1592. array(0x202A, 0x202A), // LEFT-TO-RIGHT EMBEDDING
  1593. array(0x202B, 0x202B), // RIGHT-TO-LEFT EMBEDDING
  1594. array(0x202C, 0x202C), // POP DIRECTIONAL FORMATTING
  1595. array(0x202D, 0x202D), // LEFT-TO-RIGHT OVERRIDE
  1596. array(0x202E, 0x202E), // RIGHT-TO-LEFT OVERRIDE
  1597. array(0x206A, 0x206A), // INHIBIT SYMMETRIC SWAPPING
  1598. array(0x206B, 0x206B), // ACTIVATE SYMMETRIC SWAPPING
  1599. array(0x206C, 0x206C), // INHIBIT ARABIC FORM SHAPING
  1600. array(0x206D, 0x206D), // ACTIVATE ARABIC FORM SHAPING
  1601. array(0x206E, 0x206E), // NATIONAL DIGIT SHAPES
  1602. array(0x206F, 0x206F), // NOMINAL DIGIT SHAPES
  1603. // Table C.9
  1604. array(0xE0001, 0xE0001), // LANGUAGE TAG
  1605. array(0xE0020, 0xE007F), // [TAGGING CHARACTERS]
  1606. // RFC3920
  1607. array(0x22, 0x22), // "
  1608. array(0x26, 0x26), // &
  1609. array(0x27, 0x27), // '
  1610. array(0x2F, 0x2F), // /
  1611. array(0x3A, 0x3A), // :
  1612. array(0x3C, 0x3C), // <
  1613. array(0x3E, 0x3E), // >
  1614. array(0x40, 0x40) // @
  1615. );
  1616. $pos = 0;
  1617. $result = true;
  1618. while ($pos < strlen($username))
  1619. {
  1620. $len = $uni = 0;
  1621. for ($i = 0; $i <= 5; $i++)
  1622. {
  1623. if (ord($username[$pos]) >= $boundary[$i][0] && ord($username[$pos]) <= $boundary[$i][1])
  1624. {
  1625. $len = $i + 1;
  1626. $uni = (ord($username[$pos]) - $boundary[$i][0]) * pow(2, $i * 6);
  1627. for ($k = 1; $k < $len; $k++)
  1628. {
  1629. $uni += (ord($username[$pos + $k]) - 128) * pow(2, ($i - $k) * 6);
  1630. }
  1631. break;
  1632. }
  1633. }
  1634. if ($len == 0)
  1635. {
  1636. return 'WRONG_DATA';
  1637. }
  1638. foreach ($prohibited as $pval)
  1639. {
  1640. if ($uni >= $pval[0] && $uni <= $pval[1])
  1641. {
  1642. $result = false;
  1643. break 2;
  1644. }
  1645. }
  1646. $pos = $pos + $len;
  1647. }
  1648. if (!$result)
  1649. {
  1650. return 'WRONG_DATA';
  1651. }
  1652. return false;
  1653. }
  1654. /**
  1655. * Remove avatar
  1656. */
  1657. function avatar_delete($mode, $row, $clean_db = false)
  1658. {
  1659. global $phpbb_root_path, $config, $db, $user;
  1660. // Check if the users avatar is actually *not* a group avatar
  1661. if ($mode == 'user')
  1662. {
  1663. if (strpos($row['user_avatar'], 'g') === 0 || (((int)$row['user_avatar'] !== 0) && ((int)$row['user_a…

Large files files are truncated, but you can click here to view the full file