PageRenderTime 88ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 1ms

/phpBB/includes/functions_admin.php

https://github.com/Jipem/phpbb
PHP | 3192 lines | 2313 code | 496 blank | 383 comment | 396 complexity | 58c31ddfb69643e0608b8a18198fda36 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. *
  4. * This file is part of the phpBB Forum Software package.
  5. *
  6. * @copyright (c) phpBB Limited <https://www.phpbb.com>
  7. * @license GNU General Public License, version 2 (GPL-2.0)
  8. *
  9. * For full copyright and license information, please see
  10. * the docs/CREDITS.txt file.
  11. *
  12. */
  13. /**
  14. * @ignore
  15. */
  16. if (!defined('IN_PHPBB'))
  17. {
  18. exit;
  19. }
  20. /**
  21. * Recalculate Nested Sets
  22. *
  23. * @param int $new_id first left_id (should start with 1)
  24. * @param string $pkey primary key-column (containing the id for the parent_id of the children)
  25. * @param string $table constant or fullname of the table
  26. * @param int $parent_id parent_id of the current set (default = 0)
  27. * @param array $where contains strings to compare closer on the where statement (additional)
  28. *
  29. * @author EXreaction
  30. */
  31. function recalc_nested_sets(&$new_id, $pkey, $table, $parent_id = 0, $where = array())
  32. {
  33. global $db;
  34. $sql = 'SELECT *
  35. FROM ' . $table . '
  36. WHERE parent_id = ' . (int) $parent_id .
  37. ((!empty($where)) ? ' AND ' . implode(' AND ', $where) : '') . '
  38. ORDER BY left_id ASC';
  39. $result = $db->sql_query($sql);
  40. while ($row = $db->sql_fetchrow($result))
  41. {
  42. // First we update the left_id for this module
  43. if ($row['left_id'] != $new_id)
  44. {
  45. $db->sql_query('UPDATE ' . $table . ' SET ' . $db->sql_build_array('UPDATE', array('left_id' => $new_id)) . " WHERE $pkey = {$row[$pkey]}");
  46. }
  47. $new_id++;
  48. // Then we go through any children and update their left/right id's
  49. recalc_nested_sets($new_id, $pkey, $table, $row[$pkey], $where);
  50. // Then we come back and update the right_id for this module
  51. if ($row['right_id'] != $new_id)
  52. {
  53. $db->sql_query('UPDATE ' . $table . ' SET ' . $db->sql_build_array('UPDATE', array('right_id' => $new_id)) . " WHERE $pkey = {$row[$pkey]}");
  54. }
  55. $new_id++;
  56. }
  57. $db->sql_freeresult($result);
  58. }
  59. /**
  60. * Simple version of jumpbox, just lists authed forums
  61. */
  62. function make_forum_select($select_id = false, $ignore_id = false, $ignore_acl = false, $ignore_nonpost = false, $ignore_emptycat = true, $only_acl_post = false, $return_array = false)
  63. {
  64. global $db, $user, $auth;
  65. // This query is identical to the jumpbox one
  66. $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, forum_flags, forum_options, left_id, right_id
  67. FROM ' . FORUMS_TABLE . '
  68. ORDER BY left_id ASC';
  69. $result = $db->sql_query($sql, 600);
  70. $right = 0;
  71. $padding_store = array('0' => '');
  72. $padding = '';
  73. $forum_list = ($return_array) ? array() : '';
  74. // Sometimes it could happen that forums will be displayed here not be displayed within the index page
  75. // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
  76. // If this happens, the padding could be "broken"
  77. while ($row = $db->sql_fetchrow($result))
  78. {
  79. if ($row['left_id'] < $right)
  80. {
  81. $padding .= '&nbsp; &nbsp;';
  82. $padding_store[$row['parent_id']] = $padding;
  83. }
  84. else if ($row['left_id'] > $right + 1)
  85. {
  86. $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : '';
  87. }
  88. $right = $row['right_id'];
  89. $disabled = false;
  90. if (!$ignore_acl && $auth->acl_gets(array('f_list', 'a_forum', 'a_forumadd', 'a_forumdel'), $row['forum_id']))
  91. {
  92. if ($only_acl_post && !$auth->acl_get('f_post', $row['forum_id']) || (!$auth->acl_get('m_approve', $row['forum_id']) && !$auth->acl_get('f_noapprove', $row['forum_id'])))
  93. {
  94. $disabled = true;
  95. }
  96. }
  97. else if (!$ignore_acl)
  98. {
  99. continue;
  100. }
  101. if (
  102. ((is_array($ignore_id) && in_array($row['forum_id'], $ignore_id)) || $row['forum_id'] == $ignore_id)
  103. ||
  104. // Non-postable forum with no subforums, don't display
  105. ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']) && $ignore_emptycat)
  106. ||
  107. ($row['forum_type'] != FORUM_POST && $ignore_nonpost)
  108. )
  109. {
  110. $disabled = true;
  111. }
  112. if ($return_array)
  113. {
  114. // Include some more information...
  115. $selected = (is_array($select_id)) ? ((in_array($row['forum_id'], $select_id)) ? true : false) : (($row['forum_id'] == $select_id) ? true : false);
  116. $forum_list[$row['forum_id']] = array_merge(array('padding' => $padding, 'selected' => ($selected && !$disabled), 'disabled' => $disabled), $row);
  117. }
  118. else
  119. {
  120. $selected = (is_array($select_id)) ? ((in_array($row['forum_id'], $select_id)) ? ' selected="selected"' : '') : (($row['forum_id'] == $select_id) ? ' selected="selected"' : '');
  121. $forum_list .= '<option value="' . $row['forum_id'] . '"' . (($disabled) ? ' disabled="disabled" class="disabled-option"' : $selected) . '>' . $padding . $row['forum_name'] . '</option>';
  122. }
  123. }
  124. $db->sql_freeresult($result);
  125. unset($padding_store);
  126. return $forum_list;
  127. }
  128. /**
  129. * Generate size select options
  130. */
  131. function size_select_options($size_compare)
  132. {
  133. global $user;
  134. $size_types_text = array($user->lang['BYTES'], $user->lang['KIB'], $user->lang['MIB']);
  135. $size_types = array('b', 'kb', 'mb');
  136. $s_size_options = '';
  137. for ($i = 0, $size = sizeof($size_types_text); $i < $size; $i++)
  138. {
  139. $selected = ($size_compare == $size_types[$i]) ? ' selected="selected"' : '';
  140. $s_size_options .= '<option value="' . $size_types[$i] . '"' . $selected . '>' . $size_types_text[$i] . '</option>';
  141. }
  142. return $s_size_options;
  143. }
  144. /**
  145. * Generate list of groups (option fields without select)
  146. *
  147. * @param int $group_id The default group id to mark as selected
  148. * @param array $exclude_ids The group ids to exclude from the list, false (default) if you whish to exclude no id
  149. * @param int $manage_founder If set to false (default) all groups are returned, if 0 only those groups returned not being managed by founders only, if 1 only those groups returned managed by founders only.
  150. *
  151. * @return string The list of options.
  152. */
  153. function group_select_options($group_id, $exclude_ids = false, $manage_founder = false)
  154. {
  155. global $db, $user, $config;
  156. $exclude_sql = ($exclude_ids !== false && sizeof($exclude_ids)) ? 'WHERE ' . $db->sql_in_set('group_id', array_map('intval', $exclude_ids), true) : '';
  157. $sql_and = (!$config['coppa_enable']) ? (($exclude_sql) ? ' AND ' : ' WHERE ') . "group_name <> 'REGISTERED_COPPA'" : '';
  158. $sql_founder = ($manage_founder !== false) ? (($exclude_sql || $sql_and) ? ' AND ' : ' WHERE ') . 'group_founder_manage = ' . (int) $manage_founder : '';
  159. $sql = 'SELECT group_id, group_name, group_type
  160. FROM ' . GROUPS_TABLE . "
  161. $exclude_sql
  162. $sql_and
  163. $sql_founder
  164. ORDER BY group_type DESC, group_name ASC";
  165. $result = $db->sql_query($sql);
  166. $s_group_options = '';
  167. while ($row = $db->sql_fetchrow($result))
  168. {
  169. $selected = ($row['group_id'] == $group_id) ? ' selected="selected"' : '';
  170. $s_group_options .= '<option' . (($row['group_type'] == GROUP_SPECIAL) ? ' class="sep"' : '') . ' value="' . $row['group_id'] . '"' . $selected . '>' . (($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name']) . '</option>';
  171. }
  172. $db->sql_freeresult($result);
  173. return $s_group_options;
  174. }
  175. /**
  176. * Obtain authed forums list
  177. */
  178. function get_forum_list($acl_list = 'f_list', $id_only = true, $postable_only = false, $no_cache = false)
  179. {
  180. global $db, $auth;
  181. static $forum_rows;
  182. if (!isset($forum_rows))
  183. {
  184. // This query is identical to the jumpbox one
  185. $expire_time = ($no_cache) ? 0 : 600;
  186. $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
  187. FROM ' . FORUMS_TABLE . '
  188. ORDER BY left_id ASC';
  189. $result = $db->sql_query($sql, $expire_time);
  190. $forum_rows = array();
  191. $right = $padding = 0;
  192. $padding_store = array('0' => 0);
  193. while ($row = $db->sql_fetchrow($result))
  194. {
  195. if ($row['left_id'] < $right)
  196. {
  197. $padding++;
  198. $padding_store[$row['parent_id']] = $padding;
  199. }
  200. else if ($row['left_id'] > $right + 1)
  201. {
  202. // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
  203. // @todo digging deep to find out "how" this can happen.
  204. $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
  205. }
  206. $right = $row['right_id'];
  207. $row['padding'] = $padding;
  208. $forum_rows[] = $row;
  209. }
  210. $db->sql_freeresult($result);
  211. unset($padding_store);
  212. }
  213. $rowset = array();
  214. foreach ($forum_rows as $row)
  215. {
  216. if ($postable_only && $row['forum_type'] != FORUM_POST)
  217. {
  218. continue;
  219. }
  220. if ($acl_list == '' || ($acl_list != '' && $auth->acl_gets($acl_list, $row['forum_id'])))
  221. {
  222. $rowset[] = ($id_only) ? (int) $row['forum_id'] : $row;
  223. }
  224. }
  225. return $rowset;
  226. }
  227. /**
  228. * Get forum branch
  229. */
  230. function get_forum_branch($forum_id, $type = 'all', $order = 'descending', $include_forum = true)
  231. {
  232. global $db;
  233. switch ($type)
  234. {
  235. case 'parents':
  236. $condition = 'f1.left_id BETWEEN f2.left_id AND f2.right_id';
  237. break;
  238. case 'children':
  239. $condition = 'f2.left_id BETWEEN f1.left_id AND f1.right_id';
  240. break;
  241. default:
  242. $condition = 'f2.left_id BETWEEN f1.left_id AND f1.right_id OR f1.left_id BETWEEN f2.left_id AND f2.right_id';
  243. break;
  244. }
  245. $rows = array();
  246. $sql = 'SELECT f2.*
  247. FROM ' . FORUMS_TABLE . ' f1
  248. LEFT JOIN ' . FORUMS_TABLE . " f2 ON ($condition)
  249. WHERE f1.forum_id = $forum_id
  250. ORDER BY f2.left_id " . (($order == 'descending') ? 'ASC' : 'DESC');
  251. $result = $db->sql_query($sql);
  252. while ($row = $db->sql_fetchrow($result))
  253. {
  254. if (!$include_forum && $row['forum_id'] == $forum_id)
  255. {
  256. continue;
  257. }
  258. $rows[] = $row;
  259. }
  260. $db->sql_freeresult($result);
  261. return $rows;
  262. }
  263. /**
  264. * Copies permissions from one forum to others
  265. *
  266. * @param int $src_forum_id The source forum we want to copy permissions from
  267. * @param array $dest_forum_ids The destination forum(s) we want to copy to
  268. * @param bool $clear_dest_perms True if destination permissions should be deleted
  269. * @param bool $add_log True if log entry should be added
  270. *
  271. * @return bool False on error
  272. *
  273. * @author bantu
  274. */
  275. function copy_forum_permissions($src_forum_id, $dest_forum_ids, $clear_dest_perms = true, $add_log = true)
  276. {
  277. global $db;
  278. // Only one forum id specified
  279. if (!is_array($dest_forum_ids))
  280. {
  281. $dest_forum_ids = array($dest_forum_ids);
  282. }
  283. // Make sure forum ids are integers
  284. $src_forum_id = (int) $src_forum_id;
  285. $dest_forum_ids = array_map('intval', $dest_forum_ids);
  286. // No source forum or no destination forums specified
  287. if (empty($src_forum_id) || empty($dest_forum_ids))
  288. {
  289. return false;
  290. }
  291. // Check if source forum exists
  292. $sql = 'SELECT forum_name
  293. FROM ' . FORUMS_TABLE . '
  294. WHERE forum_id = ' . $src_forum_id;
  295. $result = $db->sql_query($sql);
  296. $src_forum_name = $db->sql_fetchfield('forum_name');
  297. $db->sql_freeresult($result);
  298. // Source forum doesn't exist
  299. if (empty($src_forum_name))
  300. {
  301. return false;
  302. }
  303. // Check if destination forums exists
  304. $sql = 'SELECT forum_id, forum_name
  305. FROM ' . FORUMS_TABLE . '
  306. WHERE ' . $db->sql_in_set('forum_id', $dest_forum_ids);
  307. $result = $db->sql_query($sql);
  308. $dest_forum_ids = $dest_forum_names = array();
  309. while ($row = $db->sql_fetchrow($result))
  310. {
  311. $dest_forum_ids[] = (int) $row['forum_id'];
  312. $dest_forum_names[] = $row['forum_name'];
  313. }
  314. $db->sql_freeresult($result);
  315. // No destination forum exists
  316. if (empty($dest_forum_ids))
  317. {
  318. return false;
  319. }
  320. // From the mysql documentation:
  321. // Prior to MySQL 4.0.14, the target table of the INSERT statement cannot appear
  322. // in the FROM clause of the SELECT part of the query. This limitation is lifted in 4.0.14.
  323. // Due to this we stay on the safe side if we do the insertion "the manual way"
  324. // Rowsets we're going to insert
  325. $users_sql_ary = $groups_sql_ary = array();
  326. // Query acl users table for source forum data
  327. $sql = 'SELECT user_id, auth_option_id, auth_role_id, auth_setting
  328. FROM ' . ACL_USERS_TABLE . '
  329. WHERE forum_id = ' . $src_forum_id;
  330. $result = $db->sql_query($sql);
  331. while ($row = $db->sql_fetchrow($result))
  332. {
  333. $row = array(
  334. 'user_id' => (int) $row['user_id'],
  335. 'auth_option_id' => (int) $row['auth_option_id'],
  336. 'auth_role_id' => (int) $row['auth_role_id'],
  337. 'auth_setting' => (int) $row['auth_setting'],
  338. );
  339. foreach ($dest_forum_ids as $dest_forum_id)
  340. {
  341. $users_sql_ary[] = $row + array('forum_id' => $dest_forum_id);
  342. }
  343. }
  344. $db->sql_freeresult($result);
  345. // Query acl groups table for source forum data
  346. $sql = 'SELECT group_id, auth_option_id, auth_role_id, auth_setting
  347. FROM ' . ACL_GROUPS_TABLE . '
  348. WHERE forum_id = ' . $src_forum_id;
  349. $result = $db->sql_query($sql);
  350. while ($row = $db->sql_fetchrow($result))
  351. {
  352. $row = array(
  353. 'group_id' => (int) $row['group_id'],
  354. 'auth_option_id' => (int) $row['auth_option_id'],
  355. 'auth_role_id' => (int) $row['auth_role_id'],
  356. 'auth_setting' => (int) $row['auth_setting'],
  357. );
  358. foreach ($dest_forum_ids as $dest_forum_id)
  359. {
  360. $groups_sql_ary[] = $row + array('forum_id' => $dest_forum_id);
  361. }
  362. }
  363. $db->sql_freeresult($result);
  364. $db->sql_transaction('begin');
  365. // Clear current permissions of destination forums
  366. if ($clear_dest_perms)
  367. {
  368. $sql = 'DELETE FROM ' . ACL_USERS_TABLE . '
  369. WHERE ' . $db->sql_in_set('forum_id', $dest_forum_ids);
  370. $db->sql_query($sql);
  371. $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . '
  372. WHERE ' . $db->sql_in_set('forum_id', $dest_forum_ids);
  373. $db->sql_query($sql);
  374. }
  375. $db->sql_multi_insert(ACL_USERS_TABLE, $users_sql_ary);
  376. $db->sql_multi_insert(ACL_GROUPS_TABLE, $groups_sql_ary);
  377. if ($add_log)
  378. {
  379. add_log('admin', 'LOG_FORUM_COPIED_PERMISSIONS', $src_forum_name, implode(', ', $dest_forum_names));
  380. }
  381. $db->sql_transaction('commit');
  382. return true;
  383. }
  384. /**
  385. * Get physical file listing
  386. */
  387. function filelist($rootdir, $dir = '', $type = 'gif|jpg|jpeg|png')
  388. {
  389. $matches = array($dir => array());
  390. // Remove initial / if present
  391. $rootdir = (substr($rootdir, 0, 1) == '/') ? substr($rootdir, 1) : $rootdir;
  392. // Add closing / if not present
  393. $rootdir = ($rootdir && substr($rootdir, -1) != '/') ? $rootdir . '/' : $rootdir;
  394. // Remove initial / if present
  395. $dir = (substr($dir, 0, 1) == '/') ? substr($dir, 1) : $dir;
  396. // Add closing / if not present
  397. $dir = ($dir && substr($dir, -1) != '/') ? $dir . '/' : $dir;
  398. if (!is_dir($rootdir . $dir))
  399. {
  400. return $matches;
  401. }
  402. $dh = @opendir($rootdir . $dir);
  403. if (!$dh)
  404. {
  405. return $matches;
  406. }
  407. while (($fname = readdir($dh)) !== false)
  408. {
  409. if (is_file("$rootdir$dir$fname"))
  410. {
  411. if (filesize("$rootdir$dir$fname") && preg_match('#\.' . $type . '$#i', $fname))
  412. {
  413. $matches[$dir][] = $fname;
  414. }
  415. }
  416. else if ($fname[0] != '.' && is_dir("$rootdir$dir$fname"))
  417. {
  418. $matches += filelist($rootdir, "$dir$fname", $type);
  419. }
  420. }
  421. closedir($dh);
  422. return $matches;
  423. }
  424. /**
  425. * Move topic(s)
  426. */
  427. function move_topics($topic_ids, $forum_id, $auto_sync = true)
  428. {
  429. global $db;
  430. if (empty($topic_ids))
  431. {
  432. return;
  433. }
  434. $forum_ids = array($forum_id);
  435. if (!is_array($topic_ids))
  436. {
  437. $topic_ids = array($topic_ids);
  438. }
  439. $sql = 'DELETE FROM ' . TOPICS_TABLE . '
  440. WHERE ' . $db->sql_in_set('topic_moved_id', $topic_ids) . '
  441. AND forum_id = ' . $forum_id;
  442. $db->sql_query($sql);
  443. if ($auto_sync)
  444. {
  445. $sql = 'SELECT DISTINCT forum_id
  446. FROM ' . TOPICS_TABLE . '
  447. WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
  448. $result = $db->sql_query($sql);
  449. while ($row = $db->sql_fetchrow($result))
  450. {
  451. $forum_ids[] = $row['forum_id'];
  452. }
  453. $db->sql_freeresult($result);
  454. }
  455. $table_ary = array(TOPICS_TABLE, POSTS_TABLE, LOG_TABLE, DRAFTS_TABLE, TOPICS_TRACK_TABLE);
  456. foreach ($table_ary as $table)
  457. {
  458. $sql = "UPDATE $table
  459. SET forum_id = $forum_id
  460. WHERE " . $db->sql_in_set('topic_id', $topic_ids);
  461. $db->sql_query($sql);
  462. }
  463. unset($table_ary);
  464. if ($auto_sync)
  465. {
  466. sync('forum', 'forum_id', $forum_ids, true, true);
  467. unset($forum_ids);
  468. }
  469. }
  470. /**
  471. * Move post(s)
  472. */
  473. function move_posts($post_ids, $topic_id, $auto_sync = true)
  474. {
  475. global $db;
  476. if (!is_array($post_ids))
  477. {
  478. $post_ids = array($post_ids);
  479. }
  480. $forum_ids = array();
  481. $topic_ids = array($topic_id);
  482. $sql = 'SELECT DISTINCT topic_id, forum_id
  483. FROM ' . POSTS_TABLE . '
  484. WHERE ' . $db->sql_in_set('post_id', $post_ids);
  485. $result = $db->sql_query($sql);
  486. while ($row = $db->sql_fetchrow($result))
  487. {
  488. $forum_ids[] = (int) $row['forum_id'];
  489. $topic_ids[] = (int) $row['topic_id'];
  490. }
  491. $db->sql_freeresult($result);
  492. $sql = 'SELECT forum_id
  493. FROM ' . TOPICS_TABLE . '
  494. WHERE topic_id = ' . $topic_id;
  495. $result = $db->sql_query($sql);
  496. $forum_row = $db->sql_fetchrow($result);
  497. $db->sql_freeresult($result);
  498. if (!$forum_row)
  499. {
  500. trigger_error('NO_TOPIC');
  501. }
  502. $sql = 'UPDATE ' . POSTS_TABLE . '
  503. SET forum_id = ' . (int) $forum_row['forum_id'] . ", topic_id = $topic_id
  504. WHERE " . $db->sql_in_set('post_id', $post_ids);
  505. $db->sql_query($sql);
  506. $sql = 'UPDATE ' . ATTACHMENTS_TABLE . "
  507. SET topic_id = $topic_id, in_message = 0
  508. WHERE " . $db->sql_in_set('post_msg_id', $post_ids);
  509. $db->sql_query($sql);
  510. if ($auto_sync)
  511. {
  512. $forum_ids[] = (int) $forum_row['forum_id'];
  513. sync('topic_reported', 'topic_id', $topic_ids);
  514. sync('topic_attachment', 'topic_id', $topic_ids);
  515. sync('topic', 'topic_id', $topic_ids, true);
  516. sync('forum', 'forum_id', $forum_ids, true, true);
  517. }
  518. // Update posted information
  519. update_posted_info($topic_ids);
  520. }
  521. /**
  522. * Remove topic(s)
  523. */
  524. function delete_topics($where_type, $where_ids, $auto_sync = true, $post_count_sync = true, $call_delete_posts = true)
  525. {
  526. global $db, $config, $phpbb_container;
  527. $approved_topics = 0;
  528. $forum_ids = $topic_ids = array();
  529. if ($where_type === 'range')
  530. {
  531. $where_clause = $where_ids;
  532. }
  533. else
  534. {
  535. $where_ids = (is_array($where_ids)) ? array_unique($where_ids) : array($where_ids);
  536. if (!sizeof($where_ids))
  537. {
  538. return array('topics' => 0, 'posts' => 0);
  539. }
  540. $where_clause = $db->sql_in_set($where_type, $where_ids);
  541. }
  542. // Making sure that delete_posts does not call delete_topics again...
  543. $return = array(
  544. 'posts' => ($call_delete_posts) ? delete_posts($where_type, $where_ids, false, true, $post_count_sync, false) : 0,
  545. );
  546. $sql = 'SELECT topic_id, forum_id, topic_visibility, topic_moved_id
  547. FROM ' . TOPICS_TABLE . '
  548. WHERE ' . $where_clause;
  549. $result = $db->sql_query($sql);
  550. while ($row = $db->sql_fetchrow($result))
  551. {
  552. $forum_ids[] = $row['forum_id'];
  553. $topic_ids[] = $row['topic_id'];
  554. if ($row['topic_visibility'] == ITEM_APPROVED && !$row['topic_moved_id'])
  555. {
  556. $approved_topics++;
  557. }
  558. }
  559. $db->sql_freeresult($result);
  560. $return['topics'] = sizeof($topic_ids);
  561. if (!sizeof($topic_ids))
  562. {
  563. return $return;
  564. }
  565. $db->sql_transaction('begin');
  566. $table_ary = array(BOOKMARKS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, POLL_VOTES_TABLE, POLL_OPTIONS_TABLE, TOPICS_WATCH_TABLE, TOPICS_TABLE);
  567. foreach ($table_ary as $table)
  568. {
  569. $sql = "DELETE FROM $table
  570. WHERE " . $db->sql_in_set('topic_id', $topic_ids);
  571. $db->sql_query($sql);
  572. }
  573. unset($table_ary);
  574. $moved_topic_ids = array();
  575. // update the other forums
  576. $sql = 'SELECT topic_id, forum_id
  577. FROM ' . TOPICS_TABLE . '
  578. WHERE ' . $db->sql_in_set('topic_moved_id', $topic_ids);
  579. $result = $db->sql_query($sql);
  580. while ($row = $db->sql_fetchrow($result))
  581. {
  582. $forum_ids[] = $row['forum_id'];
  583. $moved_topic_ids[] = $row['topic_id'];
  584. }
  585. $db->sql_freeresult($result);
  586. if (sizeof($moved_topic_ids))
  587. {
  588. $sql = 'DELETE FROM ' . TOPICS_TABLE . '
  589. WHERE ' . $db->sql_in_set('topic_id', $moved_topic_ids);
  590. $db->sql_query($sql);
  591. }
  592. $db->sql_transaction('commit');
  593. if ($auto_sync)
  594. {
  595. sync('forum', 'forum_id', array_unique($forum_ids), true, true);
  596. sync('topic_reported', $where_type, $where_ids);
  597. }
  598. if ($approved_topics)
  599. {
  600. set_config_count('num_topics', $approved_topics * (-1), true);
  601. }
  602. $phpbb_notifications = $phpbb_container->get('notification_manager');
  603. $phpbb_notifications->delete_notifications(array(
  604. 'topic',
  605. 'approve_topic',
  606. 'topic_in_queue',
  607. ), $topic_ids);
  608. return $return;
  609. }
  610. /**
  611. * Remove post(s)
  612. */
  613. function delete_posts($where_type, $where_ids, $auto_sync = true, $posted_sync = true, $post_count_sync = true, $call_delete_topics = true)
  614. {
  615. global $db, $config, $phpbb_root_path, $phpEx, $auth, $user, $phpbb_container, $phpbb_dispatcher;
  616. // Notifications types to delete
  617. $delete_notifications_types = array(
  618. 'quote',
  619. 'approve_post',
  620. 'post_in_queue',
  621. );
  622. /**
  623. * Perform additional actions before post(s) deletion
  624. *
  625. * @event core.delete_posts_before
  626. * @var string where_type Variable containing posts deletion mode
  627. * @var mixed where_ids Array or comma separated list of posts ids to delete
  628. * @var bool auto_sync Flag indicating if topics/forums should be synchronized
  629. * @var bool posted_sync Flag indicating if topics_posted table should be resynchronized
  630. * @var bool post_count_sync Flag indicating if posts count should be resynchronized
  631. * @var bool call_delete_topics Flag indicating if topics having no posts should be deleted
  632. * @var array delete_notifications_types Array with notifications types to delete
  633. * @since 3.1.0-a4
  634. */
  635. $vars = array(
  636. 'where_type',
  637. 'where_ids',
  638. 'auto_sync',
  639. 'posted_sync',
  640. 'post_count_sync',
  641. 'call_delete_topics',
  642. 'delete_notifications_types',
  643. );
  644. extract($phpbb_dispatcher->trigger_event('core.delete_posts_before', compact($vars)));
  645. if ($where_type === 'range')
  646. {
  647. $where_clause = $where_ids;
  648. }
  649. else
  650. {
  651. if (is_array($where_ids))
  652. {
  653. $where_ids = array_unique($where_ids);
  654. }
  655. else
  656. {
  657. $where_ids = array($where_ids);
  658. }
  659. if (!sizeof($where_ids))
  660. {
  661. return false;
  662. }
  663. $where_ids = array_map('intval', $where_ids);
  664. /* Possible code for splitting post deletion
  665. if (sizeof($where_ids) >= 1001)
  666. {
  667. // Split into chunks of 1000
  668. $chunks = array_chunk($where_ids, 1000);
  669. foreach ($chunks as $_where_ids)
  670. {
  671. delete_posts($where_type, $_where_ids, $auto_sync, $posted_sync, $post_count_sync, $call_delete_topics);
  672. }
  673. return;
  674. }*/
  675. $where_clause = $db->sql_in_set($where_type, $where_ids);
  676. }
  677. $approved_posts = 0;
  678. $post_ids = $topic_ids = $forum_ids = $post_counts = $remove_topics = array();
  679. $sql = 'SELECT post_id, poster_id, post_visibility, post_postcount, topic_id, forum_id
  680. FROM ' . POSTS_TABLE . '
  681. WHERE ' . $where_clause;
  682. $result = $db->sql_query($sql);
  683. while ($row = $db->sql_fetchrow($result))
  684. {
  685. $post_ids[] = (int) $row['post_id'];
  686. $poster_ids[] = (int) $row['poster_id'];
  687. $topic_ids[] = (int) $row['topic_id'];
  688. $forum_ids[] = (int) $row['forum_id'];
  689. if ($row['post_postcount'] && $post_count_sync && $row['post_visibility'] == ITEM_APPROVED)
  690. {
  691. $post_counts[$row['poster_id']] = (!empty($post_counts[$row['poster_id']])) ? $post_counts[$row['poster_id']] + 1 : 1;
  692. }
  693. if ($row['post_visibility'] == ITEM_APPROVED)
  694. {
  695. $approved_posts++;
  696. }
  697. }
  698. $db->sql_freeresult($result);
  699. if (!sizeof($post_ids))
  700. {
  701. return false;
  702. }
  703. $db->sql_transaction('begin');
  704. $table_ary = array(POSTS_TABLE, REPORTS_TABLE);
  705. foreach ($table_ary as $table)
  706. {
  707. $sql = "DELETE FROM $table
  708. WHERE " . $db->sql_in_set('post_id', $post_ids);
  709. $db->sql_query($sql);
  710. }
  711. unset($table_ary);
  712. // Adjust users post counts
  713. if (sizeof($post_counts) && $post_count_sync)
  714. {
  715. foreach ($post_counts as $poster_id => $substract)
  716. {
  717. $sql = 'UPDATE ' . USERS_TABLE . '
  718. SET user_posts = 0
  719. WHERE user_id = ' . $poster_id . '
  720. AND user_posts < ' . $substract;
  721. $db->sql_query($sql);
  722. $sql = 'UPDATE ' . USERS_TABLE . '
  723. SET user_posts = user_posts - ' . $substract . '
  724. WHERE user_id = ' . $poster_id . '
  725. AND user_posts >= ' . $substract;
  726. $db->sql_query($sql);
  727. }
  728. }
  729. // Remove topics now having no posts?
  730. if (sizeof($topic_ids))
  731. {
  732. $sql = 'SELECT topic_id
  733. FROM ' . POSTS_TABLE . '
  734. WHERE ' . $db->sql_in_set('topic_id', $topic_ids) . '
  735. GROUP BY topic_id';
  736. $result = $db->sql_query($sql);
  737. while ($row = $db->sql_fetchrow($result))
  738. {
  739. $remove_topics[] = $row['topic_id'];
  740. }
  741. $db->sql_freeresult($result);
  742. // Actually, those not within remove_topics should be removed. ;)
  743. $remove_topics = array_diff($topic_ids, $remove_topics);
  744. }
  745. // Remove the message from the search index
  746. $search_type = $config['search_type'];
  747. if (!class_exists($search_type))
  748. {
  749. trigger_error('NO_SUCH_SEARCH_MODULE');
  750. }
  751. $error = false;
  752. $search = new $search_type($error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user);
  753. if ($error)
  754. {
  755. trigger_error($error);
  756. }
  757. $search->index_remove($post_ids, $poster_ids, $forum_ids);
  758. delete_attachments('post', $post_ids, false);
  759. /**
  760. * Perform additional actions during post(s) deletion
  761. *
  762. * @event core.delete_posts_in_transaction
  763. * @var array post_ids Array with deleted posts' ids
  764. * @var array poster_ids Array with deleted posts' author ids
  765. * @var array topic_ids Array with deleted posts' topic ids
  766. * @var array forum_ids Array with deleted posts' forum ids
  767. * @var string where_type Variable containing posts deletion mode
  768. * @var mixed where_ids Array or comma separated list of posts ids to delete
  769. * @var array delete_notifications_types Array with notifications types to delete
  770. * @since 3.1.0-a4
  771. */
  772. $vars = array(
  773. 'post_ids',
  774. 'poster_ids',
  775. 'topic_ids',
  776. 'forum_ids',
  777. 'where_type',
  778. 'where_ids',
  779. 'delete_notifications_types',
  780. );
  781. extract($phpbb_dispatcher->trigger_event('core.delete_posts_in_transaction', compact($vars)));
  782. $db->sql_transaction('commit');
  783. /**
  784. * Perform additional actions after post(s) deletion
  785. *
  786. * @event core.delete_posts_after
  787. * @var array post_ids Array with deleted posts' ids
  788. * @var array poster_ids Array with deleted posts' author ids
  789. * @var array topic_ids Array with deleted posts' topic ids
  790. * @var array forum_ids Array with deleted posts' forum ids
  791. * @var string where_type Variable containing posts deletion mode
  792. * @var mixed where_ids Array or comma separated list of posts ids to delete
  793. * @var array delete_notifications_types Array with notifications types to delete
  794. * @since 3.1.0-a4
  795. */
  796. $vars = array(
  797. 'post_ids',
  798. 'poster_ids',
  799. 'topic_ids',
  800. 'forum_ids',
  801. 'where_type',
  802. 'where_ids',
  803. 'delete_notifications_types',
  804. );
  805. extract($phpbb_dispatcher->trigger_event('core.delete_posts_after', compact($vars)));
  806. // Resync topics_posted table
  807. if ($posted_sync)
  808. {
  809. update_posted_info($topic_ids);
  810. }
  811. if ($auto_sync)
  812. {
  813. sync('topic_reported', 'topic_id', $topic_ids);
  814. sync('topic', 'topic_id', $topic_ids, true);
  815. sync('forum', 'forum_id', $forum_ids, true, true);
  816. }
  817. if ($approved_posts && $post_count_sync)
  818. {
  819. set_config_count('num_posts', $approved_posts * (-1), true);
  820. }
  821. // We actually remove topics now to not be inconsistent (the delete_topics function calls this function too)
  822. if (sizeof($remove_topics) && $call_delete_topics)
  823. {
  824. delete_topics('topic_id', $remove_topics, $auto_sync, $post_count_sync, false);
  825. }
  826. $phpbb_notifications = $phpbb_container->get('notification_manager');
  827. $phpbb_notifications->delete_notifications($delete_notifications_types, $post_ids);
  828. return sizeof($post_ids);
  829. }
  830. /**
  831. * Delete Attachments
  832. *
  833. * @param string $mode can be: post|message|topic|attach|user
  834. * @param mixed $ids can be: post_ids, message_ids, topic_ids, attach_ids, user_ids
  835. * @param bool $resync set this to false if you are deleting posts or topics
  836. */
  837. function delete_attachments($mode, $ids, $resync = true)
  838. {
  839. global $db, $config;
  840. // 0 is as bad as an empty array
  841. if (empty($ids))
  842. {
  843. return false;
  844. }
  845. if (is_array($ids))
  846. {
  847. $ids = array_unique($ids);
  848. $ids = array_map('intval', $ids);
  849. }
  850. else
  851. {
  852. $ids = array((int) $ids);
  853. }
  854. $sql_where = '';
  855. switch ($mode)
  856. {
  857. case 'post':
  858. case 'message':
  859. $sql_id = 'post_msg_id';
  860. $sql_where = ' AND in_message = ' . ($mode == 'message' ? 1 : 0);
  861. break;
  862. case 'topic':
  863. $sql_id = 'topic_id';
  864. break;
  865. case 'user':
  866. $sql_id = 'poster_id';
  867. break;
  868. case 'attach':
  869. default:
  870. $sql_id = 'attach_id';
  871. $mode = 'attach';
  872. break;
  873. }
  874. $post_ids = $message_ids = $topic_ids = $physical = array();
  875. // Collect post and topic ids for later use if we need to touch remaining entries (if resync is enabled)
  876. $sql = 'SELECT post_msg_id, topic_id, in_message, physical_filename, thumbnail, filesize, is_orphan
  877. FROM ' . ATTACHMENTS_TABLE . '
  878. WHERE ' . $db->sql_in_set($sql_id, $ids);
  879. $sql .= $sql_where;
  880. $result = $db->sql_query($sql);
  881. while ($row = $db->sql_fetchrow($result))
  882. {
  883. // We only need to store post/message/topic ids if resync is enabled and the file is not orphaned
  884. if ($resync && !$row['is_orphan'])
  885. {
  886. if (!$row['in_message'])
  887. {
  888. $post_ids[] = $row['post_msg_id'];
  889. $topic_ids[] = $row['topic_id'];
  890. }
  891. else
  892. {
  893. $message_ids[] = $row['post_msg_id'];
  894. }
  895. }
  896. $physical[] = array('filename' => $row['physical_filename'], 'thumbnail' => $row['thumbnail'], 'filesize' => $row['filesize'], 'is_orphan' => $row['is_orphan']);
  897. }
  898. $db->sql_freeresult($result);
  899. // Delete attachments
  900. $sql = 'DELETE FROM ' . ATTACHMENTS_TABLE . '
  901. WHERE ' . $db->sql_in_set($sql_id, $ids);
  902. $sql .= $sql_where;
  903. $db->sql_query($sql);
  904. $num_deleted = $db->sql_affectedrows();
  905. if (!$num_deleted)
  906. {
  907. return 0;
  908. }
  909. // Delete attachments from filesystem
  910. $space_removed = $files_removed = 0;
  911. foreach ($physical as $file_ary)
  912. {
  913. if (phpbb_unlink($file_ary['filename'], 'file', true) && !$file_ary['is_orphan'])
  914. {
  915. // Only non-orphaned files count to the file size
  916. $space_removed += $file_ary['filesize'];
  917. $files_removed++;
  918. }
  919. if ($file_ary['thumbnail'])
  920. {
  921. phpbb_unlink($file_ary['filename'], 'thumbnail', true);
  922. }
  923. }
  924. if ($space_removed || $files_removed)
  925. {
  926. set_config_count('upload_dir_size', $space_removed * (-1), true);
  927. set_config_count('num_files', $files_removed * (-1), true);
  928. }
  929. // If we do not resync, we do not need to adjust any message, post, topic or user entries
  930. if (!$resync)
  931. {
  932. return $num_deleted;
  933. }
  934. // No more use for the original ids
  935. unset($ids);
  936. // Now, we need to resync posts, messages, topics. We go through every one of them
  937. $post_ids = array_unique($post_ids);
  938. $message_ids = array_unique($message_ids);
  939. $topic_ids = array_unique($topic_ids);
  940. // Update post indicators for posts now no longer having attachments
  941. if (sizeof($post_ids))
  942. {
  943. // Just check which posts are still having an assigned attachment not orphaned by querying the attachments table
  944. $sql = 'SELECT post_msg_id
  945. FROM ' . ATTACHMENTS_TABLE . '
  946. WHERE ' . $db->sql_in_set('post_msg_id', $post_ids) . '
  947. AND in_message = 0
  948. AND is_orphan = 0';
  949. $result = $db->sql_query($sql);
  950. $remaining_ids = array();
  951. while ($row = $db->sql_fetchrow($result))
  952. {
  953. $remaining_ids[] = $row['post_msg_id'];
  954. }
  955. $db->sql_freeresult($result);
  956. // Now only unset those ids remaining
  957. $post_ids = array_diff($post_ids, $remaining_ids);
  958. if (sizeof($post_ids))
  959. {
  960. $sql = 'UPDATE ' . POSTS_TABLE . '
  961. SET post_attachment = 0
  962. WHERE ' . $db->sql_in_set('post_id', $post_ids);
  963. $db->sql_query($sql);
  964. }
  965. }
  966. // Update message table if messages are affected
  967. if (sizeof($message_ids))
  968. {
  969. // Just check which messages are still having an assigned attachment not orphaned by querying the attachments table
  970. $sql = 'SELECT post_msg_id
  971. FROM ' . ATTACHMENTS_TABLE . '
  972. WHERE ' . $db->sql_in_set('post_msg_id', $message_ids) . '
  973. AND in_message = 1
  974. AND is_orphan = 0';
  975. $result = $db->sql_query($sql);
  976. $remaining_ids = array();
  977. while ($row = $db->sql_fetchrow($result))
  978. {
  979. $remaining_ids[] = $row['post_msg_id'];
  980. }
  981. $db->sql_freeresult($result);
  982. // Now only unset those ids remaining
  983. $message_ids = array_diff($message_ids, $remaining_ids);
  984. if (sizeof($message_ids))
  985. {
  986. $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
  987. SET message_attachment = 0
  988. WHERE ' . $db->sql_in_set('msg_id', $message_ids);
  989. $db->sql_query($sql);
  990. }
  991. }
  992. // Now update the topics. This is a bit trickier, because there could be posts still having attachments within the topic
  993. if (sizeof($topic_ids))
  994. {
  995. // Just check which topics are still having an assigned attachment not orphaned by querying the attachments table (much less entries expected)
  996. $sql = 'SELECT topic_id
  997. FROM ' . ATTACHMENTS_TABLE . '
  998. WHERE ' . $db->sql_in_set('topic_id', $topic_ids) . '
  999. AND is_orphan = 0';
  1000. $result = $db->sql_query($sql);
  1001. $remaining_ids = array();
  1002. while ($row = $db->sql_fetchrow($result))
  1003. {
  1004. $remaining_ids[] = $row['topic_id'];
  1005. }
  1006. $db->sql_freeresult($result);
  1007. // Now only unset those ids remaining
  1008. $topic_ids = array_diff($topic_ids, $remaining_ids);
  1009. if (sizeof($topic_ids))
  1010. {
  1011. $sql = 'UPDATE ' . TOPICS_TABLE . '
  1012. SET topic_attachment = 0
  1013. WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
  1014. $db->sql_query($sql);
  1015. }
  1016. }
  1017. return $num_deleted;
  1018. }
  1019. /**
  1020. * Deletes shadow topics pointing to a specified forum.
  1021. *
  1022. * @param int $forum_id The forum id
  1023. * @param string $sql_more Additional WHERE statement, e.g. t.topic_time < (time() - 1234)
  1024. * @param bool $auto_sync Will call sync() if this is true
  1025. *
  1026. * @return array Array with affected forums
  1027. *
  1028. * @author bantu
  1029. */
  1030. function delete_topic_shadows($forum_id, $sql_more = '', $auto_sync = true)
  1031. {
  1032. global $db;
  1033. if (!$forum_id)
  1034. {
  1035. // Nothing to do.
  1036. return;
  1037. }
  1038. // Set of affected forums we have to resync
  1039. $sync_forum_ids = array();
  1040. // Amount of topics we select and delete at once.
  1041. $batch_size = 500;
  1042. do
  1043. {
  1044. $sql = 'SELECT t2.forum_id, t2.topic_id
  1045. FROM ' . TOPICS_TABLE . ' t2, ' . TOPICS_TABLE . ' t
  1046. WHERE t2.topic_moved_id = t.topic_id
  1047. AND t.forum_id = ' . (int) $forum_id . '
  1048. ' . (($sql_more) ? 'AND ' . $sql_more : '');
  1049. $result = $db->sql_query_limit($sql, $batch_size);
  1050. $topic_ids = array();
  1051. while ($row = $db->sql_fetchrow($result))
  1052. {
  1053. $topic_ids[] = (int) $row['topic_id'];
  1054. $sync_forum_ids[(int) $row['forum_id']] = (int) $row['forum_id'];
  1055. }
  1056. $db->sql_freeresult($result);
  1057. if (!empty($topic_ids))
  1058. {
  1059. $sql = 'DELETE FROM ' . TOPICS_TABLE . '
  1060. WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
  1061. $db->sql_query($sql);
  1062. }
  1063. }
  1064. while (sizeof($topic_ids) == $batch_size);
  1065. if ($auto_sync)
  1066. {
  1067. sync('forum', 'forum_id', $sync_forum_ids, true, true);
  1068. }
  1069. return $sync_forum_ids;
  1070. }
  1071. /**
  1072. * Update/Sync posted information for topics
  1073. */
  1074. function update_posted_info(&$topic_ids)
  1075. {
  1076. global $db, $config;
  1077. if (empty($topic_ids) || !$config['load_db_track'])
  1078. {
  1079. return;
  1080. }
  1081. // First of all, let us remove any posted information for these topics
  1082. $sql = 'DELETE FROM ' . TOPICS_POSTED_TABLE . '
  1083. WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
  1084. $db->sql_query($sql);
  1085. // Now, let us collect the user/topic combos for rebuilding the information
  1086. $sql = 'SELECT poster_id, topic_id
  1087. FROM ' . POSTS_TABLE . '
  1088. WHERE ' . $db->sql_in_set('topic_id', $topic_ids) . '
  1089. AND poster_id <> ' . ANONYMOUS . '
  1090. GROUP BY poster_id, topic_id';
  1091. $result = $db->sql_query($sql);
  1092. $posted = array();
  1093. while ($row = $db->sql_fetchrow($result))
  1094. {
  1095. // Add as key to make them unique (grouping by) and circumvent empty keys on array_unique
  1096. $posted[$row['poster_id']][] = $row['topic_id'];
  1097. }
  1098. $db->sql_freeresult($result);
  1099. // Now add the information...
  1100. $sql_ary = array();
  1101. foreach ($posted as $user_id => $topic_row)
  1102. {
  1103. foreach ($topic_row as $topic_id)
  1104. {
  1105. $sql_ary[] = array(
  1106. 'user_id' => (int) $user_id,
  1107. 'topic_id' => (int) $topic_id,
  1108. 'topic_posted' => 1,
  1109. );
  1110. }
  1111. }
  1112. unset($posted);
  1113. $db->sql_multi_insert(TOPICS_POSTED_TABLE, $sql_ary);
  1114. }
  1115. /**
  1116. * Delete attached file
  1117. */
  1118. function phpbb_unlink($filename, $mode = 'file', $entry_removed = false)
  1119. {
  1120. global $db, $phpbb_root_path, $config;
  1121. // Because of copying topics or modifications a physical filename could be assigned more than once. If so, do not remove the file itself.
  1122. $sql = 'SELECT COUNT(attach_id) AS num_entries
  1123. FROM ' . ATTACHMENTS_TABLE . "
  1124. WHERE physical_filename = '" . $db->sql_escape(utf8_basename($filename)) . "'";
  1125. $result = $db->sql_query($sql);
  1126. $num_entries = (int) $db->sql_fetchfield('num_entries');
  1127. $db->sql_freeresult($result);
  1128. // Do not remove file if at least one additional entry with the same name exist.
  1129. if (($entry_removed && $num_entries > 0) || (!$entry_removed && $num_entries > 1))
  1130. {
  1131. return false;
  1132. }
  1133. $filename = ($mode == 'thumbnail') ? 'thumb_' . utf8_basename($filename) : utf8_basename($filename);
  1134. return @unlink($phpbb_root_path . $config['upload_path'] . '/' . $filename);
  1135. }
  1136. /**
  1137. * All-encompasing sync function
  1138. *
  1139. * Exaples:
  1140. * <code>
  1141. * sync('topic', 'topic_id', 123); // resync topic #123
  1142. * sync('topic', 'forum_id', array(2, 3)); // resync topics from forum #2 and #3
  1143. * sync('topic'); // resync all topics
  1144. * sync('topic', 'range', 'topic_id BETWEEN 1 AND 60'); // resync a range of topics/forums (only available for 'topic' and 'forum' modes)
  1145. * </code>
  1146. *
  1147. * Modes:
  1148. * - forum Resync complete forum
  1149. * - topic Resync topics
  1150. * - topic_moved Removes topic shadows that would be in the same forum as the topic they link to
  1151. * - topic_visibility Resyncs the topic_visibility flag according to the status of the first post
  1152. * - post_reported Resyncs the post_reported flag, relying on actual reports
  1153. * - topic_reported Resyncs the topic_reported flag, relying on post_reported flags
  1154. * - post_attachement Same as post_reported, but with attachment flags
  1155. * - topic_attachement Same as topic_reported, but with attachment flags
  1156. */
  1157. function sync($mode, $where_type = '', $where_ids = '', $resync_parents = false, $sync_extra = false)
  1158. {
  1159. global $db;
  1160. if (is_array($where_ids))
  1161. {
  1162. $where_ids = array_unique($where_ids);
  1163. $where_ids = array_map('intval', $where_ids);
  1164. }
  1165. else if ($where_type != 'range')
  1166. {
  1167. $where_ids = ($where_ids) ? array((int) $where_ids) : array();
  1168. }
  1169. if ($mode == 'forum' || $mode == 'topic' || $mode == 'topic_visibility' || $mode == 'topic_reported' || $mode == 'post_reported')
  1170. {
  1171. if (!$where_type)
  1172. {
  1173. $where_sql = '';
  1174. $where_sql_and = 'WHERE';
  1175. }
  1176. else if ($where_type == 'range')
  1177. {
  1178. // Only check a range of topics/forums. For instance: 'topic_id BETWEEN 1 AND 60'
  1179. $where_sql = 'WHERE (' . $mode[0] . ".$where_ids)";
  1180. $where_sql_and = $where_sql . "\n\tAND";
  1181. }
  1182. else
  1183. {
  1184. // Do not sync the "global forum"
  1185. $where_ids = array_diff($where_ids, array(0));
  1186. if (!sizeof($where_ids))
  1187. {
  1188. // Empty array with IDs. This means that we don't have any work to do. Just return.
  1189. return;
  1190. }
  1191. // Limit the topics/forums we are syncing, use specific topic/forum IDs.
  1192. // $where_type contains the field for the where clause (forum_id, topic_id)
  1193. $where_sql = 'WHERE ' . $db->sql_in_set($mode[0] . '.' . $where_type, $where_ids);
  1194. $where_sql_and = $where_sql . "\n\tAND";
  1195. }
  1196. }
  1197. else
  1198. {
  1199. if (!sizeof($where_ids))
  1200. {
  1201. return;
  1202. }
  1203. // $where_type contains the field for the where clause (forum_id, topic_id)
  1204. $where_sql = 'WHERE ' . $db->sql_in_set($mode[0] . '.' . $where_type, $where_ids);
  1205. $where_sql_and = $where_sql . "\n\tAND";
  1206. }
  1207. switch ($mode)
  1208. {
  1209. case 'topic_moved':
  1210. $db->sql_transaction('begin');
  1211. switch ($db->sql_layer)
  1212. {
  1213. case 'mysql4':
  1214. case 'mysqli':
  1215. $sql = 'DELETE FROM ' . TOPICS_TABLE . '
  1216. USING ' . TOPICS_TABLE . ' t1, ' . TOPICS_TABLE . " t2
  1217. WHERE t1.topic_moved_id = t2.topic_id
  1218. AND t1.forum_id = t2.forum_id";
  1219. $db->sql_query($sql);
  1220. break;
  1221. default:
  1222. $sql = 'SELECT t1.topic_id
  1223. FROM ' .TOPICS_TABLE . ' t1, ' . TOPICS_TABLE . " t2
  1224. WHERE t1.topic_moved_id = t2.topic_id
  1225. AND t1.forum_id = t2.forum_id";
  1226. $result = $db->sql_query($sql);
  1227. $topic_id_ary = array();
  1228. while ($row = $db->sql_fetchrow($result))
  1229. {
  1230. $topic_id_ary[] = $row['topic_id'];
  1231. }
  1232. $db->sql_freeresult($result);
  1233. if (!sizeof($topic_id_ary))
  1234. {
  1235. return;
  1236. }
  1237. $sql = 'DELETE FROM ' . TOPICS_TABLE . '
  1238. WHERE ' . $db->sql_in_set('topic_id', $topic_id_ary);
  1239. $db->sql_query($sql);
  1240. break;
  1241. }
  1242. $db->sql_transaction('commit');
  1243. break;
  1244. case 'topic_visibility':
  1245. $db->sql_transaction('begin');
  1246. $sql = 'SELECT t.topic_id, p.post_visibility
  1247. FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  1248. $where_sql_and p.topic_id = t.topic_id
  1249. AND p.post_visibility = " . ITEM_APPROVED;
  1250. $result = $db->sql_query($sql);
  1251. $topics_approved = array();
  1252. while ($row = $db->sql_fetchrow($result))
  1253. {
  1254. $topics_approved[] = (int) $row['topic_id'];
  1255. }
  1256. $db->sql_freeresult($result);
  1257. $sql = 'SELECT t.topic_id, p.post_visibility
  1258. FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  1259. $where_sql_and " . $db->sql_in_set('t.topic_id', $topics_approved, true, true) . '
  1260. AND p.topic_id = t.topic_id
  1261. AND p.post_visibility = ' . ITEM_DELETED;
  1262. $result = $db->sql_query($sql);
  1263. $topics_softdeleted = array();
  1264. while ($row = $db->sql_fetchrow($result))
  1265. {
  1266. $topics_softdeleted[] = (int) $row['topic_id'];
  1267. }
  1268. $db->sql_freeresult($result);
  1269. $topics_softdeleted = array_diff($topics_softdeleted, $topics_approved);
  1270. $topics_not_unapproved = array_merge($topics_softdeleted, $topics_approved);
  1271. $update_ary = array(
  1272. ITEM_UNAPPROVED => (!empty($topics_not_unapproved)) ? $where_sql_and . ' ' . $db->sql_in_set('topic_id', $topics_not_unapproved, true) : '',
  1273. ITEM_APPROVED => (!empty($topics_approved)) ? ' WHERE ' . $db->sql_in_set('topic_id', $topics_approved) : '',
  1274. ITEM_DELETED => (!empty($topics_softdeleted)) ? ' WHERE ' . $db->sql_in_set('topic_id', $topics_softdeleted) : '',
  1275. );
  1276. foreach ($update_ary as $visibility => $sql_where)
  1277. {
  1278. if ($sql_where)
  1279. {
  1280. $sql = 'UPDATE ' . TOPICS_TABLE . '
  1281. SET topic_visibility = ' . $visibility . '
  1282. ' . $sql_where;
  1283. $db->sql_query($sql);
  1284. }
  1285. }
  1286. $db->sql_transaction('commit');
  1287. break;
  1288. case 'post_reported':
  1289. $post_ids = $post_reported = array();
  1290. $db->sql_transaction('begin');
  1291. $sql = 'SELECT p.post_id, p.post_reported
  1292. FROM ' . POSTS_TABLE . " p
  1293. $where_sql
  1294. GROUP BY p.post_id, p.post_reported";
  1295. $result = $db->sql_query($sql);
  1296. while ($row = $db->sql_fetchrow($result))
  1297. {
  1298. $post_ids[$row['post_id']] = $row['post_id'];
  1299. if ($row['post_reported'])
  1300. {
  1301. $post_reported[$row['post_id']] = 1;
  1302. }
  1303. }
  1304. $db->sql_freeresult($result);
  1305. $sql = 'SELECT DISTINCT(post_id)
  1306. FROM ' . REPORTS_TABLE . '
  1307. WHERE ' . $db->sql_in_set('post_id', $post_ids) . '
  1308. AND report_closed = 0';
  1309. $result = $db->sql_query($sql);
  1310. $post_ids = array();
  1311. while ($row = $db->sql_fetchrow($result))
  1312. {
  1313. if (!isset($post_reported[$row['post_id']]))
  1314. {
  1315. $post_ids[] = $row['post_id'];
  1316. }
  1317. else
  1318. {
  1319. unset($post_reported[$row['post_id']]);
  1320. }
  1321. }
  1322. $db->sql_freeresult($result);
  1323. // $post_reported should be empty by now, if it's not it contains
  1324. // posts that are falsely flagged as reported
  1325. foreach ($post_reported as $post_id => $void)
  1326. {
  1327. $post_ids[] = $post_id;
  1328. }
  1329. if (sizeof($post_ids))
  1330. {
  1331. $sql = 'UPDATE ' . POSTS_TABLE . '
  1332. SET post_reported = 1 - post_reported
  1333. WHERE ' . $db->sql_in_set('post_id', $post_ids);
  1334. $db->sql_query($sql);
  1335. }
  1336. $db->sql_transaction('commit');
  1337. break;
  1338. case 'topic_reported':
  1339. if ($sync_extra)
  1340. {
  1341. sync('post_reported', $where_type, $where_ids);
  1342. }
  1343. $topic_ids = $topic_reported = array();
  1344. $db->sql_transaction('begin');
  1345. $sql = 'SELECT DISTINCT(t.topic_id)
  1346. FROM ' . POSTS_TABLE . " t
  1347. $where_sql_and t.post_reported = 1";
  1348. $result = $db->sql_query($sql);
  1349. while ($row = $db->sql_fetchrow($result))
  1350. {
  1351. $topic_reported[$row['topic_id']] = 1;
  1352. }
  1353. $db->sql_freeresult($result);
  1354. $sql = 'SELECT t.topic_id, t.topic_reported
  1355. FROM ' . TOPICS_TABLE . " t
  1356. $where_sql";
  1357. $result = $db->sql_query($sql);
  1358. while ($row = $db->sql_fetchrow($result))
  1359. {
  1360. if ($row['topic_reported'] ^ isset($topic_reported[$row['topic_id']]))
  1361. {
  1362. $topic_ids[] = $row['topic_id'];
  1363. }
  1364. }
  1365. $db->sql_freeresult($result);
  1366. if (sizeof($topic_ids))
  1367. {
  1368. $sql = 'UPDATE ' . TOPICS_TABLE . '
  1369. SET topic_reported = 1 - topic_reported
  1370. WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
  1371. $db->sql_query($sql);
  1372. }
  1373. $db->sql_transaction('commit');
  1374. break;
  1375. case 'post_attachment':
  1376. $post_ids = $post_attachment = array();
  1377. $db->sql_transaction('begin');
  1378. $sql = 'SELECT p.post_id, p.post_attachment
  1379. FROM ' . POSTS_TABLE . " p
  1380. $where_sql
  1381. GROUP BY p.post_id, p.post_attachment";
  1382. $result = $db->sql_query($sql);
  1383. while ($row = $db->sql_fetchrow($result))
  1384. {
  1385. $post_ids[$row['post_id']] = $row['post_id'];
  1386. if ($row['post_attachment'])
  1387. {
  1388. $post_attachment[$row['post_id']] = 1;
  1389. }
  1390. }
  1391. $db->sql_freeresult($result);
  1392. $sql = 'SELECT DISTINCT(post_msg_id)
  1393. FROM ' . ATTACHMENTS_TABLE . '
  1394. WHERE ' . $db->sql_in_set('post_msg_id', $post_ids) . '
  1395. AND in_message = 0';
  1396. $result = $db->sql_query($sql);
  1397. $post_ids = array();
  1398. while ($row = $db->sql_fetchrow($result))
  1399. {
  1400. if (!isset($post_attachment[$row['post_msg_id']]))
  1401. {
  1402. $post_ids[] = $row['post_msg_id'];
  1403. }
  1404. else
  1405. {
  1406. unset($post_attachment[$row['post_msg_id']]);
  1407. }
  1408. }
  1409. $db->sql_freeresult($result);
  1410. // $post_attachment should be empty by now, if it's not it contains
  1411. // posts that are falsely flagged as having attachments
  1412. foreach ($post_attachment as $post_id => $void)
  1413. {
  1414. $post_ids[] = $post_id;
  1415. }
  1416. if (sizeof($post_ids))
  1417. {
  1418. $sql = 'UPDATE ' . POSTS_TABLE . '
  1419. SET post_attachment = 1 - post_attachment
  1420. WHERE ' . $db->sql_in_set('post_id', $post_ids);
  1421. $db->sql_query($sql);
  1422. }
  1423. $db->sql_transaction('commit');
  1424. break;
  1425. case 'topic_attachment':
  1426. if ($sync_extra)
  1427. {
  1428. sync('post_attachment', $where_type, $where_ids);
  1429. }
  1430. $topic_ids = $topic_attachment = array();
  1431. $db->sql_transaction('begin');
  1432. $sql = 'SELECT DISTINCT(t.topic_id)
  1433. FROM ' . POSTS_TABLE . " t
  1434. $where_sql_and t.post_attachment = 1";
  1435. $result = $db->sql_query($sql);
  1436. while ($row = $db->sql_fetchrow($result))
  1437. {
  1438. $topic_attachment[$row['topic_id']] = 1;
  1439. }
  1440. $db->sql_freeresult($result);
  1441. $sql = 'SELECT t.topic_id, t.topic_attachment
  1442. FROM ' . TOPICS_TABLE . " t
  1443. $where_sql";
  1444. $result = $db->sql_query($sql);
  1445. while ($row = $db->sql_fetchrow($result))
  1446. {
  1447. if ($row['topic_attachment'] ^ isset($topic_attachment[$row['topic_id']]))
  1448. {
  1449. $topic_ids[] = $row['topic_id'];
  1450. }
  1451. }
  1452. $db->sql_freeresult($result);
  1453. if (sizeof($topic_ids))
  1454. {
  1455. $sql = 'UPDATE ' . TOPICS_TABLE . '
  1456. SET topic_attachment = 1 - topic_attachment
  1457. WHERE ' . $db->sql_in_set('topic_id', $topic_ids);
  1458. $db->sql_query($sql);
  1459. }
  1460. $db->sql_transaction('commit');
  1461. break;
  1462. case 'forum':
  1463. $db->sql_transaction('begin');
  1464. // 1: Get the list of all forums
  1465. $sql = 'SELECT f.*
  1466. FROM ' . FORUMS_TABLE . " f
  1467. $where_sql";
  1468. $result = $db->sql_query($sql);
  1469. $forum_data = $forum_ids = $post_ids = $last_post_id = $post_info = array();
  1470. while ($row = $db->sql_fetchrow($result))
  1471. {
  1472. if ($row['forum_type'] == FORUM_LINK)
  1473. {
  1474. continue;
  1475. }
  1476. $forum_id = (int) $row['forum_id'];
  1477. $forum_ids[$forum_id] = $forum_id;
  1478. $forum_data[$forum_id] = $row;
  1479. if ($sync_extra)
  1480. {
  1481. $forum_data[$forum_id]['posts_approved'] = 0;
  1482. $forum_data[$forum_id]['posts_unapproved'] = 0;
  1483. $forum_data[$forum_id]['posts_softdeleted'] = 0;
  1484. $forum_data[$forum_id]['topics_approved'] = 0;
  1485. $forum_data[$forum_id]['topics_unapproved'] = 0;
  1486. $forum_data[$forum_id]['topics_softdeleted'] = 0;
  1487. }
  1488. $forum_data[$forum_id]['last_post_id'] = 0;
  1489. $forum_data[$forum_id]['last_post_subject'] = '';
  1490. $forum_data[$forum_id]['last_post_time'] = 0;
  1491. $forum_data[$forum_id]['last_poster_id'] = 0;
  1492. $forum_data[$forum_id]['last_poster_name'] = '';
  1493. $forum_data[$forum_id]['last_poster_colour'] = '';
  1494. }
  1495. $db->sql_freeresult($result);
  1496. if (!sizeof($forum_ids))
  1497. {
  1498. break;
  1499. }
  1500. $forum_ids = array_values($forum_ids);
  1501. // 2: Get topic counts for each forum (optional)
  1502. if ($sync_extra)
  1503. {
  1504. $sql = 'SELECT forum_id, topic_visibility, COUNT(topic_id) AS total_topics
  1505. FROM ' . TOPICS_TABLE . '
  1506. WHERE ' . $db->sql_in_set('forum_id', $forum_ids) . '
  1507. GROUP BY forum_id, topic_visibility';
  1508. $result = $db->sql_query($sql);
  1509. while ($row = $db->sql_fetchrow($result))
  1510. {
  1511. $forum_id = (int) $row['forum_id'];
  1512. if ($row['topic_visibility'] == ITEM_APPROVED)
  1513. {
  1514. $forum_data[$forum_id]['topics_approved'] = $row['total_topics'];
  1515. }
  1516. else if ($row['topic_visibility'] == ITEM_UNAPPROVED || $row['topic_visibility'] == ITEM_REAPPROVE)
  1517. {
  1518. $forum_data[$forum_id]['topics_unapproved'] = $row['total_topics'];
  1519. }
  1520. else if ($row['topic_visibility'] == ITEM_DELETED)
  1521. {
  1522. $forum_data[$forum_id]['topics_softdeleted'] = $row['total_topics'];
  1523. }
  1524. }
  1525. $db->sql_freeresult($result);
  1526. }
  1527. // 3: Get post count for each forum (optional)
  1528. if ($sync_extra)
  1529. {
  1530. if (sizeof($forum_ids) == 1)
  1531. {
  1532. $sql = 'SELECT SUM(t.topic_posts_approved) AS forum_posts_approved, SUM(t.topic_posts_unapproved) AS forum_posts_unapproved, SUM(t.topic_posts_softdeleted) AS forum_posts_softdeleted
  1533. FROM ' . TOPICS_TABLE . ' t
  1534. WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
  1535. AND t.topic_status <> ' . ITEM_MOVED;
  1536. }
  1537. else
  1538. {
  1539. $sql = 'SELECT t.forum_id, SUM(t.topic_posts_approved) AS forum_posts_approved, SUM(t.topic_posts_unapproved) AS forum_posts_unapproved, SUM(t.topic_posts_softdeleted) AS forum_posts_softdeleted
  1540. FROM ' . TOPICS_TABLE . ' t
  1541. WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
  1542. AND t.topic_status <> ' . ITEM_MOVED . '
  1543. GROUP BY t.forum_id';
  1544. }
  1545. $result = $db->sql_query($sql);
  1546. while ($row = $db->sql_fetchrow($result))
  1547. {
  1548. $forum_id = (sizeof($forum_ids) == 1) ? (int) $forum_ids[0] : (int) $row['forum_id'];
  1549. $forum_data[$forum_id]['posts_approved'] = (int) $row['forum_posts_approved'];
  1550. $forum_data[$forum_id]['posts_unapproved'] = (int) $row['forum_posts_unapproved'];
  1551. $forum_data[$forum_id]['posts_softdeleted'] = (int) $row['forum_posts_softdeleted'];
  1552. }
  1553. $db->sql_freeresult($result);
  1554. }
  1555. // 4: Get last_post_id for each forum
  1556. if (sizeof($forum_ids) == 1)
  1557. {
  1558. $sql = 'SELECT MAX(t.topic_last_post_id) as last_post_id
  1559. FROM ' . TOPICS_TABLE . ' t
  1560. WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
  1561. AND t.topic_visibility = ' . ITEM_APPROVED;
  1562. }
  1563. else
  1564. {
  1565. $sql = 'SELECT t.forum_id, MAX(t.topic_last_post_id) as last_post_id
  1566. FROM ' . TOPICS_TABLE . ' t
  1567. WHERE ' . $db->sql_in_set('t.forum_id', $forum_ids) . '
  1568. AND t.topic_visibility = ' . ITEM_APPROVED . '
  1569. GROUP BY t.forum_id';
  1570. }
  1571. $result = $db->sql_query($sql);
  1572. while ($row = $db->sql_fetchrow($result))
  1573. {
  1574. $forum_id = (sizeof($forum_ids) == 1) ? (int) $forum_ids[0] : (int) $row['forum_id'];
  1575. $forum_data[$forum_id]['last_post_id'] = (int) $row['last_post_id'];
  1576. $post_ids[] = $row['last_post_id'];
  1577. }
  1578. $db->sql_freeresult($result);
  1579. // 5: Retrieve last_post infos
  1580. if (sizeof($post_ids))
  1581. {
  1582. $sql = 'SELECT p.post_id, p.poster_id, p.post_subject, p.post_time, p.post_username, u.username, u.user_colour
  1583. FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
  1584. WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . '
  1585. AND p.poster_id = u.user_id';
  1586. $result = $db->sql_query($sql);
  1587. while ($row = $db->sql_fetchrow($result))
  1588. {
  1589. $post_info[$row['post_id']] = $row;
  1590. }
  1591. $db->sql_freeresult($result);
  1592. foreach ($forum_data as $forum_id => $data)
  1593. {
  1594. if ($data['last_post_id'])
  1595. {
  1596. if (isset($post_info[$data['last_post_id']]))
  1597. {
  1598. $forum_data[$forum_id]['last_post_subject'] = $post_info[$data['last_post_id']]['post_subject'];
  1599. $forum_data[$forum_id]['last_post_time'] = $post_info[$data['last_post_id']]['post_time'];
  1600. $forum_data[$forum_id]['last_poster_id'] = $post_info[$data['last_post_id']]['poster_id'];
  1601. $forum_data[$forum_id]['last_poster_name'] = ($post_info[$data['last_post_id']]['poster_id'] != ANONYMOUS) ? $post_info[$data['last_post_id']]['username'] : $post_info[$data['last_post_id']]['post_username'];
  1602. $forum_data[$forum_id]['last_poster_colour'] = $post_info[$data['last_post_id']]['user_colour'];
  1603. }
  1604. else
  1605. {
  1606. // For some reason we did not find the post in the db
  1607. $forum_data[$forum_id]['last_post_id'] = 0;
  1608. $forum_data[$forum_id]['last_post_subject'] = '';
  1609. $forum_data[$forum_id]['last_post_time'] = 0;
  1610. $forum_data[$forum_id]['last_poster_id'] = 0;
  1611. $forum_data[$forum_id]['last_poster_name'] = '';
  1612. $forum_data[$forum_id]['last_poster_colour'] = '';
  1613. }
  1614. }
  1615. }
  1616. unset($post_info);
  1617. }
  1618. // 6: Now do that thing
  1619. $fieldnames = array('last_post_id', 'last_post_subject', 'last_post_time', 'last_poster_id', 'last_poster_name', 'last_poster_colour');
  1620. if ($sync_extra)
  1621. {
  1622. array_push($fieldnames, 'posts_approved', 'posts_unapproved', 'posts_softdeleted', 'topics_approved', 'topics_unapproved', 'topics_softdeleted');
  1623. }
  1624. foreach ($forum_data as $forum_id => $row)
  1625. {
  1626. $sql_ary = array();
  1627. foreach ($fieldnames as $fieldname)
  1628. {
  1629. if ($row['forum_' . $fieldname] != $row[$fieldname])
  1630. {
  1631. if (preg_match('#(name|colour|subject)$#', $fieldname))
  1632. {
  1633. $sql_ary['forum_' . $fieldname] = (string) $row[$fieldname];
  1634. }
  1635. else
  1636. {
  1637. $sql_ary['forum_' . $fieldname] = (int) $row[$fieldname];
  1638. }
  1639. }
  1640. }
  1641. if (sizeof($sql_ary))
  1642. {
  1643. $sql = 'UPDATE ' . FORUMS_TABLE . '
  1644. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  1645. WHERE forum_id = ' . $forum_id;
  1646. $db->sql_query($sql);
  1647. }
  1648. }
  1649. $db->sql_transaction('commit');
  1650. break;
  1651. case 'topic':
  1652. $topic_data = $post_ids = $resync_forums = $delete_topics = $delete_posts = $moved_topics = array();
  1653. $db->sql_transaction('begin');
  1654. $sql = 'SELECT t.topic_id, t.forum_id, t.topic_moved_id, t.topic_visibility, ' . (($sync_extra) ? 't.topic_attachment, t.topic_reported, ' : '') . 't.topic_poster, t.topic_time, t.topic_posts_approved, t.topic_posts_unapproved, t.topic_posts_softdeleted, t.topic_first_post_id, t.topic_first_poster_name, t.topic_first_poster_colour, t.topic_last_post_id, t.topic_last_post_subject, t.topic_last_poster_id, t.topic_last_poster_name, t.topic_last_poster_colour, t.topic_last_post_time
  1655. FROM ' . TOPICS_TABLE . " t
  1656. $where_sql";
  1657. $result = $db->sql_query($sql);
  1658. while ($row = $db->sql_fetchrow($result))
  1659. {
  1660. if ($row['topic_moved_id'])
  1661. {
  1662. $moved_topics[] = $row['topic_id'];
  1663. continue;
  1664. }
  1665. $topic_id = (int) $row['topic_id'];
  1666. $topic_data[$topic_id] = $row;
  1667. $topic_data[$topic_id]['visibility'] = ITEM_UNAPPROVED;
  1668. $topic_data[$topic_id]['posts_approved'] = 0;
  1669. $topic_data[$topic_id]['posts_unapproved'] = 0;
  1670. $topic_data[$topic_id]['posts_softdeleted'] = 0;
  1671. $topic_data[$topic_id]['first_post_id'] = 0;
  1672. $topic_data[$topic_id]['last_post_id'] = 0;
  1673. unset($topic_data[$topic_id]['topic_id']);
  1674. // This array holds all topic_ids
  1675. $delete_topics[$topic_id] = '';
  1676. if ($sync_extra)
  1677. {
  1678. $topic_data[$topic_id]['reported'] = 0;
  1679. $topic_data[$topic_id]['attachment'] = 0;
  1680. }
  1681. }
  1682. $db->sql_freeresult($result);
  1683. // Use "t" as table alias because of the $where_sql clause
  1684. // NOTE: 't.post_visibility' in the GROUP BY is causing a major slowdown.
  1685. $sql = 'SELECT t.topic_id, t.post_visibility, COUNT(t.post_id) AS total_posts, MIN(t.post_id) AS first_post_id, MAX(t.post_id) AS last_post_id
  1686. FROM ' . POSTS_TABLE . " t
  1687. $where_sql
  1688. GROUP BY t.topic_id, t.post_visibility";
  1689. $result = $db->sql_query($sql);
  1690. while ($row = $db->sql_fetchrow($result))
  1691. {
  1692. $topic_id = (int) $row['topic_id'];
  1693. $row['first_post_id'] = (int) $row['first_post_id'];
  1694. $row['last_post_id'] = (int) $row['last_post_id'];
  1695. if (!isset($topic_data[$topic_id]))
  1696. {
  1697. // Hey, these posts come from a topic that does not exist
  1698. $delete_posts[$topic_id] = '';
  1699. }
  1700. else
  1701. {
  1702. // Unset the corresponding entry in $delete_topics
  1703. // When we'll be done, only topics with no posts will remain
  1704. unset($delete_topics[$topic_id]);
  1705. if ($row['post_visibility'] == ITEM_APPROVED)
  1706. {
  1707. $topic_data[$topic_id]['posts_approved'] = $row['total_posts'];
  1708. }
  1709. else if ($row['post_visibility'] == ITEM_UNAPPROVED || $row['post_visibility'] == ITEM_REAPPROVE)
  1710. {
  1711. $topic_data[$topic_id]['posts_unapproved'] = $row['total_posts'];
  1712. }
  1713. else if ($row['post_visibility'] == ITEM_DELETED)
  1714. {
  1715. $topic_data[$topic_id]['posts_softdeleted'] = $row['total_posts'];
  1716. }
  1717. if ($row['post_visibility'] == ITEM_APPROVED)
  1718. {
  1719. $topic_data[$topic_id]['visibility'] = ITEM_APPROVED;
  1720. $topic_data[$topic_id]['first_post_id'] = $row['first_post_id'];
  1721. $topic_data[$topic_id]['last_post_id'] = $row['last_post_id'];
  1722. }
  1723. else if ($topic_data[$topic_id]['visibility'] != ITEM_APPROVED)
  1724. {
  1725. // If there is no approved post, we take the min/max of the other visibilities
  1726. // for the last and first post info, because it is only visible to moderators anyway
  1727. $topic_data[$topic_id]['first_post_id'] = (!empty($topic_data[$topic_id]['first_post_id'])) ? min($topic_data[$topic_id]['first_post_id'], $row['first_post_id']) : $row['first_post_id'];
  1728. $topic_data[$topic_id]['last_post_id'] = max($topic_data[$topic_id]['last_post_id'], $row['last_post_id']);
  1729. if ($topic_data[$topic_id]['visibility'] == ITEM_UNAPPROVED || $topic_data[$topic_id]['visibility'] == ITEM_REAPPROVE)
  1730. {
  1731. // Soft delete status is stronger than unapproved.
  1732. $topic_data[$topic_id]['visibility'] = $row['post_visibility'];
  1733. }
  1734. }
  1735. }
  1736. }
  1737. $db->sql_freeresult($result);
  1738. foreach ($topic_data as $topic_id => $row)
  1739. {
  1740. $post_ids[] = $row['first_post_id'];
  1741. if ($row['first_post_id'] != $row['last_post_id'])
  1742. {
  1743. $post_ids[] = $row['last_post_id'];
  1744. }
  1745. }
  1746. // Now we delete empty topics and orphan posts
  1747. if (sizeof($delete_posts))
  1748. {
  1749. delete_posts('topic_id', array_keys($delete_posts), false);
  1750. unset($delete_posts);
  1751. }
  1752. if (!sizeof($topic_data))
  1753. {
  1754. // If we get there, topic ids were invalid or topics did not contain any posts
  1755. delete_topics($where_type, $where_ids, true);
  1756. return;
  1757. }
  1758. if (sizeof($delete_topics))
  1759. {
  1760. $delete_topic_ids = array();
  1761. foreach ($delete_topics as $topic_id => $void)
  1762. {
  1763. unset($topic_data[$topic_id]);
  1764. $delete_topic_ids[] = $topic_id;
  1765. }
  1766. delete_topics('topic_id', $delete_topic_ids, false);
  1767. unset($delete_topics, $delete_topic_ids);
  1768. }
  1769. $sql = 'SELECT p.post_id, p.topic_id, p.post_visibility, p.poster_id, p.post_subject, p.post_username, p.post_time, u.username, u.user_colour
  1770. FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
  1771. WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . '
  1772. AND u.user_id = p.poster_id';
  1773. $result = $db->sql_query($sql);
  1774. $post_ids = array();
  1775. while ($row = $db->sql_fetchrow($result))
  1776. {
  1777. $topic_id = intval($row['topic_id']);
  1778. if ($row['post_id'] == $topic_data[$topic_id]['first_post_id'])
  1779. {
  1780. $topic_data[$topic_id]['time'] = $row['post_time'];
  1781. $topic_data[$topic_id]['poster'] = $row['poster_id'];
  1782. $topic_data[$topic_id]['first_poster_name'] = ($row['poster_id'] == ANONYMOUS) ? $row['post_username'] : $row['username'];
  1783. $topic_data[$topic_id]['first_poster_colour'] = $row['user_colour'];
  1784. }
  1785. if ($row['post_id'] == $topic_data[$topic_id]['last_post_id'])
  1786. {
  1787. $topic_data[$topic_id]['last_poster_id'] = $row['poster_id'];
  1788. $topic_data[$topic_id]['last_post_subject'] = $row['post_subject'];
  1789. $topic_data[$topic_id]['last_post_time'] = $row['post_time'];
  1790. $topic_data[$topic_id]['last_poster_name'] = ($row['poster_id'] == ANONYMOUS) ? $row['post_username'] : $row['username'];
  1791. $topic_data[$topic_id]['last_poster_colour'] = $row['user_colour'];
  1792. }
  1793. }
  1794. $db->sql_freeresult($result);
  1795. // Make sure shadow topics do link to existing topics
  1796. if (sizeof($moved_topics))
  1797. {
  1798. $delete_topics = array();
  1799. $sql = 'SELECT t1.topic_id, t1.topic_moved_id
  1800. FROM ' . TOPICS_TABLE . ' t1
  1801. LEFT JOIN ' . TOPICS_TABLE . ' t2 ON (t2.topic_id = t1.topic_moved_id)
  1802. WHERE ' . $db->sql_in_set('t1.topic_id', $moved_topics) . '
  1803. AND t2.topic_id IS NULL';
  1804. $result = $db->sql_query($sql);
  1805. while ($row = $db->sql_fetchrow($result))
  1806. {
  1807. $delete_topics[] = $row['topic_id'];
  1808. }
  1809. $db->sql_freeresult($result);
  1810. if (sizeof($delete_topics))
  1811. {
  1812. delete_topics('topic_id', $delete_topics, false);
  1813. }
  1814. unset($delete_topics);
  1815. // Make sure shadow topics having no last post data being updated (this only rarely happens...)
  1816. $sql = 'SELECT topic_id, topic_moved_id, topic_last_post_id, topic_first_post_id
  1817. FROM ' . TOPICS_TABLE . '
  1818. WHERE ' . $db->sql_in_set('topic_id', $moved_topics) . '
  1819. AND topic_last_post_time = 0';
  1820. $result = $db->sql_query($sql);
  1821. $shadow_topic_data = $post_ids = array();
  1822. while ($row = $db->sql_fetchrow($result))
  1823. {
  1824. $shadow_topic_data[$row['topic_moved_id']] = $row;
  1825. $post_ids[] = $row['topic_last_post_id'];
  1826. $post_ids[] = $row['topic_first_post_id'];
  1827. }
  1828. $db->sql_freeresult($result);
  1829. $sync_shadow_topics = array();
  1830. if (sizeof($post_ids))
  1831. {
  1832. $sql = 'SELECT p.post_id, p.topic_id, p.post_visibility, p.poster_id, p.post_subject, p.post_username, p.post_time, u.username, u.user_colour
  1833. FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
  1834. WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . '
  1835. AND u.user_id = p.poster_id';
  1836. $result = $db->sql_query($sql);
  1837. $post_ids = array();
  1838. while ($row = $db->sql_fetchrow($result))
  1839. {
  1840. $topic_id = (int) $row['topic_id'];
  1841. // Ok, there should be a shadow topic. If there isn't, then there's something wrong with the db.
  1842. // However, there's not much we can do about it.
  1843. if (!empty($shadow_topic_data[$topic_id]))
  1844. {
  1845. if ($row['post_id'] == $shadow_topic_data[$topic_id]['topic_first_post_id'])
  1846. {
  1847. $orig_topic_id = $shadow_topic_data[$topic_id]['topic_id'];
  1848. if (!isset($sync_shadow_topics[$orig_topic_id]))
  1849. {
  1850. $sync_shadow_topics[$orig_topic_id] = array();
  1851. }
  1852. $sync_shadow_topics[$orig_topic_id]['topic_time'] = $row['post_time'];
  1853. $sync_shadow_topics[$orig_topic_id]['topic_poster'] = $row['poster_id'];
  1854. $sync_shadow_topics[$orig_topic_id]['topic_first_poster_name'] = ($row['poster_id'] == ANONYMOUS) ? $row['post_username'] : $row['username'];
  1855. $sync_shadow_topics[$orig_topic_id]['topic_first_poster_colour'] = $row['user_colour'];
  1856. }
  1857. if ($row['post_id'] == $shadow_topic_data[$topic_id]['topic_last_post_id'])
  1858. {
  1859. $orig_topic_id = $shadow_topic_data[$topic_id]['topic_id'];
  1860. if (!isset($sync_shadow_topics[$orig_topic_id]))
  1861. {
  1862. $sync_shadow_topics[$orig_topic_id] = array();
  1863. }
  1864. $sync_shadow_topics[$orig_topic_id]['topic_last_poster_id'] = $row['poster_id'];
  1865. $sync_shadow_topics[$orig_topic_id]['topic_last_post_subject'] = $row['post_subject'];
  1866. $sync_shadow_topics[$orig_topic_id]['topic_last_post_time'] = $row['post_time'];
  1867. $sync_shadow_topics[$orig_topic_id]['topic_last_poster_name'] = ($row['poster_id'] == ANONYMOUS) ? $row['post_username'] : $row['username'];
  1868. $sync_shadow_topics[$orig_topic_id]['topic_last_poster_colour'] = $row['user_colour'];
  1869. }
  1870. }
  1871. }
  1872. $db->sql_freeresult($result);
  1873. $shadow_topic_data = array();
  1874. // Update the information we collected
  1875. if (sizeof($sync_shadow_topics))
  1876. {
  1877. foreach ($sync_shadow_topics as $sync_topic_id => $sql_ary)
  1878. {
  1879. $sql = 'UPDATE ' . TOPICS_TABLE . '
  1880. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  1881. WHERE topic_id = ' . $sync_topic_id;
  1882. $db->sql_query($sql);
  1883. }
  1884. }
  1885. }
  1886. unset($sync_shadow_topics, $shadow_topic_data);
  1887. }
  1888. // These are fields that will be synchronised
  1889. $fieldnames = array('time', 'visibility', 'posts_approved', 'posts_unapproved', 'posts_softdeleted', 'poster', 'first_post_id', 'first_poster_name', 'first_poster_colour', 'last_post_id', 'last_post_subject', 'last_post_time', 'last_poster_id', 'last_poster_name', 'last_poster_colour');
  1890. if ($sync_extra)
  1891. {
  1892. // This routine assumes that post_reported values are correct
  1893. // if they are not, use sync('post_reported') first
  1894. $sql = 'SELECT t.topic_id, p.post_id
  1895. FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  1896. $where_sql_and p.topic_id = t.topic_id
  1897. AND p.post_reported = 1
  1898. GROUP BY t.topic_id, p.post_id";
  1899. $result = $db->sql_query($sql);
  1900. $fieldnames[] = 'reported';
  1901. while ($row = $db->sql_fetchrow($result))
  1902. {
  1903. $topic_data[intval($row['topic_id'])]['reported'] = 1;
  1904. }
  1905. $db->sql_freeresult($result);
  1906. // This routine assumes that post_attachment values are correct
  1907. // if they are not, use sync('post_attachment') first
  1908. $sql = 'SELECT t.topic_id, p.post_id
  1909. FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  1910. $where_sql_and p.topic_id = t.topic_id
  1911. AND p.post_attachment = 1
  1912. GROUP BY t.topic_id, p.post_id";
  1913. $result = $db->sql_query($sql);
  1914. $fieldnames[] = 'attachment';
  1915. while ($row = $db->sql_fetchrow($result))
  1916. {
  1917. $topic_data[intval($row['topic_id'])]['attachment'] = 1;
  1918. }
  1919. $db->sql_freeresult($result);
  1920. }
  1921. foreach ($topic_data as $topic_id => $row)
  1922. {
  1923. $sql_ary = array();
  1924. foreach ($fieldnames as $fieldname)
  1925. {
  1926. if (isset($row[$fieldname]) && isset($row['topic_' . $fieldname]) && $row['topic_' . $fieldname] != $row[$fieldname])
  1927. {
  1928. $sql_ary['topic_' . $fieldname] = $row[$fieldname];
  1929. }
  1930. }
  1931. if (sizeof($sql_ary))
  1932. {
  1933. $sql = 'UPDATE ' . TOPICS_TABLE . '
  1934. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  1935. WHERE topic_id = ' . $topic_id;
  1936. $db->sql_query($sql);
  1937. $resync_forums[$row['forum_id']] = $row['forum_id'];
  1938. }
  1939. }
  1940. unset($topic_data);
  1941. $db->sql_transaction('commit');
  1942. // if some topics have been resync'ed then resync parent forums
  1943. // except when we're only syncing a range, we don't want to sync forums during
  1944. // batch processing.
  1945. if ($resync_parents && sizeof($resync_forums) && $where_type != 'range')
  1946. {
  1947. sync('forum', 'forum_id', array_values($resync_forums), true, true);
  1948. }
  1949. break;
  1950. }
  1951. return;
  1952. }
  1953. /**
  1954. * Prune function
  1955. */
  1956. function prune($forum_id, $prune_mode, $prune_date, $prune_flags = 0, $auto_sync = true)
  1957. {
  1958. global $db;
  1959. if (!is_array($forum_id))
  1960. {
  1961. $forum_id = array($forum_id);
  1962. }
  1963. if (!sizeof($forum_id))
  1964. {
  1965. return;
  1966. }
  1967. $sql_and = '';
  1968. if (!($prune_flags & FORUM_FLAG_PRUNE_ANNOUNCE))
  1969. {
  1970. $sql_and .= ' AND topic_type <> ' . POST_ANNOUNCE;
  1971. $sql_and .= ' AND topic_type <> ' . POST_GLOBAL;
  1972. }
  1973. if (!($prune_flags & FORUM_FLAG_PRUNE_STICKY))
  1974. {
  1975. $sql_and .= ' AND topic_type <> ' . POST_STICKY;
  1976. }
  1977. if ($prune_mode == 'posted')
  1978. {
  1979. $sql_and .= " AND topic_last_post_time < $prune_date";
  1980. }
  1981. if ($prune_mode == 'viewed')
  1982. {
  1983. $sql_and .= " AND topic_last_view_time < $prune_date";
  1984. }
  1985. if ($prune_mode == 'shadow')
  1986. {
  1987. $sql_and .= ' AND topic_status = ' . ITEM_MOVED . " AND topic_last_post_time < $prune_date";
  1988. }
  1989. $sql = 'SELECT topic_id
  1990. FROM ' . TOPICS_TABLE . '
  1991. WHERE ' . $db->sql_in_set('forum_id', $forum_id) . "
  1992. AND poll_start = 0
  1993. $sql_and";
  1994. $result = $db->sql_query($sql);
  1995. $topic_list = array();
  1996. while ($row = $db->sql_fetchrow($result))
  1997. {
  1998. $topic_list[] = $row['topic_id'];
  1999. }
  2000. $db->sql_freeresult($result);
  2001. if ($prune_flags & FORUM_FLAG_PRUNE_POLL)
  2002. {
  2003. $sql = 'SELECT topic_id
  2004. FROM ' . TOPICS_TABLE . '
  2005. WHERE ' . $db->sql_in_set('forum_id', $forum_id) . "
  2006. AND poll_start > 0
  2007. AND poll_last_vote < $prune_date
  2008. $sql_and";
  2009. $result = $db->sql_query($sql);
  2010. while ($row = $db->sql_fetchrow($result))
  2011. {
  2012. $topic_list[] = $row['topic_id'];
  2013. }
  2014. $db->sql_freeresult($result);
  2015. $topic_list = array_unique($topic_list);
  2016. }
  2017. return delete_topics('topic_id', $topic_list, $auto_sync, false);
  2018. }
  2019. /**
  2020. * Function auto_prune(), this function now relies on passed vars
  2021. */
  2022. function auto_prune($forum_id, $prune_mode, $prune_flags, $prune_days, $prune_freq)
  2023. {
  2024. global $db;
  2025. $sql = 'SELECT forum_name
  2026. FROM ' . FORUMS_TABLE . "
  2027. WHERE forum_id = $forum_id";
  2028. $result = $db->sql_query($sql, 3600);
  2029. $row = $db->sql_fetchrow($result);
  2030. $db->sql_freeresult($result);
  2031. if ($row)
  2032. {
  2033. $prune_date = time() - ($prune_days * 86400);
  2034. $next_prune = time() + ($prune_freq * 86400);
  2035. prune($forum_id, $prune_mode, $prune_date, $prune_flags, true);
  2036. $sql = 'UPDATE ' . FORUMS_TABLE . "
  2037. SET prune_next = $next_prune
  2038. WHERE forum_id = $forum_id";
  2039. $db->sql_query($sql);
  2040. add_log('admin', 'LOG_AUTO_PRUNE', $row['forum_name']);
  2041. }
  2042. return;
  2043. }
  2044. /**
  2045. * Cache moderators. Called whenever permissions are changed
  2046. * via admin_permissions. Changes of usernames and group names
  2047. * must be carried through for the moderators table.
  2048. *
  2049. * @param \phpbb\db\driver\driver_interface $db Database connection
  2050. * @param \phpbb\cache\driver\driver_interface Cache driver
  2051. * @param \phpbb\auth\auth $auth Authentication object
  2052. * @return null
  2053. */
  2054. function phpbb_cache_moderators($db, $cache, $auth)
  2055. {
  2056. // Remove cached sql results
  2057. $cache->destroy('sql', MODERATOR_CACHE_TABLE);
  2058. // Clear table
  2059. switch ($db->sql_layer)
  2060. {
  2061. case 'sqlite':
  2062. case 'sqlite3':
  2063. case 'firebird':
  2064. $db->sql_query('DELETE FROM ' . MODERATOR_CACHE_TABLE);
  2065. break;
  2066. default:
  2067. $db->sql_query('TRUNCATE TABLE ' . MODERATOR_CACHE_TABLE);
  2068. break;
  2069. }
  2070. // We add moderators who have forum moderator permissions without an explicit ACL_NEVER setting
  2071. $hold_ary = $ug_id_ary = $sql_ary = array();
  2072. // Grab all users having moderative options...
  2073. $hold_ary = $auth->acl_user_raw_data(false, 'm_%', false);
  2074. // Add users?
  2075. if (sizeof($hold_ary))
  2076. {
  2077. // At least one moderative option warrants a display
  2078. $ug_id_ary = array_keys($hold_ary);
  2079. // Remove users who have group memberships with DENY moderator permissions
  2080. $sql_ary_deny = array(
  2081. 'SELECT' => 'a.forum_id, ug.user_id, g.group_id',
  2082. 'FROM' => array(
  2083. ACL_OPTIONS_TABLE => 'o',
  2084. USER_GROUP_TABLE => 'ug',
  2085. GROUPS_TABLE => 'g',
  2086. ACL_GROUPS_TABLE => 'a',
  2087. ),
  2088. 'LEFT_JOIN' => array(
  2089. array(
  2090. 'FROM' => array(ACL_ROLES_DATA_TABLE => 'r'),
  2091. 'ON' => 'a.auth_role_id = r.role_id',
  2092. ),
  2093. ),
  2094. 'WHERE' => '(o.auth_option_id = a.auth_option_id OR o.auth_option_id = r.auth_option_id)
  2095. AND ((a.auth_setting = ' . ACL_NEVER . ' AND r.auth_setting IS NULL)
  2096. OR r.auth_setting = ' . ACL_NEVER . ')
  2097. AND a.group_id = ug.group_id
  2098. AND g.group_id = ug.group_id
  2099. AND NOT (ug.group_leader = 1 AND g.group_skip_auth = 1)
  2100. AND ' . $db->sql_in_set('ug.user_id', $ug_id_ary) . "
  2101. AND ug.user_pending = 0
  2102. AND o.auth_option " . $db->sql_like_expression('m_' . $db->any_char),
  2103. );
  2104. $sql = $db->sql_build_query('SELECT', $sql_ary_deny);
  2105. $result = $db->sql_query($sql);
  2106. while ($row = $db->sql_fetchrow($result))
  2107. {
  2108. if (isset($hold_ary[$row['user_id']][$row['forum_id']]))
  2109. {
  2110. unset($hold_ary[$row['user_id']][$row['forum_id']]);
  2111. }
  2112. }
  2113. $db->sql_freeresult($result);
  2114. if (sizeof($hold_ary))
  2115. {
  2116. // Get usernames...
  2117. $sql = 'SELECT user_id, username
  2118. FROM ' . USERS_TABLE . '
  2119. WHERE ' . $db->sql_in_set('user_id', array_keys($hold_ary));
  2120. $result = $db->sql_query($sql);
  2121. $usernames_ary = array();
  2122. while ($row = $db->sql_fetchrow($result))
  2123. {
  2124. $usernames_ary[$row['user_id']] = $row['username'];
  2125. }
  2126. foreach ($hold_ary as $user_id => $forum_id_ary)
  2127. {
  2128. // Do not continue if user does not exist
  2129. if (!isset($usernames_ary[$user_id]))
  2130. {
  2131. continue;
  2132. }
  2133. foreach ($forum_id_ary as $forum_id => $auth_ary)
  2134. {
  2135. $sql_ary[] = array(
  2136. 'forum_id' => (int) $forum_id,
  2137. 'user_id' => (int) $user_id,
  2138. 'username' => (string) $usernames_ary[$user_id],
  2139. 'group_id' => 0,
  2140. 'group_name' => ''
  2141. );
  2142. }
  2143. }
  2144. }
  2145. }
  2146. // Now to the groups...
  2147. $hold_ary = $auth->acl_group_raw_data(false, 'm_%', false);
  2148. if (sizeof($hold_ary))
  2149. {
  2150. $ug_id_ary = array_keys($hold_ary);
  2151. // Make sure not hidden or special groups are involved...
  2152. $sql = 'SELECT group_name, group_id, group_type
  2153. FROM ' . GROUPS_TABLE . '
  2154. WHERE ' . $db->sql_in_set('group_id', $ug_id_ary);
  2155. $result = $db->sql_query($sql);
  2156. $groupnames_ary = array();
  2157. while ($row = $db->sql_fetchrow($result))
  2158. {
  2159. if ($row['group_type'] == GROUP_HIDDEN || $row['group_type'] == GROUP_SPECIAL)
  2160. {
  2161. unset($hold_ary[$row['group_id']]);
  2162. }
  2163. $groupnames_ary[$row['group_id']] = $row['group_name'];
  2164. }
  2165. $db->sql_freeresult($result);
  2166. foreach ($hold_ary as $group_id => $forum_id_ary)
  2167. {
  2168. // If there is no group, we do not assign it...
  2169. if (!isset($groupnames_ary[$group_id]))
  2170. {
  2171. continue;
  2172. }
  2173. foreach ($forum_id_ary as $forum_id => $auth_ary)
  2174. {
  2175. $flag = false;
  2176. foreach ($auth_ary as $auth_option => $setting)
  2177. {
  2178. // Make sure at least one ACL_YES option is set...
  2179. if ($setting == ACL_YES)
  2180. {
  2181. $flag = true;
  2182. break;
  2183. }
  2184. }
  2185. if (!$flag)
  2186. {
  2187. continue;
  2188. }
  2189. $sql_ary[] = array(
  2190. 'forum_id' => (int) $forum_id,
  2191. 'user_id' => 0,
  2192. 'username' => '',
  2193. 'group_id' => (int) $group_id,
  2194. 'group_name' => (string) $groupnames_ary[$group_id]
  2195. );
  2196. }
  2197. }
  2198. }
  2199. $db->sql_multi_insert(MODERATOR_CACHE_TABLE, $sql_ary);
  2200. }
  2201. /**
  2202. * View log
  2203. *
  2204. * @param string $mode The mode defines which log_type is used and from which log the entry is retrieved
  2205. * @param array &$log The result array with the logs
  2206. * @param mixed &$log_count If $log_count is set to false, we will skip counting all entries in the database.
  2207. * Otherwise an integer with the number of total matching entries is returned.
  2208. * @param int $limit Limit the number of entries that are returned
  2209. * @param int $offset Offset when fetching the log entries, f.e. when paginating
  2210. * @param mixed $forum_id Restrict the log entries to the given forum_id (can also be an array of forum_ids)
  2211. * @param int $topic_id Restrict the log entries to the given topic_id
  2212. * @param int $user_id Restrict the log entries to the given user_id
  2213. * @param int $log_time Only get log entries newer than the given timestamp
  2214. * @param string $sort_by SQL order option, e.g. 'l.log_time DESC'
  2215. * @param string $keywords Will only return log entries that have the keywords in log_operation or log_data
  2216. *
  2217. * @return int Returns the offset of the last valid page, if the specified offset was invalid (too high)
  2218. */
  2219. function view_log($mode, &$log, &$log_count, $limit = 0, $offset = 0, $forum_id = 0, $topic_id = 0, $user_id = 0, $limit_days = 0, $sort_by = 'l.log_time DESC', $keywords = '')
  2220. {
  2221. global $phpbb_log;
  2222. $count_logs = ($log_count !== false);
  2223. $log = $phpbb_log->get_logs($mode, $count_logs, $limit, $offset, $forum_id, $topic_id, $user_id, $limit_days, $sort_by, $keywords);
  2224. $log_count = $phpbb_log->get_log_count();
  2225. return $phpbb_log->get_valid_offset();
  2226. }
  2227. /**
  2228. * Removes moderators and administrators from foe lists.
  2229. *
  2230. * @param \phpbb\db\driver\driver_interface $db Database connection
  2231. * @param \phpbb\auth\auth $auth Authentication object
  2232. * @param array|bool $group_id If an array, remove all members of this group from foe lists, or false to ignore
  2233. * @param array|bool $user_id If an array, remove this user from foe lists, or false to ignore
  2234. * @return null
  2235. */
  2236. function phpbb_update_foes($db, $auth, $group_id = false, $user_id = false)
  2237. {
  2238. // update foes for some user
  2239. if (is_array($user_id) && sizeof($user_id))
  2240. {
  2241. $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
  2242. WHERE ' . $db->sql_in_set('zebra_id', $user_id) . '
  2243. AND foe = 1';
  2244. $db->sql_query($sql);
  2245. return;
  2246. }
  2247. // update foes for some group
  2248. if (is_array($group_id) && sizeof($group_id))
  2249. {
  2250. // Grab group settings...
  2251. $sql_ary = array(
  2252. 'SELECT' => 'a.group_id',
  2253. 'FROM' => array(
  2254. ACL_OPTIONS_TABLE => 'ao',
  2255. ACL_GROUPS_TABLE => 'a',
  2256. ),
  2257. 'LEFT_JOIN' => array(
  2258. array(
  2259. 'FROM' => array(ACL_ROLES_DATA_TABLE => 'r'),
  2260. 'ON' => 'a.auth_role_id = r.role_id',
  2261. ),
  2262. ),
  2263. 'WHERE' => '(ao.auth_option_id = a.auth_option_id OR ao.auth_option_id = r.auth_option_id)
  2264. AND ' . $db->sql_in_set('a.group_id', $group_id) . "
  2265. AND ao.auth_option IN ('a_', 'm_')",
  2266. 'GROUP_BY' => 'a.group_id',
  2267. );
  2268. $sql = $db->sql_build_query('SELECT', $sql_ary);
  2269. $result = $db->sql_query($sql);
  2270. $groups = array();
  2271. while ($row = $db->sql_fetchrow($result))
  2272. {
  2273. $groups[] = (int) $row['group_id'];
  2274. }
  2275. $db->sql_freeresult($result);
  2276. if (!sizeof($groups))
  2277. {
  2278. return;
  2279. }
  2280. switch ($db->sql_layer)
  2281. {
  2282. case 'mysqli':
  2283. case 'mysql4':
  2284. $sql = 'DELETE ' . (($db->sql_layer === 'mysqli' || version_compare($db->sql_server_info(true), '4.1', '>=')) ? 'z.*' : ZEBRA_TABLE) . '
  2285. FROM ' . ZEBRA_TABLE . ' z, ' . USER_GROUP_TABLE . ' ug
  2286. WHERE z.zebra_id = ug.user_id
  2287. AND z.foe = 1
  2288. AND ' . $db->sql_in_set('ug.group_id', $groups);
  2289. $db->sql_query($sql);
  2290. break;
  2291. default:
  2292. $sql = 'SELECT user_id
  2293. FROM ' . USER_GROUP_TABLE . '
  2294. WHERE ' . $db->sql_in_set('group_id', $groups);
  2295. $result = $db->sql_query($sql);
  2296. $users = array();
  2297. while ($row = $db->sql_fetchrow($result))
  2298. {
  2299. $users[] = (int) $row['user_id'];
  2300. }
  2301. $db->sql_freeresult($result);
  2302. if (sizeof($users))
  2303. {
  2304. $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
  2305. WHERE ' . $db->sql_in_set('zebra_id', $users) . '
  2306. AND foe = 1';
  2307. $db->sql_query($sql);
  2308. }
  2309. break;
  2310. }
  2311. return;
  2312. }
  2313. // update foes for everyone
  2314. $perms = array();
  2315. foreach ($auth->acl_get_list(false, array('a_', 'm_'), false) as $forum_id => $forum_ary)
  2316. {
  2317. foreach ($forum_ary as $auth_option => $user_ary)
  2318. {
  2319. $perms = array_merge($perms, $user_ary);
  2320. }
  2321. }
  2322. if (sizeof($perms))
  2323. {
  2324. $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
  2325. WHERE ' . $db->sql_in_set('zebra_id', array_unique($perms)) . '
  2326. AND foe = 1';
  2327. $db->sql_query($sql);
  2328. }
  2329. unset($perms);
  2330. }
  2331. /**
  2332. * Lists inactive users
  2333. */
  2334. function view_inactive_users(&$users, &$user_count, $limit = 0, $offset = 0, $limit_days = 0, $sort_by = 'user_inactive_time DESC')
  2335. {
  2336. global $db, $user;
  2337. $sql = 'SELECT COUNT(user_id) AS user_count
  2338. FROM ' . USERS_TABLE . '
  2339. WHERE user_type = ' . USER_INACTIVE .
  2340. (($limit_days) ? " AND user_inactive_time >= $limit_days" : '');
  2341. $result = $db->sql_query($sql);
  2342. $user_count = (int) $db->sql_fetchfield('user_count');
  2343. $db->sql_freeresult($result);
  2344. if ($user_count == 0)
  2345. {
  2346. // Save the queries, because there are no users to display
  2347. return 0;
  2348. }
  2349. if ($offset >= $user_count)
  2350. {
  2351. $offset = ($offset - $limit < 0) ? 0 : $offset - $limit;
  2352. }
  2353. $sql = 'SELECT *
  2354. FROM ' . USERS_TABLE . '
  2355. WHERE user_type = ' . USER_INACTIVE .
  2356. (($limit_days) ? " AND user_inactive_time >= $limit_days" : '') . "
  2357. ORDER BY $sort_by";
  2358. $result = $db->sql_query_limit($sql, $limit, $offset);
  2359. while ($row = $db->sql_fetchrow($result))
  2360. {
  2361. $row['inactive_reason'] = $user->lang['INACTIVE_REASON_UNKNOWN'];
  2362. switch ($row['user_inactive_reason'])
  2363. {
  2364. case INACTIVE_REGISTER:
  2365. $row['inactive_reason'] = $user->lang['INACTIVE_REASON_REGISTER'];
  2366. break;
  2367. case INACTIVE_PROFILE:
  2368. $row['inactive_reason'] = $user->lang['INACTIVE_REASON_PROFILE'];
  2369. break;
  2370. case INACTIVE_MANUAL:
  2371. $row['inactive_reason'] = $user->lang['INACTIVE_REASON_MANUAL'];
  2372. break;
  2373. case INACTIVE_REMIND:
  2374. $row['inactive_reason'] = $user->lang['INACTIVE_REASON_REMIND'];
  2375. break;
  2376. }
  2377. $users[] = $row;
  2378. }
  2379. return $offset;
  2380. }
  2381. /**
  2382. * Lists warned users
  2383. */
  2384. function view_warned_users(&$users, &$user_count, $limit = 0, $offset = 0, $limit_days = 0, $sort_by = 'user_warnings DESC')
  2385. {
  2386. global $db;
  2387. $sql = 'SELECT user_id, username, user_colour, user_warnings, user_last_warning
  2388. FROM ' . USERS_TABLE . '
  2389. WHERE user_warnings > 0
  2390. ' . (($limit_days) ? "AND user_last_warning >= $limit_days" : '') . "
  2391. ORDER BY $sort_by";
  2392. $result = $db->sql_query_limit($sql, $limit, $offset);
  2393. $users = $db->sql_fetchrowset($result);
  2394. $db->sql_freeresult($result);
  2395. $sql = 'SELECT count(user_id) AS user_count
  2396. FROM ' . USERS_TABLE . '
  2397. WHERE user_warnings > 0
  2398. ' . (($limit_days) ? "AND user_last_warning >= $limit_days" : '');
  2399. $result = $db->sql_query($sql);
  2400. $user_count = (int) $db->sql_fetchfield('user_count');
  2401. $db->sql_freeresult($result);
  2402. return;
  2403. }
  2404. /**
  2405. * Get database size
  2406. * Currently only mysql and mssql are supported
  2407. */
  2408. function get_database_size()
  2409. {
  2410. global $db, $user, $table_prefix;
  2411. $database_size = false;
  2412. // This code is heavily influenced by a similar routine in phpMyAdmin 2.2.0
  2413. switch ($db->sql_layer)
  2414. {
  2415. case 'mysql':
  2416. case 'mysql4':
  2417. case 'mysqli':
  2418. $sql = 'SELECT VERSION() AS mysql_version';
  2419. $result = $db->sql_query($sql);
  2420. $row = $db->sql_fetchrow($result);
  2421. $db->sql_freeresult($result);
  2422. if ($row)
  2423. {
  2424. $version = $row['mysql_version'];
  2425. if (preg_match('#(3\.23|[45]\.)#', $version))
  2426. {
  2427. $db_name = (preg_match('#^(?:3\.23\.(?:[6-9]|[1-9]{2}))|[45]\.#', $version)) ? "`{$db->dbname}`" : $db->dbname;
  2428. $sql = 'SHOW TABLE STATUS
  2429. FROM ' . $db_name;
  2430. $result = $db->sql_query($sql, 7200);
  2431. $database_size = 0;
  2432. while ($row = $db->sql_fetchrow($result))
  2433. {
  2434. if ((isset($row['Type']) && $row['Type'] != 'MRG_MyISAM') || (isset($row['Engine']) && ($row['Engine'] == 'MyISAM' || $row['Engine'] == 'InnoDB')))
  2435. {
  2436. if ($table_prefix != '')
  2437. {
  2438. if (strpos($row['Name'], $table_prefix) !== false)
  2439. {
  2440. $database_size += $row['Data_length'] + $row['Index_length'];
  2441. }
  2442. }
  2443. else
  2444. {
  2445. $database_size += $row['Data_length'] + $row['Index_length'];
  2446. }
  2447. }
  2448. }
  2449. $db->sql_freeresult($result);
  2450. }
  2451. }
  2452. break;
  2453. case 'firebird':
  2454. global $dbname;
  2455. // if it on the local machine, we can get lucky
  2456. if (file_exists($dbname))
  2457. {
  2458. $database_size = filesize($dbname);
  2459. }
  2460. break;
  2461. case 'sqlite':
  2462. case 'sqlite3':
  2463. global $dbhost;
  2464. if (file_exists($dbhost))
  2465. {
  2466. $database_size = filesize($dbhost);
  2467. }
  2468. break;
  2469. case 'mssql':
  2470. case 'mssql_odbc':
  2471. case 'mssqlnative':
  2472. $sql = 'SELECT @@VERSION AS mssql_version';
  2473. $result = $db->sql_query($sql);
  2474. $row = $db->sql_fetchrow($result);
  2475. $db->sql_freeresult($result);
  2476. $sql = 'SELECT ((SUM(size) * 8.0) * 1024.0) as dbsize
  2477. FROM sysfiles';
  2478. if ($row)
  2479. {
  2480. // Azure stats are stored elsewhere
  2481. if (strpos($row['mssql_version'], 'SQL Azure') !== false)
  2482. {
  2483. $sql = 'SELECT ((SUM(reserved_page_count) * 8.0) * 1024.0) as dbsize
  2484. FROM sys.dm_db_partition_stats';
  2485. }
  2486. }
  2487. $result = $db->sql_query($sql, 7200);
  2488. $database_size = ($row = $db->sql_fetchrow($result)) ? $row['dbsize'] : false;
  2489. $db->sql_freeresult($result);
  2490. break;
  2491. case 'postgres':
  2492. $sql = "SELECT proname
  2493. FROM pg_proc
  2494. WHERE proname = 'pg_database_size'";
  2495. $result = $db->sql_query($sql);
  2496. $row = $db->sql_fetchrow($result);
  2497. $db->sql_freeresult($result);
  2498. if ($row['proname'] == 'pg_database_size')
  2499. {
  2500. $database = $db->dbname;
  2501. if (strpos($database, '.') !== false)
  2502. {
  2503. list($database, ) = explode('.', $database);
  2504. }
  2505. $sql = "SELECT oid
  2506. FROM pg_database
  2507. WHERE datname = '$database'";
  2508. $result = $db->sql_query($sql);
  2509. $row = $db->sql_fetchrow($result);
  2510. $db->sql_freeresult($result);
  2511. $oid = $row['oid'];
  2512. $sql = 'SELECT pg_database_size(' . $oid . ') as size';
  2513. $result = $db->sql_query($sql);
  2514. $row = $db->sql_fetchrow($result);
  2515. $db->sql_freeresult($result);
  2516. $database_size = $row['size'];
  2517. }
  2518. break;
  2519. case 'oracle':
  2520. $sql = 'SELECT SUM(bytes) as dbsize
  2521. FROM user_segments';
  2522. $result = $db->sql_query($sql, 7200);
  2523. $database_size = ($row = $db->sql_fetchrow($result)) ? $row['dbsize'] : false;
  2524. $db->sql_freeresult($result);
  2525. break;
  2526. }
  2527. $database_size = ($database_size !== false) ? get_formatted_filesize($database_size) : $user->lang['NOT_AVAILABLE'];
  2528. return $database_size;
  2529. }
  2530. /**
  2531. * Retrieve contents from remotely stored file
  2532. */
  2533. function get_remote_file($host, $directory, $filename, &$errstr, &$errno, $port = 80, $timeout = 6)
  2534. {
  2535. global $user;
  2536. if ($fsock = @fsockopen($host, $port, $errno, $errstr, $timeout))
  2537. {
  2538. @fputs($fsock, "GET $directory/$filename HTTP/1.0\r\n");
  2539. @fputs($fsock, "HOST: $host\r\n");
  2540. @fputs($fsock, "Connection: close\r\n\r\n");
  2541. $timer_stop = time() + $timeout;
  2542. stream_set_timeout($fsock, $timeout);
  2543. $file_info = '';
  2544. $get_info = false;
  2545. while (!@feof($fsock))
  2546. {
  2547. if ($get_info)
  2548. {
  2549. $file_info .= @fread($fsock, 1024);
  2550. }
  2551. else
  2552. {
  2553. $line = @fgets($fsock, 1024);
  2554. if ($line == "\r\n")
  2555. {
  2556. $get_info = true;
  2557. }
  2558. else if (stripos($line, '404 not found') !== false)
  2559. {
  2560. $errstr = $user->lang('FILE_NOT_FOUND', $filename);
  2561. return false;
  2562. }
  2563. }
  2564. $stream_meta_data = stream_get_meta_data($fsock);
  2565. if (!empty($stream_meta_data['timed_out']) || time() >= $timer_stop)
  2566. {
  2567. $errstr = $user->lang['FSOCK_TIMEOUT'];
  2568. return false;
  2569. }
  2570. }
  2571. @fclose($fsock);
  2572. }
  2573. else
  2574. {
  2575. if ($errstr)
  2576. {
  2577. $errstr = utf8_convert_message($errstr);
  2578. return false;
  2579. }
  2580. else
  2581. {
  2582. $errstr = $user->lang['FSOCK_DISABLED'];
  2583. return false;
  2584. }
  2585. }
  2586. return $file_info;
  2587. }
  2588. /*
  2589. * Tidy Warnings
  2590. * Remove all warnings which have now expired from the database
  2591. * The duration of a warning can be defined by the administrator
  2592. * This only removes the warning and reduces the associated count,
  2593. * it does not remove the user note recording the contents of the warning
  2594. */
  2595. function tidy_warnings()
  2596. {
  2597. global $db, $config;
  2598. $expire_date = time() - ($config['warnings_expire_days'] * 86400);
  2599. $warning_list = $user_list = array();
  2600. $sql = 'SELECT * FROM ' . WARNINGS_TABLE . "
  2601. WHERE warning_time < $expire_date";
  2602. $result = $db->sql_query($sql);
  2603. while ($row = $db->sql_fetchrow($result))
  2604. {
  2605. $warning_list[] = $row['warning_id'];
  2606. $user_list[$row['user_id']] = isset($user_list[$row['user_id']]) ? ++$user_list[$row['user_id']] : 1;
  2607. }
  2608. $db->sql_freeresult($result);
  2609. if (sizeof($warning_list))
  2610. {
  2611. $db->sql_transaction('begin');
  2612. $sql = 'DELETE FROM ' . WARNINGS_TABLE . '
  2613. WHERE ' . $db->sql_in_set('warning_id', $warning_list);
  2614. $db->sql_query($sql);
  2615. foreach ($user_list as $user_id => $value)
  2616. {
  2617. $sql = 'UPDATE ' . USERS_TABLE . " SET user_warnings = user_warnings - $value
  2618. WHERE user_id = $user_id";
  2619. $db->sql_query($sql);
  2620. }
  2621. $db->sql_transaction('commit');
  2622. }
  2623. set_config('warnings_last_gc', time(), true);
  2624. }
  2625. /**
  2626. * Tidy database, doing some maintanance tasks
  2627. */
  2628. function tidy_database()
  2629. {
  2630. global $db;
  2631. // Here we check permission consistency
  2632. // Sometimes, it can happen permission tables having forums listed which do not exist
  2633. $sql = 'SELECT forum_id
  2634. FROM ' . FORUMS_TABLE;
  2635. $result = $db->sql_query($sql);
  2636. $forum_ids = array(0);
  2637. while ($row = $db->sql_fetchrow($result))
  2638. {
  2639. $forum_ids[] = $row['forum_id'];
  2640. }
  2641. $db->sql_freeresult($result);
  2642. // Delete those rows from the acl tables not having listed the forums above
  2643. $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . '
  2644. WHERE ' . $db->sql_in_set('forum_id', $forum_ids, true);
  2645. $db->sql_query($sql);
  2646. $sql = 'DELETE FROM ' . ACL_USERS_TABLE . '
  2647. WHERE ' . $db->sql_in_set('forum_id', $forum_ids, true);
  2648. $db->sql_query($sql);
  2649. set_config('database_last_gc', time(), true);
  2650. }
  2651. /**
  2652. * Add permission language - this will make sure custom files will be included
  2653. */
  2654. function add_permission_language()
  2655. {
  2656. global $user, $phpEx, $phpbb_extension_manager;
  2657. // add permission language files from extensions
  2658. $finder = $phpbb_extension_manager->get_finder();
  2659. $lang_files = $finder
  2660. ->prefix('permissions_')
  2661. ->suffix(".$phpEx")
  2662. ->core_path('language/' . $user->lang_name . '/')
  2663. ->extension_directory('/language/' . $user->lang_name)
  2664. ->find();
  2665. foreach ($lang_files as $lang_file => $ext_name)
  2666. {
  2667. if ($ext_name === '/')
  2668. {
  2669. $user->add_lang($lang_file);
  2670. }
  2671. else
  2672. {
  2673. $user->add_lang_ext($ext_name, $lang_file);
  2674. }
  2675. }
  2676. }
  2677. /**
  2678. * Enables a particular flag in a bitfield column of a given table.
  2679. *
  2680. * @param string $table_name The table to update
  2681. * @param string $column_name The column containing a bitfield to update
  2682. * @param int $flag The binary flag which is OR-ed with the current column value
  2683. * @param string $sql_more This string is attached to the sql query generated to update the table.
  2684. *
  2685. * @return null
  2686. */
  2687. function enable_bitfield_column_flag($table_name, $column_name, $flag, $sql_more = '')
  2688. {
  2689. global $db;
  2690. $sql = 'UPDATE ' . $table_name . '
  2691. SET ' . $column_name . ' = ' . $db->sql_bit_or($column_name, $flag) . '
  2692. ' . $sql_more;
  2693. $db->sql_query($sql);
  2694. }