diff options
Diffstat (limited to 'phpBB/phpbb')
494 files changed, 82550 insertions, 0 deletions
diff --git a/phpBB/phpbb/auth/auth.php b/phpBB/phpbb/auth/auth.php new file mode 100644 index 0000000000..37d4352c10 --- /dev/null +++ b/phpBB/phpbb/auth/auth.php @@ -0,0 +1,1121 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth; + +/** +* Permission/Auth class +*/ +class auth +{ + var $acl = array(); + var $cache = array(); + var $acl_options = array(); + var $acl_forum_ids = false; + + /** + * Init permissions + */ + function acl(&$userdata) + { + global $db, $cache; + + $this->acl = $this->cache = $this->acl_options = array(); + $this->acl_forum_ids = false; + + if (($this->acl_options = $cache->get('_acl_options')) === false) + { + $sql = 'SELECT auth_option_id, auth_option, is_global, is_local + FROM ' . ACL_OPTIONS_TABLE . ' + ORDER BY auth_option_id'; + $result = $db->sql_query($sql); + + $global = $local = 0; + $this->acl_options = array(); + while ($row = $db->sql_fetchrow($result)) + { + if ($row['is_global']) + { + $this->acl_options['global'][$row['auth_option']] = $global++; + } + + if ($row['is_local']) + { + $this->acl_options['local'][$row['auth_option']] = $local++; + } + + $this->acl_options['id'][$row['auth_option']] = (int) $row['auth_option_id']; + $this->acl_options['option'][(int) $row['auth_option_id']] = $row['auth_option']; + } + $db->sql_freeresult($result); + + $cache->put('_acl_options', $this->acl_options); + } + + if (!trim($userdata['user_permissions'])) + { + $this->acl_cache($userdata); + } + + // Fill ACL array + $this->_fill_acl($userdata['user_permissions']); + + // Verify bitstring length with options provided... + $renew = false; + $global_length = sizeof($this->acl_options['global']); + $local_length = sizeof($this->acl_options['local']); + + // Specify comparing length (bitstring is padded to 31 bits) + $global_length = ($global_length % 31) ? ($global_length - ($global_length % 31) + 31) : $global_length; + $local_length = ($local_length % 31) ? ($local_length - ($local_length % 31) + 31) : $local_length; + + // You thought we are finished now? Noooo... now compare them. + foreach ($this->acl as $forum_id => $bitstring) + { + if (($forum_id && strlen($bitstring) != $local_length) || (!$forum_id && strlen($bitstring) != $global_length)) + { + $renew = true; + break; + } + } + + // If a bitstring within the list does not match the options, we have a user with incorrect permissions set and need to renew them + if ($renew) + { + $this->acl_cache($userdata); + $this->_fill_acl($userdata['user_permissions']); + } + + return; + } + + /** + * Retrieves data wanted by acl function from the database for the + * specified user. + * + * @param int $user_id User ID + * @return array User attributes + */ + public function obtain_user_data($user_id) + { + global $db; + + $sql = 'SELECT user_id, username, user_permissions, user_type + FROM ' . USERS_TABLE . ' + WHERE user_id = ' . $user_id; + $result = $db->sql_query($sql); + $user_data = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + return $user_data; + } + + /** + * Fill ACL array with relevant bitstrings from user_permissions column + * @access private + */ + function _fill_acl($user_permissions) + { + $seq_cache = array(); + $this->acl = array(); + $user_permissions = explode("\n", $user_permissions); + + foreach ($user_permissions as $f => $seq) + { + if ($seq) + { + $i = 0; + + if (!isset($this->acl[$f])) + { + $this->acl[$f] = ''; + } + + while ($subseq = substr($seq, $i, 6)) + { + if (isset($seq_cache[$subseq])) + { + $converted = $seq_cache[$subseq]; + } + else + { + $converted = $seq_cache[$subseq] = str_pad(base_convert($subseq, 36, 2), 31, 0, STR_PAD_LEFT); + } + + // We put the original bitstring into the acl array + $this->acl[$f] .= $converted; + $i += 6; + } + } + } + } + + /** + * Look up an option + * if the option is prefixed with !, then the result becomes negated + * + * If a forum id is specified the local option will be combined with a global option if one exist. + * If a forum id is not specified, only the global option will be checked. + */ + function acl_get($opt, $f = 0) + { + $negate = false; + + if (strpos($opt, '!') === 0) + { + $negate = true; + $opt = substr($opt, 1); + } + + if (!isset($this->cache[$f][$opt])) + { + // We combine the global/local option with an OR because some options are global and local. + // If the user has the global permission the local one is true too and vice versa + $this->cache[$f][$opt] = false; + + // Is this option a global permission setting? + if (isset($this->acl_options['global'][$opt])) + { + if (isset($this->acl[0])) + { + $this->cache[$f][$opt] = $this->acl[0][$this->acl_options['global'][$opt]]; + } + } + + // Is this option a local permission setting? + // But if we check for a global option only, we won't combine the options... + if ($f != 0 && isset($this->acl_options['local'][$opt])) + { + if (isset($this->acl[$f]) && isset($this->acl[$f][$this->acl_options['local'][$opt]])) + { + $this->cache[$f][$opt] |= $this->acl[$f][$this->acl_options['local'][$opt]]; + } + } + } + + // Founder always has all global options set to true... + return ($negate) ? !$this->cache[$f][$opt] : $this->cache[$f][$opt]; + } + + /** + * Get forums with the specified permission setting + * + * @param string $opt The permission name to lookup. If prefixed with !, the result is negated. + * @param bool $clean set to true if only values needs to be returned which are set/unset + * + * @return array Contains the forum ids with the specified permission set to true. + This is a nested array: array => forum_id => permission => true + */ + function acl_getf($opt, $clean = false) + { + $acl_f = array(); + $negate = false; + + if (strpos($opt, '!') === 0) + { + $negate = true; + $opt = substr($opt, 1); + } + + // If we retrieve a list of forums not having permissions in, we need to get every forum_id + if ($negate) + { + if ($this->acl_forum_ids === false) + { + global $db; + + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE; + + if (sizeof($this->acl)) + { + $sql .= ' WHERE ' . $db->sql_in_set('forum_id', array_keys($this->acl), true); + } + $result = $db->sql_query($sql); + + $this->acl_forum_ids = array(); + while ($row = $db->sql_fetchrow($result)) + { + $this->acl_forum_ids[] = $row['forum_id']; + } + $db->sql_freeresult($result); + } + } + + if (isset($this->acl_options['local'][$opt])) + { + foreach ($this->acl as $f => $bitstring) + { + // Skip global settings + if (!$f) + { + continue; + } + + $allowed = (!isset($this->cache[$f][$opt])) ? $this->acl_get($opt, $f) : $this->cache[$f][$opt]; + + if (!$clean) + { + $acl_f[$f][$opt] = ($negate) ? !$allowed : $allowed; + } + else + { + if (($negate && !$allowed) || (!$negate && $allowed)) + { + $acl_f[$f][$opt] = 1; + } + } + } + } + + // If we get forum_ids not having this permission, we need to fill the remaining parts + if ($negate && sizeof($this->acl_forum_ids)) + { + foreach ($this->acl_forum_ids as $f) + { + $acl_f[$f][$opt] = 1; + } + } + + return $acl_f; + } + + /** + * Get local permission state for any forum. + * + * Returns true if user has the permission in one or more forums, false if in no forum. + * If global option is checked it returns the global state (same as acl_get($opt)) + * Local option has precedence... + */ + function acl_getf_global($opt) + { + if (is_array($opt)) + { + // evaluates to true as soon as acl_getf_global is true for one option + foreach ($opt as $check_option) + { + if ($this->acl_getf_global($check_option)) + { + return true; + } + } + + return false; + } + + if (isset($this->acl_options['local'][$opt])) + { + foreach ($this->acl as $f => $bitstring) + { + // Skip global settings + if (!$f) + { + continue; + } + + // as soon as the user has any permission we're done so return true + if ((!isset($this->cache[$f][$opt])) ? $this->acl_get($opt, $f) : $this->cache[$f][$opt]) + { + return true; + } + } + } + else if (isset($this->acl_options['global'][$opt])) + { + return $this->acl_get($opt); + } + + return false; + } + + /** + * Get permission settings (more than one) + */ + function acl_gets() + { + $args = func_get_args(); + $f = array_pop($args); + + if (!is_numeric($f)) + { + $args[] = $f; + $f = 0; + } + + // alternate syntax: acl_gets(array('m_', 'a_'), $forum_id) + if (is_array($args[0])) + { + $args = $args[0]; + } + + $acl = 0; + foreach ($args as $opt) + { + $acl |= $this->acl_get($opt, $f); + } + + return $acl; + } + + /** + * Get permission listing based on user_id/options/forum_ids + * + * Be careful when using this function with permissions a_, m_, u_ and f_ ! + * It may not work correctly. When a user group grants an a_* permission, + * e.g. a_foo, but the user's a_foo permission is set to "Never", then + * the user does not in fact have the a_ permission. + * But the user will still be listed as having the a_ permission. + * + * For more information see: http://tracker.phpbb.com/browse/PHPBB3-10252 + */ + function acl_get_list($user_id = false, $opts = false, $forum_id = false) + { + if ($user_id !== false && !is_array($user_id) && $opts === false && $forum_id === false) + { + $hold_ary = array($user_id => $this->acl_raw_data_single_user($user_id)); + } + else + { + $hold_ary = $this->acl_raw_data($user_id, $opts, $forum_id); + } + + $auth_ary = array(); + foreach ($hold_ary as $user_id => $forum_ary) + { + foreach ($forum_ary as $forum_id => $auth_option_ary) + { + foreach ($auth_option_ary as $auth_option => $auth_setting) + { + if ($auth_setting) + { + $auth_ary[$forum_id][$auth_option][] = $user_id; + } + } + } + } + + return $auth_ary; + } + + /** + * Cache data to user_permissions row + */ + function acl_cache(&$userdata) + { + global $db; + + // Empty user_permissions + $userdata['user_permissions'] = ''; + + $hold_ary = $this->acl_raw_data_single_user($userdata['user_id']); + + // Key 0 in $hold_ary are global options, all others are forum_ids + + // If this user is founder we're going to force fill the admin options ... + if ($userdata['user_type'] == USER_FOUNDER) + { + foreach ($this->acl_options['global'] as $opt => $id) + { + if (strpos($opt, 'a_') === 0) + { + $hold_ary[0][$this->acl_options['id'][$opt]] = ACL_YES; + } + } + } + + $hold_str = $this->build_bitstring($hold_ary); + + if ($hold_str) + { + $userdata['user_permissions'] = $hold_str; + + $sql = 'UPDATE ' . USERS_TABLE . " + SET user_permissions = '" . $db->sql_escape($userdata['user_permissions']) . "', + user_perm_from = 0 + WHERE user_id = " . $userdata['user_id']; + $db->sql_query($sql); + } + + return; + } + + /** + * Build bitstring from permission set + */ + function build_bitstring(&$hold_ary) + { + $hold_str = ''; + + if (sizeof($hold_ary)) + { + ksort($hold_ary); + + $last_f = 0; + + foreach ($hold_ary as $f => $auth_ary) + { + $ary_key = (!$f) ? 'global' : 'local'; + + $bitstring = array(); + foreach ($this->acl_options[$ary_key] as $opt => $id) + { + if (isset($auth_ary[$this->acl_options['id'][$opt]])) + { + $bitstring[$id] = $auth_ary[$this->acl_options['id'][$opt]]; + + $option_key = substr($opt, 0, strpos($opt, '_') + 1); + + // If one option is allowed, the global permission for this option has to be allowed too + // example: if the user has the a_ permission this means he has one or more a_* permissions + if ($auth_ary[$this->acl_options['id'][$opt]] == ACL_YES && (!isset($bitstring[$this->acl_options[$ary_key][$option_key]]) || $bitstring[$this->acl_options[$ary_key][$option_key]] == ACL_NEVER)) + { + $bitstring[$this->acl_options[$ary_key][$option_key]] = ACL_YES; + } + } + else + { + $bitstring[$id] = ACL_NEVER; + } + } + + // Now this bitstring defines the permission setting for the current forum $f (or global setting) + $bitstring = implode('', $bitstring); + + // The line number indicates the id, therefore we have to add empty lines for those ids not present + $hold_str .= str_repeat("\n", $f - $last_f); + + // Convert bitstring for storage - we do not use binary/bytes because PHP's string functions are not fully binary safe + for ($i = 0, $bit_length = strlen($bitstring); $i < $bit_length; $i += 31) + { + $hold_str .= str_pad(base_convert(str_pad(substr($bitstring, $i, 31), 31, 0, STR_PAD_RIGHT), 2, 36), 6, 0, STR_PAD_LEFT); + } + + $last_f = $f; + } + unset($bitstring); + + $hold_str = rtrim($hold_str); + } + + return $hold_str; + } + + /** + * Clear one or all users cached permission settings + */ + function acl_clear_prefetch($user_id = false) + { + global $db, $cache, $phpbb_dispatcher; + + // Rebuild options cache + $cache->destroy('_role_cache'); + + $sql = 'SELECT * + FROM ' . ACL_ROLES_DATA_TABLE . ' + ORDER BY role_id ASC'; + $result = $db->sql_query($sql); + + $this->role_cache = array(); + while ($row = $db->sql_fetchrow($result)) + { + $this->role_cache[$row['role_id']][$row['auth_option_id']] = (int) $row['auth_setting']; + } + $db->sql_freeresult($result); + + foreach ($this->role_cache as $role_id => $role_options) + { + $this->role_cache[$role_id] = serialize($role_options); + } + + $cache->put('_role_cache', $this->role_cache); + + // Now empty user permissions + $where_sql = ''; + + if ($user_id !== false) + { + $user_id = (!is_array($user_id)) ? $user_id = array((int) $user_id) : array_map('intval', $user_id); + $where_sql = ' WHERE ' . $db->sql_in_set('user_id', $user_id); + } + + $sql = 'UPDATE ' . USERS_TABLE . " + SET user_permissions = '', + user_perm_from = 0 + $where_sql"; + $db->sql_query($sql); + + /** + * Event is triggered after user(s) permission settings cache has been cleared + * + * @event core.acl_clear_prefetch_after + * @var mixed user_id User ID(s) + * @since 3.1.11-RC1 + */ + $vars = array('user_id'); + extract($phpbb_dispatcher->trigger_event('core.acl_clear_prefetch_after', compact($vars))); + + return; + } + + /** + * Get assigned roles + */ + function acl_role_data($user_type, $role_type, $ug_id = false, $forum_id = false) + { + global $db; + + $roles = array(); + + $sql_id = ($user_type == 'user') ? 'user_id' : 'group_id'; + + $sql_ug = ($ug_id !== false) ? ((!is_array($ug_id)) ? "AND a.$sql_id = $ug_id" : 'AND ' . $db->sql_in_set("a.$sql_id", $ug_id)) : ''; + $sql_forum = ($forum_id !== false) ? ((!is_array($forum_id)) ? "AND a.forum_id = $forum_id" : 'AND ' . $db->sql_in_set('a.forum_id', $forum_id)) : ''; + + // Grab assigned roles... + $sql = 'SELECT a.auth_role_id, a.' . $sql_id . ', a.forum_id + FROM ' . (($user_type == 'user') ? ACL_USERS_TABLE : ACL_GROUPS_TABLE) . ' a, ' . ACL_ROLES_TABLE . " r + WHERE a.auth_role_id = r.role_id + AND r.role_type = '" . $db->sql_escape($role_type) . "' + $sql_ug + $sql_forum + ORDER BY r.role_order ASC"; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $roles[$row[$sql_id]][$row['forum_id']] = $row['auth_role_id']; + } + $db->sql_freeresult($result); + + return $roles; + } + + /** + * Get raw acl data based on user/option/forum + */ + function acl_raw_data($user_id = false, $opts = false, $forum_id = false) + { + global $db; + + $sql_user = ($user_id !== false) ? ((!is_array($user_id)) ? 'user_id = ' . (int) $user_id : $db->sql_in_set('user_id', array_map('intval', $user_id))) : ''; + $sql_forum = ($forum_id !== false) ? ((!is_array($forum_id)) ? 'AND a.forum_id = ' . (int) $forum_id : 'AND ' . $db->sql_in_set('a.forum_id', array_map('intval', $forum_id))) : ''; + + $sql_opts = $sql_opts_select = $sql_opts_from = ''; + $hold_ary = array(); + + if ($opts !== false) + { + $sql_opts_select = ', ao.auth_option'; + $sql_opts_from = ', ' . ACL_OPTIONS_TABLE . ' ao'; + $this->build_auth_option_statement('ao.auth_option', $opts, $sql_opts); + } + + $sql_ary = array(); + + // Grab non-role settings - user-specific + $sql_ary[] = 'SELECT a.user_id, a.forum_id, a.auth_setting, a.auth_option_id' . $sql_opts_select . ' + FROM ' . ACL_USERS_TABLE . ' a' . $sql_opts_from . ' + WHERE a.auth_role_id = 0 ' . + (($sql_opts_from) ? 'AND a.auth_option_id = ao.auth_option_id ' : '') . + (($sql_user) ? 'AND a.' . $sql_user : '') . " + $sql_forum + $sql_opts"; + + // Now the role settings - user-specific + $sql_ary[] = 'SELECT a.user_id, a.forum_id, r.auth_option_id, r.auth_setting, r.auth_option_id' . $sql_opts_select . ' + FROM ' . ACL_USERS_TABLE . ' a, ' . ACL_ROLES_DATA_TABLE . ' r' . $sql_opts_from . ' + WHERE a.auth_role_id = r.role_id ' . + (($sql_opts_from) ? 'AND r.auth_option_id = ao.auth_option_id ' : '') . + (($sql_user) ? 'AND a.' . $sql_user : '') . " + $sql_forum + $sql_opts"; + + foreach ($sql_ary as $sql) + { + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $option = ($sql_opts_select) ? $row['auth_option'] : $this->acl_options['option'][$row['auth_option_id']]; + $hold_ary[$row['user_id']][$row['forum_id']][$option] = $row['auth_setting']; + } + $db->sql_freeresult($result); + } + + $sql_ary = array(); + + // Now grab group settings - non-role specific... + $sql_ary[] = 'SELECT ug.user_id, a.forum_id, a.auth_setting, a.auth_option_id' . $sql_opts_select . ' + FROM ' . ACL_GROUPS_TABLE . ' a, ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g' . $sql_opts_from . ' + WHERE a.auth_role_id = 0 ' . + (($sql_opts_from) ? 'AND a.auth_option_id = ao.auth_option_id ' : '') . ' + AND a.group_id = ug.group_id + AND g.group_id = ug.group_id + AND ug.user_pending = 0 + AND NOT (ug.group_leader = 1 AND g.group_skip_auth = 1) + ' . (($sql_user) ? 'AND ug.' . $sql_user : '') . " + $sql_forum + $sql_opts"; + + // Now grab group settings - role specific... + $sql_ary[] = 'SELECT ug.user_id, a.forum_id, r.auth_setting, r.auth_option_id' . $sql_opts_select . ' + FROM ' . ACL_GROUPS_TABLE . ' a, ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g, ' . ACL_ROLES_DATA_TABLE . ' r' . $sql_opts_from . ' + WHERE a.auth_role_id = r.role_id ' . + (($sql_opts_from) ? 'AND r.auth_option_id = ao.auth_option_id ' : '') . ' + AND a.group_id = ug.group_id + AND g.group_id = ug.group_id + AND ug.user_pending = 0 + AND NOT (ug.group_leader = 1 AND g.group_skip_auth = 1) + ' . (($sql_user) ? 'AND ug.' . $sql_user : '') . " + $sql_forum + $sql_opts"; + + foreach ($sql_ary as $sql) + { + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $option = ($sql_opts_select) ? $row['auth_option'] : $this->acl_options['option'][$row['auth_option_id']]; + + if (!isset($hold_ary[$row['user_id']][$row['forum_id']][$option]) || (isset($hold_ary[$row['user_id']][$row['forum_id']][$option]) && $hold_ary[$row['user_id']][$row['forum_id']][$option] != ACL_NEVER)) + { + $hold_ary[$row['user_id']][$row['forum_id']][$option] = $row['auth_setting']; + + // If we detect ACL_NEVER, we will unset the flag option (within building the bitstring it is correctly set again) + if ($row['auth_setting'] == ACL_NEVER) + { + $flag = substr($option, 0, strpos($option, '_') + 1); + + if (isset($hold_ary[$row['user_id']][$row['forum_id']][$flag]) && $hold_ary[$row['user_id']][$row['forum_id']][$flag] == ACL_YES) + { + unset($hold_ary[$row['user_id']][$row['forum_id']][$flag]); + +/* if (in_array(ACL_YES, $hold_ary[$row['user_id']][$row['forum_id']])) + { + $hold_ary[$row['user_id']][$row['forum_id']][$flag] = ACL_YES; + } +*/ + } + } + } + } + $db->sql_freeresult($result); + } + + return $hold_ary; + } + + /** + * Get raw user based permission settings + */ + function acl_user_raw_data($user_id = false, $opts = false, $forum_id = false) + { + global $db; + + $sql_user = ($user_id !== false) ? ((!is_array($user_id)) ? 'user_id = ' . (int) $user_id : $db->sql_in_set('user_id', array_map('intval', $user_id))) : ''; + $sql_forum = ($forum_id !== false) ? ((!is_array($forum_id)) ? 'AND a.forum_id = ' . (int) $forum_id : 'AND ' . $db->sql_in_set('a.forum_id', array_map('intval', $forum_id))) : ''; + + $sql_opts = ''; + $hold_ary = $sql_ary = array(); + + if ($opts !== false) + { + $this->build_auth_option_statement('ao.auth_option', $opts, $sql_opts); + } + + // Grab user settings - non-role specific... + $sql_ary[] = 'SELECT a.user_id, a.forum_id, a.auth_setting, a.auth_option_id, ao.auth_option + FROM ' . ACL_USERS_TABLE . ' a, ' . ACL_OPTIONS_TABLE . ' ao + WHERE a.auth_role_id = 0 + AND a.auth_option_id = ao.auth_option_id ' . + (($sql_user) ? 'AND a.' . $sql_user : '') . " + $sql_forum + $sql_opts + ORDER BY a.forum_id, ao.auth_option"; + + // Now the role settings - user-specific + $sql_ary[] = 'SELECT a.user_id, a.forum_id, r.auth_option_id, r.auth_setting, r.auth_option_id, ao.auth_option + FROM ' . ACL_USERS_TABLE . ' a, ' . ACL_ROLES_DATA_TABLE . ' r, ' . ACL_OPTIONS_TABLE . ' ao + WHERE a.auth_role_id = r.role_id + AND r.auth_option_id = ao.auth_option_id ' . + (($sql_user) ? 'AND a.' . $sql_user : '') . " + $sql_forum + $sql_opts + ORDER BY a.forum_id, ao.auth_option"; + + foreach ($sql_ary as $sql) + { + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $hold_ary[$row['user_id']][$row['forum_id']][$row['auth_option']] = $row['auth_setting']; + } + $db->sql_freeresult($result); + } + + return $hold_ary; + } + + /** + * Get raw group based permission settings + */ + function acl_group_raw_data($group_id = false, $opts = false, $forum_id = false) + { + global $db; + + $sql_group = ($group_id !== false) ? ((!is_array($group_id)) ? 'group_id = ' . (int) $group_id : $db->sql_in_set('group_id', array_map('intval', $group_id))) : ''; + $sql_forum = ($forum_id !== false) ? ((!is_array($forum_id)) ? 'AND a.forum_id = ' . (int) $forum_id : 'AND ' . $db->sql_in_set('a.forum_id', array_map('intval', $forum_id))) : ''; + + $sql_opts = ''; + $hold_ary = $sql_ary = array(); + + if ($opts !== false) + { + $this->build_auth_option_statement('ao.auth_option', $opts, $sql_opts); + } + + // Grab group settings - non-role specific... + $sql_ary[] = 'SELECT a.group_id, a.forum_id, a.auth_setting, a.auth_option_id, ao.auth_option + FROM ' . ACL_GROUPS_TABLE . ' a, ' . ACL_OPTIONS_TABLE . ' ao + WHERE a.auth_role_id = 0 + AND a.auth_option_id = ao.auth_option_id ' . + (($sql_group) ? 'AND a.' . $sql_group : '') . " + $sql_forum + $sql_opts + ORDER BY a.forum_id, ao.auth_option"; + + // Now grab group settings - role specific... + $sql_ary[] = 'SELECT a.group_id, a.forum_id, r.auth_setting, r.auth_option_id, ao.auth_option + FROM ' . ACL_GROUPS_TABLE . ' a, ' . ACL_ROLES_DATA_TABLE . ' r, ' . ACL_OPTIONS_TABLE . ' ao + WHERE a.auth_role_id = r.role_id + AND r.auth_option_id = ao.auth_option_id ' . + (($sql_group) ? 'AND a.' . $sql_group : '') . " + $sql_forum + $sql_opts + ORDER BY a.forum_id, ao.auth_option"; + + foreach ($sql_ary as $sql) + { + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $hold_ary[$row['group_id']][$row['forum_id']][$row['auth_option']] = $row['auth_setting']; + } + $db->sql_freeresult($result); + } + + return $hold_ary; + } + + /** + * Get raw acl data based on user for caching user_permissions + * This function returns the same data as acl_raw_data(), but without the user id as the first key within the array. + */ + function acl_raw_data_single_user($user_id) + { + global $db, $cache; + + // Check if the role-cache is there + if (($this->role_cache = $cache->get('_role_cache')) === false) + { + $this->role_cache = array(); + + // We pre-fetch roles + $sql = 'SELECT * + FROM ' . ACL_ROLES_DATA_TABLE . ' + ORDER BY role_id ASC'; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $this->role_cache[$row['role_id']][$row['auth_option_id']] = (int) $row['auth_setting']; + } + $db->sql_freeresult($result); + + foreach ($this->role_cache as $role_id => $role_options) + { + $this->role_cache[$role_id] = serialize($role_options); + } + + $cache->put('_role_cache', $this->role_cache); + } + + $hold_ary = array(); + + // Grab user-specific permission settings + $sql = 'SELECT forum_id, auth_option_id, auth_role_id, auth_setting + FROM ' . ACL_USERS_TABLE . ' + WHERE user_id = ' . $user_id; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + // If a role is assigned, assign all options included within this role. Else, only set this one option. + if ($row['auth_role_id']) + { + $hold_ary[$row['forum_id']] = (empty($hold_ary[$row['forum_id']])) ? unserialize($this->role_cache[$row['auth_role_id']]) : $hold_ary[$row['forum_id']] + unserialize($this->role_cache[$row['auth_role_id']]); + } + else + { + $hold_ary[$row['forum_id']][$row['auth_option_id']] = $row['auth_setting']; + } + } + $db->sql_freeresult($result); + + // Now grab group-specific permission settings + $sql = 'SELECT a.forum_id, a.auth_option_id, a.auth_role_id, a.auth_setting + FROM ' . ACL_GROUPS_TABLE . ' a, ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g + WHERE a.group_id = ug.group_id + AND g.group_id = ug.group_id + AND ug.user_pending = 0 + AND NOT (ug.group_leader = 1 AND g.group_skip_auth = 1) + AND ug.user_id = ' . $user_id; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + if (!$row['auth_role_id']) + { + $this->_set_group_hold_ary($hold_ary[$row['forum_id']], $row['auth_option_id'], $row['auth_setting']); + } + else if (!empty($this->role_cache[$row['auth_role_id']])) + { + foreach (unserialize($this->role_cache[$row['auth_role_id']]) as $option_id => $setting) + { + $this->_set_group_hold_ary($hold_ary[$row['forum_id']], $option_id, $setting); + } + } + } + $db->sql_freeresult($result); + + return $hold_ary; + } + + /** + * Private function snippet for setting a specific piece of the hold_ary + */ + function _set_group_hold_ary(&$hold_ary, $option_id, $setting) + { + if (!isset($hold_ary[$option_id]) || (isset($hold_ary[$option_id]) && $hold_ary[$option_id] != ACL_NEVER)) + { + $hold_ary[$option_id] = $setting; + + // If we detect ACL_NEVER, we will unset the flag option (within building the bitstring it is correctly set again) + if ($setting == ACL_NEVER) + { + $flag = substr($this->acl_options['option'][$option_id], 0, strpos($this->acl_options['option'][$option_id], '_') + 1); + $flag = (int) $this->acl_options['id'][$flag]; + + if (isset($hold_ary[$flag]) && $hold_ary[$flag] == ACL_YES) + { + unset($hold_ary[$flag]); + +/* This is uncommented, because i suspect this being slightly wrong due to mixed permission classes being possible + if (in_array(ACL_YES, $hold_ary)) + { + $hold_ary[$flag] = ACL_YES; + }*/ + } + } + } + } + + /** + * Authentication plug-ins is largely down to Sergey Kanareykin, our thanks to him. + */ + function login($username, $password, $autologin = false, $viewonline = 1, $admin = 0) + { + global $db, $user, $phpbb_root_path, $phpEx, $phpbb_container; + global $phpbb_dispatcher; + + $provider_collection = $phpbb_container->get('auth.provider_collection'); + + $provider = $provider_collection->get_provider(); + if ($provider) + { + $login = $provider->login($username, $password); + + // If the auth module wants us to create an empty profile do so and then treat the status as LOGIN_SUCCESS + if ($login['status'] == LOGIN_SUCCESS_CREATE_PROFILE) + { + // we are going to use the user_add function so include functions_user.php if it wasn't defined yet + if (!function_exists('user_add')) + { + include($phpbb_root_path . 'includes/functions_user.' . $phpEx); + } + + user_add($login['user_row'], (isset($login['cp_data'])) ? $login['cp_data'] : false); + + $sql = 'SELECT user_id, username, user_password, user_passchg, user_email, user_type + FROM ' . USERS_TABLE . " + WHERE username_clean = '" . $db->sql_escape(utf8_clean_string($username)) . "'"; + $result = $db->sql_query($sql); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if (!$row) + { + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'AUTH_NO_PROFILE_CREATED', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + $login = array( + 'status' => LOGIN_SUCCESS, + 'error_msg' => false, + 'user_row' => $row, + ); + } + + // If the auth provider wants us to link an empty account do so and redirect + if ($login['status'] == LOGIN_SUCCESS_LINK_PROFILE) + { + // If this status exists a fourth field is in the $login array called 'redirect_data' + // This data is passed along as GET data to the next page allow the account to be linked + + $params = array('mode' => 'login_link'); + $url = append_sid($phpbb_root_path . 'ucp.' . $phpEx, array_merge($params, $login['redirect_data'])); + + redirect($url); + } + + /** + * Event is triggered after checking for valid username and password, and before the actual session creation. + * + * @event core.auth_login_session_create_before + * @var array login Variable containing login array + * @var bool admin Boolean variable whether user is logging into the ACP + * @var string username Username of user to log in + * @var bool autologin Boolean variable signaling whether login is triggered via auto login + * @since 3.1.7-RC1 + */ + $vars = array( + 'login', + 'admin', + 'username', + 'autologin', + ); + extract($phpbb_dispatcher->trigger_event('core.auth_login_session_create_before', compact($vars))); + + // If login succeeded, we will log the user in... else we pass the login array through... + if ($login['status'] == LOGIN_SUCCESS) + { + $old_session_id = $user->session_id; + + if ($admin) + { + global $SID, $_SID; + + $cookie_expire = time() - 31536000; + $user->set_cookie('u', '', $cookie_expire); + $user->set_cookie('sid', '', $cookie_expire); + unset($cookie_expire); + + $SID = '?sid='; + $user->session_id = $_SID = ''; + } + + $result = $user->session_create($login['user_row']['user_id'], $admin, $autologin, $viewonline); + + // Successful session creation + if ($result === true) + { + // If admin re-authentication we remove the old session entry because a new one has been created... + if ($admin) + { + // the login array is used because the user ids do not differ for re-authentication + $sql = 'DELETE FROM ' . SESSIONS_TABLE . " + WHERE session_id = '" . $db->sql_escape($old_session_id) . "' + AND session_user_id = {$login['user_row']['user_id']}"; + $db->sql_query($sql); + } + + return array( + 'status' => LOGIN_SUCCESS, + 'error_msg' => false, + 'user_row' => $login['user_row'], + ); + } + + return array( + 'status' => LOGIN_BREAK, + 'error_msg' => $result, + 'user_row' => $login['user_row'], + ); + } + + return $login; + } + + trigger_error('Authentication method not found', E_USER_ERROR); + } + + /** + * Fill auth_option statement for later querying based on the supplied options + */ + function build_auth_option_statement($key, $auth_options, &$sql_opts) + { + global $db; + + if (!is_array($auth_options)) + { + if (strpos($auth_options, '%') !== false) + { + $sql_opts = "AND $key " . $db->sql_like_expression(str_replace('%', $db->get_any_char(), $auth_options)); + } + else + { + $sql_opts = "AND $key = '" . $db->sql_escape($auth_options) . "'"; + } + } + else + { + $is_like_expression = false; + + foreach ($auth_options as $option) + { + if (strpos($option, '%') !== false) + { + $is_like_expression = true; + } + } + + if (!$is_like_expression) + { + $sql_opts = 'AND ' . $db->sql_in_set($key, $auth_options); + } + else + { + $sql = array(); + + foreach ($auth_options as $option) + { + if (strpos($option, '%') !== false) + { + $sql[] = $key . ' ' . $db->sql_like_expression(str_replace('%', $db->get_any_char(), $option)); + } + else + { + $sql[] = $key . " = '" . $db->sql_escape($option) . "'"; + } + } + + $sql_opts = 'AND (' . implode(' OR ', $sql) . ')'; + } + } + } +} diff --git a/phpBB/phpbb/auth/index.htm b/phpBB/phpbb/auth/index.htm new file mode 100644 index 0000000000..ee1f723a7d --- /dev/null +++ b/phpBB/phpbb/auth/index.htm @@ -0,0 +1,10 @@ +<html> +<head> +<title></title> +<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> +</head> + +<body bgcolor="#FFFFFF" text="#000000"> + +</body> +</html> diff --git a/phpBB/phpbb/auth/provider/apache.php b/phpBB/phpbb/auth/provider/apache.php new file mode 100644 index 0000000000..aa5bf64335 --- /dev/null +++ b/phpBB/phpbb/auth/provider/apache.php @@ -0,0 +1,264 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider; + +/** +* Apache authentication provider for phpBB3 +*/ +class apache extends \phpbb\auth\provider\base +{ + /** + * phpBB passwords manager + * + * @var \phpbb\passwords\manager + */ + protected $passwords_manager; + + /** + * Apache Authentication Constructor + * + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\config\config $config Config object + * @param \phpbb\passwords\manager $passwords_manager Passwords Manager object + * @param \phpbb\request\request $request Request object + * @param \phpbb\user $user User object + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $php_ext PHP file extension + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, \phpbb\passwords\manager $passwords_manager, \phpbb\request\request $request, \phpbb\user $user, $phpbb_root_path, $php_ext) + { + $this->db = $db; + $this->config = $config; + $this->passwords_manager = $passwords_manager; + $this->request = $request; + $this->user = $user; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * {@inheritdoc} + */ + public function init() + { + if (!$this->request->is_set('PHP_AUTH_USER', \phpbb\request\request_interface::SERVER) || $this->user->data['username'] !== htmlspecialchars_decode($this->request->server('PHP_AUTH_USER'))) + { + return $this->user->lang['APACHE_SETUP_BEFORE_USE']; + } + return false; + } + + /** + * {@inheritdoc} + */ + public function login($username, $password) + { + // do not allow empty password + if (!$password) + { + return array( + 'status' => LOGIN_ERROR_PASSWORD, + 'error_msg' => 'NO_PASSWORD_SUPPLIED', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + if (!$username) + { + return array( + 'status' => LOGIN_ERROR_USERNAME, + 'error_msg' => 'LOGIN_ERROR_USERNAME', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + if (!$this->request->is_set('PHP_AUTH_USER', \phpbb\request\request_interface::SERVER)) + { + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'LOGIN_ERROR_EXTERNAL_AUTH_APACHE', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + $php_auth_user = htmlspecialchars_decode($this->request->server('PHP_AUTH_USER')); + $php_auth_pw = htmlspecialchars_decode($this->request->server('PHP_AUTH_PW')); + + if (!empty($php_auth_user) && !empty($php_auth_pw)) + { + if ($php_auth_user !== $username) + { + return array( + 'status' => LOGIN_ERROR_USERNAME, + 'error_msg' => 'LOGIN_ERROR_USERNAME', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + $sql = 'SELECT user_id, username, user_password, user_passchg, user_email, user_type + FROM ' . USERS_TABLE . " + WHERE username = '" . $this->db->sql_escape($php_auth_user) . "'"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + // User inactive... + if ($row['user_type'] == USER_INACTIVE || $row['user_type'] == USER_IGNORE) + { + return array( + 'status' => LOGIN_ERROR_ACTIVE, + 'error_msg' => 'ACTIVE_ERROR', + 'user_row' => $row, + ); + } + + // Successful login... + return array( + 'status' => LOGIN_SUCCESS, + 'error_msg' => false, + 'user_row' => $row, + ); + } + + // this is the user's first login so create an empty profile + return array( + 'status' => LOGIN_SUCCESS_CREATE_PROFILE, + 'error_msg' => false, + 'user_row' => $this->user_row($php_auth_user, $php_auth_pw), + ); + } + + // Not logged into apache + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'LOGIN_ERROR_EXTERNAL_AUTH_APACHE', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + /** + * {@inheritdoc} + */ + public function autologin() + { + if (!$this->request->is_set('PHP_AUTH_USER', \phpbb\request\request_interface::SERVER)) + { + return array(); + } + + $php_auth_user = htmlspecialchars_decode($this->request->server('PHP_AUTH_USER')); + $php_auth_pw = htmlspecialchars_decode($this->request->server('PHP_AUTH_PW')); + + if (!empty($php_auth_user) && !empty($php_auth_pw)) + { + set_var($php_auth_user, $php_auth_user, 'string', true); + set_var($php_auth_pw, $php_auth_pw, 'string', true); + + $sql = 'SELECT * + FROM ' . USERS_TABLE . " + WHERE username = '" . $this->db->sql_escape($php_auth_user) . "'"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + return ($row['user_type'] == USER_INACTIVE || $row['user_type'] == USER_IGNORE) ? array() : $row; + } + + if (!function_exists('user_add')) + { + include($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + + // create the user if he does not exist yet + user_add($this->user_row($php_auth_user, $php_auth_pw)); + + $sql = 'SELECT * + FROM ' . USERS_TABLE . " + WHERE username_clean = '" . $this->db->sql_escape(utf8_clean_string($php_auth_user)) . "'"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + return $row; + } + } + + return array(); + } + + /** + * This function generates an array which can be passed to the user_add + * function in order to create a user + * + * @param string $username The username of the new user. + * @param string $password The password of the new user. + * @return array Contains data that can be passed directly to + * the user_add function. + */ + private function user_row($username, $password) + { + // first retrieve default group id + $sql = 'SELECT group_id + FROM ' . GROUPS_TABLE . " + WHERE group_name = '" . $this->db->sql_escape('REGISTERED') . "' + AND group_type = " . GROUP_SPECIAL; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$row) + { + trigger_error('NO_GROUP'); + } + + // generate user account data + return array( + 'username' => $username, + 'user_password' => $this->passwords_manager->hash($password), + 'user_email' => '', + 'group_id' => (int) $row['group_id'], + 'user_type' => USER_NORMAL, + 'user_ip' => $this->user->ip, + 'user_new' => ($this->config['new_member_post_limit']) ? 1 : 0, + ); + } + + /** + * {@inheritdoc} + */ + public function validate_session($user) + { + // Check if PHP_AUTH_USER is set and handle this case + if ($this->request->is_set('PHP_AUTH_USER', \phpbb\request\request_interface::SERVER)) + { + $php_auth_user = $this->request->server('PHP_AUTH_USER'); + + return ($php_auth_user === $user['username']) ? true : false; + } + + // PHP_AUTH_USER is not set. A valid session is now determined by the user type (anonymous/bot or not) + if ($user['user_type'] == USER_IGNORE) + { + return true; + } + + return false; + } +} diff --git a/phpBB/phpbb/auth/provider/base.php b/phpBB/phpbb/auth/provider/base.php new file mode 100644 index 0000000000..dea27ccc25 --- /dev/null +++ b/phpBB/phpbb/auth/provider/base.php @@ -0,0 +1,108 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider; + +/** +* Base authentication provider class that all other providers should implement +*/ +abstract class base implements \phpbb\auth\provider\provider_interface +{ + /** + * {@inheritdoc} + */ + public function init() + { + return; + } + + /** + * {@inheritdoc} + */ + public function autologin() + { + return; + } + + /** + * {@inheritdoc} + */ + public function acp() + { + return; + } + + /** + * {@inheritdoc} + */ + public function get_acp_template($new_config) + { + return; + } + + /** + * {@inheritdoc} + */ + public function get_login_data() + { + return; + } + + /** + * {@inheritdoc} + */ + public function get_auth_link_data($user_id = 0) + { + return; + } + + /** + * {@inheritdoc} + */ + public function logout($data, $new_session) + { + return; + } + + /** + * {@inheritdoc} + */ + public function validate_session($user) + { + return; + } + + /** + * {@inheritdoc} + */ + public function login_link_has_necessary_data($login_link_data) + { + return; + } + + /** + * {@inheritdoc} + */ + public function link_account(array $link_data) + { + return; + } + + /** + * {@inheritdoc} + */ + public function unlink_account(array $link_data) + { + return; + } +} diff --git a/phpBB/phpbb/auth/provider/db.php b/phpBB/phpbb/auth/provider/db.php new file mode 100644 index 0000000000..d8c5fb72de --- /dev/null +++ b/phpBB/phpbb/auth/provider/db.php @@ -0,0 +1,239 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider; + +/** + * Database authentication provider for phpBB3 + * This is for authentication via the integrated user table + */ +class db extends \phpbb\auth\provider\base +{ + /** + * phpBB passwords manager + * + * @var \phpbb\passwords\manager + */ + protected $passwords_manager; + + /** + * DI container + * + * @var \Symfony\Component\DependencyInjection\ContainerInterface + */ + protected $phpbb_container; + + /** + * Database Authentication Constructor + * + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\config\config $config + * @param \phpbb\passwords\manager $passwords_manager + * @param \phpbb\request\request $request + * @param \phpbb\user $user + * @param \Symfony\Component\DependencyInjection\ContainerInterface $phpbb_container DI container + * @param string $phpbb_root_path + * @param string $php_ext + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, \phpbb\passwords\manager $passwords_manager, \phpbb\request\request $request, \phpbb\user $user, \Symfony\Component\DependencyInjection\ContainerInterface $phpbb_container, $phpbb_root_path, $php_ext) + { + $this->db = $db; + $this->config = $config; + $this->passwords_manager = $passwords_manager; + $this->request = $request; + $this->user = $user; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->phpbb_container = $phpbb_container; + } + + /** + * {@inheritdoc} + */ + public function login($username, $password) + { + // Auth plugins get the password untrimmed. + // For compatibility we trim() here. + $password = trim($password); + + // do not allow empty password + if (!$password) + { + return array( + 'status' => LOGIN_ERROR_PASSWORD, + 'error_msg' => 'NO_PASSWORD_SUPPLIED', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + if (!$username) + { + return array( + 'status' => LOGIN_ERROR_USERNAME, + 'error_msg' => 'LOGIN_ERROR_USERNAME', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + $username_clean = utf8_clean_string($username); + + $sql = 'SELECT * + FROM ' . USERS_TABLE . " + WHERE username_clean = '" . $this->db->sql_escape($username_clean) . "'"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (($this->user->ip && !$this->config['ip_login_limit_use_forwarded']) || + ($this->user->forwarded_for && $this->config['ip_login_limit_use_forwarded'])) + { + $sql = 'SELECT COUNT(*) AS attempts + FROM ' . LOGIN_ATTEMPT_TABLE . ' + WHERE attempt_time > ' . (time() - (int) $this->config['ip_login_limit_time']); + if ($this->config['ip_login_limit_use_forwarded']) + { + $sql .= " AND attempt_forwarded_for = '" . $this->db->sql_escape($this->user->forwarded_for) . "'"; + } + else + { + $sql .= " AND attempt_ip = '" . $this->db->sql_escape($this->user->ip) . "' "; + } + + $result = $this->db->sql_query($sql); + $attempts = (int) $this->db->sql_fetchfield('attempts'); + $this->db->sql_freeresult($result); + + $attempt_data = array( + 'attempt_ip' => $this->user->ip, + 'attempt_browser' => trim(substr($this->user->browser, 0, 149)), + 'attempt_forwarded_for' => $this->user->forwarded_for, + 'attempt_time' => time(), + 'user_id' => ($row) ? (int) $row['user_id'] : 0, + 'username' => $username, + 'username_clean' => $username_clean, + ); + $sql = 'INSERT INTO ' . LOGIN_ATTEMPT_TABLE . $this->db->sql_build_array('INSERT', $attempt_data); + $this->db->sql_query($sql); + } + else + { + $attempts = 0; + } + + if (!$row) + { + if ($this->config['ip_login_limit_max'] && $attempts >= $this->config['ip_login_limit_max']) + { + return array( + 'status' => LOGIN_ERROR_ATTEMPTS, + 'error_msg' => 'LOGIN_ERROR_ATTEMPTS', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + return array( + 'status' => LOGIN_ERROR_USERNAME, + 'error_msg' => 'LOGIN_ERROR_USERNAME', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + $show_captcha = ($this->config['max_login_attempts'] && $row['user_login_attempts'] >= $this->config['max_login_attempts']) || + ($this->config['ip_login_limit_max'] && $attempts >= $this->config['ip_login_limit_max']); + + // If there are too many login attempts, we need to check for a confirm image + // Every auth module is able to define what to do by itself... + if ($show_captcha) + { + $captcha_factory = $this->phpbb_container->get('captcha.factory'); + $captcha = $captcha_factory->get_instance($this->config['captcha_plugin']); + $captcha->init(CONFIRM_LOGIN); + $vc_response = $captcha->validate($row); + if ($vc_response) + { + return array( + 'status' => LOGIN_ERROR_ATTEMPTS, + 'error_msg' => 'LOGIN_ERROR_ATTEMPTS', + 'user_row' => $row, + ); + } + else + { + $captcha->reset(); + } + + } + + // Check password ... + if ($this->passwords_manager->check($password, $row['user_password'], $row)) + { + // Check for old password hash... + if ($this->passwords_manager->convert_flag || strlen($row['user_password']) == 32) + { + $hash = $this->passwords_manager->hash($password); + + // Update the password in the users table to the new format + $sql = 'UPDATE ' . USERS_TABLE . " + SET user_password = '" . $this->db->sql_escape($hash) . "' + WHERE user_id = {$row['user_id']}"; + $this->db->sql_query($sql); + + $row['user_password'] = $hash; + } + + $sql = 'DELETE FROM ' . LOGIN_ATTEMPT_TABLE . ' + WHERE user_id = ' . $row['user_id']; + $this->db->sql_query($sql); + + if ($row['user_login_attempts'] != 0) + { + // Successful, reset login attempts (the user passed all stages) + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_login_attempts = 0 + WHERE user_id = ' . $row['user_id']; + $this->db->sql_query($sql); + } + + // User inactive... + if ($row['user_type'] == USER_INACTIVE || $row['user_type'] == USER_IGNORE) + { + return array( + 'status' => LOGIN_ERROR_ACTIVE, + 'error_msg' => 'ACTIVE_ERROR', + 'user_row' => $row, + ); + } + + // Successful login... set user_login_attempts to zero... + return array( + 'status' => LOGIN_SUCCESS, + 'error_msg' => false, + 'user_row' => $row, + ); + } + + // Password incorrect - increase login attempts + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_login_attempts = user_login_attempts + 1 + WHERE user_id = ' . (int) $row['user_id'] . ' + AND user_login_attempts < ' . LOGIN_ATTEMPTS_MAX; + $this->db->sql_query($sql); + + // Give status about wrong password... + return array( + 'status' => ($show_captcha) ? LOGIN_ERROR_ATTEMPTS : LOGIN_ERROR_PASSWORD, + 'error_msg' => 'LOGIN_ERROR_PASSWORD', + 'user_row' => $row, + ); + } +} diff --git a/phpBB/phpbb/auth/provider/index.htm b/phpBB/phpbb/auth/provider/index.htm new file mode 100644 index 0000000000..ee1f723a7d --- /dev/null +++ b/phpBB/phpbb/auth/provider/index.htm @@ -0,0 +1,10 @@ +<html> +<head> +<title></title> +<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> +</head> + +<body bgcolor="#FFFFFF" text="#000000"> + +</body> +</html> diff --git a/phpBB/phpbb/auth/provider/ldap.php b/phpBB/phpbb/auth/provider/ldap.php new file mode 100644 index 0000000000..c48b771ab0 --- /dev/null +++ b/phpBB/phpbb/auth/provider/ldap.php @@ -0,0 +1,348 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider; + +/** + * Database authentication provider for phpBB3 + * This is for authentication via the integrated user table + */ +class ldap extends \phpbb\auth\provider\base +{ + /** + * phpBB passwords manager + * + * @var \phpbb\passwords\manager + */ + protected $passwords_manager; + + /** + * LDAP Authentication Constructor + * + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\config\config $config Config object + * @param \phpbb\passwords\manager $passwords_manager Passwords manager object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, \phpbb\passwords\manager $passwords_manager, \phpbb\user $user) + { + $this->db = $db; + $this->config = $config; + $this->passwords_manager = $passwords_manager; + $this->user = $user; + } + + /** + * {@inheritdoc} + */ + public function init() + { + if (!@extension_loaded('ldap')) + { + return $this->user->lang['LDAP_NO_LDAP_EXTENSION']; + } + + $this->config['ldap_port'] = (int) $this->config['ldap_port']; + if ($this->config['ldap_port']) + { + $ldap = @ldap_connect($this->config['ldap_server'], $this->config['ldap_port']); + } + else + { + $ldap = @ldap_connect($this->config['ldap_server']); + } + + if (!$ldap) + { + return $this->user->lang['LDAP_NO_SERVER_CONNECTION']; + } + + @ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); + @ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0); + + if ($this->config['ldap_user'] || $this->config['ldap_password']) + { + if (!@ldap_bind($ldap, htmlspecialchars_decode($this->config['ldap_user']), htmlspecialchars_decode($this->config['ldap_password']))) + { + return $this->user->lang['LDAP_INCORRECT_USER_PASSWORD']; + } + } + + // ldap_connect only checks whether the specified server is valid, so the connection might still fail + $search = @ldap_search( + $ldap, + htmlspecialchars_decode($this->config['ldap_base_dn']), + $this->ldap_user_filter($this->user->data['username']), + (empty($this->config['ldap_email'])) ? + array(htmlspecialchars_decode($this->config['ldap_uid'])) : + array(htmlspecialchars_decode($this->config['ldap_uid']), htmlspecialchars_decode($this->config['ldap_email'])), + 0, + 1 + ); + + if ($search === false) + { + return $this->user->lang['LDAP_SEARCH_FAILED']; + } + + $result = @ldap_get_entries($ldap, $search); + + @ldap_close($ldap); + + if (!is_array($result) || sizeof($result) < 2) + { + return sprintf($this->user->lang['LDAP_NO_IDENTITY'], $this->user->data['username']); + } + + if (!empty($this->config['ldap_email']) && !isset($result[0][htmlspecialchars_decode($this->config['ldap_email'])])) + { + return $this->user->lang['LDAP_NO_EMAIL']; + } + + return false; + } + + /** + * {@inheritdoc} + */ + public function login($username, $password) + { + // do not allow empty password + if (!$password) + { + return array( + 'status' => LOGIN_ERROR_PASSWORD, + 'error_msg' => 'NO_PASSWORD_SUPPLIED', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + if (!$username) + { + return array( + 'status' => LOGIN_ERROR_USERNAME, + 'error_msg' => 'LOGIN_ERROR_USERNAME', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + if (!@extension_loaded('ldap')) + { + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'LDAP_NO_LDAP_EXTENSION', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + $this->config['ldap_port'] = (int) $this->config['ldap_port']; + if ($this->config['ldap_port']) + { + $ldap = @ldap_connect($this->config['ldap_server'], $this->config['ldap_port']); + } + else + { + $ldap = @ldap_connect($this->config['ldap_server']); + } + + if (!$ldap) + { + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'LDAP_NO_SERVER_CONNECTION', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + @ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); + @ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0); + + if ($this->config['ldap_user'] || $this->config['ldap_password']) + { + if (!@ldap_bind($ldap, htmlspecialchars_decode($this->config['ldap_user']), htmlspecialchars_decode($this->config['ldap_password']))) + { + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'LDAP_NO_SERVER_CONNECTION', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + } + + $search = @ldap_search( + $ldap, + htmlspecialchars_decode($this->config['ldap_base_dn']), + $this->ldap_user_filter($username), + (empty($this->config['ldap_email'])) ? + array(htmlspecialchars_decode($this->config['ldap_uid'])) : + array(htmlspecialchars_decode($this->config['ldap_uid']), htmlspecialchars_decode($this->config['ldap_email'])), + 0, + 1 + ); + + $ldap_result = @ldap_get_entries($ldap, $search); + + if (is_array($ldap_result) && sizeof($ldap_result) > 1) + { + if (@ldap_bind($ldap, $ldap_result[0]['dn'], htmlspecialchars_decode($password))) + { + @ldap_close($ldap); + + $sql ='SELECT user_id, username, user_password, user_passchg, user_email, user_type + FROM ' . USERS_TABLE . " + WHERE username_clean = '" . $this->db->sql_escape(utf8_clean_string($username)) . "'"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + unset($ldap_result); + + // User inactive... + if ($row['user_type'] == USER_INACTIVE || $row['user_type'] == USER_IGNORE) + { + return array( + 'status' => LOGIN_ERROR_ACTIVE, + 'error_msg' => 'ACTIVE_ERROR', + 'user_row' => $row, + ); + } + + // Successful login... set user_login_attempts to zero... + return array( + 'status' => LOGIN_SUCCESS, + 'error_msg' => false, + 'user_row' => $row, + ); + } + else + { + // retrieve default group id + $sql = 'SELECT group_id + FROM ' . GROUPS_TABLE . " + WHERE group_name = '" . $this->db->sql_escape('REGISTERED') . "' + AND group_type = " . GROUP_SPECIAL; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$row) + { + trigger_error('NO_GROUP'); + } + + // generate user account data + $ldap_user_row = array( + 'username' => $username, + 'user_password' => $this->passwords_manager->hash($password), + 'user_email' => (!empty($this->config['ldap_email'])) ? utf8_htmlspecialchars($ldap_result[0][htmlspecialchars_decode($this->config['ldap_email'])][0]) : '', + 'group_id' => (int) $row['group_id'], + 'user_type' => USER_NORMAL, + 'user_ip' => $this->user->ip, + 'user_new' => ($this->config['new_member_post_limit']) ? 1 : 0, + ); + + unset($ldap_result); + + // this is the user's first login so create an empty profile + return array( + 'status' => LOGIN_SUCCESS_CREATE_PROFILE, + 'error_msg' => false, + 'user_row' => $ldap_user_row, + ); + } + } + else + { + unset($ldap_result); + @ldap_close($ldap); + + // Give status about wrong password... + return array( + 'status' => LOGIN_ERROR_PASSWORD, + 'error_msg' => 'LOGIN_ERROR_PASSWORD', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + } + + @ldap_close($ldap); + + return array( + 'status' => LOGIN_ERROR_USERNAME, + 'error_msg' => 'LOGIN_ERROR_USERNAME', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + /** + * {@inheritdoc} + */ + public function acp() + { + // These are fields required in the config table + return array( + 'ldap_server', 'ldap_port', 'ldap_base_dn', 'ldap_uid', 'ldap_user_filter', 'ldap_email', 'ldap_user', 'ldap_password', + ); + } + + /** + * {@inheritdoc} + */ + public function get_acp_template($new_config) + { + return array( + 'TEMPLATE_FILE' => 'auth_provider_ldap.html', + 'TEMPLATE_VARS' => array( + 'AUTH_LDAP_BASE_DN' => $new_config['ldap_base_dn'], + 'AUTH_LDAP_EMAIL' => $new_config['ldap_email'], + 'AUTH_LDAP_PASSORD' => $new_config['ldap_password'] !== '' ? '********' : '', + 'AUTH_LDAP_PORT' => $new_config['ldap_port'], + 'AUTH_LDAP_SERVER' => $new_config['ldap_server'], + 'AUTH_LDAP_UID' => $new_config['ldap_uid'], + 'AUTH_LDAP_USER' => $new_config['ldap_user'], + 'AUTH_LDAP_USER_FILTER' => $new_config['ldap_user_filter'], + ), + ); + } + + /** + * Generates a filter string for ldap_search to find a user + * + * @param $username string Username identifying the searched user + * + * @return string A filter string for ldap_search + */ + private function ldap_user_filter($username) + { + $filter = '(' . $this->config['ldap_uid'] . '=' . $this->ldap_escape(htmlspecialchars_decode($username)) . ')'; + if ($this->config['ldap_user_filter']) + { + $_filter = ($this->config['ldap_user_filter'][0] == '(' && substr($this->config['ldap_user_filter'], -1) == ')') ? $this->config['ldap_user_filter'] : "({$this->config['ldap_user_filter']})"; + $filter = "(&{$filter}{$_filter})"; + } + return $filter; + } + + /** + * Escapes an LDAP AttributeValue + * + * @param string $string The string to be escaped + * @return string The escaped string + */ + private function ldap_escape($string) + { + return str_replace(array('*', '\\', '(', ')'), array('\\*', '\\\\', '\\(', '\\)'), $string); + } +} diff --git a/phpBB/phpbb/auth/provider/oauth/oauth.php b/phpBB/phpbb/auth/provider/oauth/oauth.php new file mode 100644 index 0000000000..bd2a414033 --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/oauth.php @@ -0,0 +1,672 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth; + +use OAuth\Common\Consumer\Credentials; + +/** +* OAuth authentication provider for phpBB3 +*/ +class oauth extends \phpbb\auth\provider\base +{ + /** + * Database driver + * + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * phpBB config + * + * @var \phpbb\config\config + */ + protected $config; + + /** + * phpBB passwords manager + * + * @var \phpbb\passwords\manager + */ + protected $passwords_manager; + + /** + * phpBB request object + * + * @var \phpbb\request\request_interface + */ + protected $request; + + /** + * phpBB user + * + * @var \phpbb\user + */ + protected $user; + + /** + * OAuth token table + * + * @var string + */ + protected $auth_provider_oauth_token_storage_table; + + /** + * OAuth account association table + * + * @var string + */ + protected $auth_provider_oauth_token_account_assoc; + + /** + * All OAuth service providers + * + * @var \phpbb\di\service_collection Contains \phpbb\auth\provider\oauth\service_interface + */ + protected $service_providers; + + /** + * Users table + * + * @var string + */ + protected $users_table; + + /** + * Cached current uri object + * + * @var \OAuth\Common\Http\Uri\UriInterface|null + */ + protected $current_uri; + + /** + * DI container + * + * @var \Symfony\Component\DependencyInjection\ContainerInterface + */ + protected $phpbb_container; + + /** + * phpBB event dispatcher + * + * @var \phpbb\event\dispatcher_interface + */ + protected $dispatcher; + + /** + * phpBB root path + * + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP file extension + * + * @var string + */ + protected $php_ext; + + /** + * OAuth Authentication Constructor + * + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\config\config $config + * @param \phpbb\passwords\manager $passwords_manager + * @param \phpbb\request\request_interface $request + * @param \phpbb\user $user + * @param string $auth_provider_oauth_token_storage_table + * @param string $auth_provider_oauth_token_account_assoc + * @param \phpbb\di\service_collection $service_providers Contains \phpbb\auth\provider\oauth\service_interface + * @param string $users_table + * @param \Symfony\Component\DependencyInjection\ContainerInterface $phpbb_container DI container + * @param \phpbb\event\dispatcher_interface $dispatcher phpBB event dispatcher + * @param string $phpbb_root_path + * @param string $php_ext + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, \phpbb\passwords\manager $passwords_manager, \phpbb\request\request_interface $request, \phpbb\user $user, $auth_provider_oauth_token_storage_table, $auth_provider_oauth_token_account_assoc, \phpbb\di\service_collection $service_providers, $users_table, \Symfony\Component\DependencyInjection\ContainerInterface $phpbb_container, \phpbb\event\dispatcher_interface $dispatcher, $phpbb_root_path, $php_ext) + { + $this->db = $db; + $this->config = $config; + $this->passwords_manager = $passwords_manager; + $this->request = $request; + $this->user = $user; + $this->auth_provider_oauth_token_storage_table = $auth_provider_oauth_token_storage_table; + $this->auth_provider_oauth_token_account_assoc = $auth_provider_oauth_token_account_assoc; + $this->service_providers = $service_providers; + $this->users_table = $users_table; + $this->phpbb_container = $phpbb_container; + $this->dispatcher = $dispatcher; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * {@inheritdoc} + */ + public function init() + { + // This does not test whether or not the key and secret provided are valid. + foreach ($this->service_providers as $service_provider) + { + $credentials = $service_provider->get_service_credentials(); + + if (($credentials['key'] && !$credentials['secret']) || (!$credentials['key'] && $credentials['secret'])) + { + return $this->user->lang['AUTH_PROVIDER_OAUTH_ERROR_ELEMENT_MISSING']; + } + } + return false; + } + + /** + * {@inheritdoc} + */ + public function login($username, $password) + { + // Temporary workaround for only having one authentication provider available + if (!$this->request->is_set('oauth_service')) + { + $provider = new \phpbb\auth\provider\db($this->db, $this->config, $this->passwords_manager, $this->request, $this->user, $this->phpbb_container, $this->phpbb_root_path, $this->php_ext); + return $provider->login($username, $password); + } + + // Requst the name of the OAuth service + $service_name_original = $this->request->variable('oauth_service', '', false); + $service_name = 'auth.provider.oauth.service.' . strtolower($service_name_original); + if ($service_name_original === '' || !array_key_exists($service_name, $this->service_providers)) + { + return array( + 'status' => LOGIN_ERROR_EXTERNAL_AUTH, + 'error_msg' => 'LOGIN_ERROR_OAUTH_SERVICE_DOES_NOT_EXIST', + 'user_row' => array('user_id' => ANONYMOUS), + ); + } + + // Get the service credentials for the given service + $service_credentials = $this->service_providers[$service_name]->get_service_credentials(); + + $storage = new \phpbb\auth\provider\oauth\token_storage($this->db, $this->user, $this->auth_provider_oauth_token_storage_table); + $query = 'mode=login&login=external&oauth_service=' . $service_name_original; + $service = $this->get_service($service_name_original, $storage, $service_credentials, $query, $this->service_providers[$service_name]->get_auth_scope()); + + if ($this->request->is_set('code', \phpbb\request\request_interface::GET)) + { + $this->service_providers[$service_name]->set_external_service_provider($service); + $unique_id = $this->service_providers[$service_name]->perform_auth_login(); + + // Check to see if this provider is already assosciated with an account + $data = array( + 'provider' => $service_name_original, + 'oauth_provider_id' => $unique_id + ); + $sql = 'SELECT user_id FROM ' . $this->auth_provider_oauth_token_account_assoc . ' + WHERE ' . $this->db->sql_build_array('SELECT', $data); + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$row) + { + // The user does not yet exist, ask to link or create profile + return array( + 'status' => LOGIN_SUCCESS_LINK_PROFILE, + 'error_msg' => 'LOGIN_OAUTH_ACCOUNT_NOT_LINKED', + 'user_row' => array(), + 'redirect_data' => array( + 'auth_provider' => 'oauth', + 'login_link_oauth_service' => $service_name_original, + ), + ); + } + + // Retrieve the user's account + $sql = 'SELECT user_id, username, user_password, user_passchg, user_email, user_type, user_login_attempts + FROM ' . $this->users_table . ' + WHERE user_id = ' . (int) $row['user_id']; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$row) + { + throw new \Exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_ENTRY'); + } + + // Update token storage to store the user_id + $storage->set_user_id($row['user_id']); + + /** + * Event is triggered after user is successfuly logged in via OAuth. + * + * @event core.auth_oauth_login_after + * @var array row User row + * @since 3.1.11-RC1 + */ + $vars = array( + 'row', + ); + extract($this->dispatcher->trigger_event('core.auth_oauth_login_after', compact($vars))); + + // The user is now authenticated and can be logged in + return array( + 'status' => LOGIN_SUCCESS, + 'error_msg' => false, + 'user_row' => $row, + ); + } + else + { + $url = $service->getAuthorizationUri(); + header('Location: ' . $url); + } + } + + /** + * Returns the cached current_uri object or creates and caches it if it is + * not already created. In each case the query string is updated based on + * the $query parameter. + * + * @param string $service_name The name of the service + * @param string $query The query string of the current_uri + * used in redirects + * @return \OAuth\Common\Http\Uri\UriInterface + */ + protected function get_current_uri($service_name, $query) + { + if ($this->current_uri) + { + $this->current_uri->setQuery($query); + return $this->current_uri; + } + + $uri_factory = new \OAuth\Common\Http\Uri\UriFactory(); + $super_globals = $this->request->get_super_global(\phpbb\request\request_interface::SERVER); + if (!empty($super_globals['HTTP_X_FORWARDED_PROTO']) && $super_globals['HTTP_X_FORWARDED_PROTO'] === 'https') + { + $super_globals['HTTPS'] = 'on'; + $super_globals['SERVER_PORT'] = 443; + } + $current_uri = $uri_factory->createFromSuperGlobalArray($super_globals); + $current_uri->setQuery($query); + + $this->current_uri = $current_uri; + return $current_uri; + } + + /** + * Returns a new service object + * + * @param string $service_name The name of the service + * @param \phpbb\auth\provider\oauth\token_storage $storage + * @param array $service_credentials {@see \phpbb\auth\provider\oauth\oauth::get_service_credentials} + * @param string $query The query string of the + * current_uri used in redirection + * @param array $scopes The scope of the request against + * the api. + * @return \OAuth\Common\Service\ServiceInterface + * @throws \Exception + */ + protected function get_service($service_name, \phpbb\auth\provider\oauth\token_storage $storage, array $service_credentials, $query, array $scopes = array()) + { + $current_uri = $this->get_current_uri($service_name, $query); + + // Setup the credentials for the requests + $credentials = new Credentials( + $service_credentials['key'], + $service_credentials['secret'], + $current_uri->getAbsoluteUri() + ); + + $service_factory = new \OAuth\ServiceFactory(); + $service = $service_factory->createService($service_name, $credentials, $storage, $scopes); + + if (!$service) + { + throw new \Exception('AUTH_PROVIDER_OAUTH_ERROR_SERVICE_NOT_CREATED'); + } + + return $service; + } + + /** + * {@inheritdoc} + */ + public function get_login_data() + { + $login_data = array( + 'TEMPLATE_FILE' => 'login_body_oauth.html', + 'BLOCK_VAR_NAME' => 'oauth', + 'BLOCK_VARS' => array(), + ); + + foreach ($this->service_providers as $service_name => $service_provider) + { + // Only include data if the credentials are set + $credentials = $service_provider->get_service_credentials(); + if ($credentials['key'] && $credentials['secret']) + { + $actual_name = str_replace('auth.provider.oauth.service.', '', $service_name); + $redirect_url = build_url(false) . '&login=external&oauth_service=' . $actual_name; + $login_data['BLOCK_VARS'][$service_name] = array( + 'REDIRECT_URL' => redirect($redirect_url, true), + 'SERVICE_NAME' => $this->user->lang['AUTH_PROVIDER_OAUTH_SERVICE_' . strtoupper($actual_name)], + ); + } + } + + return $login_data; + } + + /** + * {@inheritdoc} + */ + public function acp() + { + $ret = array(); + + foreach ($this->service_providers as $service_name => $service_provider) + { + $actual_name = str_replace('auth.provider.oauth.service.', '', $service_name); + $ret[] = 'auth_oauth_' . $actual_name . '_key'; + $ret[] = 'auth_oauth_' . $actual_name . '_secret'; + } + + return $ret; + } + + /** + * {@inheritdoc} + */ + public function get_acp_template($new_config) + { + $ret = array( + 'BLOCK_VAR_NAME' => 'oauth_services', + 'BLOCK_VARS' => array(), + 'TEMPLATE_FILE' => 'auth_provider_oauth.html', + 'TEMPLATE_VARS' => array(), + ); + + foreach ($this->service_providers as $service_name => $service_provider) + { + $actual_name = str_replace('auth.provider.oauth.service.', '', $service_name); + $ret['BLOCK_VARS'][$actual_name] = array( + 'ACTUAL_NAME' => $this->user->lang['AUTH_PROVIDER_OAUTH_SERVICE_' . strtoupper($actual_name)], + 'KEY' => $new_config['auth_oauth_' . $actual_name . '_key'], + 'NAME' => $actual_name, + 'SECRET' => $new_config['auth_oauth_' . $actual_name . '_secret'], + ); + } + + return $ret; + } + + /** + * {@inheritdoc} + */ + public function login_link_has_necessary_data($login_link_data) + { + if (empty($login_link_data)) + { + return 'LOGIN_LINK_NO_DATA_PROVIDED'; + } + + if (!array_key_exists('oauth_service', $login_link_data) || !$login_link_data['oauth_service'] || + !array_key_exists('link_method', $login_link_data) || !$login_link_data['link_method']) + { + return 'LOGIN_LINK_MISSING_DATA'; + } + + return null; + } + + /** + * {@inheritdoc} + */ + public function link_account(array $link_data) + { + // Check for a valid link method (auth_link or login_link) + if (!array_key_exists('link_method', $link_data) || + !in_array($link_data['link_method'], array( + 'auth_link', + 'login_link', + ))) + { + return 'LOGIN_LINK_MISSING_DATA'; + } + + // We must have an oauth_service listed, check for it two ways + if (!array_key_exists('oauth_service', $link_data) || !$link_data['oauth_service']) + { + $link_data['oauth_service'] = $this->request->variable('oauth_service', ''); + + if (!$link_data['oauth_service']) + { + return 'LOGIN_LINK_MISSING_DATA'; + } + } + + $service_name = 'auth.provider.oauth.service.' . strtolower($link_data['oauth_service']); + if (!array_key_exists($service_name, $this->service_providers)) + { + return 'LOGIN_ERROR_OAUTH_SERVICE_DOES_NOT_EXIST'; + } + + switch ($link_data['link_method']) + { + case 'auth_link': + return $this->link_account_auth_link($link_data, $service_name); + case 'login_link': + return $this->link_account_login_link($link_data, $service_name); + } + } + + /** + * Performs the account linking for login_link + * + * @param array $link_data The same variable given to {@see \phpbb\auth\provider\provider_interface::link_account} + * @param string $service_name The name of the service being used in + * linking. + * @return string|null Returns a language constant (string) if an error is + * encountered, or null on success. + */ + protected function link_account_login_link(array $link_data, $service_name) + { + $storage = new \phpbb\auth\provider\oauth\token_storage($this->db, $this->user, $this->auth_provider_oauth_token_storage_table); + + // Check for an access token, they should have one + if (!$storage->has_access_token_by_session($service_name)) + { + return 'LOGIN_LINK_ERROR_OAUTH_NO_ACCESS_TOKEN'; + } + + // Prepare the query string + $query = 'mode=login_link&login_link_oauth_service=' . strtolower($link_data['oauth_service']); + + // Prepare for an authentication request + $service_credentials = $this->service_providers[$service_name]->get_service_credentials(); + $scopes = $this->service_providers[$service_name]->get_auth_scope(); + $service = $this->get_service(strtolower($link_data['oauth_service']), $storage, $service_credentials, $query, $scopes); + $this->service_providers[$service_name]->set_external_service_provider($service); + + // The user has already authenticated successfully, request to authenticate again + $unique_id = $this->service_providers[$service_name]->perform_token_auth(); + + // Insert into table, they will be able to log in after this + $data = array( + 'user_id' => $link_data['user_id'], + 'provider' => strtolower($link_data['oauth_service']), + 'oauth_provider_id' => $unique_id, + ); + + $this->link_account_perform_link($data); + // Update token storage to store the user_id + $storage->set_user_id($link_data['user_id']); + } + + /** + * Performs the account linking for auth_link + * + * @param array $link_data The same variable given to {@see \phpbb\auth\provider\provider_interface::link_account} + * @param string $service_name The name of the service being used in + * linking. + * @return string|null Returns a language constant (string) if an error is + * encountered, or null on success. + */ + protected function link_account_auth_link(array $link_data, $service_name) + { + $storage = new \phpbb\auth\provider\oauth\token_storage($this->db, $this->user, $this->auth_provider_oauth_token_storage_table); + $query = 'i=ucp_auth_link&mode=auth_link&link=1&oauth_service=' . strtolower($link_data['oauth_service']); + $service_credentials = $this->service_providers[$service_name]->get_service_credentials(); + $scopes = $this->service_providers[$service_name]->get_auth_scope(); + $service = $this->get_service(strtolower($link_data['oauth_service']), $storage, $service_credentials, $query, $scopes); + + if ($this->request->is_set('code', \phpbb\request\request_interface::GET)) + { + $this->service_providers[$service_name]->set_external_service_provider($service); + $unique_id = $this->service_providers[$service_name]->perform_auth_login(); + + // Insert into table, they will be able to log in after this + $data = array( + 'user_id' => $this->user->data['user_id'], + 'provider' => strtolower($link_data['oauth_service']), + 'oauth_provider_id' => $unique_id, + ); + + $this->link_account_perform_link($data); + } + else + { + $url = $service->getAuthorizationUri(); + header('Location: ' . $url); + } + } + + /** + * Performs the query that inserts an account link + * + * @param array $data This array is passed to db->sql_build_array + */ + protected function link_account_perform_link(array $data) + { + $sql = 'INSERT INTO ' . $this->auth_provider_oauth_token_account_assoc . ' + ' . $this->db->sql_build_array('INSERT', $data); + $this->db->sql_query($sql); + + /** + * Event is triggered after user links account. + * + * @event core.auth_oauth_link_after + * @var array data User row + * @since 3.1.11-RC1 + */ + $vars = array( + 'data', + ); + extract($this->dispatcher->trigger_event('core.auth_oauth_link_after', compact($vars))); + } + + /** + * {@inheritdoc} + */ + public function logout($data, $new_session) + { + // Clear all tokens belonging to the user + $storage = new \phpbb\auth\provider\oauth\token_storage($this->db, $this->user, $this->auth_provider_oauth_token_storage_table); + $storage->clearAllTokens(); + + return; + } + + /** + * {@inheritdoc} + */ + public function get_auth_link_data($user_id = 0) + { + $block_vars = array(); + + // Get all external accounts tied to the current user + $data = array( + 'user_id' => ($user_id <= 0) ? (int) $this->user->data['user_id'] : (int) $user_id, + ); + $sql = 'SELECT oauth_provider_id, provider FROM ' . $this->auth_provider_oauth_token_account_assoc . ' + WHERE ' . $this->db->sql_build_array('SELECT', $data); + $result = $this->db->sql_query($sql); + $rows = $this->db->sql_fetchrowset($result); + $this->db->sql_freeresult($result); + + $oauth_user_ids = array(); + + if ($rows !== false && sizeof($rows)) + { + foreach ($rows as $row) + { + $oauth_user_ids[$row['provider']] = $row['oauth_provider_id']; + } + } + unset($rows); + + foreach ($this->service_providers as $service_name => $service_provider) + { + // Only include data if the credentials are set + $credentials = $service_provider->get_service_credentials(); + if ($credentials['key'] && $credentials['secret']) + { + $actual_name = str_replace('auth.provider.oauth.service.', '', $service_name); + + $block_vars[$service_name] = array( + 'HIDDEN_FIELDS' => array( + 'link' => (!isset($oauth_user_ids[$actual_name])), + 'oauth_service' => $actual_name, + ), + + 'SERVICE_NAME' => $this->user->lang['AUTH_PROVIDER_OAUTH_SERVICE_' . strtoupper($actual_name)], + 'UNIQUE_ID' => (isset($oauth_user_ids[$actual_name])) ? $oauth_user_ids[$actual_name] : null, + ); + } + } + + return array( + 'BLOCK_VAR_NAME' => 'oauth', + 'BLOCK_VARS' => $block_vars, + + 'TEMPLATE_FILE' => 'ucp_auth_link_oauth.html', + ); + } + + /** + * {@inheritdoc} + */ + public function unlink_account(array $link_data) + { + if (!array_key_exists('oauth_service', $link_data) || !$link_data['oauth_service']) + { + return 'LOGIN_LINK_MISSING_DATA'; + } + + // Remove user specified in $link_data if possible + $user_id = isset($link_data['user_id']) ? $link_data['user_id'] : $this->user->data['user_id']; + + // Remove the link + $sql = 'DELETE FROM ' . $this->auth_provider_oauth_token_account_assoc . " + WHERE provider = '" . $this->db->sql_escape($link_data['oauth_service']) . "' + AND user_id = " . (int) $user_id; + $this->db->sql_query($sql); + + // Clear all tokens belonging to the user on this servce + $service_name = 'auth.provider.oauth.service.' . strtolower($link_data['oauth_service']); + $storage = new \phpbb\auth\provider\oauth\token_storage($this->db, $this->user, $this->auth_provider_oauth_token_storage_table); + $storage->clearToken($service_name); + } +} diff --git a/phpBB/phpbb/auth/provider/oauth/service/base.php b/phpBB/phpbb/auth/provider/oauth/service/base.php new file mode 100644 index 0000000000..6adf64aa30 --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/service/base.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth\service; + +/** +* Base OAuth abstract class that all OAuth services should implement +*/ +abstract class base implements \phpbb\auth\provider\oauth\service\service_interface +{ + /** + * External OAuth service provider + * + * @var \OAuth\Common\Service\ServiceInterface + */ + protected $service_provider; + + /** + * {@inheritdoc} + */ + public function get_external_service_provider() + { + return $this->service_provider; + } + + /** + * {@inheritdoc} + */ + public function get_auth_scope() + { + return array(); + } + + /** + * {@inheritdoc} + */ + public function set_external_service_provider(\OAuth\Common\Service\ServiceInterface $service_provider) + { + $this->service_provider = $service_provider; + } +} diff --git a/phpBB/phpbb/auth/provider/oauth/service/bitly.php b/phpBB/phpbb/auth/provider/oauth/service/bitly.php new file mode 100644 index 0000000000..25e731a02c --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/service/bitly.php @@ -0,0 +1,94 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth\service; + +/** +* Bitly OAuth service +*/ +class bitly extends \phpbb\auth\provider\oauth\service\base +{ + /** + * phpBB config + * + * @var \phpbb\config\config + */ + protected $config; + + /** + * phpBB request + * + * @var \phpbb\request\request_interface + */ + protected $request; + + /** + * Constructor + * + * @param \phpbb\config\config $config + * @param \phpbb\request\request_interface $request + */ + public function __construct(\phpbb\config\config $config, \phpbb\request\request_interface $request) + { + $this->config = $config; + $this->request = $request; + } + + /** + * {@inheritdoc} + */ + public function get_service_credentials() + { + return array( + 'key' => $this->config['auth_oauth_bitly_key'], + 'secret' => $this->config['auth_oauth_bitly_secret'], + ); + } + + /** + * {@inheritdoc} + */ + public function perform_auth_login() + { + if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Bitly)) + { + throw new \phpbb\auth\provider\oauth\service\exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE'); + } + + // This was a callback request from bitly, get the token + $this->service_provider->requestAccessToken($this->request->variable('code', '')); + + // Send a request with it + $result = json_decode($this->service_provider->request('user/info'), true); + + // Return the unique identifier returned from bitly + return $result['data']['login']; + } + + /** + * {@inheritdoc} + */ + public function perform_token_auth() + { + if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Bitly)) + { + throw new \phpbb\auth\provider\oauth\service\exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE'); + } + + // Send a request with it + $result = json_decode($this->service_provider->request('user/info'), true); + + // Return the unique identifier returned from bitly + return $result['data']['login']; + } +} diff --git a/phpBB/phpbb/auth/provider/oauth/service/exception.php b/phpBB/phpbb/auth/provider/oauth/service/exception.php new file mode 100644 index 0000000000..d3e95bef0d --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/service/exception.php @@ -0,0 +1,21 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth\service; + +/** +* OAuth service exception class +*/ +class exception extends \RuntimeException +{ +} diff --git a/phpBB/phpbb/auth/provider/oauth/service/facebook.php b/phpBB/phpbb/auth/provider/oauth/service/facebook.php new file mode 100644 index 0000000000..bb98835e07 --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/service/facebook.php @@ -0,0 +1,94 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth\service; + +/** +* Facebook OAuth service +*/ +class facebook extends base +{ + /** + * phpBB config + * + * @var \phpbb\config\config + */ + protected $config; + + /** + * phpBB request + * + * @var \phpbb\request\request_interface + */ + protected $request; + + /** + * Constructor + * + * @param \phpbb\config\config $config + * @param \phpbb\request\request_interface $request + */ + public function __construct(\phpbb\config\config $config, \phpbb\request\request_interface $request) + { + $this->config = $config; + $this->request = $request; + } + + /** + * {@inheritdoc} + */ + public function get_service_credentials() + { + return array( + 'key' => $this->config['auth_oauth_facebook_key'], + 'secret' => $this->config['auth_oauth_facebook_secret'], + ); + } + + /** + * {@inheritdoc} + */ + public function perform_auth_login() + { + if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Facebook)) + { + throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE'); + } + + // This was a callback request, get the token + $this->service_provider->requestAccessToken($this->request->variable('code', '')); + + // Send a request with it + $result = json_decode($this->service_provider->request('/me'), true); + + // Return the unique identifier + return $result['id']; + } + + /** + * {@inheritdoc} + */ + public function perform_token_auth() + { + if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Facebook)) + { + throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE'); + } + + // Send a request with it + $result = json_decode($this->service_provider->request('/me'), true); + + // Return the unique identifier + return $result['id']; + } +} diff --git a/phpBB/phpbb/auth/provider/oauth/service/google.php b/phpBB/phpbb/auth/provider/oauth/service/google.php new file mode 100644 index 0000000000..cb9f83a94f --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/service/google.php @@ -0,0 +1,105 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth\service; + +/** +* Google OAuth service +*/ +class google extends base +{ + /** + * phpBB config + * + * @var \phpbb\config\config + */ + protected $config; + + /** + * phpBB request + * + * @var \phpbb\request\request_interface + */ + protected $request; + + /** + * Constructor + * + * @param \phpbb\config\config $config + * @param \phpbb\request\request_interface $request + */ + public function __construct(\phpbb\config\config $config, \phpbb\request\request_interface $request) + { + $this->config = $config; + $this->request = $request; + } + + /** + * {@inheritdoc} + */ + public function get_auth_scope() + { + return array( + 'userinfo_email', + 'userinfo_profile', + ); + } + + /** + * {@inheritdoc} + */ + public function get_service_credentials() + { + return array( + 'key' => $this->config['auth_oauth_google_key'], + 'secret' => $this->config['auth_oauth_google_secret'], + ); + } + + /** + * {@inheritdoc} + */ + public function perform_auth_login() + { + if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Google)) + { + throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE'); + } + + // This was a callback request, get the token + $this->service_provider->requestAccessToken($this->request->variable('code', '')); + + // Send a request with it + $result = json_decode($this->service_provider->request('https://www.googleapis.com/oauth2/v1/userinfo'), true); + + // Return the unique identifier + return $result['id']; + } + + /** + * {@inheritdoc} + */ + public function perform_token_auth() + { + if (!($this->service_provider instanceof \OAuth\OAuth2\Service\Google)) + { + throw new exception('AUTH_PROVIDER_OAUTH_ERROR_INVALID_SERVICE_TYPE'); + } + + // Send a request with it + $result = json_decode($this->service_provider->request('https://www.googleapis.com/oauth2/v1/userinfo'), true); + + // Return the unique identifier + return $result['id']; + } +} diff --git a/phpBB/phpbb/auth/provider/oauth/service/service_interface.php b/phpBB/phpbb/auth/provider/oauth/service/service_interface.php new file mode 100644 index 0000000000..e84eb247b6 --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/service/service_interface.php @@ -0,0 +1,73 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth\service; + +/** +* OAuth service interface +*/ +interface service_interface +{ + /** + * Returns an array of the scopes necessary for auth + * + * @return array An array of the required scopes + */ + public function get_auth_scope(); + + /** + * Returns the external library service provider once it has been set + * + * @param \OAuth\Common\Service\ServiceInterface|null + */ + public function get_external_service_provider(); + + /** + * Returns an array containing the service credentials belonging to requested + * service. + * + * @return array An array containing the 'key' and the 'secret' of the + * service in the form: + * array( + * 'key' => string + * 'secret' => string + * ) + */ + public function get_service_credentials(); + + /** + * Returns the results of the authentication in json format + * + * @throws \phpbb\auth\provider\oauth\service\exception + * @return string The unique identifier returned by the service provider + * that is used to authenticate the user with phpBB. + */ + public function perform_auth_login(); + + /** + * Returns the results of the authentication in json format + * Use this function when the user already has an access token + * + * @throws \phpbb\auth\provider\oauth\service\exception + * @return string The unique identifier returned by the service provider + * that is used to authenticate the user with phpBB. + */ + public function perform_token_auth(); + + /** + * Sets the external library service provider + * + * @param \OAuth\Common\Service\ServiceInterface $service_provider + */ + public function set_external_service_provider(\OAuth\Common\Service\ServiceInterface $service_provider); +} diff --git a/phpBB/phpbb/auth/provider/oauth/token_storage.php b/phpBB/phpbb/auth/provider/oauth/token_storage.php new file mode 100644 index 0000000000..9b6afae255 --- /dev/null +++ b/phpBB/phpbb/auth/provider/oauth/token_storage.php @@ -0,0 +1,364 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider\oauth; + +use OAuth\OAuth1\Token\StdOAuth1Token; +use OAuth\Common\Token\TokenInterface; +use OAuth\Common\Storage\TokenStorageInterface; +use OAuth\Common\Storage\Exception\TokenNotFoundException; + +/** +* OAuth storage wrapper for phpbb's cache +*/ +class token_storage implements TokenStorageInterface +{ + /** + * Cache driver. + * + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * phpBB user + * + * @var \phpbb\user + */ + protected $user; + + /** + * OAuth token table + * + * @var string + */ + protected $auth_provider_oauth_table; + + /** + * @var object|TokenInterface + */ + protected $cachedToken; + + /** + * Creates token storage for phpBB. + * + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\user $user + * @param string $auth_provider_oauth_table + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\user $user, $auth_provider_oauth_table) + { + $this->db = $db; + $this->user = $user; + $this->auth_provider_oauth_table = $auth_provider_oauth_table; + } + + /** + * {@inheritdoc} + */ + public function retrieveAccessToken($service) + { + $service = $this->get_service_name_for_db($service); + + if ($this->cachedToken instanceof TokenInterface) + { + return $this->cachedToken; + } + + $data = array( + 'user_id' => (int) $this->user->data['user_id'], + 'provider' => $service, + ); + + if ((int) $this->user->data['user_id'] === ANONYMOUS) + { + $data['session_id'] = $this->user->data['session_id']; + } + + return $this->_retrieve_access_token($data); + } + + /** + * {@inheritdoc} + */ + public function storeAccessToken($service, TokenInterface $token) + { + $service = $this->get_service_name_for_db($service); + + $this->cachedToken = $token; + + $data = array( + 'user_id' => (int) $this->user->data['user_id'], + 'provider' => $service, + 'oauth_token' => $this->json_encode_token($token), + 'session_id' => $this->user->data['session_id'], + ); + + $sql = 'INSERT INTO ' . $this->auth_provider_oauth_table . ' + ' . $this->db->sql_build_array('INSERT', $data); + $this->db->sql_query($sql); + } + + /** + * {@inheritdoc} + */ + public function hasAccessToken($service) + { + $service = $this->get_service_name_for_db($service); + + if ($this->cachedToken) + { + return true; + } + + $data = array( + 'user_id' => (int) $this->user->data['user_id'], + 'provider' => $service, + ); + + if ((int) $this->user->data['user_id'] === ANONYMOUS) + { + $data['session_id'] = $this->user->data['session_id']; + } + + return $this->_has_acess_token($data); + } + + /** + * {@inheritdoc} + */ + public function clearToken($service) + { + $service = $this->get_service_name_for_db($service); + + $this->cachedToken = null; + + $sql = 'DELETE FROM ' . $this->auth_provider_oauth_table . ' + WHERE user_id = ' . (int) $this->user->data['user_id'] . " + AND provider = '" . $this->db->sql_escape($service) . "'"; + + if ((int) $this->user->data['user_id'] === ANONYMOUS) + { + $sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'"; + } + + $this->db->sql_query($sql); + } + + /** + * {@inheritdoc} + */ + public function clearAllTokens() + { + $this->cachedToken = null; + + $sql = 'DELETE FROM ' . $this->auth_provider_oauth_table . ' + WHERE user_id = ' . (int) $this->user->data['user_id']; + + if ((int) $this->user->data['user_id'] === ANONYMOUS) + { + $sql .= " AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'"; + } + + $this->db->sql_query($sql); + } + + /** + * Updates the user_id field in the database assosciated with the token + * + * @param int $user_id + */ + public function set_user_id($user_id) + { + if (!$this->cachedToken) + { + return; + } + + $sql = 'UPDATE ' . $this->auth_provider_oauth_table . ' + SET ' . $this->db->sql_build_array('UPDATE', array( + 'user_id' => (int) $user_id + )) . ' + WHERE user_id = ' . (int) $this->user->data['user_id'] . " + AND session_id = '" . $this->db->sql_escape($this->user->data['session_id']) . "'"; + $this->db->sql_query($sql); + } + + /** + * Checks to see if an access token exists solely by the session_id of the user + * + * @param string $service The name of the OAuth service + * @return bool true if they have token, false if they don't + */ + public function has_access_token_by_session($service) + { + $service = $this->get_service_name_for_db($service); + + if ($this->cachedToken) + { + return true; + } + + $data = array( + 'session_id' => $this->user->data['session_id'], + 'provider' => $service, + ); + + return $this->_has_acess_token($data); + } + + /** + * A helper function that performs the query for has access token functions + * + * @param array $data + * @return bool + */ + protected function _has_acess_token($data) + { + return (bool) $this->get_access_token_row($data); + } + + public function retrieve_access_token_by_session($service) + { + $service = $this->get_service_name_for_db($service); + + if ($this->cachedToken instanceof TokenInterface) + { + return $this->cachedToken; + } + + $data = array( + 'session_id' => $this->user->data['session_id'], + 'provider' => $service, + ); + + return $this->_retrieve_access_token($data); + } + + /** + * A helper function that performs the query for retrieve access token functions + * Also checks if the token is a valid token + * + * @param array $data + * @return mixed + * @throws \OAuth\Common\Storage\Exception\TokenNotFoundException + */ + protected function _retrieve_access_token($data) + { + $row = $this->get_access_token_row($data); + + if (!$row) + { + throw new TokenNotFoundException('AUTH_PROVIDER_OAUTH_TOKEN_ERROR_NOT_STORED'); + } + + $token = $this->json_decode_token($row['oauth_token']); + + // Ensure that the token was serialized/unserialized correctly + if (!($token instanceof TokenInterface)) + { + $this->clearToken($data['provider']); + throw new TokenNotFoundException('AUTH_PROVIDER_OAUTH_TOKEN_ERROR_INCORRECTLY_STORED'); + } + + $this->cachedToken = $token; + return $token; + } + + /** + * A helper function that performs the query for retrieving an access token + * + * @param array $data + * @return mixed + */ + protected function get_access_token_row($data) + { + $sql = 'SELECT oauth_token FROM ' . $this->auth_provider_oauth_table . ' + WHERE ' . $this->db->sql_build_array('SELECT', $data); + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + return $row; + } + + public function json_encode_token(TokenInterface $token) + { + $members = array( + 'accessToken' => $token->getAccessToken(), + 'endOfLife' => $token->getEndOfLife(), + 'extraParams' => $token->getExtraParams(), + 'refreshToken' => $token->getRefreshToken(), + + 'token_class' => get_class($token), + ); + + // Handle additional data needed for OAuth1 tokens + if ($token instanceof StdOAuth1Token) + { + $members['requestToken'] = $token->getRequestToken(); + $members['requestTokenSecret'] = $token->getRequestTokenSecret(); + $members['accessTokenSecret'] = $token->getAccessTokenSecret(); + } + + return json_encode($members); + } + + public function json_decode_token($json) + { + $token_data = json_decode($json, true); + + if ($token_data === null) + { + throw new TokenNotFoundException('AUTH_PROVIDER_OAUTH_TOKEN_ERROR_INCORRECTLY_STORED'); + } + + $token_class = $token_data['token_class']; + $access_token = $token_data['accessToken']; + $refresh_token = $token_data['refreshToken']; + $endOfLife = $token_data['endOfLife']; + $extra_params = $token_data['extraParams']; + + // Create the token + $token = new $token_class($access_token, $refresh_token, TokenInterface::EOL_NEVER_EXPIRES, $extra_params); + $token->setEndOfLife($endOfLife); + + // Handle OAuth 1.0 specific elements + if ($token instanceof StdOAuth1Token) + { + $token->setRequestToken($token_data['requestToken']); + $token->setRequestTokenSecret($token_data['requestTokenSecret']); + $token->setAccessTokenSecret($token_data['accessTokenSecret']); + } + + return $token; + } + + /** + * Returns the name of the service as it must be stored in the database. + * + * @param string $service The name of the OAuth service + * @return string The name of the OAuth service as it needs to be stored + * in the database. + */ + protected function get_service_name_for_db($service) + { + // Enforce the naming convention for oauth services + if (strpos($service, 'auth.provider.oauth.service.') !== 0) + { + $service = 'auth.provider.oauth.service.' . strtolower($service); + } + + return $service; + } +} diff --git a/phpBB/phpbb/auth/provider/provider_interface.php b/phpBB/phpbb/auth/provider/provider_interface.php new file mode 100644 index 0000000000..35e0f559a1 --- /dev/null +++ b/phpBB/phpbb/auth/provider/provider_interface.php @@ -0,0 +1,197 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth\provider; + +/** +* The interface authentication provider classes have to implement. +*/ +interface provider_interface +{ + /** + * Checks whether the user is currently identified to the authentication + * provider. + * Called in acp_board while setting authentication plugins. + * Changing to an authentication provider will not be permitted in acp_board + * if there is an error. + * + * @return boolean|string False if the user is identified, otherwise an + * error message, or null if not implemented. + */ + public function init(); + + /** + * Performs login. + * + * @param string $username The name of the user being authenticated. + * @param string $password The password of the user. + * @return array An associative array of the format: + * array( + * 'status' => status constant + * 'error_msg' => string + * 'user_row' => array + * ) + * A fourth key of the array may be present: + * 'redirect_data' This key is only used when 'status' is + * equal to LOGIN_SUCCESS_LINK_PROFILE and its value is an + * associative array that is turned into GET variables on + * the redirect url. + */ + public function login($username, $password); + + /** + * Autologin function + * + * @return array|null containing the user row, empty if no auto login + * should take place, or null if not impletmented. + */ + public function autologin(); + + /** + * This function is used to output any required fields in the authentication + * admin panel. It also defines any required configuration table fields. + * + * @return array|null Returns null if not implemented or an array of the + * configuration fields of the provider. + */ + public function acp(); + + /** + * This function updates the template with variables related to the acp + * options with whatever configuraton values are passed to it as an array. + * It then returns the name of the acp file related to this authentication + * provider. + * @param array $new_config Contains the new configuration values that + * have been set in acp_board. + * @return array|null Returns null if not implemented or an array with + * the template file name and an array of the vars + * that the template needs that must conform to the + * following example: + * array( + * 'TEMPLATE_FILE' => string, + * 'TEMPLATE_VARS' => array(...), + * ) + * An optional third element may be added to this + * array: 'BLOCK_VAR_NAME'. If this is present, + * then its value should be a string that is used + * to designate the name of the loop used in the + * ACP template file. When this is present, an + * additional key named 'BLOCK_VARS' is required. + * This must be an array containing at least one + * array of variables that will be assigned during + * the loop in the template. An example of this is + * presented below: + * array( + * 'BLOCK_VAR_NAME' => string, + * 'BLOCK_VARS' => array( + * 'KEY IS UNIMPORTANT' => array(...), + * ), + * 'TEMPLATE_FILE' => string, + * 'TEMPLATE_VARS' => array(...), + * ) + */ + public function get_acp_template($new_config); + + /** + * Returns an array of data necessary to build custom elements on the login + * form. + * + * @return array|null If this function is not implemented on an auth + * provider then it returns null. If it is implemented + * it will return an array of up to four elements of + * which only 'TEMPLATE_FILE'. If 'BLOCK_VAR_NAME' is + * present then 'BLOCK_VARS' must also be present in + * the array. The fourth element 'VARS' is also + * optional. The array, with all four elements present + * looks like the following: + * array( + * 'TEMPLATE_FILE' => string, + * 'BLOCK_VAR_NAME' => string, + * 'BLOCK_VARS' => array(...), + * 'VARS' => array(...), + * ) + */ + public function get_login_data(); + + /** + * Performs additional actions during logout. + * + * @param array $data An array corresponding to + * \phpbb\session::data + * @param boolean $new_session True for a new session, false for no new + * session. + */ + public function logout($data, $new_session); + + /** + * The session validation function checks whether the user is still logged + * into phpBB. + * + * @param array $user + * @return boolean true if the given user is authenticated, false if the + * session should be closed, or null if not implemented. + */ + public function validate_session($user); + + /** + * Checks to see if $login_link_data contains all information except for the + * user_id of an account needed to successfully link an external account to + * a forum account. + * + * @param array $login_link_data Any data needed to link a phpBB account to + * an external account. + * @return string|null Returns a string with a language constant if there + * is data missing or null if there is no error. + */ + public function login_link_has_necessary_data($login_link_data); + + /** + * Links an external account to a phpBB account. + * + * @param array $link_data Any data needed to link a phpBB account to + * an external account. + */ + public function link_account(array $link_data); + + /** + * Returns an array of data necessary to build the ucp_auth_link page + * + * @param int $user_id User ID for whom the data should be retrieved. + * defaults to 0, which is not a valid ID. The method + * should fall back to the current user's ID in this + * case. + * @return array|null If this function is not implemented on an auth + * provider then it returns null. If it is implemented + * it will return an array of up to four elements of + * which only 'TEMPLATE_FILE'. If 'BLOCK_VAR_NAME' is + * present then 'BLOCK_VARS' must also be present in + * the array. The fourth element 'VARS' is also + * optional. The array, with all four elements present + * looks like the following: + * array( + * 'TEMPLATE_FILE' => string, + * 'BLOCK_VAR_NAME' => string, + * 'BLOCK_VARS' => array(...), + * 'VARS' => array(...), + * ) + */ + public function get_auth_link_data($user_id = 0); + + /** + * Unlinks an external account from a phpBB account. + * + * @param array $link_data Any data needed to unlink a phpBB account + * from a phpbb account. + */ + public function unlink_account(array $link_data); +} diff --git a/phpBB/phpbb/auth/provider_collection.php b/phpBB/phpbb/auth/provider_collection.php new file mode 100644 index 0000000000..8e7e9e2cc1 --- /dev/null +++ b/phpBB/phpbb/auth/provider_collection.php @@ -0,0 +1,67 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\auth; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* Collection of auth providers to be configured at container compile time. +*/ +class provider_collection extends \phpbb\di\service_collection +{ + /** @var \phpbb\config\config phpBB Config */ + protected $config; + + /** + * Constructor + * + * @param ContainerInterface $container Container object + * @param \phpbb\config\config $config phpBB config + */ + public function __construct(ContainerInterface $container, \phpbb\config\config $config) + { + $this->container = $container; + $this->config = $config; + } + + /** + * Get an auth provider. + * + * @param string $provider_name The name of the auth provider + * @return object Default auth provider selected in config if it + * does exist. Otherwise the standard db auth + * provider. + * @throws \RuntimeException If neither the auth provider that + * is specified by the phpBB config nor the db + * auth provider exist. The db auth provider + * should always exist in a phpBB installation. + */ + public function get_provider($provider_name = '') + { + $provider_name = ($provider_name !== '') ? $provider_name : basename(trim($this->config['auth_method'])); + if ($this->offsetExists('auth.provider.' . $provider_name)) + { + return $this->offsetGet('auth.provider.' . $provider_name); + } + // Revert to db auth provider if selected method does not exist + else if ($this->offsetExists('auth.provider.db')) + { + return $this->offsetGet('auth.provider.db'); + } + else + { + throw new \RuntimeException(sprintf('The authentication provider for the authentication method "%1$s" does not exist. It was not possible to recover from this by reverting to the database authentication provider.', $this->config['auth_method'])); + } + } +} diff --git a/phpBB/phpbb/avatar/driver/driver.php b/phpBB/phpbb/avatar/driver/driver.php new file mode 100644 index 0000000000..ad186635f2 --- /dev/null +++ b/phpBB/phpbb/avatar/driver/driver.php @@ -0,0 +1,147 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar\driver; + +/** +* Base class for avatar drivers +*/ +abstract class driver implements \phpbb\avatar\driver\driver_interface +{ + /** + * Avatar driver name + * @var string + */ + protected $name; + + /** + * Current board configuration + * @var \phpbb\config\config + */ + protected $config; + + /** + * Current $phpbb_root_path + * @var string + */ + protected $phpbb_root_path; + + /** + * Current $php_ext + * @var string + */ + protected $php_ext; + + /** + * Path Helper + * @var \phpbb\path_helper + */ + protected $path_helper; + + /** + * Cache driver + * @var \phpbb\cache\driver\driver_interface + */ + protected $cache; + + /** + * Array of allowed avatar image extensions + * Array is used for setting the allowed extensions in the fileupload class + * and as a base for a regex of allowed extensions, which will be formed by + * imploding the array with a "|". + * + * @var array + */ + protected $allowed_extensions = array( + 'gif', + 'jpg', + 'jpeg', + 'png', + ); + + /** + * Construct a driver object + * + * @param \phpbb\config\config $config phpBB configuration + * @param string $phpbb_root_path Path to the phpBB root + * @param string $php_ext PHP file extension + * @param \phpbb\path_helper $path_helper phpBB path helper + * @param \phpbb\cache\driver\driver_interface $cache Cache driver + */ + public function __construct(\phpbb\config\config $config, $phpbb_root_path, $php_ext, \phpbb\path_helper $path_helper, \phpbb\cache\driver\driver_interface $cache = null) + { + $this->config = $config; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->path_helper = $path_helper; + $this->cache = $cache; + } + + /** + * {@inheritdoc} + */ + public function get_custom_html($user, $row, $alt = '') + { + return ''; + } + + /** + * {@inheritdoc} + */ + public function prepare_form_acp($user) + { + return array(); + } + + /** + * {@inheritdoc} + */ + public function delete($row) + { + return true; + } + + /** + * {@inheritdoc} + */ + public function get_name() + { + return $this->name; + } + + /** + * {@inheritdoc} + */ + public function get_config_name() + { + return preg_replace('#^phpbb\\\\avatar\\\\driver\\\\#', '', get_class($this)); + } + + /** + * {@inheritdoc} + */ + public function get_acp_template_name() + { + return 'acp_avatar_options_' . $this->get_config_name() . '.html'; + } + + /** + * Sets the name of the driver. + * + * @param string $name Driver name + */ + public function set_name($name) + { + $this->name = $name; + } +} diff --git a/phpBB/phpbb/avatar/driver/driver_interface.php b/phpBB/phpbb/avatar/driver/driver_interface.php new file mode 100644 index 0000000000..7d6c2cff8a --- /dev/null +++ b/phpBB/phpbb/avatar/driver/driver_interface.php @@ -0,0 +1,127 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar\driver; + +/** +* Interface for avatar drivers +*/ +interface driver_interface +{ + /** + * Returns the name of the driver. + * + * @return string Name of driver. + */ + public function get_name(); + + /** + * Returns the config name of the driver. To be used in accessing the CONFIG variables. + * + * @return string Config name of driver. + */ + public function get_config_name(); + + /** + * Get the avatar url and dimensions + * + * @param array $row User data or group data that has been cleaned with + * \phpbb\avatar\manager::clean_row + * @return array Avatar data, must have keys src, width and height, e.g. + * ['src' => '', 'width' => 0, 'height' => 0] + */ + public function get_data($row); + + /** + * Returns custom html if it is needed for displaying this avatar + * + * @param \phpbb\user $user phpBB user object + * @param array $row User data or group data that has been cleaned with + * \phpbb\avatar\manager::clean_row + * @param string $alt Alternate text for avatar image + * + * @return string HTML + */ + public function get_custom_html($user, $row, $alt = ''); + + /** + * Prepare form for changing the settings of this avatar + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + * @param array $row User data or group data that has been cleaned with + * \phpbb\avatar\manager::clean_row + * @param array &$error Reference to an error array that is filled by this + * function. Key values can either be a string with a language key or + * an array that will be passed to vsprintf() with the language key in + * the first array key. + * + * @return bool True if form has been successfully prepared + */ + public function prepare_form($request, $template, $user, $row, &$error); + + /** + * Prepare form for changing the acp settings of this avatar + * + * @param \phpbb\user $user phpBB user object + * + * @return array Array of configuration options as consumed by acp_board. + * The setting for enabling/disabling the avatar will be handled by + * the avatar manager. + */ + public function prepare_form_acp($user); + + /** + * Process form data + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + * @param array $row User data or group data that has been cleaned with + * \phpbb\avatar\manager::clean_row + * @param array &$error Reference to an error array that is filled by this + * function. Key values can either be a string with a language key or + * an array that will be passed to vsprintf() with the language key in + * the first array key. + * + * @return array Array containing the avatar data as follows: + * ['avatar'], ['avatar_width'], ['avatar_height'] + */ + public function process_form($request, $template, $user, $row, &$error); + + /** + * Delete avatar + * + * @param array $row User data or group data that has been cleaned with + * \phpbb\avatar\manager::clean_row + * + * @return bool True if avatar has been deleted or there is no need to delete, + * i.e. when the avatar is not hosted locally. + */ + public function delete($row); + + /** + * Get the avatar driver's template name + * + * @return string Avatar driver's template name + */ + public function get_template_name(); + + /** + * Get the avatar driver's template name (ACP) + * + * @return string Avatar driver's template name + */ + public function get_acp_template_name(); +} diff --git a/phpBB/phpbb/avatar/driver/gravatar.php b/phpBB/phpbb/avatar/driver/gravatar.php new file mode 100644 index 0000000000..7a43b55852 --- /dev/null +++ b/phpBB/phpbb/avatar/driver/gravatar.php @@ -0,0 +1,198 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar\driver; + +/** +* Handles avatars hosted at gravatar.com +*/ +class gravatar extends \phpbb\avatar\driver\driver +{ + /** + * The URL for the gravatar service + */ + const GRAVATAR_URL = '//secure.gravatar.com/avatar/'; + + /** + * {@inheritdoc} + */ + public function get_data($row) + { + return array( + 'src' => $row['avatar'], + 'width' => $row['avatar_width'], + 'height' => $row['avatar_height'], + ); + } + + /** + * {@inheritdoc} + */ + public function get_custom_html($user, $row, $alt = '') + { + return '<img src="' . $this->get_gravatar_url($row) . '" ' . + ($row['avatar_width'] ? ('width="' . $row['avatar_width'] . '" ') : '') . + ($row['avatar_height'] ? ('height="' . $row['avatar_height'] . '" ') : '') . + 'alt="' . ((!empty($user->lang[$alt])) ? $user->lang[$alt] : $alt) . '" />'; + } + + /** + * {@inheritdoc} + */ + public function prepare_form($request, $template, $user, $row, &$error) + { + $template->assign_vars(array( + 'AVATAR_GRAVATAR_WIDTH' => (($row['avatar_type'] == $this->get_name() || $row['avatar_type'] == 'gravatar') && $row['avatar_width']) ? $row['avatar_width'] : $request->variable('avatar_gravatar_width', ''), + 'AVATAR_GRAVATAR_HEIGHT' => (($row['avatar_type'] == $this->get_name() || $row['avatar_type'] == 'gravatar') && $row['avatar_height']) ? $row['avatar_height'] : $request->variable('avatar_gravatar_width', ''), + 'AVATAR_GRAVATAR_EMAIL' => (($row['avatar_type'] == $this->get_name() || $row['avatar_type'] == 'gravatar') && $row['avatar']) ? $row['avatar'] : '', + )); + + return true; + } + + /** + * {@inheritdoc} + */ + public function process_form($request, $template, $user, $row, &$error) + { + $row['avatar'] = $request->variable('avatar_gravatar_email', ''); + $row['avatar_width'] = $request->variable('avatar_gravatar_width', 0); + $row['avatar_height'] = $request->variable('avatar_gravatar_height', 0); + + if (empty($row['avatar'])) + { + return false; + } + + if (!function_exists('validate_data')) + { + require($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + + $validate_array = validate_data( + array( + 'email' => $row['avatar'], + ), + array( + 'email' => array( + array('string', false, 6, 60), + array('email'), + ), + ) + ); + + $error = array_merge($error, $validate_array); + + if (!empty($error)) + { + return false; + } + + // Make sure getimagesize works... + if (function_exists('getimagesize') && ($row['avatar_width'] <= 0 || $row['avatar_height'] <= 0)) + { + /** + * default to the minimum of the maximum allowed avatar size if the size + * is not or only partially entered + */ + $row['avatar_width'] = $row['avatar_height'] = min($this->config['avatar_max_width'], $this->config['avatar_max_height']); + $url = $this->get_gravatar_url($row); + + if (($row['avatar_width'] <= 0 || $row['avatar_height'] <= 0) && (($image_data = getimagesize($url)) === false)) + { + $error[] = 'UNABLE_GET_IMAGE_SIZE'; + return false; + } + + if (!empty($image_data) && ($image_data[0] <= 0 || $image_data[1] <= 0)) + { + $error[] = 'AVATAR_NO_SIZE'; + return false; + } + + $row['avatar_width'] = ($row['avatar_width'] && $row['avatar_height']) ? $row['avatar_width'] : $image_data[0]; + $row['avatar_height'] = ($row['avatar_width'] && $row['avatar_height']) ? $row['avatar_height'] : $image_data[1]; + } + + if ($row['avatar_width'] <= 0 || $row['avatar_height'] <= 0) + { + $error[] = 'AVATAR_NO_SIZE'; + return false; + } + + if ($this->config['avatar_max_width'] || $this->config['avatar_max_height']) + { + if ($row['avatar_width'] > $this->config['avatar_max_width'] || $row['avatar_height'] > $this->config['avatar_max_height']) + { + $error[] = array('AVATAR_WRONG_SIZE', $this->config['avatar_min_width'], $this->config['avatar_min_height'], $this->config['avatar_max_width'], $this->config['avatar_max_height'], $row['avatar_width'], $row['avatar_height']); + return false; + } + } + + if ($this->config['avatar_min_width'] || $this->config['avatar_min_height']) + { + if ($row['avatar_width'] < $this->config['avatar_min_width'] || $row['avatar_height'] < $this->config['avatar_min_height']) + { + $error[] = array('AVATAR_WRONG_SIZE', $this->config['avatar_min_width'], $this->config['avatar_min_height'], $this->config['avatar_max_width'], $this->config['avatar_max_height'], $row['avatar_width'], $row['avatar_height']); + return false; + } + } + + return array( + 'avatar' => $row['avatar'], + 'avatar_width' => $row['avatar_width'], + 'avatar_height' => $row['avatar_height'], + ); + } + + /** + * {@inheritdoc} + */ + public function get_template_name() + { + return 'ucp_avatar_options_gravatar.html'; + } + + /** + * Build gravatar URL for output on page + * + * @param array $row User data or group data that has been cleaned with + * \phpbb\avatar\manager::clean_row + * @return string Gravatar URL + */ + protected function get_gravatar_url($row) + { + global $phpbb_dispatcher; + + $url = self::GRAVATAR_URL; + $url .= md5(strtolower(trim($row['avatar']))); + + if ($row['avatar_width'] || $row['avatar_height']) + { + $url .= '?s=' . max($row['avatar_width'], $row['avatar_height']); + } + + /** + * Modify gravatar url + * + * @event core.get_gravatar_url_after + * @var string row User data or group data + * @var string url Gravatar URL + * @since 3.1.7-RC1 + */ + $vars = array('row', 'url'); + extract($phpbb_dispatcher->trigger_event('core.get_gravatar_url_after', compact($vars))); + + return $url; + } +} diff --git a/phpBB/phpbb/avatar/driver/local.php b/phpBB/phpbb/avatar/driver/local.php new file mode 100644 index 0000000000..75c384f31e --- /dev/null +++ b/phpBB/phpbb/avatar/driver/local.php @@ -0,0 +1,205 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar\driver; + +/** +* Handles avatars selected from the board gallery +*/ +class local extends \phpbb\avatar\driver\driver +{ + /** + * {@inheritdoc} + */ + public function get_data($row) + { + $root_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? generate_board_url() . '/' : $this->path_helper->get_web_root_path(); + + return array( + 'src' => $root_path . $this->config['avatar_gallery_path'] . '/' . $row['avatar'], + 'width' => $row['avatar_width'], + 'height' => $row['avatar_height'], + ); + } + + /** + * {@inheritdoc} + */ + public function prepare_form($request, $template, $user, $row, &$error) + { + $avatar_list = $this->get_avatar_list($user); + $category = $request->variable('avatar_local_cat', key($avatar_list)); + + foreach ($avatar_list as $cat => $null) + { + if (!empty($avatar_list[$cat])) + { + $template->assign_block_vars('avatar_local_cats', array( + 'NAME' => $cat, + 'SELECTED' => ($cat == $category), + )); + } + + if ($cat != $category) + { + unset($avatar_list[$cat]); + } + } + + if (!empty($avatar_list[$category])) + { + $template->assign_vars(array( + 'AVATAR_LOCAL_SHOW' => true, + )); + + $table_cols = isset($row['avatar_gallery_cols']) ? $row['avatar_gallery_cols'] : 4; + $row_count = $col_count = $avatar_pos = 0; + $avatar_count = sizeof($avatar_list[$category]); + + reset($avatar_list[$category]); + + while ($avatar_pos < $avatar_count) + { + $img = current($avatar_list[$category]); + next($avatar_list[$category]); + + if ($col_count == 0) + { + ++$row_count; + $template->assign_block_vars('avatar_local_row', array( + )); + } + + $template->assign_block_vars('avatar_local_row.avatar_local_col', array( + 'AVATAR_IMAGE' => $this->phpbb_root_path . $this->config['avatar_gallery_path'] . '/' . $img['file'], + 'AVATAR_NAME' => $img['name'], + 'AVATAR_FILE' => $img['filename'], + 'CHECKED' => $img['file'] === $row['avatar'], + )); + + $template->assign_block_vars('avatar_local_row.avatar_local_option', array( + 'AVATAR_FILE' => $img['filename'], + 'S_OPTIONS_AVATAR' => $img['filename'], + 'CHECKED' => $img['file'] === $row['avatar'], + )); + + $col_count = ($col_count + 1) % $table_cols; + + ++$avatar_pos; + } + } + + return true; + } + + /** + * {@inheritdoc} + */ + public function prepare_form_acp($user) + { + return array( + 'avatar_gallery_path' => array('lang' => 'AVATAR_GALLERY_PATH', 'validate' => 'rpath', 'type' => 'text:20:255', 'explain' => true), + ); + } + + /** + * {@inheritdoc} + */ + public function process_form($request, $template, $user, $row, &$error) + { + $avatar_list = $this->get_avatar_list($user); + $category = $request->variable('avatar_local_cat', ''); + + $file = $request->variable('avatar_local_file', ''); + + if (empty($category) || empty($file)) + { + return false; + } + + if (!isset($avatar_list[$category][urldecode($file)])) + { + $error[] = 'AVATAR_URL_NOT_FOUND'; + return false; + } + + return array( + 'avatar' => ($category != $user->lang['NO_AVATAR_CATEGORY']) ? $category . '/' . $file : $file, + 'avatar_width' => $avatar_list[$category][urldecode($file)]['width'], + 'avatar_height' => $avatar_list[$category][urldecode($file)]['height'], + ); + } + + /** + * {@inheritdoc} + */ + public function get_template_name() + { + return 'ucp_avatar_options_local.html'; + } + + /** + * Get a list of avatars that are locally available + * Results get cached for 24 hours (86400 seconds) + * + * @param \phpbb\user $user User object + * + * @return array Array containing the locally available avatars + */ + protected function get_avatar_list($user) + { + $avatar_list = ($this->cache == null) ? false : $this->cache->get('_avatar_local_list'); + + if ($avatar_list === false) + { + $avatar_list = array(); + $path = $this->phpbb_root_path . $this->config['avatar_gallery_path']; + + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS), \RecursiveIteratorIterator::SELF_FIRST); + foreach ($iterator as $file_info) + { + $file_path = $file_info->getPath(); + $image = $file_info->getFilename(); + + // Match all images in the gallery folder + if (preg_match('#^[^&\'"<>]+\.(?:' . implode('|', $this->allowed_extensions) . ')$#i', $image) && is_file($file_path . '/' . $image)) + { + if (function_exists('getimagesize')) + { + $dims = getimagesize($file_path . '/' . $image); + } + else + { + $dims = array(0, 0); + } + $cat = ($path == $file_path) ? $user->lang['NO_AVATAR_CATEGORY'] : str_replace("$path/", '', $file_path); + $avatar_list[$cat][$image] = array( + 'file' => ($cat != $user->lang['NO_AVATAR_CATEGORY']) ? str_replace('%2F', '/', rawurlencode($cat)) . '/' . rawurlencode($image) : rawurlencode($image), + 'filename' => rawurlencode($image), + 'name' => ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $image))), + 'width' => $dims[0], + 'height' => $dims[1], + ); + } + } + ksort($avatar_list); + + if ($this->cache != null) + { + $this->cache->put('_avatar_local_list', $avatar_list, 86400); + } + } + + return $avatar_list; + } +} diff --git a/phpBB/phpbb/avatar/driver/remote.php b/phpBB/phpbb/avatar/driver/remote.php new file mode 100644 index 0000000000..2811cc2389 --- /dev/null +++ b/phpBB/phpbb/avatar/driver/remote.php @@ -0,0 +1,224 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar\driver; + +/** +* Handles avatars hosted remotely +*/ +class remote extends \phpbb\avatar\driver\driver +{ + /** + * {@inheritdoc} + */ + public function get_data($row) + { + return array( + 'src' => $row['avatar'], + 'width' => $row['avatar_width'], + 'height' => $row['avatar_height'], + ); + } + + /** + * {@inheritdoc} + */ + public function prepare_form($request, $template, $user, $row, &$error) + { + $template->assign_vars(array( + 'AVATAR_REMOTE_WIDTH' => ((in_array($row['avatar_type'], array(AVATAR_REMOTE, $this->get_name(), 'remote'))) && $row['avatar_width']) ? $row['avatar_width'] : $request->variable('avatar_remote_width', ''), + 'AVATAR_REMOTE_HEIGHT' => ((in_array($row['avatar_type'], array(AVATAR_REMOTE, $this->get_name(), 'remote'))) && $row['avatar_height']) ? $row['avatar_height'] : $request->variable('avatar_remote_width', ''), + 'AVATAR_REMOTE_URL' => ((in_array($row['avatar_type'], array(AVATAR_REMOTE, $this->get_name(), 'remote'))) && $row['avatar']) ? $row['avatar'] : '', + )); + + return true; + } + + /** + * {@inheritdoc} + */ + public function process_form($request, $template, $user, $row, &$error) + { + $url = $request->variable('avatar_remote_url', ''); + $width = $request->variable('avatar_remote_width', 0); + $height = $request->variable('avatar_remote_height', 0); + + if (empty($url)) + { + return false; + } + + if (!preg_match('#^(http|https|ftp)://#i', $url)) + { + $url = 'http://' . $url; + } + + if (!function_exists('validate_data')) + { + require($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + + $validate_array = validate_data( + array( + 'url' => $url, + ), + array( + 'url' => array('string', true, 5, 255), + ) + ); + + $error = array_merge($error, $validate_array); + + if (!empty($error)) + { + return false; + } + + // Check if this url looks alright + // Do not allow specifying the port (see RFC 3986) or IP addresses + if (!preg_match('#^(http|https|ftp)://(?:(.*?\.)*?[a-z0-9\-]+?\.[a-z]{2,4}|(?:\d{1,3}\.){3,5}\d{1,3}):?([0-9]*?).*?\.('. implode('|', $this->allowed_extensions) . ')$#i', $url) || + preg_match('@^(http|https|ftp)://[^/:?#]+:[0-9]+[/:?#]@i', $url) || + preg_match('#^(http|https|ftp)://(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])#i', $url) || + preg_match('#^(http|https|ftp)://(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){0,5}(?:[\dA-F]{1,4}(?::[\dA-F]{1,4})?|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:)|(?:::))#i', $url)) + { + $error[] = 'AVATAR_URL_INVALID'; + return false; + } + + // Make sure getimagesize works... + if (function_exists('getimagesize')) + { + if (($width <= 0 || $height <= 0) && (($image_data = @getimagesize($url)) === false)) + { + $error[] = 'UNABLE_GET_IMAGE_SIZE'; + return false; + } + + if (!empty($image_data) && ($image_data[0] <= 0 || $image_data[1] <= 0)) + { + $error[] = 'AVATAR_NO_SIZE'; + return false; + } + + $width = ($width && $height) ? $width : $image_data[0]; + $height = ($width && $height) ? $height : $image_data[1]; + } + + if ($width <= 0 || $height <= 0) + { + $error[] = 'AVATAR_NO_SIZE'; + return false; + } + + if (!class_exists('fileupload')) + { + include($this->phpbb_root_path . 'includes/functions_upload.' . $this->php_ext); + } + + $types = \fileupload::image_types(); + $extension = strtolower(\filespec::get_extension($url)); + + // Check if this is actually an image + if ($file_stream = @fopen($url, 'r')) + { + // Timeout after 1 second + stream_set_timeout($file_stream, 1); + // read some data to ensure headers are present + fread($file_stream, 1024); + $meta = stream_get_meta_data($file_stream); + + if (isset($meta['wrapper_data']['headers']) && is_array($meta['wrapper_data']['headers'])) + { + $headers = $meta['wrapper_data']['headers']; + } + else if (isset($meta['wrapper_data']) && is_array($meta['wrapper_data'])) + { + $headers = $meta['wrapper_data']; + } + else + { + $headers = array(); + } + + foreach ($headers as $header) + { + $header = preg_split('/ /', $header, 2); + if (strtr(strtolower(trim($header[0], ':')), '_', '-') === 'content-type') + { + if (strpos($header[1], 'image/') !== 0) + { + $error[] = 'AVATAR_URL_INVALID'; + fclose($file_stream); + return false; + } + else + { + fclose($file_stream); + break; + } + } + } + } + else + { + $error[] = 'AVATAR_URL_INVALID'; + return false; + } + + if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]]))) + { + if (!isset($types[$image_data[2]])) + { + $error[] = 'UNABLE_GET_IMAGE_SIZE'; + } + else + { + $error[] = array('IMAGE_FILETYPE_MISMATCH', $types[$image_data[2]][0], $extension); + } + + return false; + } + + if ($this->config['avatar_max_width'] || $this->config['avatar_max_height']) + { + if ($width > $this->config['avatar_max_width'] || $height > $this->config['avatar_max_height']) + { + $error[] = array('AVATAR_WRONG_SIZE', $this->config['avatar_min_width'], $this->config['avatar_min_height'], $this->config['avatar_max_width'], $this->config['avatar_max_height'], $width, $height); + return false; + } + } + + if ($this->config['avatar_min_width'] || $this->config['avatar_min_height']) + { + if ($width < $this->config['avatar_min_width'] || $height < $this->config['avatar_min_height']) + { + $error[] = array('AVATAR_WRONG_SIZE', $this->config['avatar_min_width'], $this->config['avatar_min_height'], $this->config['avatar_max_width'], $this->config['avatar_max_height'], $width, $height); + return false; + } + } + + return array( + 'avatar' => $url, + 'avatar_width' => $width, + 'avatar_height' => $height, + ); + } + + /** + * {@inheritdoc} + */ + public function get_template_name() + { + return 'ucp_avatar_options_remote.html'; + } +} diff --git a/phpBB/phpbb/avatar/driver/upload.php b/phpBB/phpbb/avatar/driver/upload.php new file mode 100644 index 0000000000..0dae5607f6 --- /dev/null +++ b/phpBB/phpbb/avatar/driver/upload.php @@ -0,0 +1,307 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar\driver; + +/** +* Handles avatars uploaded to the board +*/ +class upload extends \phpbb\avatar\driver\driver +{ + /** + * @var \phpbb\mimetype\guesser + */ + protected $mimetype_guesser; + + /** + * @var \phpbb\event\dispatcher_interface + */ + protected $dispatcher; + + /** + * Construct a driver object + * + * @param \phpbb\config\config $config phpBB configuration + * @param string $phpbb_root_path Path to the phpBB root + * @param string $php_ext PHP file extension + * @param \phpbb_path_helper $path_helper phpBB path helper + * @param \phpbb\mimetype\guesser $mimetype_guesser Mimetype guesser + * @param \phpbb\event\dispatcher_interface $dispatcher phpBB Event dispatcher object + * @param \phpbb\cache\driver\driver_interface $cache Cache driver + */ + public function __construct(\phpbb\config\config $config, $phpbb_root_path, $php_ext, \phpbb\path_helper $path_helper, \phpbb\mimetype\guesser $mimetype_guesser, \phpbb\event\dispatcher_interface $dispatcher, \phpbb\cache\driver\driver_interface $cache = null) + { + $this->config = $config; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->path_helper = $path_helper; + $this->mimetype_guesser = $mimetype_guesser; + $this->dispatcher = $dispatcher; + $this->cache = $cache; + } + + /** + * {@inheritdoc} + */ + public function get_data($row) + { + $root_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? generate_board_url() . '/' : $this->path_helper->get_web_root_path(); + + return array( + 'src' => $root_path . 'download/file.' . $this->php_ext . '?avatar=' . $row['avatar'], + 'width' => $row['avatar_width'], + 'height' => $row['avatar_height'], + ); + } + + /** + * {@inheritdoc} + */ + public function prepare_form($request, $template, $user, $row, &$error) + { + if (!$this->can_upload()) + { + return false; + } + + $template->assign_vars(array( + 'S_UPLOAD_AVATAR_URL' => ($this->config['allow_avatar_remote_upload']) ? true : false, + 'AVATAR_UPLOAD_SIZE' => $this->config['avatar_filesize'], + )); + + return true; + } + + /** + * {@inheritdoc} + */ + public function process_form($request, $template, $user, $row, &$error) + { + if (!$this->can_upload()) + { + return false; + } + + if (!class_exists('fileupload')) + { + include($this->phpbb_root_path . 'includes/functions_upload.' . $this->php_ext); + } + + $upload = new \fileupload('AVATAR_', $this->allowed_extensions, $this->config['avatar_filesize'], $this->config['avatar_min_width'], $this->config['avatar_min_height'], $this->config['avatar_max_width'], $this->config['avatar_max_height'], (isset($this->config['mime_triggers']) ? explode('|', $this->config['mime_triggers']) : false)); + + $url = $request->variable('avatar_upload_url', ''); + $upload_file = $request->file('avatar_upload_file'); + + if (!empty($upload_file['name'])) + { + $file = $upload->form_upload('avatar_upload_file', $this->mimetype_guesser); + } + else if (!empty($this->config['allow_avatar_remote_upload']) && !empty($url)) + { + if (!preg_match('#^(http|https|ftp)://#i', $url)) + { + $url = 'http://' . $url; + } + + if (!function_exists('validate_data')) + { + require($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + + $validate_array = validate_data( + array( + 'url' => $url, + ), + array( + 'url' => array('string', true, 5, 255), + ) + ); + + $error = array_merge($error, $validate_array); + + if (!empty($error)) + { + return false; + } + + // Do not allow specifying the port (see RFC 3986) or IP addresses + // remote_upload() will do its own check for allowed filetypes + if (preg_match('@^(http|https|ftp)://[^/:?#]+:[0-9]+[/:?#]@i', $url) || + preg_match('#^(http|https|ftp)://(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])#i', $url) || + preg_match('#^(http|https|ftp)://(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){0,5}(?:[\dA-F]{1,4}(?::[\dA-F]{1,4})?|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:)|(?:::))#i', $url)) + { + $error[] = 'AVATAR_URL_INVALID'; + return false; + } + + $file = $upload->remote_upload($url, $this->mimetype_guesser); + } + else + { + return false; + } + + $prefix = $this->config['avatar_salt'] . '_'; + $file->clean_filename('avatar', $prefix, $row['id']); + + // If there was an error during upload, then abort operation + if (sizeof($file->error)) + { + $file->remove(); + $error = $file->error; + return false; + } + + // Calculate new destination + $destination = $this->config['avatar_path']; + + // Adjust destination path (no trailing slash) + if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\') + { + $destination = substr($destination, 0, -1); + } + + $destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination); + if ($destination && ($destination[0] == '/' || $destination[0] == "\\")) + { + $destination = ''; + } + + $filedata = array( + 'filename' => $file->get('filename'), + 'filesize' => $file->get('filesize'), + 'mimetype' => $file->get('mimetype'), + 'extension' => $file->get('extension'), + 'physical_filename' => $file->get('realname'), + 'real_filename' => $file->get('uploadname'), + ); + + /** + * Before moving new file in place (and eventually overwriting the existing avatar with the newly uploaded avatar) + * + * @event core.avatar_driver_upload_move_file_before + * @var array filedata Array containing uploaded file data + * @var string destination Destination directory where the file is going to be moved + * @var string prefix Prefix for the avatar filename + * @var array row Array with avatar row data + * @var array error Array of errors, if filled in by this event file will not be moved + * @since 3.1.6-RC1 + * @changed 3.1.9-RC1 Added filedata + */ + $vars = array( + 'filedata', + 'destination', + 'prefix', + 'row', + 'error', + ); + extract($this->dispatcher->trigger_event('core.avatar_driver_upload_move_file_before', compact($vars))); + + unset($filedata); + + if (!sizeof($error)) + { + // Move file and overwrite any existing image + $file->move_file($destination, true); + } + + // If there was an error during move, then clean up leftovers + $error = array_merge($error, $file->error); + if (sizeof($error)) + { + $file->remove(); + return false; + } + + // Delete current avatar if not overwritten + $ext = substr(strrchr($row['avatar'], '.'), 1); + if ($ext && $ext !== $file->get('extension')) + { + $this->delete($row); + } + + return array( + 'avatar' => $row['id'] . '_' . time() . '.' . $file->get('extension'), + 'avatar_width' => $file->get('width'), + 'avatar_height' => $file->get('height'), + ); + } + + /** + * {@inheritdoc} + */ + public function prepare_form_acp($user) + { + return array( + 'allow_avatar_remote_upload'=> array('lang' => 'ALLOW_REMOTE_UPLOAD', 'validate' => 'bool', 'type' => 'radio:yes_no', 'explain' => true), + 'avatar_filesize' => array('lang' => 'MAX_FILESIZE', 'validate' => 'int:0', 'type' => 'number:0', 'explain' => true, 'append' => ' ' . $user->lang['BYTES']), + 'avatar_path' => array('lang' => 'AVATAR_STORAGE_PATH', 'validate' => 'rpath', 'type' => 'text:20:255', 'explain' => true), + ); + } + + /** + * {@inheritdoc} + */ + public function delete($row) + { + + $error = array(); + $destination = $this->config['avatar_path']; + $prefix = $this->config['avatar_salt'] . '_'; + $ext = substr(strrchr($row['avatar'], '.'), 1); + $filename = $this->phpbb_root_path . $destination . '/' . $prefix . $row['id'] . '.' . $ext; + + /** + * Before deleting an existing avatar + * + * @event core.avatar_driver_upload_delete_before + * @var string destination Destination directory where the file is going to be deleted + * @var string prefix Prefix for the avatar filename + * @var array row Array with avatar row data + * @var array error Array of errors, if filled in by this event file will not be deleted + * @since 3.1.6-RC1 + */ + $vars = array( + 'destination', + 'prefix', + 'row', + 'error', + ); + extract($this->dispatcher->trigger_event('core.avatar_driver_upload_delete_before', compact($vars))); + + if (!sizeof($error) && file_exists($filename)) + { + @unlink($filename); + } + + return true; + } + + /** + * {@inheritdoc} + */ + public function get_template_name() + { + return 'ucp_avatar_options_upload.html'; + } + + /** + * Check if user is able to upload an avatar + * + * @return bool True if user can upload, false if not + */ + protected function can_upload() + { + return (file_exists($this->phpbb_root_path . $this->config['avatar_path']) && phpbb_is_writable($this->phpbb_root_path . $this->config['avatar_path']) && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')); + } +} diff --git a/phpBB/phpbb/avatar/manager.php b/phpBB/phpbb/avatar/manager.php new file mode 100644 index 0000000000..26eb17c265 --- /dev/null +++ b/phpBB/phpbb/avatar/manager.php @@ -0,0 +1,354 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\avatar; + +class manager +{ + /** + * phpBB configuration + * @var \phpbb\config\config + */ + protected $config; + + /** + * Array that contains a list of enabled drivers + * @var array + */ + static protected $enabled_drivers = false; + + /** + * Array that contains all available avatar drivers which are passed via the + * service container + * @var array + */ + protected $avatar_drivers; + + /** + * Default avatar data row + * @var array + */ + static protected $default_row = array( + 'avatar' => '', + 'avatar_type' => '', + 'avatar_width' => 0, + 'avatar_height' => 0, + ); + + /** + * Construct an avatar manager object + * + * @param \phpbb\config\config $config phpBB configuration + * @param array $avatar_drivers Avatar drivers passed via the service container + */ + public function __construct(\phpbb\config\config $config, $avatar_drivers) + { + $this->config = $config; + $this->register_avatar_drivers($avatar_drivers); + } + + /** + * Register avatar drivers + * + * @param array $avatar_drivers Service collection of avatar drivers + */ + protected function register_avatar_drivers($avatar_drivers) + { + if (!empty($avatar_drivers)) + { + foreach ($avatar_drivers as $driver) + { + $this->avatar_drivers[$driver->get_name()] = $driver; + } + } + } + + /** + * Get the driver object specified by the avatar type + * + * @param string $avatar_type Avatar type; by default an avatar's service container name + * @param bool $load_enabled Load only enabled avatars + * + * @return object Avatar driver object + */ + public function get_driver($avatar_type, $load_enabled = true) + { + if (self::$enabled_drivers === false) + { + $this->load_enabled_drivers(); + } + + $avatar_drivers = ($load_enabled) ? self::$enabled_drivers : $this->get_all_drivers(); + + // Legacy stuff... + switch ($avatar_type) + { + case AVATAR_GALLERY: + $avatar_type = 'avatar.driver.local'; + break; + case AVATAR_UPLOAD: + $avatar_type = 'avatar.driver.upload'; + break; + case AVATAR_REMOTE: + $avatar_type = 'avatar.driver.remote'; + break; + } + + if (!isset($avatar_drivers[$avatar_type])) + { + return null; + } + + /* + * There is no need to handle invalid avatar types as the following code + * will cause a ServiceNotFoundException if the type does not exist + */ + $driver = $this->avatar_drivers[$avatar_type]; + + return $driver; + } + + /** + * Load the list of enabled drivers + * This is executed once and fills self::$enabled_drivers + */ + protected function load_enabled_drivers() + { + if (!empty($this->avatar_drivers)) + { + self::$enabled_drivers = array(); + foreach ($this->avatar_drivers as $driver) + { + if ($this->is_enabled($driver)) + { + self::$enabled_drivers[$driver->get_name()] = $driver->get_name(); + } + } + asort(self::$enabled_drivers); + } + } + + /** + * Get a list of all avatar drivers + * + * As this function will only be called in the ACP avatar settings page, it + * doesn't make much sense to cache the list of all avatar drivers like the + * list of the enabled drivers. + * + * @return array Array containing a list of all avatar drivers + */ + public function get_all_drivers() + { + $drivers = array(); + + if (!empty($this->avatar_drivers)) + { + foreach ($this->avatar_drivers as $driver) + { + $drivers[$driver->get_name()] = $driver->get_name(); + } + asort($drivers); + } + + return $drivers; + } + + /** + * Get a list of enabled avatar drivers + * + * @return array Array containing a list of the enabled avatar drivers + */ + public function get_enabled_drivers() + { + if (self::$enabled_drivers === false) + { + $this->load_enabled_drivers(); + } + + return self::$enabled_drivers; + } + + /** + * Strip out user_, group_, or other prefixes from array keys + * + * @param array $row User data or group data + * @param string $prefix Prefix of data keys (e.g. user), should not include the trailing underscore + * + * @return array User or group data with keys that have been + * stripped from the preceding "user_" or "group_" + * Also the group id is prefixed with g, when the prefix group is removed. + */ + static public function clean_row($row, $prefix = '') + { + // Upon creation of a user/group $row might be empty + if (empty($row)) + { + return self::$default_row; + } + + $output = array(); + foreach ($row as $key => $value) + { + $key = preg_replace("#^(?:{$prefix}_)#", '', $key); + $output[$key] = $value; + } + + if ($prefix === 'group' && isset($output['id'])) + { + $output['id'] = 'g' . $output['id']; + } + + return $output; + } + + /** + * Clean driver names that are returned from template files + * Underscores are replaced with dots + * + * @param string $name Driver name + * + * @return string Cleaned driver name + */ + static public function clean_driver_name($name) + { + return str_replace(array('\\', '_'), '.', $name); + } + + /** + * Prepare driver names for use in template files + * Dots are replaced with underscores + * + * @param string $name Clean driver name + * + * @return string Prepared driver name + */ + static public function prepare_driver_name($name) + { + return str_replace('.', '_', $name); + } + + /** + * Check if avatar is enabled + * + * @param object $driver Avatar driver object + * + * @return bool True if avatar is enabled, false if it's disabled + */ + public function is_enabled($driver) + { + $config_name = $driver->get_config_name(); + + return $this->config["allow_avatar_{$config_name}"]; + } + + /** + * Get the settings array for enabling/disabling an avatar driver + * + * @param object $driver Avatar driver object + * + * @return array Array of configuration options as consumed by acp_board + */ + public function get_avatar_settings($driver) + { + $config_name = $driver->get_config_name(); + + return array( + 'allow_avatar_' . $config_name => array('lang' => 'ALLOW_' . strtoupper(str_replace('\\', '_', $config_name)), 'validate' => 'bool', 'type' => 'radio:yes_no', 'explain' => false), + ); + } + + /** + * Replace "error" strings with their real, localized form + * + * @param \phpbb\user phpBB User object + * @param array $error Array containing error strings + * Key values can either be a string with a language key or an array + * that will be passed to vsprintf() with the language key in the + * first array key. + * + * @return array Array containing the localized error strings + */ + public function localize_errors(\phpbb\user $user, $error) + { + foreach ($error as $key => $lang) + { + if (is_array($lang)) + { + $lang_key = array_shift($lang); + $error[$key] = vsprintf($user->lang($lang_key), $lang); + } + else + { + $error[$key] = $user->lang("$lang"); + } + } + + return $error; + } + + /** + * Handle deleting avatars + * + * @param \phpbb\db\driver\driver_interface $db phpBB dbal + * @param \phpbb\user $user phpBB user object + * @param array $avatar_data Cleaned user data containing the user's + * avatar data + * @param string $table Database table from which the avatar should be deleted + * @param string $prefix Prefix of user data columns in database + * @return null + */ + public function handle_avatar_delete(\phpbb\db\driver\driver_interface $db, \phpbb\user $user, $avatar_data, $table, $prefix) + { + if ($driver = $this->get_driver($avatar_data['avatar_type'])) + { + $driver->delete($avatar_data); + } + + $result = $this->prefix_avatar_columns($prefix, self::$default_row); + + $sql = 'UPDATE ' . $table . ' + SET ' . $db->sql_build_array('UPDATE', $result) . ' + WHERE ' . $prefix . 'id = ' . (int) $avatar_data['id']; + $db->sql_query($sql); + + // Make sure we also delete this avatar from the users + if ($prefix === 'group_') + { + $result = $this->prefix_avatar_columns('user_', self::$default_row); + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET ' . $db->sql_build_array('UPDATE', $result) . " + WHERE user_avatar = '" . $db->sql_escape($avatar_data['avatar']) . "'"; + $db->sql_query($sql); + } + } + + /** + * Prefix avatar columns + * + * @param string $prefix Column prefix + * @param array $data Column data + * + * @return array Column data with prefixed column names + */ + public function prefix_avatar_columns($prefix, $data) + { + foreach ($data as $key => $value) + { + $data[$prefix . $key] = $value; + unset($data[$key]); + } + + return $data; + } +} diff --git a/phpBB/phpbb/cache/driver/apc.php b/phpBB/phpbb/cache/driver/apc.php new file mode 100644 index 0000000000..521d5d41ea --- /dev/null +++ b/phpBB/phpbb/cache/driver/apc.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM for APC +*/ +class apc extends \phpbb\cache\driver\memory +{ + var $extension = 'apc'; + + /** + * {@inheritDoc} + */ + function purge() + { + apc_clear_cache('user'); + + parent::purge(); + } + + /** + * Fetch an item from the cache + * + * @access protected + * @param string $var Cache key + * @return mixed Cached data + */ + function _read($var) + { + return apc_fetch($this->key_prefix . $var); + } + + /** + * Store data in the cache + * + * @access protected + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + function _write($var, $data, $ttl = 2592000) + { + return apc_store($this->key_prefix . $var, $data, $ttl); + } + + /** + * Remove an item from the cache + * + * @access protected + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + function _delete($var) + { + return apc_delete($this->key_prefix . $var); + } +} diff --git a/phpBB/phpbb/cache/driver/base.php b/phpBB/phpbb/cache/driver/base.php new file mode 100644 index 0000000000..53c50eeda3 --- /dev/null +++ b/phpBB/phpbb/cache/driver/base.php @@ -0,0 +1,236 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +abstract class base implements \phpbb\cache\driver\driver_interface +{ + var $vars = array(); + var $is_modified = false; + + var $sql_rowset = array(); + var $sql_row_pointer = array(); + var $cache_dir = ''; + + /** + * {@inheritDoc} + */ + function purge() + { + // Purge all phpbb cache files + try + { + $iterator = new \DirectoryIterator($this->cache_dir); + } + catch (\Exception $e) + { + return; + } + + foreach ($iterator as $fileInfo) + { + if ($fileInfo->isDot()) + { + continue; + } + $filename = $fileInfo->getFilename(); + if ($fileInfo->isDir()) + { + $this->remove_dir($fileInfo->getPathname()); + } + else if (strpos($filename, 'container_') === 0 || + strpos($filename, 'url_matcher') === 0 || + strpos($filename, 'sql_') === 0 || + strpos($filename, 'data_') === 0) + { + $this->remove_file($fileInfo->getPathname()); + } + } + + unset($this->vars); + unset($this->sql_rowset); + unset($this->sql_row_pointer); + + if (function_exists('opcache_reset')) + { + @opcache_reset(); + } + + $this->vars = array(); + $this->sql_rowset = array(); + $this->sql_row_pointer = array(); + + $this->is_modified = false; + } + + /** + * {@inheritDoc} + */ + function unload() + { + $this->save(); + unset($this->vars); + unset($this->sql_rowset); + unset($this->sql_row_pointer); + + $this->vars = array(); + $this->sql_rowset = array(); + $this->sql_row_pointer = array(); + } + + /** + * {@inheritDoc} + */ + function sql_load($query) + { + // Remove extra spaces and tabs + $query = preg_replace('/[\n\r\s\t]+/', ' ', $query); + + if (($rowset = $this->_read('sql_' . md5($query))) === false) + { + return false; + } + + $query_id = sizeof($this->sql_rowset); + $this->sql_rowset[$query_id] = $rowset; + $this->sql_row_pointer[$query_id] = 0; + + return $query_id; + } + + /** + * {@inheritDoc} + */ + function sql_exists($query_id) + { + return isset($this->sql_rowset[$query_id]); + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id) + { + if ($this->sql_row_pointer[$query_id] < sizeof($this->sql_rowset[$query_id])) + { + return $this->sql_rowset[$query_id][$this->sql_row_pointer[$query_id]++]; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchfield($query_id, $field) + { + if ($this->sql_row_pointer[$query_id] < sizeof($this->sql_rowset[$query_id])) + { + return (isset($this->sql_rowset[$query_id][$this->sql_row_pointer[$query_id]][$field])) ? $this->sql_rowset[$query_id][$this->sql_row_pointer[$query_id]++][$field] : false; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, $query_id) + { + if ($rownum >= sizeof($this->sql_rowset[$query_id])) + { + return false; + } + + $this->sql_row_pointer[$query_id] = $rownum; + return true; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id) + { + if (!isset($this->sql_rowset[$query_id])) + { + return false; + } + + unset($this->sql_rowset[$query_id]); + unset($this->sql_row_pointer[$query_id]); + + return true; + } + + /** + * Removes/unlinks file + * + * @param string $filename Filename to remove + * @param bool $check Check file permissions + * @return bool True if the file was successfully removed, otherwise false + */ + function remove_file($filename, $check = false) + { + if (!function_exists('phpbb_is_writable')) + { + global $phpbb_root_path, $phpEx; + include($phpbb_root_path . 'includes/functions.' . $phpEx); + } + + if ($check && !phpbb_is_writable($this->cache_dir)) + { + // E_USER_ERROR - not using language entry - intended. + trigger_error('Unable to remove files within ' . $this->cache_dir . '. Please check directory permissions.', E_USER_ERROR); + } + + return @unlink($filename); + } + + /** + * Remove directory + * + * @param string $dir Directory to remove + * + * @return null + */ + protected function remove_dir($dir) + { + try + { + $iterator = new \DirectoryIterator($dir); + } + catch (\Exception $e) + { + return; + } + + foreach ($iterator as $fileInfo) + { + if ($fileInfo->isDot()) + { + continue; + } + + if ($fileInfo->isDir()) + { + $this->remove_dir($fileInfo->getPathname()); + } + else + { + $this->remove_file($fileInfo->getPathname()); + } + } + + @rmdir($dir); + } +} diff --git a/phpBB/phpbb/cache/driver/driver_interface.php b/phpBB/phpbb/cache/driver/driver_interface.php new file mode 100644 index 0000000000..9ac9ca0c59 --- /dev/null +++ b/phpBB/phpbb/cache/driver/driver_interface.php @@ -0,0 +1,167 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* An interface that all cache drivers must implement +*/ +interface driver_interface +{ + /** + * Load global cache + * + * @return mixed False if an error was encountered, otherwise the data type of the cached data + */ + public function load(); + + /** + * Unload cache object + * + * @return null + */ + public function unload(); + + /** + * Save modified objects + * + * @return null + */ + public function save(); + + /** + * Tidy cache + * + * @return null + */ + public function tidy(); + + /** + * Get saved cache object + * + * @param string $var_name Cache key + * @return mixed False if an error was encountered, otherwise the saved cached object + */ + public function get($var_name); + + /** + * Put data into cache + * + * @param string $var_name Cache key + * @param mixed $var Cached data to store + * @param int $ttl Time-to-live of cached data + * @return null + */ + public function put($var_name, $var, $ttl = 0); + + /** + * Purge cache data + * + * @return null + */ + public function purge(); + + /** + * Destroy cache data + * + * @param string $var_name Cache key + * @param string $table Table name + * @return null + */ + public function destroy($var_name, $table = ''); + + /** + * Check if a given cache entry exists + * + * @param string $var_name Cache key + * + * @return bool True if cache file exists and has not expired. + * False otherwise. + */ + public function _exists($var_name); + + /** + * Load result of an SQL query from cache. + * + * @param string $query SQL query + * + * @return int|bool Query ID (integer) if cache contains a rowset + * for the specified query. + * False otherwise. + */ + public function sql_load($query); + + /** + * Save result of an SQL query in cache. + * + * In persistent cache stores, this function stores the query + * result to persistent storage. In other words, there is no need + * to call save() afterwards. + * + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param string $query SQL query, should be used for generating storage key + * @param mixed $query_result The result from \dbal::sql_query, to be passed to + * \dbal::sql_fetchrow to get all rows and store them + * in cache. + * @param int $ttl Time to live, after this timeout the query should + * expire from the cache. + * @return int|mixed If storing in cache succeeded, an integer $query_id + * representing the query should be returned. Otherwise + * the original $query_result should be returned. + */ + public function sql_save(\phpbb\db\driver\driver_interface $db, $query, $query_result, $ttl); + + /** + * Check if result for a given SQL query exists in cache. + * + * @param int $query_id + * @return bool + */ + public function sql_exists($query_id); + + /** + * Fetch row from cache (database) + * + * @param int $query_id + * @return array|bool The query result if found in the cache, otherwise + * false. + */ + public function sql_fetchrow($query_id); + + /** + * Fetch a field from the current row of a cached database result (database) + * + * @param int $query_id + * @param string $field The name of the column. + * @return string|bool The field of the query result if found in the cache, + * otherwise false. + */ + public function sql_fetchfield($query_id, $field); + + /** + * Seek a specific row in an a cached database result (database) + * + * @param int $rownum Row to seek to. + * @param int $query_id + * @return bool + */ + public function sql_rowseek($rownum, $query_id); + + /** + * Free memory used for a cached database result (database) + * + * @param int $query_id + * @return bool + */ + public function sql_freeresult($query_id); +} diff --git a/phpBB/phpbb/cache/driver/eaccelerator.php b/phpBB/phpbb/cache/driver/eaccelerator.php new file mode 100644 index 0000000000..1697758acc --- /dev/null +++ b/phpBB/phpbb/cache/driver/eaccelerator.php @@ -0,0 +1,105 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM for eAccelerator +* @todo Missing locks from destroy() talk with David +*/ +class eaccelerator extends \phpbb\cache\driver\memory +{ + var $extension = 'eaccelerator'; + var $function = 'eaccelerator_get'; + + var $serialize_header = '#phpbb-serialized#'; + + /** + * {@inheritDoc} + */ + function purge() + { + foreach (eaccelerator_list_keys() as $var) + { + // @todo Check why the substr() + // @todo Only unset vars matching $this->key_prefix + eaccelerator_rm(substr($var['name'], 1)); + } + + parent::purge(); + } + + /** + * {@inheritDoc} + */ + function tidy() + { + eaccelerator_gc(); + + set_config('cache_last_gc', time(), true); + } + + /** + * Fetch an item from the cache + * + * @access protected + * @param string $var Cache key + * @return mixed Cached data + */ + function _read($var) + { + $result = eaccelerator_get($this->key_prefix . $var); + + if ($result === null) + { + return false; + } + + // Handle serialized objects + if (is_string($result) && strpos($result, $this->serialize_header . 'O:') === 0) + { + $result = unserialize(substr($result, strlen($this->serialize_header))); + } + + return $result; + } + + /** + * Store data in the cache + * + * @access protected + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + function _write($var, $data, $ttl = 2592000) + { + // Serialize objects and make them easy to detect + $data = (is_object($data)) ? $this->serialize_header . serialize($data) : $data; + + return eaccelerator_put($this->key_prefix . $var, $data, $ttl); + } + + /** + * Remove an item from the cache + * + * @access protected + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + function _delete($var) + { + return eaccelerator_rm($this->key_prefix . $var); + } +} diff --git a/phpBB/phpbb/cache/driver/file.php b/phpBB/phpbb/cache/driver/file.php new file mode 100644 index 0000000000..1e9ee960dc --- /dev/null +++ b/phpBB/phpbb/cache/driver/file.php @@ -0,0 +1,606 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM File Based Caching +*/ +class file extends \phpbb\cache\driver\base +{ + var $var_expires = array(); + + /** + * Set cache path + * + * @param string $cache_dir Define the path to the cache directory (default: $phpbb_root_path . 'cache/') + */ + function __construct($cache_dir = null) + { + global $phpbb_root_path; + $this->cache_dir = !is_null($cache_dir) ? $cache_dir : $phpbb_root_path . 'cache/'; + } + + /** + * {@inheritDoc} + */ + function load() + { + return $this->_read('data_global'); + } + + /** + * {@inheritDoc} + */ + function unload() + { + parent::unload(); + unset($this->var_expires); + $this->var_expires = array(); + } + + /** + * {@inheritDoc} + */ + function save() + { + if (!$this->is_modified) + { + return; + } + + global $phpEx; + + if (!$this->_write('data_global')) + { + if (!function_exists('phpbb_is_writable')) + { + global $phpbb_root_path; + include($phpbb_root_path . 'includes/functions.' . $phpEx); + } + + // Now, this occurred how often? ... phew, just tell the user then... + if (!phpbb_is_writable($this->cache_dir)) + { + // We need to use die() here, because else we may encounter an infinite loop (the message handler calls $cache->unload()) + die('Fatal: ' . $this->cache_dir . ' is NOT writable.'); + exit; + } + + die('Fatal: Not able to open ' . $this->cache_dir . 'data_global.' . $phpEx); + exit; + } + + $this->is_modified = false; + } + + /** + * {@inheritDoc} + */ + function tidy() + { + global $phpEx; + + $dir = @opendir($this->cache_dir); + + if (!$dir) + { + return; + } + + $time = time(); + + while (($entry = readdir($dir)) !== false) + { + if (!preg_match('/^(sql_|data_(?!global))/', $entry)) + { + continue; + } + + if (!($handle = @fopen($this->cache_dir . $entry, 'rb'))) + { + continue; + } + + // Skip the PHP header + fgets($handle); + + // Skip expiration + $expires = (int) fgets($handle); + + fclose($handle); + + if ($time >= $expires) + { + $this->remove_file($this->cache_dir . $entry); + } + } + closedir($dir); + + if (file_exists($this->cache_dir . 'data_global.' . $phpEx)) + { + if (!sizeof($this->vars)) + { + $this->load(); + } + + foreach ($this->var_expires as $var_name => $expires) + { + if ($time >= $expires) + { + $this->destroy($var_name); + } + } + } + + set_config('cache_last_gc', time(), true); + } + + /** + * {@inheritDoc} + */ + function get($var_name) + { + if ($var_name[0] == '_') + { + if (!$this->_exists($var_name)) + { + return false; + } + + return $this->_read('data' . $var_name); + } + else + { + return ($this->_exists($var_name)) ? $this->vars[$var_name] : false; + } + } + + /** + * {@inheritDoc} + */ + function put($var_name, $var, $ttl = 31536000) + { + if ($var_name[0] == '_') + { + $this->_write('data' . $var_name, $var, time() + $ttl); + } + else + { + $this->vars[$var_name] = $var; + $this->var_expires[$var_name] = time() + $ttl; + $this->is_modified = true; + } + } + + /** + * {@inheritDoc} + */ + function purge() + { + parent::purge(); + $this->var_expires = array(); + } + + /** + * {@inheritDoc} + */ + function destroy($var_name, $table = '') + { + global $phpEx; + + if ($var_name == 'sql' && !empty($table)) + { + if (!is_array($table)) + { + $table = array($table); + } + + $dir = @opendir($this->cache_dir); + + if (!$dir) + { + return; + } + + while (($entry = readdir($dir)) !== false) + { + if (strpos($entry, 'sql_') !== 0) + { + continue; + } + + if (!($handle = @fopen($this->cache_dir . $entry, 'rb'))) + { + continue; + } + + // Skip the PHP header + fgets($handle); + + // Skip expiration + fgets($handle); + + // Grab the query, remove the LF + $query = substr(fgets($handle), 0, -1); + + fclose($handle); + + foreach ($table as $check_table) + { + // Better catch partial table names than no table names. ;) + if (strpos($query, $check_table) !== false) + { + $this->remove_file($this->cache_dir . $entry); + break; + } + } + } + closedir($dir); + + return; + } + + if (!$this->_exists($var_name)) + { + return; + } + + if ($var_name[0] == '_') + { + $this->remove_file($this->cache_dir . 'data' . $var_name . ".$phpEx", true); + } + else if (isset($this->vars[$var_name])) + { + $this->is_modified = true; + unset($this->vars[$var_name]); + unset($this->var_expires[$var_name]); + + // We save here to let the following cache hits succeed + $this->save(); + } + } + + /** + * {@inheritDoc} + */ + function _exists($var_name) + { + if ($var_name[0] == '_') + { + global $phpEx; + $var_name = $this->clean_varname($var_name); + return file_exists($this->cache_dir . 'data' . $var_name . ".$phpEx"); + } + else + { + if (!sizeof($this->vars)) + { + $this->load(); + } + + if (!isset($this->var_expires[$var_name])) + { + return false; + } + + return (time() > $this->var_expires[$var_name]) ? false : isset($this->vars[$var_name]); + } + } + + /** + * {@inheritDoc} + */ + function sql_save(\phpbb\db\driver\driver_interface $db, $query, $query_result, $ttl) + { + // Remove extra spaces and tabs + $query = preg_replace('/[\n\r\s\t]+/', ' ', $query); + + $query_id = sizeof($this->sql_rowset); + $this->sql_rowset[$query_id] = array(); + $this->sql_row_pointer[$query_id] = 0; + + while ($row = $db->sql_fetchrow($query_result)) + { + $this->sql_rowset[$query_id][] = $row; + } + $db->sql_freeresult($query_result); + + if ($this->_write('sql_' . md5($query), $this->sql_rowset[$query_id], $ttl + time(), $query)) + { + return $query_id; + } + + return $query_result; + } + + /** + * Read cached data from a specified file + * + * @access private + * @param string $filename Filename to write + * @return mixed False if an error was encountered, otherwise the data type of the cached data + */ + function _read($filename) + { + global $phpEx; + + $filename = $this->clean_varname($filename); + $file = "{$this->cache_dir}$filename.$phpEx"; + + $type = substr($filename, 0, strpos($filename, '_')); + + if (!file_exists($file)) + { + return false; + } + + if (!($handle = @fopen($file, 'rb'))) + { + return false; + } + + // Skip the PHP header + fgets($handle); + + if ($filename == 'data_global') + { + $this->vars = $this->var_expires = array(); + + $time = time(); + + while (($expires = (int) fgets($handle)) && !feof($handle)) + { + // Number of bytes of data + $bytes = substr(fgets($handle), 0, -1); + + if (!is_numeric($bytes) || ($bytes = (int) $bytes) === 0) + { + // We cannot process the file without a valid number of bytes + // so we discard it + fclose($handle); + + $this->vars = $this->var_expires = array(); + $this->is_modified = false; + + $this->remove_file($file); + + return false; + } + + if ($time >= $expires) + { + fseek($handle, $bytes, SEEK_CUR); + + continue; + } + + $var_name = substr(fgets($handle), 0, -1); + + // Read the length of bytes that consists of data. + $data = fread($handle, $bytes - strlen($var_name)); + $data = @unserialize($data); + + // Don't use the data if it was invalid + if ($data !== false) + { + $this->vars[$var_name] = $data; + $this->var_expires[$var_name] = $expires; + } + + // Absorb the LF + fgets($handle); + } + + fclose($handle); + + $this->is_modified = false; + + return true; + } + else + { + $data = false; + $line = 0; + + while (($buffer = fgets($handle)) && !feof($handle)) + { + $buffer = substr($buffer, 0, -1); // Remove the LF + + // $buffer is only used to read integers + // if it is non numeric we have an invalid + // cache file, which we will now remove. + if (!is_numeric($buffer)) + { + break; + } + + if ($line == 0) + { + $expires = (int) $buffer; + + if (time() >= $expires) + { + break; + } + + if ($type == 'sql') + { + // Skip the query + fgets($handle); + } + } + else if ($line == 1) + { + $bytes = (int) $buffer; + + // Never should have 0 bytes + if (!$bytes) + { + break; + } + + // Grab the serialized data + $data = fread($handle, $bytes); + + // Read 1 byte, to trigger EOF + fread($handle, 1); + + if (!feof($handle)) + { + // Somebody tampered with our data + $data = false; + } + break; + } + else + { + // Something went wrong + break; + } + $line++; + } + fclose($handle); + + // unserialize if we got some data + $data = ($data !== false) ? @unserialize($data) : $data; + + if ($data === false) + { + $this->remove_file($file); + return false; + } + + return $data; + } + } + + /** + * Write cache data to a specified file + * + * 'data_global' is a special case and the generated format is different for this file: + * <code> + * <?php exit; ?> + * (expiration) + * (length of var and serialised data) + * (var) + * (serialised data) + * ... (repeat) + * </code> + * + * The other files have a similar format: + * <code> + * <?php exit; ?> + * (expiration) + * (query) [SQL files only] + * (length of serialised data) + * (serialised data) + * </code> + * + * @access private + * @param string $filename Filename to write + * @param mixed $data Data to store + * @param int $expires Timestamp when the data expires + * @param string $query Query when caching SQL queries + * @return bool True if the file was successfully created, otherwise false + */ + function _write($filename, $data = null, $expires = 0, $query = '') + { + global $phpEx; + + $filename = $this->clean_varname($filename); + $file = "{$this->cache_dir}$filename.$phpEx"; + + $lock = new \phpbb\lock\flock($file); + $lock->acquire(); + + if ($handle = @fopen($file, 'wb')) + { + // File header + fwrite($handle, '<' . '?php exit; ?' . '>'); + + if ($filename == 'data_global') + { + // Global data is a different format + foreach ($this->vars as $var => $data) + { + if (strpos($var, "\r") !== false || strpos($var, "\n") !== false) + { + // CR/LF would cause fgets() to read the cache file incorrectly + // do not cache test entries, they probably won't be read back + // the cache keys should really be alphanumeric with a few symbols. + continue; + } + $data = serialize($data); + + // Write out the expiration time + fwrite($handle, "\n" . $this->var_expires[$var] . "\n"); + + // Length of the remaining data for this var (ignoring two LF's) + fwrite($handle, strlen($data . $var) . "\n"); + fwrite($handle, $var . "\n"); + fwrite($handle, $data); + } + } + else + { + fwrite($handle, "\n" . $expires . "\n"); + + if (strpos($filename, 'sql_') === 0) + { + fwrite($handle, $query . "\n"); + } + $data = serialize($data); + + fwrite($handle, strlen($data) . "\n"); + fwrite($handle, $data); + } + + fclose($handle); + + if (function_exists('opcache_invalidate')) + { + @opcache_invalidate($file); + } + + if (!function_exists('phpbb_chmod')) + { + global $phpbb_root_path; + include($phpbb_root_path . 'includes/functions.' . $phpEx); + } + + phpbb_chmod($file, CHMOD_READ | CHMOD_WRITE); + + $return_value = true; + } + else + { + $return_value = false; + } + + $lock->release(); + + return $return_value; + } + + /** + * Replace slashes in the file name + * + * @param string $varname name of a cache variable + * @return string $varname name that is safe to use as a filename + */ + protected function clean_varname($varname) + { + return str_replace(array('/', '\\'), '-', $varname); + } +} diff --git a/phpBB/phpbb/cache/driver/memcache.php b/phpBB/phpbb/cache/driver/memcache.php new file mode 100644 index 0000000000..57f138f574 --- /dev/null +++ b/phpBB/phpbb/cache/driver/memcache.php @@ -0,0 +1,122 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +if (!defined('PHPBB_ACM_MEMCACHE_PORT')) +{ + define('PHPBB_ACM_MEMCACHE_PORT', 11211); +} + +if (!defined('PHPBB_ACM_MEMCACHE_COMPRESS')) +{ + define('PHPBB_ACM_MEMCACHE_COMPRESS', false); +} + +if (!defined('PHPBB_ACM_MEMCACHE_HOST')) +{ + define('PHPBB_ACM_MEMCACHE_HOST', 'localhost'); +} + +if (!defined('PHPBB_ACM_MEMCACHE')) +{ + //can define multiple servers with host1/port1,host2/port2 format + define('PHPBB_ACM_MEMCACHE', PHPBB_ACM_MEMCACHE_HOST . '/' . PHPBB_ACM_MEMCACHE_PORT); +} + +/** +* ACM for Memcached +*/ +class memcache extends \phpbb\cache\driver\memory +{ + var $extension = 'memcache'; + + var $memcache; + var $flags = 0; + + function __construct() + { + // Call the parent constructor + parent::__construct(); + + $this->memcache = new \Memcache; + foreach (explode(',', PHPBB_ACM_MEMCACHE) as $u) + { + preg_match('#(.*)/(\d+)#', $u, $parts); + $this->memcache->addServer(trim($parts[1]), (int) trim($parts[2])); + } + $this->flags = (PHPBB_ACM_MEMCACHE_COMPRESS) ? MEMCACHE_COMPRESSED : 0; + } + + /** + * {@inheritDoc} + */ + function unload() + { + parent::unload(); + + $this->memcache->close(); + } + + /** + * {@inheritDoc} + */ + function purge() + { + $this->memcache->flush(); + + parent::purge(); + } + + /** + * Fetch an item from the cache + * + * @access protected + * @param string $var Cache key + * @return mixed Cached data + */ + function _read($var) + { + return $this->memcache->get($this->key_prefix . $var); + } + + /** + * Store data in the cache + * + * @access protected + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + function _write($var, $data, $ttl = 2592000) + { + if (!$this->memcache->replace($this->key_prefix . $var, $data, $this->flags, $ttl)) + { + return $this->memcache->set($this->key_prefix . $var, $data, $this->flags, $ttl); + } + return true; + } + + /** + * Remove an item from the cache + * + * @access protected + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + function _delete($var) + { + return $this->memcache->delete($this->key_prefix . $var); + } +} diff --git a/phpBB/phpbb/cache/driver/memcached.php b/phpBB/phpbb/cache/driver/memcached.php new file mode 100644 index 0000000000..a7da22d7e8 --- /dev/null +++ b/phpBB/phpbb/cache/driver/memcached.php @@ -0,0 +1,134 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +if (!defined('PHPBB_ACM_MEMCACHED_PORT')) +{ + define('PHPBB_ACM_MEMCACHED_PORT', 11211); +} + +if (!defined('PHPBB_ACM_MEMCACHED_COMPRESS')) +{ + define('PHPBB_ACM_MEMCACHED_COMPRESS', true); +} + +if (!defined('PHPBB_ACM_MEMCACHED_HOST')) +{ + define('PHPBB_ACM_MEMCACHED_HOST', 'localhost'); +} + +if (!defined('PHPBB_ACM_MEMCACHED')) +{ + //can define multiple servers with host1/port1,host2/port2 format + define('PHPBB_ACM_MEMCACHED', PHPBB_ACM_MEMCACHED_HOST . '/' . PHPBB_ACM_MEMCACHED_PORT); +} + +/** +* ACM for Memcached +*/ +class memcached extends \phpbb\cache\driver\memory +{ + /** @var string Extension to use */ + protected $extension = 'memcached'; + + /** @var \Memcached Memcached class */ + protected $memcached; + + /** @var int Flags */ + protected $flags = 0; + + /** + * Memcached constructor + */ + public function __construct() + { + // Call the parent constructor + parent::__construct(); + + $this->memcached = new \Memcached(); + $this->memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); + // Memcached defaults to using compression, disable if we don't want + // to use it + if (!PHPBB_ACM_MEMCACHED_COMPRESS) + { + $this->memcached->setOption(\Memcached::OPT_COMPRESSION, false); + } + + foreach (explode(',', PHPBB_ACM_MEMCACHE) as $u) + { + preg_match('#(.*)/(\d+)#', $u, $parts); + $this->memcache->addServer(trim($parts[1]), (int) trim($parts[2])); + } + } + + /** + * {@inheritDoc} + */ + public function unload() + { + parent::unload(); + + unset($this->memcached); + } + + /** + * {@inheritDoc} + */ + public function purge() + { + $this->memcached->flush(); + + parent::purge(); + } + + /** + * Fetch an item from the cache + * + * @param string $var Cache key + * + * @return mixed Cached data + */ + protected function _read($var) + { + return $this->memcached->get($this->key_prefix . $var); + } + + /** + * Store data in the cache + * + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + protected function _write($var, $data, $ttl = 2592000) + { + if (!$this->memcached->replace($this->key_prefix . $var, $data, $ttl)) + { + return $this->memcached->set($this->key_prefix . $var, $data, $ttl); + } + return true; + } + + /** + * Remove an item from the cache + * + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + protected function _delete($var) + { + return $this->memcached->delete($this->key_prefix . $var); + } +} diff --git a/phpBB/phpbb/cache/driver/memory.php b/phpBB/phpbb/cache/driver/memory.php new file mode 100644 index 0000000000..0b0e323e3d --- /dev/null +++ b/phpBB/phpbb/cache/driver/memory.php @@ -0,0 +1,281 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM Abstract Memory Class +*/ +abstract class memory extends \phpbb\cache\driver\base +{ + var $key_prefix; + + /** + * Set cache path + */ + function __construct() + { + global $phpbb_root_path, $dbname, $table_prefix; + + $this->cache_dir = $phpbb_root_path . 'cache/'; + $this->key_prefix = substr(md5($dbname . $table_prefix), 0, 8) . '_'; + + if (!isset($this->extension) || !extension_loaded($this->extension)) + { + global $acm_type; + + trigger_error("Could not find required extension [{$this->extension}] for the ACM module $acm_type.", E_USER_ERROR); + } + + if (isset($this->function) && !function_exists($this->function)) + { + global $acm_type; + + trigger_error("The required function [{$this->function}] is not available for the ACM module $acm_type.", E_USER_ERROR); + } + } + + /** + * {@inheritDoc} + */ + function load() + { + // grab the global cache + $this->vars = $this->_read('global'); + + if ($this->vars !== false) + { + return true; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function save() + { + if (!$this->is_modified) + { + return; + } + + $this->_write('global', $this->vars, 2592000); + + $this->is_modified = false; + } + + /** + * {@inheritDoc} + */ + function tidy() + { + // cache has auto GC, no need to have any code here :) + + set_config('cache_last_gc', time(), true); + } + + /** + * {@inheritDoc} + */ + function get($var_name) + { + if ($var_name[0] == '_') + { + if (!$this->_exists($var_name)) + { + return false; + } + + return $this->_read($var_name); + } + else + { + return ($this->_exists($var_name)) ? $this->vars[$var_name] : false; + } + } + + /** + * {@inheritDoc} + */ + function put($var_name, $var, $ttl = 2592000) + { + if ($var_name[0] == '_') + { + $this->_write($var_name, $var, $ttl); + } + else + { + $this->vars[$var_name] = $var; + $this->is_modified = true; + } + } + + /** + * {@inheritDoc} + */ + function destroy($var_name, $table = '') + { + if ($var_name == 'sql' && !empty($table)) + { + if (!is_array($table)) + { + $table = array($table); + } + + foreach ($table as $table_name) + { + // gives us the md5s that we want + $temp = $this->_read('sql_' . $table_name); + + if ($temp === false) + { + continue; + } + + // delete each query ref + foreach ($temp as $md5_id => $void) + { + $this->_delete('sql_' . $md5_id); + } + + // delete the table ref + $this->_delete('sql_' . $table_name); + } + + return; + } + + if (!$this->_exists($var_name)) + { + return; + } + + if ($var_name[0] == '_') + { + $this->_delete($var_name); + } + else if (isset($this->vars[$var_name])) + { + $this->is_modified = true; + unset($this->vars[$var_name]); + + // We save here to let the following cache hits succeed + $this->save(); + } + } + + /** + * {@inheritDoc} + */ + function _exists($var_name) + { + if ($var_name[0] == '_') + { + return $this->_isset($var_name); + } + else + { + if (!sizeof($this->vars)) + { + $this->load(); + } + + return isset($this->vars[$var_name]); + } + } + + /** + * {@inheritDoc} + */ + function sql_save(\phpbb\db\driver\driver_interface $db, $query, $query_result, $ttl) + { + // Remove extra spaces and tabs + $query = preg_replace('/[\n\r\s\t]+/', ' ', $query); + $hash = md5($query); + + // determine which tables this query belongs to + // Some queries use backticks, namely the get_database_size() query + // don't check for conformity, the SQL would error and not reach here. + if (!preg_match_all('/(?:FROM \\(?(`?\\w+`?(?: \\w+)?(?:, ?`?\\w+`?(?: \\w+)?)*)\\)?)|(?:JOIN (`?\\w+`?(?: \\w+)?))/', $query, $regs, PREG_SET_ORDER)) + { + // Bail out if the match fails. + return $query_result; + } + + $tables = array(); + foreach ($regs as $match) + { + if ($match[0][0] == 'F') + { + $tables = array_merge($tables, array_map('trim', explode(',', $match[1]))); + } + else + { + $tables[] = $match[2]; + } + } + + foreach ($tables as $table_name) + { + // Remove backticks + $table_name = ($table_name[0] == '`') ? substr($table_name, 1, -1) : $table_name; + + if (($pos = strpos($table_name, ' ')) !== false) + { + $table_name = substr($table_name, 0, $pos); + } + + $temp = $this->_read('sql_' . $table_name); + + if ($temp === false) + { + $temp = array(); + } + + $temp[$hash] = true; + + // This must never expire + $this->_write('sql_' . $table_name, $temp, 0); + } + + // store them in the right place + $query_id = sizeof($this->sql_rowset); + $this->sql_rowset[$query_id] = array(); + $this->sql_row_pointer[$query_id] = 0; + + while ($row = $db->sql_fetchrow($query_result)) + { + $this->sql_rowset[$query_id][] = $row; + } + $db->sql_freeresult($query_result); + + $this->_write('sql_' . $hash, $this->sql_rowset[$query_id], $ttl); + + return $query_id; + } + + /** + * Check if a cache var exists + * + * @access protected + * @param string $var Cache key + * @return bool True if it exists, otherwise false + */ + function _isset($var) + { + // Most caches don't need to check + return true; + } +} diff --git a/phpBB/phpbb/cache/driver/null.php b/phpBB/phpbb/cache/driver/null.php new file mode 100644 index 0000000000..a45cf97862 --- /dev/null +++ b/phpBB/phpbb/cache/driver/null.php @@ -0,0 +1,151 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM Null Caching +*/ +class null extends \phpbb\cache\driver\base +{ + /** + * Set cache path + */ + function __construct() + { + } + + /** + * {@inheritDoc} + */ + function load() + { + return true; + } + + /** + * {@inheritDoc} + */ + function unload() + { + } + + /** + * {@inheritDoc} + */ + function save() + { + } + + /** + * {@inheritDoc} + */ + function tidy() + { + // This cache always has a tidy room. + set_config('cache_last_gc', time(), true); + } + + /** + * {@inheritDoc} + */ + function get($var_name) + { + return false; + } + + /** + * {@inheritDoc} + */ + function put($var_name, $var, $ttl = 0) + { + } + + /** + * {@inheritDoc} + */ + function purge() + { + } + + /** + * {@inheritDoc} + */ + function destroy($var_name, $table = '') + { + } + + /** + * {@inheritDoc} + */ + function _exists($var_name) + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_load($query) + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_save(\phpbb\db\driver\driver_interface $db, $query, $query_result, $ttl) + { + return $query_result; + } + + /** + * {@inheritDoc} + */ + function sql_exists($query_id) + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id) + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchfield($query_id, $field) + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, $query_id) + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id) + { + return false; + } +} diff --git a/phpBB/phpbb/cache/driver/redis.php b/phpBB/phpbb/cache/driver/redis.php new file mode 100644 index 0000000000..eda774491c --- /dev/null +++ b/phpBB/phpbb/cache/driver/redis.php @@ -0,0 +1,158 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +if (!defined('PHPBB_ACM_REDIS_PORT')) +{ + define('PHPBB_ACM_REDIS_PORT', 6379); +} + +if (!defined('PHPBB_ACM_REDIS_HOST')) +{ + define('PHPBB_ACM_REDIS_HOST', 'localhost'); +} + +/** +* ACM for Redis +* +* Compatible with the php extension phpredis available +* at https://github.com/nicolasff/phpredis +* +*/ +class redis extends \phpbb\cache\driver\memory +{ + var $extension = 'redis'; + + var $redis; + + /** + * Creates a redis cache driver. + * + * The following global constants affect operation: + * + * PHPBB_ACM_REDIS_HOST + * PHPBB_ACM_REDIS_PORT + * PHPBB_ACM_REDIS_PASSWORD + * PHPBB_ACM_REDIS_DB + * + * There are no publicly documented constructor parameters. + */ + function __construct() + { + // Call the parent constructor + parent::__construct(); + + $this->redis = new \Redis(); + + $args = func_get_args(); + if (!empty($args)) + { + $ok = call_user_func_array(array($this->redis, 'connect'), $args); + } + else + { + $ok = $this->redis->connect(PHPBB_ACM_REDIS_HOST, PHPBB_ACM_REDIS_PORT); + } + + if (!$ok) + { + trigger_error('Could not connect to redis server'); + } + + if (defined('PHPBB_ACM_REDIS_PASSWORD')) + { + if (!$this->redis->auth(PHPBB_ACM_REDIS_PASSWORD)) + { + global $acm_type; + + trigger_error("Incorrect password for the ACM module $acm_type.", E_USER_ERROR); + } + } + + $this->redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP); + $this->redis->setOption(\Redis::OPT_PREFIX, $this->key_prefix); + + if (defined('PHPBB_ACM_REDIS_DB')) + { + if (!$this->redis->select(PHPBB_ACM_REDIS_DB)) + { + global $acm_type; + + trigger_error("Incorrect database for the ACM module $acm_type.", E_USER_ERROR); + } + } + } + + /** + * {@inheritDoc} + */ + function unload() + { + parent::unload(); + + $this->redis->close(); + } + + /** + * {@inheritDoc} + */ + function purge() + { + $this->redis->flushDB(); + + parent::purge(); + } + + /** + * Fetch an item from the cache + * + * @access protected + * @param string $var Cache key + * @return mixed Cached data + */ + function _read($var) + { + return $this->redis->get($var); + } + + /** + * Store data in the cache + * + * @access protected + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + function _write($var, $data, $ttl = 2592000) + { + return $this->redis->setex($var, $ttl, $data); + } + + /** + * Remove an item from the cache + * + * @access protected + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + function _delete($var) + { + if ($this->redis->delete($var) > 0) + { + return true; + } + return false; + } +} diff --git a/phpBB/phpbb/cache/driver/wincache.php b/phpBB/phpbb/cache/driver/wincache.php new file mode 100644 index 0000000000..632b534362 --- /dev/null +++ b/phpBB/phpbb/cache/driver/wincache.php @@ -0,0 +1,73 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM for WinCache +*/ +class wincache extends \phpbb\cache\driver\memory +{ + var $extension = 'wincache'; + + /** + * {@inheritDoc} + */ + function purge() + { + wincache_ucache_clear(); + + parent::purge(); + } + + /** + * Fetch an item from the cache + * + * @access protected + * @param string $var Cache key + * @return mixed Cached data + */ + function _read($var) + { + $success = false; + $result = wincache_ucache_get($this->key_prefix . $var, $success); + + return ($success) ? $result : false; + } + + /** + * Store data in the cache + * + * @access protected + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + function _write($var, $data, $ttl = 2592000) + { + return wincache_ucache_set($this->key_prefix . $var, $data, $ttl); + } + + /** + * Remove an item from the cache + * + * @access protected + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + function _delete($var) + { + return wincache_ucache_delete($this->key_prefix . $var); + } +} diff --git a/phpBB/phpbb/cache/driver/xcache.php b/phpBB/phpbb/cache/driver/xcache.php new file mode 100644 index 0000000000..0c845a6a8d --- /dev/null +++ b/phpBB/phpbb/cache/driver/xcache.php @@ -0,0 +1,107 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache\driver; + +/** +* ACM for XCache +* +* To use this module you need ini_get() enabled and the following INI settings configured as follows: +* - xcache.var_size > 0 +* - xcache.admin.enable_auth = off (or xcache.admin.user and xcache.admin.password set) +* +*/ +class xcache extends \phpbb\cache\driver\memory +{ + var $extension = 'XCache'; + + function __construct() + { + parent::__construct(); + + if (!function_exists('ini_get') || (int) ini_get('xcache.var_size') <= 0) + { + trigger_error('Increase xcache.var_size setting above 0 or enable ini_get() to use this ACM module.', E_USER_ERROR); + } + } + + /** + * {@inheritDoc} + */ + function purge() + { + // Run before for XCache, if admin functions are disabled it will terminate execution + parent::purge(); + + // If the admin authentication is enabled but not set up, this will cause a nasty error. + // Not much we can do about it though. + $n = xcache_count(XC_TYPE_VAR); + + for ($i = 0; $i < $n; $i++) + { + xcache_clear_cache(XC_TYPE_VAR, $i); + } + } + + /** + * Fetch an item from the cache + * + * @access protected + * @param string $var Cache key + * @return mixed Cached data + */ + function _read($var) + { + $result = xcache_get($this->key_prefix . $var); + + return ($result !== null) ? $result : false; + } + + /** + * Store data in the cache + * + * @access protected + * @param string $var Cache key + * @param mixed $data Data to store + * @param int $ttl Time-to-live of cached data + * @return bool True if the operation succeeded + */ + function _write($var, $data, $ttl = 2592000) + { + return xcache_set($this->key_prefix . $var, $data, $ttl); + } + + /** + * Remove an item from the cache + * + * @access protected + * @param string $var Cache key + * @return bool True if the operation succeeded + */ + function _delete($var) + { + return xcache_unset($this->key_prefix . $var); + } + + /** + * Check if a cache var exists + * + * @access protected + * @param string $var Cache key + * @return bool True if it exists, otherwise false + */ + function _isset($var) + { + return xcache_isset($this->key_prefix . $var); + } +} diff --git a/phpBB/phpbb/cache/service.php b/phpBB/phpbb/cache/service.php new file mode 100644 index 0000000000..56727c2ad5 --- /dev/null +++ b/phpBB/phpbb/cache/service.php @@ -0,0 +1,390 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cache; + +/** +* Class for grabbing/handling cached entries +*/ +class service +{ + /** + * Cache driver. + * + * @var \phpbb\cache\driver\driver_interface + */ + protected $driver; + + /** + * The config. + * + * @var \phpbb\config\config + */ + protected $config; + + /** + * Database connection. + * + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * Root path. + * + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP file extension. + * + * @var string + */ + protected $php_ext; + + /** + * Creates a cache service around a cache driver + * + * @param \phpbb\cache\driver\driver_interface $driver The cache driver + * @param \phpbb\config\config $config The config + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param string $phpbb_root_path Root path + * @param string $php_ext PHP file extension + */ + public function __construct(\phpbb\cache\driver\driver_interface $driver, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, $phpbb_root_path, $php_ext) + { + $this->set_driver($driver); + $this->config = $config; + $this->db = $db; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * Returns the cache driver used by this cache service. + * + * @return \phpbb\cache\driver\driver_interface The cache driver + */ + public function get_driver() + { + return $this->driver; + } + + /** + * Replaces the cache driver used by this cache service. + * + * @param \phpbb\cache\driver\driver_interface $driver The cache driver + */ + public function set_driver(\phpbb\cache\driver\driver_interface $driver) + { + $this->driver = $driver; + } + + public function __call($method, $arguments) + { + return call_user_func_array(array($this->driver, $method), $arguments); + } + + /** + * Obtain list of naughty words and build preg style replacement arrays for use by the + * calling script + */ + function obtain_word_list() + { + if (($censors = $this->driver->get('_word_censors')) === false) + { + $sql = 'SELECT word, replacement + FROM ' . WORDS_TABLE; + $result = $this->db->sql_query($sql); + + $censors = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $censors['match'][] = get_censor_preg_expression($row['word']); + $censors['replace'][] = $row['replacement']; + } + $this->db->sql_freeresult($result); + + $this->driver->put('_word_censors', $censors); + } + + return $censors; + } + + /** + * Obtain currently listed icons + */ + function obtain_icons() + { + if (($icons = $this->driver->get('_icons')) === false) + { + // Topic icons + $sql = 'SELECT * + FROM ' . ICONS_TABLE . ' + ORDER BY icons_order'; + $result = $this->db->sql_query($sql); + + $icons = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $icons[$row['icons_id']]['img'] = $row['icons_url']; + $icons[$row['icons_id']]['width'] = (int) $row['icons_width']; + $icons[$row['icons_id']]['height'] = (int) $row['icons_height']; + $icons[$row['icons_id']]['display'] = (bool) $row['display_on_posting']; + } + $this->db->sql_freeresult($result); + + $this->driver->put('_icons', $icons); + } + + return $icons; + } + + /** + * Obtain ranks + */ + function obtain_ranks() + { + if (($ranks = $this->driver->get('_ranks')) === false) + { + $sql = 'SELECT * + FROM ' . RANKS_TABLE . ' + ORDER BY rank_min DESC'; + $result = $this->db->sql_query($sql); + + $ranks = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + if ($row['rank_special']) + { + unset($row['rank_min']); + $ranks['special'][$row['rank_id']] = $row; + } + else + { + $ranks['normal'][$row['rank_id']] = $row; + } + } + $this->db->sql_freeresult($result); + + $this->driver->put('_ranks', $ranks); + } + + return $ranks; + } + + /** + * Obtain allowed extensions + * + * @param mixed $forum_id If false then check for private messaging, if int then check for forum id. If true, then only return extension informations. + * + * @return array allowed extensions array. + */ + function obtain_attach_extensions($forum_id) + { + if (($extensions = $this->driver->get('_extensions')) === false) + { + $extensions = array( + '_allowed_post' => array(), + '_allowed_pm' => array(), + ); + + // The rule is to only allow those extensions defined. ;) + $sql = 'SELECT e.extension, g.* + FROM ' . EXTENSIONS_TABLE . ' e, ' . EXTENSION_GROUPS_TABLE . ' g + WHERE e.group_id = g.group_id + AND (g.allow_group = 1 OR g.allow_in_pm = 1)'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $extension = strtolower(trim($row['extension'])); + + $extensions[$extension] = array( + 'display_cat' => (int) $row['cat_id'], + 'download_mode' => (int) $row['download_mode'], + 'upload_icon' => trim($row['upload_icon']), + 'max_filesize' => (int) $row['max_filesize'], + 'allow_group' => $row['allow_group'], + 'allow_in_pm' => $row['allow_in_pm'], + 'group_name' => $row['group_name'], + ); + + $allowed_forums = ($row['allowed_forums']) ? unserialize(trim($row['allowed_forums'])) : array(); + + // Store allowed extensions forum wise + if ($row['allow_group']) + { + $extensions['_allowed_post'][$extension] = (!sizeof($allowed_forums)) ? 0 : $allowed_forums; + } + + if ($row['allow_in_pm']) + { + $extensions['_allowed_pm'][$extension] = 0; + } + } + $this->db->sql_freeresult($result); + + $this->driver->put('_extensions', $extensions); + } + + // Forum post + if ($forum_id === false) + { + // We are checking for private messages, therefore we only need to get the pm extensions... + $return = array('_allowed_' => array()); + + foreach ($extensions['_allowed_pm'] as $extension => $check) + { + $return['_allowed_'][$extension] = 0; + $return[$extension] = $extensions[$extension]; + } + + $extensions = $return; + } + else if ($forum_id === true) + { + return $extensions; + } + else + { + $forum_id = (int) $forum_id; + $return = array('_allowed_' => array()); + + foreach ($extensions['_allowed_post'] as $extension => $check) + { + // Check for allowed forums + if (is_array($check)) + { + $allowed = (!in_array($forum_id, $check)) ? false : true; + } + else + { + $allowed = true; + } + + if ($allowed) + { + $return['_allowed_'][$extension] = 0; + $return[$extension] = $extensions[$extension]; + } + } + + $extensions = $return; + } + + if (!isset($extensions['_allowed_'])) + { + $extensions['_allowed_'] = array(); + } + + return $extensions; + } + + /** + * Obtain active bots + */ + function obtain_bots() + { + if (($bots = $this->driver->get('_bots')) === false) + { + switch ($this->db->get_sql_layer()) + { + case 'mssql': + case 'mssql_odbc': + case 'mssqlnative': + $sql = 'SELECT user_id, bot_agent, bot_ip + FROM ' . BOTS_TABLE . ' + WHERE bot_active = 1 + ORDER BY LEN(bot_agent) DESC'; + break; + + // LENGTH supported by MySQL, IBM DB2 and Oracle for sure... + default: + $sql = 'SELECT user_id, bot_agent, bot_ip + FROM ' . BOTS_TABLE . ' + WHERE bot_active = 1 + ORDER BY LENGTH(bot_agent) DESC'; + break; + } + $result = $this->db->sql_query($sql); + + $bots = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $bots[] = $row; + } + $this->db->sql_freeresult($result); + + $this->driver->put('_bots', $bots); + } + + return $bots; + } + + /** + * Obtain cfg file data + */ + function obtain_cfg_items($style) + { + $parsed_array = $this->driver->get('_cfg_' . $style['style_path']); + + if ($parsed_array === false) + { + $parsed_array = array(); + } + + $filename = $this->phpbb_root_path . 'styles/' . $style['style_path'] . '/style.cfg'; + + if (!file_exists($filename)) + { + return $parsed_array; + } + + if (!isset($parsed_array['filetime']) || (($this->config['load_tplcompile'] && @filemtime($filename) > $parsed_array['filetime']))) + { + // Re-parse cfg file + $parsed_array = parse_cfg_file($filename); + $parsed_array['filetime'] = @filemtime($filename); + + $this->driver->put('_cfg_' . $style['style_path'], $parsed_array); + } + + return $parsed_array; + } + + /** + * Obtain disallowed usernames + */ + function obtain_disallowed_usernames() + { + if (($usernames = $this->driver->get('_disallowed_usernames')) === false) + { + $sql = 'SELECT disallow_username + FROM ' . DISALLOW_TABLE; + $result = $this->db->sql_query($sql); + + $usernames = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $usernames[] = str_replace('%', '.*?', preg_quote(utf8_clean_string($row['disallow_username']), '#')); + } + $this->db->sql_freeresult($result); + + $this->driver->put('_disallowed_usernames', $usernames); + } + + return $usernames; + } +} diff --git a/phpBB/phpbb/captcha/char_cube3d.php b/phpBB/phpbb/captcha/char_cube3d.php new file mode 100644 index 0000000000..a712b16dce --- /dev/null +++ b/phpBB/phpbb/captcha/char_cube3d.php @@ -0,0 +1,277 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha; + +class char_cube3d +{ + var $bitmap; + var $bitmap_width; + var $bitmap_height; + + var $basis_matrix = array(array(1, 0, 0), array(0, 1, 0), array(0, 0, 1)); + var $abs_x = array(1, 0); + var $abs_y = array(0, 1); + var $x = 0; + var $y = 1; + var $z = 2; + var $letter = ''; + + /** + */ + function __construct(&$bitmaps, $letter) + { + $this->bitmap = $bitmaps['data'][$letter]; + $this->bitmap_width = $bitmaps['width']; + $this->bitmap_height = $bitmaps['height']; + + $this->basis_matrix[0][0] = mt_rand(-600, 600); + $this->basis_matrix[0][1] = mt_rand(-600, 600); + $this->basis_matrix[0][2] = (mt_rand(0, 1) * 2000) - 1000; + $this->basis_matrix[1][0] = mt_rand(-1000, 1000); + $this->basis_matrix[1][1] = mt_rand(-1000, 1000); + $this->basis_matrix[1][2] = mt_rand(-1000, 1000); + + $this->normalize($this->basis_matrix[0]); + $this->normalize($this->basis_matrix[1]); + $this->basis_matrix[2] = $this->cross_product($this->basis_matrix[0], $this->basis_matrix[1]); + $this->normalize($this->basis_matrix[2]); + + // $this->basis_matrix[1] might not be (probably isn't) orthogonal to $basis_matrix[0] + $this->basis_matrix[1] = $this->cross_product($this->basis_matrix[0], $this->basis_matrix[2]); + $this->normalize($this->basis_matrix[1]); + + // Make sure our cube is facing into the canvas (assuming +z == in) + for ($i = 0; $i < 3; ++$i) + { + if ($this->basis_matrix[$i][2] < 0) + { + $this->basis_matrix[$i][0] *= -1; + $this->basis_matrix[$i][1] *= -1; + $this->basis_matrix[$i][2] *= -1; + } + } + + // Force our "z" basis vector to be the one with greatest absolute z value + $this->x = 0; + $this->y = 1; + $this->z = 2; + + // Swap "y" with "z" + if ($this->basis_matrix[1][2] > $this->basis_matrix[2][2]) + { + $this->z = 1; + $this->y = 2; + } + + // Swap "x" with "z" + if ($this->basis_matrix[0][2] > $this->basis_matrix[$this->z][2]) + { + $this->x = $this->z; + $this->z = 0; + } + + // Still need to determine which of $x,$y are which. + // wrong orientation if y's y-component is less than it's x-component + // likewise if x's x-component is less than it's y-component + // if they disagree, go with the one with the greater weight difference. + // rotate if positive + $weight = (abs($this->basis_matrix[$this->x][1]) - abs($this->basis_matrix[$this->x][0])) + (abs($this->basis_matrix[$this->y][0]) - abs($this->basis_matrix[$this->y][1])); + + // Swap "x" with "y" + if ($weight > 0) + { + list($this->x, $this->y) = array($this->y, $this->x); + } + + $this->abs_x = array($this->basis_matrix[$this->x][0], $this->basis_matrix[$this->x][1]); + $this->abs_y = array($this->basis_matrix[$this->y][0], $this->basis_matrix[$this->y][1]); + + if ($this->abs_x[0] < 0) + { + $this->abs_x[0] *= -1; + $this->abs_x[1] *= -1; + } + + if ($this->abs_y[1] > 0) + { + $this->abs_y[0] *= -1; + $this->abs_y[1] *= -1; + } + + $this->letter = $letter; + } + + /** + * Draw a character + */ + function drawchar($scale, $xoff, $yoff, $img, $background, $colours) + { + $width = $this->bitmap_width; + $height = $this->bitmap_height; + $bitmap = $this->bitmap; + + $colour1 = $colours[array_rand($colours)]; + $colour2 = $colours[array_rand($colours)]; + + $swapx = ($this->basis_matrix[$this->x][0] > 0); + $swapy = ($this->basis_matrix[$this->y][1] < 0); + + for ($y = 0; $y < $height; ++$y) + { + for ($x = 0; $x < $width; ++$x) + { + $xp = ($swapx) ? ($width - $x - 1) : $x; + $yp = ($swapy) ? ($height - $y - 1) : $y; + + if ($bitmap[$height - $yp - 1][$xp]) + { + $dx = $this->scale($this->abs_x, ($xp - ($swapx ? ($width / 2) : ($width / 2) - 1)) * $scale); + $dy = $this->scale($this->abs_y, ($yp - ($swapy ? ($height / 2) : ($height / 2) - 1)) * $scale); + $xo = $xoff + $dx[0] + $dy[0]; + $yo = $yoff + $dx[1] + $dy[1]; + + $origin = array(0, 0, 0); + $xvec = $this->scale($this->basis_matrix[$this->x], $scale); + $yvec = $this->scale($this->basis_matrix[$this->y], $scale); + $face_corner = $this->sum2($xvec, $yvec); + + $zvec = $this->scale($this->basis_matrix[$this->z], $scale); + $x_corner = $this->sum2($xvec, $zvec); + $y_corner = $this->sum2($yvec, $zvec); + + imagefilledpolygon($img, $this->gen_poly($xo, $yo, $origin, $xvec, $x_corner,$zvec), 4, $colour1); + imagefilledpolygon($img, $this->gen_poly($xo, $yo, $origin, $yvec, $y_corner,$zvec), 4, $colour2); + + $face = $this->gen_poly($xo, $yo, $origin, $xvec, $face_corner, $yvec); + + imagefilledpolygon($img, $face, 4, $background); + imagepolygon($img, $face, 4, $colour1); + } + } + } + } + + /* + * return a roughly acceptable range of sizes for rendering with this texttype + */ + function range() + { + return array(3, 4); + } + + /** + * Vector length + */ + function vectorlen($vector) + { + return sqrt(pow($vector[0], 2) + pow($vector[1], 2) + pow($vector[2], 2)); + } + + /** + * Normalize + */ + function normalize(&$vector, $length = 1) + { + $length = (( $length < 1) ? 1 : $length); + $length /= $this->vectorlen($vector); + $vector[0] *= $length; + $vector[1] *= $length; + $vector[2] *= $length; + } + + /** + */ + function cross_product($vector1, $vector2) + { + $retval = array(0, 0, 0); + $retval[0] = (($vector1[1] * $vector2[2]) - ($vector1[2] * $vector2[1])); + $retval[1] = -(($vector1[0] * $vector2[2]) - ($vector1[2] * $vector2[0])); + $retval[2] = (($vector1[0] * $vector2[1]) - ($vector1[1] * $vector2[0])); + + return $retval; + } + + /** + */ + function sum($vector1, $vector2) + { + return array($vector1[0] + $vector2[0], $vector1[1] + $vector2[1], $vector1[2] + $vector2[2]); + } + + /** + */ + function sum2($vector1, $vector2) + { + return array($vector1[0] + $vector2[0], $vector1[1] + $vector2[1]); + } + + /** + */ + function scale($vector, $length) + { + if (sizeof($vector) == 2) + { + return array($vector[0] * $length, $vector[1] * $length); + } + + return array($vector[0] * $length, $vector[1] * $length, $vector[2] * $length); + } + + /** + */ + function gen_poly($xoff, $yoff, &$vec1, &$vec2, &$vec3, &$vec4) + { + $poly = array(); + $poly[0] = $xoff + $vec1[0]; + $poly[1] = $yoff + $vec1[1]; + $poly[2] = $xoff + $vec2[0]; + $poly[3] = $yoff + $vec2[1]; + $poly[4] = $xoff + $vec3[0]; + $poly[5] = $yoff + $vec3[1]; + $poly[6] = $xoff + $vec4[0]; + $poly[7] = $yoff + $vec4[1]; + + return $poly; + } + + /** + * dimensions + */ + function dimensions($size) + { + $xn = $this->scale($this->basis_matrix[$this->x], -($this->bitmap_width / 2) * $size); + $xp = $this->scale($this->basis_matrix[$this->x], ($this->bitmap_width / 2) * $size); + $yn = $this->scale($this->basis_matrix[$this->y], -($this->bitmap_height / 2) * $size); + $yp = $this->scale($this->basis_matrix[$this->y], ($this->bitmap_height / 2) * $size); + + $p = array(); + $p[0] = $this->sum2($xn, $yn); + $p[1] = $this->sum2($xp, $yn); + $p[2] = $this->sum2($xp, $yp); + $p[3] = $this->sum2($xn, $yp); + + $min_x = $max_x = $p[0][0]; + $min_y = $max_y = $p[0][1]; + + for ($i = 1; $i < 4; ++$i) + { + $min_x = ($min_x > $p[$i][0]) ? $p[$i][0] : $min_x; + $min_y = ($min_y > $p[$i][1]) ? $p[$i][1] : $min_y; + $max_x = ($max_x < $p[$i][0]) ? $p[$i][0] : $max_x; + $max_y = ($max_y < $p[$i][1]) ? $p[$i][1] : $max_y; + } + + return array($min_x, $min_y, $max_x, $max_y); + } +} diff --git a/phpBB/phpbb/captcha/colour_manager.php b/phpBB/phpbb/captcha/colour_manager.php new file mode 100644 index 0000000000..6ca3c3fd2c --- /dev/null +++ b/phpBB/phpbb/captcha/colour_manager.php @@ -0,0 +1,527 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha; + +class colour_manager +{ + var $img; + var $mode; + var $colours; + var $named_colours; + + /** + * Create the colour manager, link it to the image resource + */ + function __construct($img, $background = false, $mode = 'ahsv') + { + $this->img = $img; + $this->mode = $mode; + $this->colours = array(); + $this->named_colours = array(); + + if ($background !== false) + { + $bg = $this->allocate_named('background', $background); + imagefill($this->img, 0, 0, $bg); + } + } + + /** + * Lookup a named colour resource + */ + function get_resource($named_colour) + { + if (isset($this->named_colours[$named_colour])) + { + return $this->named_colours[$named_colour]; + } + + if (isset($this->named_rgb[$named_colour])) + { + return $this->allocate_named($named_colour, $this->named_rgb[$named_colour], 'rgb'); + } + + return false; + } + + /** + * Assign a name to a colour resource + */ + function name_colour($name, $resource) + { + $this->named_colours[$name] = $resource; + } + + /** + * names and allocates a colour resource + */ + function allocate_named($name, $colour, $mode = false) + { + $resource = $this->allocate($colour, $mode); + + if ($resource !== false) + { + $this->name_colour($name, $resource); + } + return $resource; + } + + /** + * allocates a specified colour into the image + */ + function allocate($colour, $mode = false) + { + if ($mode === false) + { + $mode = $this->mode; + } + + if (!is_array($colour)) + { + if (isset($this->named_rgb[$colour])) + { + return $this->allocate_named($colour, $this->named_rgb[$colour], 'rgb'); + } + + if (!is_int($colour)) + { + return false; + } + + $mode = 'rgb'; + $colour = array(255 & ($colour >> 16), 255 & ($colour >> 8), 255 & $colour); + } + + if (isset($colour['mode'])) + { + $mode = $colour['mode']; + unset($colour['mode']); + } + + if (isset($colour['random'])) + { + unset($colour['random']); + // everything else is params + return $this->random_colour($colour, $mode); + } + + $rgb = $this->model_convert($colour, $mode, 'rgb'); + $store = ($this->mode == 'rgb') ? $rgb : $this->model_convert($colour, $mode, $this->mode); + $resource = imagecolorallocate($this->img, $rgb[0], $rgb[1], $rgb[2]); + $this->colours[$resource] = $store; + + return $resource; + } + + /** + * randomly generates a colour, with optional params + */ + function random_colour($params = array(), $mode = false) + { + if ($mode === false) + { + $mode = $this->mode; + } + + switch ($mode) + { + case 'rgb': + // @TODO random rgb generation. do we intend to do this, or is it just too tedious? + break; + + case 'ahsv': + case 'hsv': + default: + + $default_params = array( + 'hue_bias' => false, // degree / 'r'/'g'/'b'/'c'/'m'/'y' /'o' + 'hue_range' => false, // if hue bias, then difference range +/- from bias + 'min_saturation' => 30, // 0 - 100 + 'max_saturation' => 80, // 0 - 100 + 'min_value' => 30, // 0 - 100 + 'max_value' => 80, // 0 - 100 + ); + + $alt = ($mode == 'ahsv') ? true : false; + $params = array_merge($default_params, $params); + + $min_hue = 0; + $max_hue = 359; + $min_saturation = max(0, $params['min_saturation']); + $max_saturation = min(100, $params['max_saturation']); + $min_value = max(0, $params['min_value']); + $max_value = min(100, $params['max_value']); + + if ($params['hue_bias'] !== false) + { + if (is_numeric($params['hue_bias'])) + { + $h = intval($params['hue_bias']) % 360; + } + else + { + switch ($params['hue_bias']) + { + case 'o': + $h = $alt ? 60 : 30; + break; + + case 'y': + $h = $alt ? 120 : 60; + break; + + case 'g': + $h = $alt ? 180 : 120; + break; + + case 'c': + $h = $alt ? 210 : 180; + break; + + case 'b': + $h = 240; + break; + + case 'm': + $h = 300; + break; + + case 'r': + default: + $h = 0; + break; + } + } + + $min_hue = $h + 360; + $max_hue = $h + 360; + + if ($params['hue_range']) + { + $min_hue -= min(180, $params['hue_range']); + $max_hue += min(180, $params['hue_range']); + } + } + + $h = mt_rand($min_hue, $max_hue); + $s = mt_rand($min_saturation, $max_saturation); + $v = mt_rand($min_value, $max_value); + + return $this->allocate(array($h, $s, $v), $mode); + + break; + } + } + + /** + */ + function colour_scheme($resource, $include_original = true) + { + $mode = 'hsv'; + + if (($pre = $this->get_resource($resource)) !== false) + { + $resource = $pre; + } + + $colour = $this->model_convert($this->colours[$resource], $this->mode, $mode); + $results = ($include_original) ? array($resource) : array(); + $colour2 = $colour3 = $colour4 = $colour; + $colour2[0] += 150; + $colour3[0] += 180; + $colour4[0] += 210; + + $results[] = $this->allocate($colour2, $mode); + $results[] = $this->allocate($colour3, $mode); + $results[] = $this->allocate($colour4, $mode); + + return $results; + } + + /** + */ + function mono_range($resource, $count = 5, $include_original = true) + { + if (is_array($resource)) + { + $results = array(); + for ($i = 0, $size = sizeof($resource); $i < $size; ++$i) + { + $results = array_merge($results, $this->mono_range($resource[$i], $count, $include_original)); + } + return $results; + } + + $mode = (in_array($this->mode, array('hsv', 'ahsv'), true) ? $this->mode : 'ahsv'); + if (($pre = $this->get_resource($resource)) !== false) + { + $resource = $pre; + } + + $colour = $this->model_convert($this->colours[$resource], $this->mode, $mode); + + $results = array(); + if ($include_original) + { + $results[] = $resource; + $count--; + } + + // This is a hard problem. I chicken out and try to maintain readability at the cost of less randomness. + + while ($count > 0) + { + $colour[1] = ($colour[1] + mt_rand(40,60)) % 99; + $colour[2] = ($colour[2] + mt_rand(40,60)); + $results[] = $this->allocate($colour, $mode); + $count--; + } + return $results; + } + + /** + * Convert from one colour model to another + */ + function model_convert($colour, $from_model, $to_model) + { + if ($from_model == $to_model) + { + return $colour; + } + + switch ($to_model) + { + case 'hsv': + + switch ($from_model) + { + case 'ahsv': + return $this->ah2h($colour); + break; + + case 'rgb': + return $this->rgb2hsv($colour); + break; + } + break; + + case 'ahsv': + + switch ($from_model) + { + case 'hsv': + return $this->h2ah($colour); + break; + + case 'rgb': + return $this->h2ah($this->rgb2hsv($colour)); + break; + } + break; + + case 'rgb': + switch ($from_model) + { + case 'hsv': + return $this->hsv2rgb($colour); + break; + + case 'ahsv': + return $this->hsv2rgb($this->ah2h($colour)); + break; + } + break; + } + return false; + } + + /** + * Slightly altered from wikipedia's algorithm + */ + function hsv2rgb($hsv) + { + $this->normalize_hue($hsv[0]); + + $h = $hsv[0]; + $s = min(1, max(0, $hsv[1] / 100)); + $v = min(1, max(0, $hsv[2] / 100)); + + // calculate hue sector + $hi = floor($hsv[0] / 60); + + // calculate opposite colour + $p = $v * (1 - $s); + + // calculate distance between hex vertices + $f = ($h / 60) - $hi; + + // coming in or going out? + if (!($hi & 1)) + { + $f = 1 - $f; + } + + // calculate adjacent colour + $q = $v * (1 - ($f * $s)); + + switch ($hi) + { + case 0: + $rgb = array($v, $q, $p); + break; + + case 1: + $rgb = array($q, $v, $p); + break; + + case 2: + $rgb = array($p, $v, $q); + break; + + case 3: + $rgb = array($p, $q, $v); + break; + + case 4: + $rgb = array($q, $p, $v); + break; + + case 5: + $rgb = array($v, $p, $q); + break; + + default: + return array(0, 0, 0); + break; + } + + return array(255 * $rgb[0], 255 * $rgb[1], 255 * $rgb[2]); + } + + /** + * (more than) Slightly altered from wikipedia's algorithm + */ + function rgb2hsv($rgb) + { + $r = min(255, max(0, $rgb[0])); + $g = min(255, max(0, $rgb[1])); + $b = min(255, max(0, $rgb[2])); + $max = max($r, $g, $b); + $min = min($r, $g, $b); + + $v = $max / 255; + $s = (!$max) ? 0 : 1 - ($min / $max); + + // if max - min is 0, we want hue to be 0 anyway. + $h = $max - $min; + + if ($h) + { + switch ($max) + { + case $g: + $h = 120 + (60 * ($b - $r) / $h); + break; + + case $b: + $h = 240 + (60 * ($r - $g) / $h); + break; + + case $r: + $h = 360 + (60 * ($g - $b) / $h); + break; + } + } + $this->normalize_hue($h); + + return array($h, $s * 100, $v * 100); + } + + /** + */ + function normalize_hue(&$hue) + { + $hue %= 360; + + if ($hue < 0) + { + $hue += 360; + } + } + + /** + * Alternate hue to hue + */ + function ah2h($ahue) + { + if (is_array($ahue)) + { + $ahue[0] = $this->ah2h($ahue[0]); + return $ahue; + } + $this->normalize_hue($ahue); + + // blue through red is already ok + if ($ahue >= 240) + { + return $ahue; + } + + // ahue green is at 180 + if ($ahue >= 180) + { + // return (240 - (2 * (240 - $ahue))); + return (2 * $ahue) - 240; // equivalent + } + + // ahue yellow is at 120 (RYB rather than RGB) + if ($ahue >= 120) + { + return $ahue - 60; + } + + return $ahue / 2; + } + + /** + * hue to Alternate hue + */ + function h2ah($hue) + { + if (is_array($hue)) + { + $hue[0] = $this->h2ah($hue[0]); + return $hue; + } + $this->normalize_hue($hue); + + // blue through red is already ok + if ($hue >= 240) + { + return $hue; + } + else if ($hue <= 60) + { + return $hue * 2; + } + else if ($hue <= 120) + { + return $hue + 60; + } + else + { + return ($hue + 240) / 2; + } + } +} diff --git a/phpBB/phpbb/captcha/factory.php b/phpBB/phpbb/captcha/factory.php new file mode 100644 index 0000000000..dd44aca8bb --- /dev/null +++ b/phpBB/phpbb/captcha/factory.php @@ -0,0 +1,88 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha; + +class factory +{ + /** + * @var \Symfony\Component\DependencyInjection\ContainerInterface + */ + private $container; + + /** + * @var \phpbb\di\service_collection + */ + private $plugins; + + /** + * Constructor + * + * @param \Symfony\Component\DependencyInjection\ContainerInterface $container + * @param \phpbb\di\service_collection $plugins + */ + public function __construct(\Symfony\Component\DependencyInjection\ContainerInterface $container, \phpbb\di\service_collection $plugins) + { + $this->container = $container; + $this->plugins = $plugins; + } + + /** + * Return a new instance of a given plugin + * + * @param $name + * @return object + */ + public function get_instance($name) + { + return $this->container->get($name); + } + + /** + * Call the garbage collector + * + * @param string $name The name to the captcha service. + */ + function garbage_collect($name) + { + $captcha = $this->get_instance($name); + $captcha->garbage_collect(0); + } + + /** + * Return a list of all registered CAPTCHA plugins + * + * @returns array + */ + function get_captcha_types() + { + $captchas = array( + 'available' => array(), + 'unavailable' => array(), + ); + + foreach ($this->plugins as $plugin => $plugin_instance) + { + if ($plugin_instance->is_available()) + { + $captchas['available'][$plugin] = $plugin_instance->get_name(); + } + else + { + $captchas['unavailable'][$plugin] = $plugin_instance->get_name(); + } + } + + return $captchas; + } +} diff --git a/phpBB/phpbb/captcha/gd.php b/phpBB/phpbb/captcha/gd.php new file mode 100644 index 0000000000..652df28f8a --- /dev/null +++ b/phpBB/phpbb/captcha/gd.php @@ -0,0 +1,1847 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha; + +class gd +{ + var $width = 360; + var $height = 96; + + /** + * Create the image containing $code with a seed of $seed + */ + function execute($code, $seed) + { + global $config; + + mt_srand($seed); + + // Create image + $img = imagecreatetruecolor($this->width, $this->height); + + // Generate colours + $colour = new colour_manager($img, array( + 'random' => true, + 'min_value' => 60, + ), 'hsv'); + + $scheme = $colour->colour_scheme('background', false); + $scheme = $colour->mono_range($scheme, 10, false); + shuffle($scheme); + + $bg_colours = array_splice($scheme, mt_rand(6, 12)); + + // Generate code characters + $characters = $sizes = $bounding_boxes = $noise = array(); + $width_avail = $this->width - 15; + $code_len = strlen($code); + $captcha_bitmaps = $this->captcha_bitmaps(); + + for ($i = 0; $i < $code_len; ++$i) + { + $characters[$i] = new char_cube3d($captcha_bitmaps, $code[$i]); + + list($min, $max) = $characters[$i]->range(); + $sizes[$i] = mt_rand($min, $max); + + $box = $characters[$i]->dimensions($sizes[$i]); + $width_avail -= ($box[2] - $box[0]); + $bounding_boxes[$i] = $box; + } + + // Redistribute leftover x-space + $offset = array(); + for ($i = 0; $i < $code_len; ++$i) + { + $denom = ($code_len - $i); + $denom = max(1.3, $denom); + $offset[$i] = phpbb_mt_rand(0, (int) round((1.5 * $width_avail) / $denom)); + $width_avail -= $offset[$i]; + } + + if ($config['captcha_gd_x_grid']) + { + $grid = (int) $config['captcha_gd_x_grid']; + for ($y = 0; $y < $this->height; $y += mt_rand($grid - 2, $grid + 2)) + { + $current_colour = $scheme[array_rand($scheme)]; + imageline($img, mt_rand(0,4), mt_rand($y - 3, $y), mt_rand($this->width - 5, $this->width), mt_rand($y - 3, $y), $current_colour); + } + } + + if ($config['captcha_gd_y_grid']) + { + $grid = (int) $config['captcha_gd_y_grid']; + for ($x = 0; $x < $this->width; $x += mt_rand($grid - 2, $grid + 2)) + { + $current_colour = $scheme[array_rand($scheme)]; + imagedashedline($img, mt_rand($x -3, $x + 3), mt_rand(0, 4), mt_rand($x -3, $x + 3), mt_rand($this->height - 5, $this->height), $current_colour); + } + } + + if ($config['captcha_gd_wave'] && ($config['captcha_gd_y_grid'] || $config['captcha_gd_y_grid'])) + { + $this->wave($img); + } + + if ($config['captcha_gd_3d_noise']) + { + $xoffset = mt_rand(0,9); + $noise_bitmaps = $this->captcha_noise_bg_bitmaps(); + for ($i = 0; $i < $code_len; ++$i) + { + $noise[$i] = new char_cube3d($noise_bitmaps, mt_rand(1, sizeof($noise_bitmaps['data']))); + + list($min, $max) = $noise[$i]->range(); + //$box = $noise[$i]->dimensions($sizes[$i]); + } + $xoffset = 0; + for ($i = 0; $i < $code_len; ++$i) + { + $dimm = $bounding_boxes[$i]; + $xoffset += ($offset[$i] - $dimm[0]); + $yoffset = mt_rand(-$dimm[1], $this->height - $dimm[3]); + + $noise[$i]->drawchar($sizes[$i], $xoffset, $yoffset, $img, $colour->get_resource('background'), $scheme); + $xoffset += $dimm[2]; + } + } + + $xoffset = 5; + for ($i = 0; $i < $code_len; ++$i) + { + $dimm = $bounding_boxes[$i]; + $xoffset += ($offset[$i] - $dimm[0]); + $yoffset = mt_rand(-$dimm[1], $this->height - $dimm[3]); + + $characters[$i]->drawchar($sizes[$i], $xoffset, $yoffset, $img, $colour->get_resource('background'), $scheme); + $xoffset += $dimm[2]; + } + + if ($config['captcha_gd_wave']) + { + $this->wave($img); + } + + if ($config['captcha_gd_foreground_noise']) + { + $this->noise_line($img, 0, 0, $this->width, $this->height, $colour->get_resource('background'), $scheme, $bg_colours); + } + + // Send image + header('Content-Type: image/png'); + header('Cache-control: no-cache, no-store'); + imagepng($img); + imagedestroy($img); + } + + /** + * Sinus + */ + function wave($img) + { + global $config; + + $period_x = mt_rand(12,18); + $period_y = mt_rand(7,14); + $amp_x = mt_rand(5,10); + $amp_y = mt_rand(2,4); + $socket = mt_rand(0,100); + + $dampen_x = mt_rand($this->width/5, $this->width/2); + $dampen_y = mt_rand($this->height/5, $this->height/2); + $direction_x = (mt_rand (0, 1)); + $direction_y = (mt_rand (0, 1)); + + for ($i = 0; $i < $this->width; $i++) + { + $dir = ($direction_x) ? $i : ($this->width - $i); + imagecopy($img, $img, $i-1, sin($socket+ $i/($period_x + $dir/$dampen_x)) * $amp_x, $i, 0, 1, $this->height); + } + $socket = mt_rand(0,100); + for ($i = 0; $i < $this->height; $i++) + { + $dir = ($direction_y) ? $i : ($this->height - $i); + imagecopy($img, $img ,sin($socket + $i/($period_y + ($dir)/$dampen_y)) * $amp_y, $i-1, 0, $i, $this->width, 1); + } + return $img; + } + + /** + * Noise line + */ + function noise_line($img, $min_x, $min_y, $max_x, $max_y, $bg, $font, $non_font) + { + imagesetthickness($img, 2); + + $x1 = $min_x; + $x2 = $max_x; + $y1 = $min_y; + $y2 = $min_y; + + do + { + $line = array_merge( + array_fill(0, mt_rand(30, 60), $non_font[array_rand($non_font)]), + array_fill(0, mt_rand(30, 60), $bg) + ); + + imagesetstyle($img, $line); + imageline($img, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED); + + $y1 += mt_rand(12, 35); + $y2 += mt_rand(12, 35); + } + while ($y1 < $max_y && $y2 < $max_y); + + $x1 = $min_x; + $x2 = $min_x; + $y1 = $min_y; + $y2 = $max_y; + + do + { + $line = array_merge( + array_fill(0, mt_rand(30, 60), $non_font[array_rand($non_font)]), + array_fill(0, mt_rand(30, 60), $bg) + ); + + imagesetstyle($img, $line); + imageline($img, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED); + + $x1 += mt_rand(20, 35); + $x2 += mt_rand(20, 35); + } + while ($x1 < $max_x && $x2 < $max_x); + imagesetthickness($img, 1); + } + + function captcha_noise_bg_bitmaps() + { + return array( + 'width' => 15, + 'height' => 5, + 'data' => array( + + 1 => array( + array(1,0,0,0,1,0,0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,1,0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,1,0,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0,0,0,1,0,0,0), + ), + 2 => array( + array(1,1,mt_rand(0,1),1,0,1,1,1,1,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,1,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,1,1,0,1,1,1), + ), + 3 => array( + array(1,0,0,0,0,0,0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0,0,0,0,0,1,0), + array(0,0,0,0,1,0,0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,0,0,0,0,0,0,1), + ), + 4 => array( + array(1,0,1,0,1,0,0,1,1,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,1,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(1,0,1,0,0,0,0,0,0,0,0,0,0,0,0), + ), + 5 => array( + array(1,1,1,1,0,0,0,1,1,1,0,0,1,0,1), + array(0,0,0,0,0,0,0,1,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(1,0,1,0,0,0,0,0,0,0,0,0,0,0,0), + ), + 6 => array( + array(mt_rand(0,1),mt_rand(0,1),mt_rand(0,1),mt_rand(0,1),mt_rand(0,1),0,mt_rand(0,1),mt_rand(0,1),mt_rand(0,1),mt_rand(0,1),mt_rand(0,1),0,mt_rand(0,1),mt_rand(0,1),mt_rand(0,1)), + array(0,0,0,0,0,0,0,mt_rand(0,1),0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(mt_rand(0,1),0,mt_rand(0,1),0,0,0,0,0,0,0,0,0,0,0,0), + ), + 7 => array( + array(0,0,0,0,0,0,0,0,0,0,1,1,0,1,1), + array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + array(0,0,1,1,0,0,0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,1,0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0), + ), + )); + } + + /** + * Return bitmaps + */ + function captcha_bitmaps() + { + global $config; + + $chars = array( + 'A' => array( + array( + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,1,1,1,1,1,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,1,1,0,1,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,1,1,1,1,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,0,0,0,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,1,1,0,0,0,1,1,0), + array(1,1,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,1), + array(0,0,0,0,0,1,1,1,1), + array(0,0,0,1,1,1,0,0,1), + array(0,1,1,1,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,1,0,0,0,0,1,1,1), + array(0,1,1,1,1,1,1,0,1), + ), + ), + 'B' => array( + array( + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + ), + array( + array(1,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + ), + array( + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,1,1,1,1,0,0), + ), + ), + 'C' => array( + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,1,1,1,1,1,0,1), + array(0,1,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,1), + array(0,0,1,1,1,1,1,0,1), + ), + ), + 'D' => array( + array( + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + ), + array( + array(1,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,1,1,1,1,1,0,1), + array(0,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,1,0,0,0,1,1,1), + array(0,0,1,1,1,1,1,0,1), + ), + ), + 'E' => array( + array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,1,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,1,1,0,0,0,1,1,0), + array(1,1,0,0,0,0,0,1,1), + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(1,1,0,0,0,0,0,1,1), + array(0,1,1,1,1,1,1,1,0), + ), + ), + 'F' => array( + array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + ), + array( + array(0,1,1,1,1,1,1,1,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,0,0,0), + ), + array( + array(0,0,0,1,1,0,0,0,0), + array(0,0,1,1,0,0,0,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,1,1,1,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + ), + ), + 'G' => array( + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,1,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,1,1,1,1,1,0,1), + array(0,1,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,1,1,1,1,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,1), + array(0,0,1,1,1,1,1,0,1), + ), + array( + array(0,0,1,1,1,1,1,0,1), + array(0,1,1,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,1,1,0,0,0,0,0,1), + array(0,0,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,1), + array(1,1,1,1,1,1,1,1,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + ), + 'H' => array( + array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + ), + array( + array(1,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,1,1,1,1,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,0,0,0,1,1,1), + ), + array( + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,1,1,1,0,0,0), + array(1,1,1,1,0,1,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + ), + ), + 'I' => array( + array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(0,0,0,1,1,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,1,1,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,1,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,1,1,0,0,0), + ), + ), + 'J' => array( + array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,0,1,1,0,0,0,0,0), + ), + array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,1,0,0,1,0,0,0,0), + array(1,0,1,1,0,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,0,1,1,0,0,0,0,0), + ), + ), + 'K' => array( + array( // New 'K', supplied by NeoThermic + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,1,0,0,0,0,0), + array(1,0,1,0,0,0,0,0,0), + array(1,1,0,0,0,0,0,0,0), + array(1,0,1,0,0,0,0,0,0), + array(1,0,0,1,0,0,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + ), + array( + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,1,0,0), + array(0,1,0,0,0,1,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,1,0,1,0,0,0,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,1,0,1,0,0,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,1,0,0,0,1,0,0,0), + array(0,1,0,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,0,0,0,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,1,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,1,0,1,0,0,0,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,1,0,1,0,0,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,1,0,0,0,1,0,0,0), + array(0,1,0,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + ), + ), + 'L' => array( + array( + array(0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,1), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,0,1,1,1,0,0,0,0), + ), + ), + 'M' => array( + array( + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,0,1,0,0,0,1,0,1), + array(1,0,1,0,0,0,1,0,1), + array(1,0,1,0,0,0,1,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,1,0,1,0,1,0,1,0), + array(0,1,0,1,0,1,0,1,0), + array(0,1,0,1,0,1,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,0,0,0,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,1,1,1,0,1,1,1,0), + array(1,1,0,1,1,1,0,1,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + ), + ), + 'N' => array( + array( + array(1,1,0,0,0,0,0,0,1), + array(1,1,0,0,0,0,0,0,1), + array(1,0,1,0,0,0,0,0,1), + array(1,0,1,0,0,0,0,0,1), + array(1,0,0,1,0,0,0,0,1), + array(1,0,0,1,0,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,0,1,0,0,1), + array(1,0,0,0,0,1,0,0,1), + array(1,0,0,0,0,0,1,0,1), + array(1,0,0,0,0,0,1,0,1), + array(1,0,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,0,0,0,0,1,0), + array(0,1,1,0,0,0,0,1,0), + array(0,1,1,0,0,0,0,1,0), + array(0,1,0,1,0,0,0,1,0), + array(0,1,0,1,0,0,0,1,0), + array(0,1,0,1,0,0,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,0,1,1,0,1,0), + array(0,1,0,0,0,1,0,1,0), + array(0,1,0,0,0,1,1,1,0), + array(0,1,0,0,0,0,1,1,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,0,0,0,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(1,0,1,1,1,1,0,0,0), + array(1,1,1,0,0,1,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + ), + ), + 'O' => array( + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,1,1,1,1,1,0,0,0), + array(1,1,1,0,0,1,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,1,0,0,0,1,1,0,0), + array(0,1,1,1,1,1,0,0,0), + ), + ), + 'P' => array( + array( + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + ), + array( + array(1,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,1,1,0,0,0,0,0), + array(1,1,0,1,1,0,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,1,1,0,0,0,0), + array(1,1,1,1,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + ), + ), + 'Q' => array( + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,1,0,0,1), + array(1,0,0,0,0,0,1,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,1), + ), + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,1,0,0,1,1,0,1,1), + array(0,1,1,1,1,1,1,1,0), + array(0,0,0,0,0,0,1,1,0), + array(0,0,0,0,0,0,0,1,1), + array(0,0,0,0,0,0,0,0,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,1,1,1,1), + array(0,0,0,0,1,1,0,0,1), + array(0,0,0,0,1,0,0,0,1), + array(0,0,0,0,1,0,0,0,1), + array(0,0,0,0,1,1,0,1,1), + array(0,0,0,0,0,1,1,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + ), + ), + 'R' => array( + array( + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(1,1,1,0,0,0,0,0,0), + array(1,0,0,1,0,0,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + ), + array( + array(1,1,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(0,1,1,0,0,0,0,0,0), + array(0,1,1,1,0,0,0,0,0), + array(0,1,0,1,1,0,0,0,0), + array(0,1,0,0,1,1,0,0,0), + array(0,1,0,0,0,1,1,0,0), + array(0,1,0,0,0,0,1,1,0), + array(1,1,1,0,0,0,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,0,0,0,0), + array(1,1,0,0,1,1,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + ), + ), + 'S' => array( + array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,1,1,1,1,1,0,1), + array(0,1,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,1,0,0,0,0,0,1,0), + array(1,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,1,1,1,1,0,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,0,0,0,0,0,0,0), + array(0,1,1,1,1,0,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(1,0,0,0,1,1,0,0,0), + array(0,1,1,1,1,0,0,0,0), + ), + ), + 'T' => array( + array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + ), + array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,1,0,0,0,1), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,1,1,0,0,0), + ), + array( + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,1,1,1,1,1,1,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,1,0,0,0), + array(0,0,0,0,0,1,1,1,0), + ), + ), + 'U' => array( + array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,1,1), + array(0,0,1,1,0,0,1,1,1), + array(0,0,0,1,1,1,1,0,1), + ), + ), + 'V' => array( + array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + ), + ), + 'W' => array( + array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,1,0,0,0,1,0,1), + array(1,0,1,0,0,0,1,0,1), + array(1,0,1,0,0,0,1,0,1), + array(1,1,0,0,0,0,0,1,1), + array(1,1,0,0,0,0,0,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,1,1,1,0,1,0), + array(0,1,0,1,0,1,0,1,0), + array(0,1,1,1,0,1,1,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,1,1,1,0,1,0), + array(0,1,0,1,0,1,0,1,0), + array(0,1,1,1,0,1,1,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,0), + ), + ), + 'X' => array( + array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,1,1,0,0,0,1,1,1), + array(0,0,0,0,0,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,0,1,1,0,1,1,0,0), + array(0,0,0,1,1,1,0,0,0), + array(0,0,0,1,1,1,0,0,0), + array(0,0,1,1,0,1,1,0,0), + array(0,1,1,0,0,0,1,1,0), + array(0,0,0,0,0,0,0,0,0), + ), + ), + 'Y' => array( + array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(1,1,1,0,0,0,1,1,1), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,1,1,0,0,0), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,1,0,0,0,0,1), + array(0,0,0,1,1,0,0,0,1), + array(0,0,0,0,1,0,0,1,1), + array(0,0,0,0,1,1,0,1,0), + array(0,0,0,0,0,1,1,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,1,0,0,0), + array(0,0,1,1,1,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + ), + 'Z' => array( + array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,1,1), + ), + array( + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,1,1,1,1,1,1,1,0), + array(0,0,0,0,0,1,1,0,0), + array(0,0,0,0,1,1,0,0,0), + array(0,0,0,1,1,0,0,0,0), + array(0,0,1,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,1,1,1,1,1,1,0), + ), + ), + ); + return array( + 'width' => 9, + 'height' => 15, + 'data' => array( + + 'A' => $chars['A'][mt_rand(0, min(sizeof($chars['A']), $config['captcha_gd_fonts']) -1)], + 'B' => $chars['B'][mt_rand(0, min(sizeof($chars['B']), $config['captcha_gd_fonts']) -1)], + 'C' => $chars['C'][mt_rand(0, min(sizeof($chars['C']), $config['captcha_gd_fonts']) -1)], + 'D' => $chars['D'][mt_rand(0, min(sizeof($chars['D']), $config['captcha_gd_fonts']) -1)], + 'E' => $chars['E'][mt_rand(0, min(sizeof($chars['E']), $config['captcha_gd_fonts']) -1)], + 'F' => $chars['F'][mt_rand(0, min(sizeof($chars['F']), $config['captcha_gd_fonts']) -1)], + 'G' => $chars['G'][mt_rand(0, min(sizeof($chars['G']), $config['captcha_gd_fonts']) -1)], + 'H' => $chars['H'][mt_rand(0, min(sizeof($chars['H']), $config['captcha_gd_fonts']) -1)], + 'I' => $chars['I'][mt_rand(0, min(sizeof($chars['I']), $config['captcha_gd_fonts']) -1)], + 'J' => $chars['J'][mt_rand(0, min(sizeof($chars['J']), $config['captcha_gd_fonts']) -1)], + 'K' => $chars['K'][mt_rand(0, min(sizeof($chars['K']), $config['captcha_gd_fonts']) -1)], + 'L' => $chars['L'][mt_rand(0, min(sizeof($chars['L']), $config['captcha_gd_fonts']) -1)], + 'M' => $chars['M'][mt_rand(0, min(sizeof($chars['M']), $config['captcha_gd_fonts']) -1)], + 'N' => $chars['N'][mt_rand(0, min(sizeof($chars['N']), $config['captcha_gd_fonts']) -1)], + 'O' => $chars['O'][mt_rand(0, min(sizeof($chars['O']), $config['captcha_gd_fonts']) -1)], + 'P' => $chars['P'][mt_rand(0, min(sizeof($chars['P']), $config['captcha_gd_fonts']) -1)], + 'Q' => $chars['Q'][mt_rand(0, min(sizeof($chars['Q']), $config['captcha_gd_fonts']) -1)], + 'R' => $chars['R'][mt_rand(0, min(sizeof($chars['R']), $config['captcha_gd_fonts']) -1)], + 'S' => $chars['S'][mt_rand(0, min(sizeof($chars['S']), $config['captcha_gd_fonts']) -1)], + 'T' => $chars['T'][mt_rand(0, min(sizeof($chars['T']), $config['captcha_gd_fonts']) -1)], + 'U' => $chars['U'][mt_rand(0, min(sizeof($chars['U']), $config['captcha_gd_fonts']) -1)], + 'V' => $chars['V'][mt_rand(0, min(sizeof($chars['V']), $config['captcha_gd_fonts']) -1)], + 'W' => $chars['W'][mt_rand(0, min(sizeof($chars['W']), $config['captcha_gd_fonts']) -1)], + 'X' => $chars['X'][mt_rand(0, min(sizeof($chars['X']), $config['captcha_gd_fonts']) -1)], + 'Y' => $chars['Y'][mt_rand(0, min(sizeof($chars['Y']), $config['captcha_gd_fonts']) -1)], + 'Z' => $chars['Z'][mt_rand(0, min(sizeof($chars['Z']), $config['captcha_gd_fonts']) -1)], + + '1' => array( + array(0,0,0,1,1,0,0,0,0), + array(0,0,1,0,1,0,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,1,1,1,1,1,1,1,0), + ), + '2' => array( // New '2' supplied by Anon + array(0,0,0,1,1,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,1,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,0), + ), + '3' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + '4' => array( + array(0,0,0,0,0,0,1,1,0), + array(0,0,0,0,0,1,0,1,0), + array(0,0,0,0,1,0,0,1,0), + array(0,0,0,1,0,0,0,1,0), + array(0,0,1,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + ), + '5' => array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + '6' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,1,1,1,1,0,0), + array(1,0,1,0,0,0,0,1,0), + array(1,1,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + '7' => array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + ), + '8' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + '9' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,1), + array(0,1,0,0,0,0,1,0,1), + array(0,0,1,1,1,1,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + ), + ) + ); + } +} diff --git a/phpBB/phpbb/captcha/gd_wave.php b/phpBB/phpbb/captcha/gd_wave.php new file mode 100644 index 0000000000..d48fc753a5 --- /dev/null +++ b/phpBB/phpbb/captcha/gd_wave.php @@ -0,0 +1,845 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha; + +/** +* Wave3D CAPTCHA +*/ +class gd_wave +{ + var $width = 360; + var $height = 96; + + function execute($code, $seed) + { + global $starttime; + + // seed the random generator + mt_srand($seed); + + // set height and width + $img_x = $this->width; + $img_y = $this->height; + + // Generate image + $img = imagecreatetruecolor($img_x, $img_y); + $x_grid = mt_rand(6, 10); + $y_grid = mt_rand(6, 10); + + // Ok, so lets cut to the chase. We could accurately represent this in 3d and + // do all the appropriate linear transforms. my questions is... why bother? + // The computational overhead is unnecessary when you consider the simple fact: + // we're not here to accurately represent a model, but to just show off some random-ish + // polygons + + // Conceive of 3 spaces. + // 1) planar-space (discrete "pixel" grid) + // 2) 3-space. (planar-space with z/height aspect) + // 3) image space (pixels on the screen) + // resolution of the planar-space we're embedding the text code in + $plane_x = 100; + $plane_y = 30; + + $subdivision_factor = 3; + + // $box is the 4 points in img_space that correspond to the corners of the plane in 3-space + $box = array( + 'upper_left' => array( + 'x' => mt_rand(5, 15), + 'y' => mt_rand(10, 15) + ), + 'upper_right' => array( + 'x' => mt_rand($img_x - 35, $img_x - 19), + 'y' => mt_rand(10, 17) + ), + 'lower_left' => array( + 'x' => mt_rand($img_x - 45, $img_x - 5), + 'y' => mt_rand($img_y - 15, $img_y - 0), + ), + ); + + $box['lower_right'] = array( + 'x' => $box['lower_left']['x'] + $box['upper_left']['x'] - $box['upper_right']['x'], + 'y' => $box['lower_left']['y'] + $box['upper_left']['y'] - $box['upper_right']['y'], + ); + + // TODO + $background = imagecolorallocate($img, mt_rand(155, 255), mt_rand(155, 255), mt_rand(155, 255)); + imagefill($img, 0, 0, $background); + $black = imagecolorallocate($img, 0, 0, 0); + + $random = array(); + $fontcolors = array(); + + for ($i = 0; $i < 15; ++$i) + { + $random[$i] = imagecolorallocate($img, mt_rand(120, 255), mt_rand(120, 255), mt_rand(120, 255)); + } + + $fontcolors[0] = imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); + + $colors = array(); + + $minr = mt_rand(20, 30); + $ming = mt_rand(20, 30); + $minb = mt_rand(20, 30); + + $maxr = mt_rand(150, 230); + $maxg = mt_rand(150, 230); + $maxb = mt_rand(150, 230); + + for ($i = -30; $i <= 30; ++$i) + { + $coeff1 = ($i + 12) / 45; + $coeff2 = 1 - $coeff1; + $colors[$i] = imagecolorallocate($img, ($coeff2 * $maxr) + ($coeff1 * $minr), ($coeff2 * $maxg) + ($coeff1 * $ming), ($coeff2 * $maxb) + ($coeff1 * $minb)); + } + + // $img_buffer is the last row of 3-space positions (converted to img-space), cached + // (using this means we don't need to recalculate all 4 positions for each new polygon, + // merely the newest point that we're adding, which is then cached. + $img_buffer = array(array(), array()); + + // In image-space, the x- and y-offset necessary to move one unit in the x-direction in planar-space + $dxx = ($box['upper_right']['x'] - $box['upper_left']['x']) / ($subdivision_factor * $plane_x); + $dxy = ($box['upper_right']['y'] - $box['upper_left']['y']) / ($subdivision_factor * $plane_x); + + // In image-space, the x- and y-offset necessary to move one unit in the y-direction in planar-space + $dyx = ($box['lower_right']['x'] - $box['upper_left']['x']) / ($subdivision_factor * $plane_y); + $dyy = ($box['lower_right']['y'] - $box['upper_left']['y']) / ($subdivision_factor * $plane_y); + + // Initial captcha-letter offset in planar-space + $plane_offset_x = mt_rand(3, 8); + $plane_offset_y = mt_rand( 12, 15); + + // character map + $map = $this->captcha_bitmaps(); + + // matrix + $plane = array(); + + // for each character, we'll silkscreen it into our boolean pixel plane + for ($c = 0, $code_num = strlen($code); $c < $code_num; ++$c) + { + $letter = $code[$c]; + + for ($x = $map['width'] - 1; $x >= 0; --$x) + { + for ($y = $map['height'] - 1; $y >= 0; --$y) + { + if ($map['data'][$letter][$y][$x]) + { + $plane[$y + $plane_offset_y + (($c & 1) ? 1 : -1)][$x + $plane_offset_x] = true; + } + } + } + $plane_offset_x += 11; + } + + // calculate our first buffer, we can't actually draw polys with these yet + // img_pos_prev == screen x,y location to our immediate left. + // img_pos_cur == current screen x,y location + // we calculate screen position of our + // current cell based on the difference from the previous cell + // rather than recalculating from absolute coordinates + // What we cache into the $img_buffer contains the raised text coordinates. + $img_pos_prev = $img_buffer[0][0] = array($box['upper_left']['x'], $box['upper_left']['y']); + $cur_height = $prev_height = $this->wave_height(0, 0, $subdivision_factor); + $full_x = $plane_x * $subdivision_factor; + $full_y = $plane_y * $subdivision_factor; + + for ($x = 1; $x <= $full_x; ++$x) + { + $cur_height = $this->wave_height($x, 0, $subdivision_factor); + $offset = $cur_height - $prev_height; + $img_pos_cur = array($img_pos_prev[0] + $dxx, $img_pos_prev[1] + $dxy + $offset); + + $img_buffer[0][$x] = $img_pos_cur; + $img_pos_prev = $img_pos_cur; + $prev_height = $cur_height; + } + + for ($y = 1; $y <= $full_y; ++$y) + { + // swap buffers + $buffer_cur = $y & 1; + $buffer_prev = 1 - $buffer_cur; + + $prev_height = $this->wave_height(0, $y, $subdivision_factor); + $offset = $prev_height - $this->wave_height(0, $y - 1, $subdivision_factor); + $img_pos_cur = array($img_buffer[$buffer_prev][0][0] + $dyx, min($img_buffer[$buffer_prev][0][1] + $dyy + $offset, $img_y - 1)); + + // make sure we don't try to write off the page + $img_pos_prev = $img_pos_cur; + + $img_buffer[$buffer_cur][0] = $img_pos_cur; + + for ($x = 1; $x <= $full_x; ++$x) + { + $cur_height = $this->wave_height($x, $y, $subdivision_factor) + $this->grid_height($x, $y, $x_grid, $y_grid, 1); + + // height is a z-factor, not a y-factor + $offset = $cur_height - $prev_height; + $img_pos_cur = array($img_pos_prev[0] + $dxx, $img_pos_prev[1] + $dxy + $offset); + + // height is float, index it to an int, get closest color + $color = $colors[intval($cur_height)]; + $img_pos_prev = $img_pos_cur; + $prev_height = $cur_height; + + $y_index_old = intval(($y - 1) / $subdivision_factor); + $y_index_new = intval($y / $subdivision_factor); + $x_index_old = intval(($x - 1) / $subdivision_factor); + $x_index_new = intval($x / $subdivision_factor); + + if (!empty($plane[$y_index_new][$x_index_new])) + { + $img_pos_cur[1] += $this->wave_height($x, $y, $subdivision_factor, 1) - 30 - $cur_height; + $color = $colors[20]; + } + $img_pos_cur[1] = min($img_pos_cur[1], $img_y - 1); + $img_buffer[$buffer_cur][$x] = $img_pos_cur; + + // Smooth the edges as much as possible by having not more than one low<->high traingle per square + // Otherwise, just + $diag_down = (empty($plane[$y_index_old][$x_index_old]) == empty($plane[$y_index_new][$x_index_new])); + $diag_up = (empty($plane[$y_index_old][$x_index_new]) == empty($plane[$y_index_new][$x_index_old])); + + // natural switching + $mode = ($x + $y) & 1; + + // override if it requires it + if ($diag_down != $diag_up) + { + $mode = $diag_up; + } + + if ($mode) + { + // +-/ / + // 1 |/ 2 /| + // / /-+ + $poly1 = array_merge($img_buffer[$buffer_cur][$x - 1], $img_buffer[$buffer_prev][$x - 1], $img_buffer[$buffer_prev][$x]); + $poly2 = array_merge($img_buffer[$buffer_cur][$x - 1], $img_buffer[$buffer_cur][$x], $img_buffer[$buffer_prev][$x]); + } + else + { + // \ \-+ + // 1 |\ 2 \| + // +-\ \ + $poly1 = array_merge($img_buffer[$buffer_cur][$x - 1], $img_buffer[$buffer_prev][$x - 1], $img_buffer[$buffer_cur][$x]); + $poly2 = array_merge($img_buffer[$buffer_prev][$x - 1], $img_buffer[$buffer_prev][$x], $img_buffer[$buffer_cur][$x]); + } + + imagefilledpolygon($img, $poly1, 3, $color); + imagefilledpolygon($img, $poly2, 3, $color); + } + } + + // Output image + header('Content-Type: image/png'); + header('Cache-control: no-cache, no-store'); + //$mtime = explode(' ', microtime()); + //$totaltime = $mtime[0] + $mtime[1] - $starttime; + + //echo $totaltime . "<br />\n"; + //echo memory_get_usage() - $tmp; + imagepng($img); + imagedestroy($img); + } + + function wave_height($x, $y, $factor = 1, $tweak = 0.7) + { + // stretch the wave. TODO: pretty it up + $x = $x/5 + 180; + $y = $y/4; + return ((sin($x / (3 * $factor)) + sin($y / (3 * $factor))) * 10 * $tweak); + } + + function grid_height($x, $y, $x_grid, $y_grid, $factor = 1) + { + return ((!($x % ($x_grid * $factor)) || !($y % ($y_grid * $factor))) ? 3 : 0); + } + + function captcha_bitmaps() + { + return array( + 'width' => 9, + 'height' => 13, + 'data' => array( + 'A' => array( + array(0,0,1,1,1,1,0,0,0), + array(0,1,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'B' => array( + array(1,1,1,1,1,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,1,0,0), + array(1,1,1,1,1,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,1,0,0), + array(1,1,1,1,1,1,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'C' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'D' => array( + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'E' => array( + array(0,0,1,1,1,1,1,1,1), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'F' => array( + array(0,0,1,1,1,1,1,1,0), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,1,1,1,1,1,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'G' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'H' => array( + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,1,1,1,1,1,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'I' => array( + array(0,1,1,1,1,1,1,1,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,1,1,1,1,1,1,1,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'J' => array( + array(0,0,0,0,0,0,1,1,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,1,0), + array(0,0,0,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'K' => array( + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,1,0,0,0,0,0), + array(1,0,1,0,0,0,0,0,0), + array(1,1,0,0,0,0,0,0,0), + array(1,0,1,0,0,0,0,0,0), + array(1,0,0,1,0,0,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'L' => array( + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'M' => array( + array(0,1,0,0,0,0,0,1,0), + array(0,1,1,0,0,0,1,1,0), + array(0,1,0,1,0,1,0,1,0), + array(0,1,0,0,1,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'N' => array( + array(1,0,0,0,0,0,0,0,1), + array(1,1,0,0,0,0,0,0,1), + array(1,0,1,0,0,0,0,0,1), + array(1,0,0,1,0,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,0,0,1,0,0,1), + array(1,0,0,0,0,0,1,0,1), + array(1,0,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'O' => array( + array(0,0,0,1,1,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,1,1,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'P' => array( + array(1,1,1,1,1,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,1,0,0), + array(1,1,1,1,1,1,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'Q' => array( + array(0,0,1,1,1,1,0,0,0), + array(0,1,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,1,0,0,1,0), + array(1,0,0,0,0,1,0,1,0), + array(0,1,0,0,0,0,1,0,0), + array(0,0,1,1,1,1,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'R' => array( + array(1,1,1,1,1,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,1,0,0), + array(1,1,1,1,1,1,0,0,0), + array(1,0,1,0,0,0,0,0,0), + array(1,0,0,1,0,0,0,0,0), + array(1,0,0,0,1,0,0,0,0), + array(1,0,0,0,0,1,0,0,0), + array(1,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'S' => array( + array(0,0,1,1,1,1,1,1,1), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(1,1,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'T' => array( + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'U' => array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'V' => array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'W' => array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,1,0,0,0,1), + array(1,0,0,1,0,1,0,0,1), + array(1,0,1,0,0,0,1,0,1), + array(1,1,0,0,0,0,0,1,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'X' => array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'Y' => array( + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,0,0,0,1,0,0), + array(0,0,0,1,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + 'Z' => array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,1), + array(1,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '1' => array( + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,1,0,0,0,0), + array(0,0,1,0,1,0,0,0,0), + array(0,1,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,1,1,1,1,1,1,1,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '2' => array( + array(0,0,0,1,1,1,0,0,0), + array(0,0,1,0,0,0,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,1,0,0,0,0,0), + array(0,0,1,0,0,0,0,0,0), + array(0,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,0,0), + ), + '3' => array( + array(0,0,0,1,1,1,1,0,0), + array(0,0,1,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,1,0), + array(0,0,0,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '4' => array( + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,1,0), + array(0,0,0,0,0,1,0,1,0), + array(0,0,0,0,1,0,0,1,0), + array(0,0,0,1,0,0,0,1,0), + array(0,0,1,0,0,0,0,1,0), + array(0,1,1,1,1,1,1,1,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '5' => array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(0,1,0,0,0,0,0,0,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '6' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,0,0,0,0,0,0), + array(1,0,0,1,1,1,1,0,0), + array(1,0,1,0,0,0,0,1,0), + array(1,1,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '7' => array( + array(1,1,1,1,1,1,1,1,1), + array(1,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,1,0), + array(0,0,0,0,0,0,1,0,0), + array(0,0,0,0,0,1,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,1,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '8' => array( + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,1,0,0,0,0,0,1,0), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(1,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,0), + array(0,0,1,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + '9' => array( + array(0,0,0,1,1,1,1,0,0), + array(0,0,1,0,0,0,0,1,0), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,1,1), + array(0,0,1,1,1,1,1,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,0,0,0,0,0,0,0,1), + array(0,1,0,0,0,0,0,0,1), + array(0,0,1,0,0,0,0,1,0), + array(0,0,0,1,1,1,1,0,0), + array(0,0,0,0,0,0,0,0,0), + array(0,0,0,0,0,0,0,0,0), + ), + ) + ); + } +} diff --git a/phpBB/phpbb/captcha/non_gd.php b/phpBB/phpbb/captcha/non_gd.php new file mode 100644 index 0000000000..3818672f17 --- /dev/null +++ b/phpBB/phpbb/captcha/non_gd.php @@ -0,0 +1,386 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha; + +/** +* Main non-gd captcha class +* @ignore +*/ +class non_gd +{ + var $filtered_pngs; + var $width = 320; + var $height = 50; + + /** + * Define filtered pngs on init + */ + function __construct() + { + // If we can we will generate a single filtered png, we avoid nastiness via emulation of some Zlib stuff + $this->define_filtered_pngs(); + } + + /** + * Create the image containing $code with a seed of $seed + */ + function execute($code, $seed) + { + $img_height = $this->height - 10; + $img_width = 0; + + mt_srand($seed); + + $char_widths = $hold_chars = array(); + $code_len = strlen($code); + + for ($i = 0; $i < $code_len; $i++) + { + $char = $code[$i]; + + $width = mt_rand(0, 4); + $raw_width = $this->filtered_pngs[$char]['width']; + $char_widths[$i] = $width; + $img_width += $raw_width - $width; + + // Split the char into chunks of $raw_width + 1 length + if (empty($hold_chars[$char])) + { + $hold_chars[$char] = str_split(base64_decode($this->filtered_pngs[$char]['data']), $raw_width + 1); + } + } + + $offset_x = mt_rand(0, $this->width - $img_width); + $offset_y = mt_rand(0, $this->height - $img_height); + + $image = ''; + for ($i = 0; $i < $this->height; $i++) + { + $image .= chr(0); + + if ($i > $offset_y && $i < $offset_y + $img_height) + { + for ($j = 0; $j < $offset_x; $j++) + { + $image .= chr(mt_rand(140, 255)); + } + + for ($j = 0; $j < $code_len; $j++) + { + $image .= $this->randomise(substr($hold_chars[$code{$j}][$i - $offset_y - 1], 1), $char_widths[$j]); + } + + for ($j = $offset_x + $img_width; $j < $this->width; $j++) + { + $image .= chr(mt_rand(140, 255)); + } + } + else + { + for ($j = 0; $j < $this->width; $j++) + { + $image .= chr(mt_rand(140, 255)); + } + } + } + unset($hold_chars); + + $image = $this->create_png($image, $this->width, $this->height); + + // Output image + header('Content-Type: image/png'); + header('Cache-control: no-cache, no-store'); + echo $image; + exit; + } + + /** + * This is designed to randomise the pixels of the image data within + * certain limits so as to keep it readable. It also varies the image + * width a little + */ + function randomise($scanline, $width) + { + $new_line = ''; + + $end = strlen($scanline) - ceil($width/2); + for ($i = (int) floor($width / 2); $i < $end; $i++) + { + $pixel = ord($scanline{$i}); + + if ($pixel < 190) + { + $new_line .= chr(mt_rand(0, 205)); + } + else if ($pixel > 190) + { + $new_line .= chr(mt_rand(145, 255)); + } + else + { + $new_line .= $scanline{$i}; + } + } + + return $new_line; + } + + /** + * This creates a chunk of the given type, with the given data + * of the given length adding the relevant crc + */ + function png_chunk($length, $type, $data) + { + $raw = $type . $data; + + return pack('N', $length) . $raw . pack('N', crc32($raw)); + } + + /** + * Creates greyscale 8bit png - The PNG spec can be found at + * http://www.libpng.org/pub/png/spec/PNG-Contents.html we use + * png because it's a fully recognised open standard and supported + * by practically all modern browsers and OSs + */ + function create_png($raw_image, $width, $height) + { + // SIG + $image = pack('C8', 137, 80, 78, 71, 13, 10, 26, 10); + + // IHDR + $raw = pack('N2', $width, $height); + $raw .= pack('C5', 8, 0, 0, 0, 0); + $image .= $this->png_chunk(13, 'IHDR', $raw); + + // IDAT + if (@extension_loaded('zlib')) + { + $raw_image = gzcompress($raw_image); + $length = strlen($raw_image); + } + else + { + // The total length of this image, uncompressed, is just a calculation of pixels + $length = ($width + 1) * $height; + + // Adler-32 hash generation + // Note: The hash is _backwards_ so we must reverse it + + if (@extension_loaded('hash')) + { + $adler_hash = strrev(hash('adler32', $raw_image, true)); + } + else if (@extension_loaded('mhash')) + { + $adler_hash = strrev(mhash(MHASH_ADLER32, $raw_image)); + } + else + { + // Optimized Adler-32 loop ported from the GNU Classpath project + $temp_length = $length; + $s1 = 1; + $s2 = $index = 0; + + while ($temp_length > 0) + { + // We can defer the modulo operation: + // s1 maximally grows from 65521 to 65521 + 255 * 3800 + // s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31 + $substract_value = ($temp_length < 3800) ? $temp_length : 3800; + $temp_length -= $substract_value; + + while (--$substract_value >= 0) + { + $s1 += ord($raw_image[$index]); + $s2 += $s1; + + $index++; + } + + $s1 %= 65521; + $s2 %= 65521; + } + $adler_hash = pack('N', ($s2 << 16) | $s1); + } + + // This is the same thing as gzcompress($raw_image, 0) but does not need zlib + $raw_image = pack('C3v2', 0x78, 0x01, 0x01, $length, ~$length) . $raw_image . $adler_hash; + + // The Zlib header + Adler hash make us add on 11 + $length += 11; + } + + // IDAT + $image .= $this->png_chunk($length, 'IDAT', $raw_image); + + // IEND + $image .= $this->png_chunk(0, 'IEND', ''); + + return $image; + } + + /** + * png image data + * Each 'data' element is base64_encoded uncompressed IDAT + */ + function define_filtered_pngs() + { + $this->filtered_pngs = array( + '0' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A///////////////////olFAkBAAAGDyA4P///M31/////////////wD////////////////0dAgAAAAAAAAAAAAEcPipFGHn////////////AP//////////////6DAAAAAAAAAAAAAAAAAALSEAN+T///////////8A//////////////xAAAAAAAAAAAAAAAAAAAAAACPA/////////////wD/////////////oAAAAAAAAAAAAAAAAAAAAAAAev//////////////AP////////////8oAAAAAAAAPNj/zDAAAAAAAABD//////////////8A////////////1AAAAAAAABjw////5BAAAAAAAADo/////////////wD///////////+QAAAAAAAAbP//////QgAAAAAAAKj/////////////AP///////////1wAAAAAAACs/////8AXAAAAAAAAcP////////////8A////////////OAAAAAAAAND////dNwAAAAAAAABI/////////////wD///////////8gAAAAAAAA4P//7koACwAAAAAAACT/////////////AP///////////wgAAAAAAAD///VqAwaPAAAAAAAAEP////////////8A////////////AAAAAAAAAP/8kQYDavUAAAAAAAAA/////////////wD///////////8AAAAAAAAA/6kNAEru/wAAAAAAAAD/////////////AP///////////wAAAAAAAADAIwA33f//AAAAAAAAAP////////////8A////////////FAAAAAAAADYAI8D///8AAAAAAAAQ/////////////wD///////////8kAAAAAAAAAA2p////5AAAAAAAACD/////////////AP///////////0gAAAAAAAAFkfz////UAAAAAAAAQP////////////8A////////////cAAAAAAAAET1/////7AAAAAAAABo/////////////wD///////////+oAAAAAAAAXfX/////sAAAAAAAAGj/////////////AAAAALgAAAAAAAAwAAAAAAAAAAAAAAD////////////oAAAAAAAACOT////oEAAAAAAAAOD/////////////AP////////////8+AAAAAAAAKMz/zDQAAAAAAAA0//////////////8A////////////7jgAAAAAAAAAAAAAAAAAAAAAAKT//////////////wD///////////VqAwIAAAAAAAAAAAAAAAAAAAA8////////////////AP//////////rQcDaVEAAAAAAAAAAAAAAAAAKOj///////////////8A///////////nblnu/IAIAAAAAAAAAAAAAFzw/////////////////wD////////////79////+iITCAAAAAgSITg////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////w==', + 'width' => 40 + ), + '1' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////8BAAAAAAAP//////////////////AP////////////////////////9sAAAAAAAA//////////////////8A////////////////////////pAAAAAAAAAD//////////////////wD//////////////////////6wEAAAAAAAAAP//////////////////AP////////////////////h4AAAAAAAAAAAA//////////////////8A//////////////////ygJAAAAAAAAAAAAAD//////////////////wD//////////////9x8HAAAAAAAAAAAAAAAAP//////////////////AP//////////////AAAAAAAAAAAAAAAAAAAA//////////////////8A//////////////8AAAAAAAAAAAAAAAAAAAD//////////////////wD//////////////wAAAAAAAAR4AAAAAAAAAP//////////////////AP//////////////AAAAAAA4zP8AAAAAAAAA//////////////////8A//////////////8AAAA4sP///wAAAAAAAAD//////////////////wD//////////////yR80P//////AAAAAAAAAP//////////////////AP////////////////////////8AAAAAAAAA//////////////////8A/////////////////////////wAAAAAAAAD//////////////////wD/////////////////////////AAAAAAAAAP//////////////////AP////////////////////////8AAAAAAAAA//////////////////8A/////////////////////////wAAAAAAAAD//////////////////wD/////////////////////////AAAAAAAAAP//////////////////AP////////////////////////8AAAAAAAAA//////////////////8A/////////////////////////wAAAAAAAAD//////////////////wD/////////////////////////AAAAAAAAAP//////////////////AP////////////////////////8AAAAAAAAA//////////////////8A/////////////////////////wAAAAAAAAD//////////////////wD/////////////////////////AAAAAAAAAP//////////////////AP////////////////////////8AAAAAAAAA//////////////////8A/////////////////////////wAAAAAAAAD//////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '2' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP/////////////////okFAkCAAABCBIfNT///////////////////8A///////////////8hAgAAAAAAAAAAAAAAFTo/////////////////wD//////////////1QAAAAAAAAAAAAAAAAAACjo////////////////AP////////////+MAAAAAAAAAAAAAAAAAAAAADj///////////////8A////////////9BAAAAAAAAAAAAAAAAAAAAAAALD//////////////wD///////////+gAAAAAAAAAHjs+KwMAAAAAAAAVP//////////////AP///////////1gAAAAAAABM/////6QAAAAAAAAU//////////////8A////////////KAAAAAAAALj/////+AAAAAAAAAD//////////////wD///////////+MfGBMOCAI8P/////wAAAAAAAACP//////////////AP///////////////////////////5wAAAAAAAAw//////////////8A///////////////////////////oFAAAAAAAAHz//////////////wD/////////////////////////6CgAAAAAAAAE3P//////////////AP///////////////////////9ggAAAAAAAAAHT///////////////8A//////////////////////+0DAAAAAAAAAA8+P///////////////wD/////////////////////gAAAAAAAAAAAKOj/////////////////AP//////////////////9FAAAAAAAAAAADzw//////////////////8A/////////////////+g4AAAAAAAAAABk/P///////////////////wD////////////////oKAAAAAAAAAAMqP//////////////////////AP//////////////6CgAAAAAAAAAMNz///////////////////////8A//////////////g4AAAAAAAAAFT0/////////////////////////wD/////////////bAAAAAAAAABU/P//////////////////////////AP///////////8wAAAAAAAAAAAAAAAAAAAAAAAAA//////////////8A////////////SAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////9wAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////hAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////8A//////////9AAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////xAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '3' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD////////////////8sGg0FAAAACA4cLz8////////////////////AP//////////////rBgAAAAAAAAAAAAAACTA//////////////////8A/////////////3QAAAAAAAAAAAAAAAAAAASs/////////////////wD///////////+YAAAAAAAAAAAAAAAAAAAAAAjc////////////////AP//////////6AwAAAAAAAAAAAAAAAAAAAAAAGT///////////////8A//////////94AAAAAAAABJDw/8g4AAAAAAAAHP///////////////wD//////////yAAAAAAAACE/////9gAAAAAAAAA////////////////AP///////////NSwiGQ4FOT//////AAAAAAAABD///////////////8A//////////////////////////+YAAAAAAAAVP///////////////wD//////////////////////P/ggAQAAAAAAATM////////////////AP////////////////////9gAAAAAAAAAAAElP////////////////8A/////////////////////0AAAAAAAAAAHLj//////////////////wD/////////////////////OAAAAAAAAAAwkPj/////////////////AP////////////////////8gAAAAAAAAAAAAINj///////////////8A/////////////////////xAAAAAAAAAAAAAAIPD//////////////wD/////////////////////uOz/4HgEAAAAAAAAhP//////////////AP///////////////////////////3wAAAAAAAAw//////////////8A////////////////////////////6AAAAAAAAAj//////////////wD/////////////////////////////AAAAAAAAAP//////////////AP//////////tJh8YEQoDNz//////+AAAAAAAAAY//////////////8A//////////88AAAAAAAAaP//////dAAAAAAAAEz//////////////wD//////////6QAAAAAAAAAdOD/5HQAAAAAAAAApP//////////////AP///////////CgAAAAAAAAAAAAAAAAAAAAAACD4//////////////8A////////////yAQAAAAAAAAAAAAAAAAAAAAEuP///////////////wD/////////////rAQAAAAAAAAAAAAAAAAABJD/////////////////AP//////////////zDQAAAAAAAAAAAAAACTA//////////////////8A/////////////////8BwOCAAAAAUNGi0/P///////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '4' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP//////////////////////////nAAAAAAAAAD///////////////8A/////////////////////////8AEAAAAAAAAAP///////////////wD////////////////////////gGAAAAAAAAAAA////////////////AP//////////////////////9DAAAAAAAAAAAAD///////////////8A//////////////////////9UAAAAAAAAAAAAAP///////////////wD/////////////////////hAAAAAAAAAAAAAAA////////////////AP///////////////////7QAAAAAAAAAAAAAAAD///////////////8A///////////////////UDAAAAAAUAAAAAAAAAP///////////////wD/////////////////7CQAAAAABMAAAAAAAAAA////////////////AP////////////////xEAAAAAACU/wAAAAAAAAD///////////////8A////////////////cAAAAAAAZP//AAAAAAAAAP///////////////wD//////////////6AAAAAAADz8//8AAAAAAAAA////////////////AP/////////////IBAAAAAAc6P///wAAAAAAAAD///////////////8A////////////5BgAAAAADMz/////AAAAAAAAAP///////////////wD///////////g0AAAAAACk//////8AAAAAAAAA////////////////AP//////////XAAAAAAAfP///////wAAAAAAAAD///////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////8A////////////////////////////AAAAAAAAAP///////////////wD///////////////////////////8AAAAAAAAA////////////////AP///////////////////////////wAAAAAAAAD///////////////8A////////////////////////////AAAAAAAAAP///////////////wD///////////////////////////8AAAAAAAAA////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '5' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP//////////////8AAAAAAAAAAAAAAAAAAAAAAA//////////////8A///////////////MAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////////6wAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////////iAAAAAAAAAAAAAAAAAAAAAAA//////////////8A//////////////9kAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////////0QAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////////IAAAAAAAYP////////////////////////////8A//////////////wAAAAAAAB8/////////////////////////////wD/////////////3AAAAAAAAIj/////////////////////////////AP////////////+4AAAAAAAAoLRYHAAEKGTE//////////////////8A/////////////5QAAAAAAAAQAAAAAAAAAABY9P///////////////wD/////////////dAAAAAAAAAAAAAAAAAAAAAA89P//////////////AP////////////9QAAAAAAAAAAAAAAAAAAAAAABg//////////////8A/////////////zAAAAAAAAAAAAAAAAAAAAAAAADQ/////////////wD/////////////IAAAAAAAAGjY/+h4BAAAAAAAAGz/////////////AP//////////////9NS0lHSc//////90AAAAAAAALP////////////8A/////////////////////////////9QAAAAAAAAE/////////////wD//////////////////////////////wAAAAAAAAD/////////////AP/////////////////////////////8AAAAAAAAEP////////////8A////////////pIRwWEAgDOD//////8wAAAAAAAA8/////////////wD///////////9EAAAAAAAAaP//////ZAAAAAAAAHz/////////////AP///////////6QAAAAAAAAAaOD/4GQAAAAAAAAE4P////////////8A/////////////CQAAAAAAAAAAAAAAAAAAAAAAGD//////////////wD/////////////yAQAAAAAAAAAAAAAAAAAAAAc7P//////////////AP//////////////rAwAAAAAAAAAAAAAAAAAGNj///////////////8A////////////////0EAAAAAAAAAAAAAAAFTo/////////////////wD//////////////////8h4QCAAAAAcQHzU////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '6' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD///////////////////+0ZCwMAAAUNGjI////////////////////AP/////////////////EMAAAAAAAAAAAAABM6P////////////////8A////////////////lAQAAAAAAAAAAAAAAAAo6P///////////////wD//////////////6wAAAAAAAAAAAAAAAAAAABI////////////////AP/////////////oEAAAAAAAAAAAAAAAAAAAAACw//////////////8A/////////////3AAAAAAAAAoxP/YPAAAAAAAAEj//////////////wD////////////4EAAAAAAACOD////YDCBAVGiAoP//////////////AP///////////7gAAAAAAABY//////////////////////////////8A////////////eAAAAAAAAJT//////////////////////////////wD///////////9MAAAAAAAAvP/IXBgABCx03P//////////////////AP///////////ygAAAAAAADcdAAAAAAAAAAEiP////////////////8A////////////FAAAAAAAAFAAAAAAAAAAAAAAcP///////////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAlP//////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAQ8P////////////8A////////////AAAAAAAAAABAyP/kZAAAAAAAAACQ/////////////wD///////////8MAAAAAAAALPj/////WAAAAAAAAET/////////////AP///////////yQAAAAAAACY///////MAAAAAAAAFP////////////8A////////////SAAAAAAAAMD///////wAAAAAAAAA/////////////wD///////////9wAAAAAAAAvP///////wAAAAAAAAD/////////////AP///////////7QAAAAAAACI///////UAAAAAAAAJP////////////8A////////////+AwAAAAAACDw/////2wAAAAAAABY/////////////wD/////////////cAAAAAAAADC8/Ox4AAAAAAAAAKj/////////////AP/////////////oEAAAAAAAAAAAAAAAAAAAAAAk/P////////////8A//////////////+oAAAAAAAAAAAAAAAAAAAABLj//////////////wD///////////////+QAAAAAAAAAAAAAAAAAACQ////////////////AP////////////////+0JAAAAAAAAAAAAAAkuP////////////////8A///////////////////8sGg0FAAADCxgqPz//////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '7' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAABP////////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAAAy4/////////////wD//////////////////////////+QUAAAAAAAEuP//////////////AP/////////////////////////8QAAAAAAAAKT///////////////8A/////////////////////////4wAAAAAAAB0/////////////////wD////////////////////////cCAAAAAAANPz/////////////////AP///////////////////////0QAAAAAAATY//////////////////8A//////////////////////+0AAAAAAAAeP///////////////////wD//////////////////////CQAAAAAABTw////////////////////AP////////////////////+gAAAAAAAAkP////////////////////8A/////////////////////ywAAAAAABDw/////////////////////wD///////////////////+4AAAAAAAAbP//////////////////////AP///////////////////1wAAAAAAADQ//////////////////////8A///////////////////4DAAAAAAAMP///////////////////////wD//////////////////7QAAAAAAAB8////////////////////////AP//////////////////aAAAAAAAAMj///////////////////////8A//////////////////8oAAAAAAAM/P///////////////////////wD/////////////////8AAAAAAAAET/////////////////////////AP////////////////+0AAAAAAAAcP////////////////////////8A/////////////////4wAAAAAAACY/////////////////////////wD/////////////////WAAAAAAAAMD/////////////////////////AP////////////////80AAAAAAAA4P////////////////////////8A/////////////////xAAAAAAAAD4/////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '8' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD////////////////////IdDQUAAAEIEiA1P//////////////////AP/////////////////gRAAAAAAAAAAAAAAAROD///////////////8A////////////////0BgAAAAAAAAAAAAAAAAAEMj//////////////wD///////////////AcAAAAAAAAAAAAAAAAAAAAHPD/////////////AP//////////////hAAAAAAAAAAAAAAAAAAAAAAAhP////////////8A//////////////8sAAAAAAAAKMz/zCgAAAAAAAAs/////////////wD//////////////wAAAAAAAADM////zAAAAAAAAAD/////////////AP//////////////BAAAAAAAAP//////AAAAAAAABP////////////8A//////////////8sAAAAAAAAzP///9QAAAAAAAAw/////////////wD//////////////3wAAAAAAAAoyP/YNAAAAAAAAIT/////////////AP//////////////7BgAAAAAAAAAAAAAAAAAAAAc8P////////////8A////////////////xBgAAAAAAAAAAAAAAAAAGNj//////////////wD/////////////////tAQAAAAAAAAAAAAAAACo////////////////AP///////////////HAAAAAAAAAAAAAAAAAAAAB8//////////////8A//////////////9gAAAAAAAAAAAAAAAAAAAAAAB8/////////////wD/////////////wAAAAAAAAABk4P/UWAAAAAAAAATQ////////////AP////////////9UAAAAAAAAaP//////XAAAAAAAAGT///////////8A/////////////xgAAAAAAADg///////cAAAAAAAAJP///////////wD/////////////AAAAAAAAAP////////8AAAAAAAAA////////////AP////////////8AAAAAAAAA4P//////3AAAAAAAAAT///////////8A/////////////ygAAAAAAABg//////9cAAAAAAAALP///////////wD/////////////ZAAAAAAAAABY1P/cXAAAAAAAAABw////////////AP/////////////QAAAAAAAAAAAAAAAAAAAAAAAABNz///////////8A//////////////9gAAAAAAAAAAAAAAAAAAAAAAB0/////////////wD///////////////Q8AAAAAAAAAAAAAAAAAAAAUPz/////////////AP////////////////x4CAAAAAAAAAAAAAAAEIT8//////////////8A///////////////////smFQwGAAAABg0ZKT0/////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + '9' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD///////////////////ysYCwMAAAUNGiw/P//////////////////AP////////////////+4JAAAAAAAAAAAAAAkuP////////////////8A////////////////lAQAAAAAAAAAAAAAAAAAkP///////////////wD//////////////8AEAAAAAAAAAAAAAAAAAAAAqP//////////////AP/////////////8JAAAAAAAAAAAAAAAAAAAAAAQ7P////////////8A/////////////6wAAAAAAAAAfOz8vCwAAAAAAABw/////////////wD/////////////WAAAAAAAAHD/////7BgAAAAAAAz4////////////AP////////////8kAAAAAAAA1P//////hAAAAAAAALT///////////8A/////////////wAAAAAAAAD///////+4AAAAAAAAcP///////////wD/////////////AAAAAAAAAPz//////8AAAAAAAABI////////////AP////////////8UAAAAAAAAzP//////lAAAAAAAACT///////////8A/////////////0QAAAAAAABY//////gsAAAAAAAADP///////////wD/////////////kAAAAAAAAABw5P/IPAAAAAAAAAAA////////////AP/////////////wEAAAAAAAAAAAAAAAAAAAAAAAAAD///////////8A//////////////+UAAAAAAAAAAAAAAAAAAAAAAAAAP///////////wD///////////////9wAAAAAAAAAAAAAFAAAAAAAAAU////////////AP////////////////+IBAAAAAAAAABw3AAAAAAAACj///////////8A///////////////////cdCwEABhcxP+8AAAAAAAATP///////////wD//////////////////////////////5AAAAAAAAB4////////////AP//////////////////////////////UAAAAAAAALj///////////8A//////////////+kgGxUQCAM2P///+AIAAAAAAAQ+P///////////wD//////////////0gAAAAAAAA42P/EKAAAAAAAAHD/////////////AP//////////////sAAAAAAAAAAAAAAAAAAAAAAQ6P////////////8A////////////////TAAAAAAAAAAAAAAAAAAAAKz//////////////wD////////////////oKAAAAAAAAAAAAAAAAASU////////////////AP/////////////////sUAAAAAAAAAAAAAAwxP////////////////8A////////////////////yHA0FAAADCxktP///////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'A' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD//////////////////+QAAAAAAAAAAAAAAOT/////////////////AP//////////////////kAAAAAAAAAAAAAAAkP////////////////8A//////////////////88AAAAAAAAAAAAAAA8/////////////////wD/////////////////5AAAAAAAAAAAAAAAAADk////////////////AP////////////////+QAAAAAAAAAAAAAAAAAJD///////////////8A/////////////////zwAAAAAAAAAAAAAAAAAPP///////////////wD////////////////kAAAAAAAAAAgAAAAAAAAA5P//////////////AP///////////////5AAAAAAAAAAgAAAAAAAAACQ//////////////8A////////////////PAAAAAAAAAz8HAAAAAAAADz//////////////wD//////////////+QAAAAAAAAAWP9kAAAAAAAAANz/////////////AP//////////////kAAAAAAAAACk/7wAAAAAAAAAhP////////////8A//////////////88AAAAAAAABOz//BQAAAAAAAAw/////////////wD/////////////4AAAAAAAAAA8////ZAAAAAAAAADc////////////AP////////////+EAAAAAAAAAIj///+8AAAAAAAAAIT///////////8A/////////////zAAAAAAAAAA2P////wQAAAAAAAAMP///////////wD////////////cAAAAAAAAACT//////1wAAAAAAAAA3P//////////AP///////////4QAAAAAAAAAAAAAAAAAAAAAAAAAAACE//////////8A////////////MAAAAAAAAAAAAAAAAAAAAAAAAAAAADD//////////wD//////////9wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANz/////////AP//////////hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhP////////8A//////////8wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAw/////////wD/////////3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADc////////AP////////+EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIT///////8A/////////zAAAAAAAAAAhP///////////2QAAAAAAAAAMP///////wD////////cAAAAAAAAAADM////////////vAAAAAAAAAAA3P//////AP///////4QAAAAAAAAAHP/////////////4DAAAAAAAAACE//////8A////////MAAAAAAAAABk//////////////9cAAAAAAAAADD//////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'B' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAEDh83P///////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAEhP//////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAeP////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAxP///////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAABY////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAABT///////////8A//////////8AAAAAAAAAAP/////4zEwAAAAAAAAAAP///////////wD//////////wAAAAAAAAAA////////7AAAAAAAAAAQ////////////AP//////////AAAAAAAAAAD////////sAAAAAAAAAEj///////////8A//////////8AAAAAAAAAAP/////4zEQAAAAAAAAAtP///////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAFz/////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAiA/P////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAIjPj//////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAGKz/////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAJT///////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAABNz//////////wD//////////wAAAAAAAAAA///////sqCAAAAAAAAAAbP//////////AP//////////AAAAAAAAAAD/////////yAAAAAAAAAAs//////////8A//////////8AAAAAAAAAAP//////////AAAAAAAAAAT//////////wD//////////wAAAAAAAAAA/////////7wAAAAAAAAAAP//////////AP//////////AAAAAAAAAAD//////+ikGAAAAAAAAAAY//////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFT//////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsP//////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAADj///////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAc6P///////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAATOj/////////////AP//////////AAAAAAAAAAAAAAAAAAAEIEBkkNj///////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'C' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP//////////////////5JRULBAAAAgkTIDQ//////////////////8A////////////////1FAAAAAAAAAAAAAAAABAyP///////////////wD//////////////4gEAAAAAAAAAAAAAAAAAAAElP//////////////AP////////////9wAAAAAAAAAAAAAAAAAAAAAAAAlP////////////8A////////////kAAAAAAAAAAAAAAAAAAAAAAAAAAEyP///////////wD//////////9wIAAAAAAAAAAAAAAAAAAAAAAAAAAAw////////////AP//////////WAAAAAAAAAAAWMz/8JwQAAAAAAAAAACw//////////8A/////////+wEAAAAAAAAAID//////9QMAAAAAAAAAET//////////wD/////////nAAAAAAAAAAo/P///////3wAAAAABDBspP//////////AP////////9gAAAAAAAAAIz/////////3BxQjMT0//////////////8A/////////zQAAAAAAAAAzP///////////////////////////////wD/////////GAAAAAAAAADo////////////////////////////////AP////////8AAAAAAAAAAP////////////////////////////////8A/////////wAAAAAAAAAA/////////////////////////////////wD/////////AAAAAAAAAAD/////////////////////////////////AP////////8cAAAAAAAAAOj///////////////////////////////8A/////////zgAAAAAAAAA0P/////////kIGio7P///////////////wD/////////bAAAAAAAAACg/////////5wAAAAAMHS49P//////////AP////////+oAAAAAAAAAEz/////////PAAAAAAAAAAc//////////8A//////////QIAAAAAAAAALz//////6QAAAAAAAAAAGT//////////wD//////////3AAAAAAAAAADIzo/+SEBAAAAAAAAAAAyP//////////AP//////////7BAAAAAAAAAAAAAAAAAAAAAAAAAAAED///////////8A////////////rAAAAAAAAAAAAAAAAAAAAAAAAAAE0P///////////wD/////////////fAAAAAAAAAAAAAAAAAAAAAAAAJz/////////////AP//////////////iAQAAAAAAAAAAAAAAAAAAASY//////////////8A////////////////yEAAAAAAAAAAAAAAAAA8yP///////////////wD//////////////////9yIUCwQAAAAIEB4yP//////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'D' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD///////////8AAAAAAAAAAAAAAAAADChQkOT/////////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAABGjw//////////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAACDY/////////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAABjk////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAED///////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAKj//////////wD///////////8AAAAAAAAAAP///+isSAAAAAAAAAAANP//////////AP///////////wAAAAAAAAAA////////hAAAAAAAAAAA2P////////8A////////////AAAAAAAAAAD/////////MAAAAAAAAACQ/////////wD///////////8AAAAAAAAAAP////////+MAAAAAAAAAFj/////////AP///////////wAAAAAAAAAA/////////8gAAAAAAAAAMP////////8A////////////AAAAAAAAAAD/////////5AAAAAAAAAAY/////////wD///////////8AAAAAAAAAAP//////////AAAAAAAAAAD/////////AP///////////wAAAAAAAAAA//////////8AAAAAAAAAAP////////8A////////////AAAAAAAAAAD//////////wAAAAAAAAAA/////////wD///////////8AAAAAAAAAAP/////////wAAAAAAAAABD/////////AP///////////wAAAAAAAAAA/////////9QAAAAAAAAAJP////////8A////////////AAAAAAAAAAD/////////qAAAAAAAAABI/////////wD///////////8AAAAAAAAAAP////////9QAAAAAAAAAHj/////////AP///////////wAAAAAAAAAA////////uAAAAAAAAAAAvP////////8A////////////AAAAAAAAAAD////w0HwEAAAAAAAAACT8/////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAoP//////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAAADz8//////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAY6P///////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAKNz/////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAACHT0//////////////8A////////////AAAAAAAAAAAAAAAAABg4bKj0/////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'E' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP//////////AAAAAAAAAAD///////////////////////////////8A//////////8AAAAAAAAAAP///////////////////////////////wD//////////wAAAAAAAAAA////////////////////////////////AP//////////AAAAAAAAAAD///////////////////////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////8A//////////8AAAAAAAAAAP///////////////////////////////wD//////////wAAAAAAAAAA////////////////////////////////AP//////////AAAAAAAAAAD///////////////////////////////8A//////////8AAAAAAAAAAP///////////////////////////////wD//////////wAAAAAAAAAA////////////////////////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'F' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAP///////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAP///////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'G' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD//////////////////MB8TCgQAAAACCA4YJzs////////////////AP///////////////JQcAAAAAAAAAAAAAAAAAAhw8P////////////8A/////////////9gwAAAAAAAAAAAAAAAAAAAAAAAk2P///////////wD////////////EDAAAAAAAAAAAAAAAAAAAAAAAAAAc7P//////////AP//////////2AwAAAAAAAAAAAAAAAAAAAAAAAAAAABY//////////8A//////////wwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADQ/////////wD/////////kAAAAAAAAAAAEHzQ/P/gmCAAAAAAAAAAAFz/////////AP////////wcAAAAAAAAACjg////////8CwAAAAAAAAgWP////////8A////////vAAAAAAAAAAI2P//////////yBRAcJjI8P///////////wD///////94AAAAAAAAAGD/////////////////////////////////AP///////0AAAAAAAAAAsP////////////////////////////////8A////////IAAAAAAAAADc/////////////////////////////////wD///////8AAAAAAAAAAP///////wAAAAAAAAAAAAAAAAD/////////AP///////wAAAAAAAAAA////////AAAAAAAAAAAAAAAAAP////////8A////////AAAAAAAAAAD///////8AAAAAAAAAAAAAAAAA/////////wD///////8gAAAAAAAAAOD//////wAAAAAAAAAAAAAAAAD/////////AP///////0AAAAAAAAAAtP//////AAAAAAAAAAAAAAAAAP////////8A////////cAAAAAAAAABw//////8AAAAAAAAAAAAAAAAA/////////wD///////+8AAAAAAAAABDs////////////AAAAAAAAAAD/////////AP////////wYAAAAAAAAADz0//////////AAAAAAAAAAAP////////8A/////////5AAAAAAAAAAACCY4P//3KhcCAAAAAAAAAAA/////////wD/////////+CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////AP//////////xAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIP////////8A////////////rAQAAAAAAAAAAAAAAAAAAAAAAAAAAGTw/////////wD/////////////vBQAAAAAAAAAAAAAAAAAAAAAADjI////////////AP//////////////8HAQAAAAAAAAAAAAAAAAAEiw//////////////8A//////////////////iwcEAgBAAABCA4aKDk/////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'H' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'I' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAP///////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAP///////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAP///////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAP///////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAA////////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAD///////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'J' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP///////////////////////////wAAAAAAAAAA//////////////8A////////////////////////////AAAAAAAAAAD//////////////wD///////////////////////////8AAAAAAAAAAP//////////////AP///////////////////////////wAAAAAAAAAA//////////////8A////////////////////////////AAAAAAAAAAD//////////////wD///////////////////////////8AAAAAAAAAAP//////////////AP///////////////////////////wAAAAAAAAAA//////////////8A////////////////////////////AAAAAAAAAAD//////////////wD///////////////////////////8AAAAAAAAAAP//////////////AP///////////////////////////wAAAAAAAAAA//////////////8A////////////////////////////AAAAAAAAAAD//////////////wD///////////////////////////8AAAAAAAAAAP//////////////AP///////////////////////////wAAAAAAAAAA//////////////8A////////////////////////////AAAAAAAAAAD//////////////wD///////////////////////////8AAAAAAAAAAP//////////////AP///////////////////////////wAAAAAAAAAA//////////////8A////////////////////////////AAAAAAAAAAj//////////////wD//////////+zMrIxwUDAQ//////wAAAAAAAAAIP//////////////AP//////////DAAAAAAAAADo////2AAAAAAAAAA0//////////////8A//////////8wAAAAAAAAAKj///+YAAAAAAAAAFj//////////////wD//////////2gAAAAAAAAAIND/yBgAAAAAAAAAkP//////////////AP//////////vAAAAAAAAAAAAAAAAAAAAAAAAADc//////////////8A////////////MAAAAAAAAAAAAAAAAAAAAAAAUP///////////////wD////////////EBAAAAAAAAAAAAAAAAAAAABjk////////////////AP////////////+sBAAAAAAAAAAAAAAAAAAY2P////////////////8A///////////////EMAAAAAAAAAAAAAAAVOj//////////////////wD/////////////////vHBAIAAAABg8fNT/////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'K' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD///////8AAAAAAAAAAP//////////wAQAAAAAAAAAAABw////////AP///////wAAAAAAAAAA/////////9AMAAAAAAAAAAAAcP////////8A////////AAAAAAAAAAD////////cGAAAAAAAAAAAAHD//////////wD///////8AAAAAAAAAAP//////6CgAAAAAAAAAAABs////////////AP///////wAAAAAAAAAA//////Q0AAAAAAAAAAAAVPz///////////8A////////AAAAAAAAAAD////8RAAAAAAAAAAAAFT8/////////////wD///////8AAAAAAAAAAP///1gAAAAAAAAAAABU/P//////////////AP///////wAAAAAAAAAA//9wAAAAAAAAAAAASPz///////////////8A////////AAAAAAAAAAD/jAAAAAAAAAAAADz0/////////////////wD///////8AAAAAAAAAAKQAAAAAAAAAAAA89P//////////////////AP///////wAAAAAAAAAABAAAAAAAAAAAFPT///////////////////8A////////AAAAAAAAAAAAAAAAAAAAAAAApP///////////////////wD///////8AAAAAAAAAAAAAAAAAAAAAAAAU8P//////////////////AP///////wAAAAAAAAAAAAAAAAAAAAAAAABk//////////////////8A////////AAAAAAAAAAAAAAAAAAAAAAAAAADE/////////////////wD///////8AAAAAAAAAAAAAAAAoEAAAAAAAACz8////////////////AP///////wAAAAAAAAAAAAAAGNiAAAAAAAAAAIj///////////////8A////////AAAAAAAAAAAAABjY//gYAAAAAAAACOD//////////////wD///////8AAAAAAAAAAAAY2P///5wAAAAAAAAASP//////////////AP///////wAAAAAAAAAAGNj//////CgAAAAAAAAAqP////////////8A////////AAAAAAAAAADI////////sAAAAAAAAAAc8P///////////wD///////8AAAAAAAAAAP//////////QAAAAAAAAABs////////////AP///////wAAAAAAAAAA///////////IAAAAAAAAAATI//////////8A////////AAAAAAAAAAD///////////9YAAAAAAAAADD8/////////wD///////8AAAAAAAAAAP///////////9wEAAAAAAAAAJD/////////AP///////wAAAAAAAAAA/////////////3AAAAAAAAAADOT///////8A////////AAAAAAAAAAD/////////////7BAAAAAAAAAAUP///////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'L' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAD/////////////////////////////AP////////////8AAAAAAAAAAP////////////////////////////8A/////////////wAAAAAAAAAA/////////////////////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A/////////////wAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD/////////////AAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'M' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A//////8AAAAAAAAAAAAAAHz//////3wAAAAAAAAAAAAAAP///////wD//////wAAAAAAAAAAAAAATP//////UAAAAAAAAAAAAAAA////////AP//////AAAAAAAAAAAAAAAc//////8cAAAAAAAAAAAAAAD///////8A//////8AAAAAAAAAAAAAAADw////8AAAAAAAAAAAAAAAAP///////wD//////wAAAAAAAAAAAAAAALz////AAAAAAAAAAAAAAAAA////////AP//////AAAAAAAAAAAAAAAAkP///5AAAAAAAAAAAAAAAAD///////8A//////8AAAAAAAAAAAAAAABc////ZAAAAAAAAAAAAAAAAP///////wD//////wAAAAAAAAAoAAAAADD///8wAAAAACQAAAAAAAAA////////AP//////AAAAAAAAAFwAAAAABPz//AgAAAAAXAAAAAAAAAD///////8A//////8AAAAAAAAAkAAAAAAA0P/UAAAAAACQAAAAAAAAAP///////wD//////wAAAAAAAADMAAAAAACg/6gAAAAAAMQAAAAAAAAA////////AP//////AAAAAAAAAPgEAAAAAHD/dAAAAAAE+AAAAAAAAAD///////8A//////8AAAAAAAAA/zQAAAAAQP9IAAAAADD/AAAAAAAAAP///////wD//////wAAAAAAAAD/bAAAAAAQ/xQAAAAAaP8AAAAAAAAA////////AP//////AAAAAAAAAP+gAAAAAADQAAAAAACc/wAAAAAAAAD///////8A//////8AAAAAAAAA/9QAAAAAAGgAAAAAAND/AAAAAAAAAP///////wD//////wAAAAAAAAD//wwAAAAAFAAAAAAM/P8AAAAAAAAA////////AP//////AAAAAAAAAP//RAAAAAAAAAAAADz//wAAAAAAAAD///////8A//////8AAAAAAAAA//94AAAAAAAAAAAAcP//AAAAAAAAAP///////wD//////wAAAAAAAAD//7AAAAAAAAAAAACo//8AAAAAAAAA////////AP//////AAAAAAAAAP//5AAAAAAAAAAAANz//wAAAAAAAAD///////8A//////8AAAAAAAAA////HAAAAAAAAAAQ////AAAAAAAAAP///////wD//////wAAAAAAAAD///9QAAAAAAAAAEz///8AAAAAAAAA////////AP//////AAAAAAAAAP///4gAAAAAAAAAfP///wAAAAAAAAD///////8A//////8AAAAAAAAA////vAAAAAAAAACw////AAAAAAAAAP///////wD//////wAAAAAAAAD////wAAAAAAAAAOz///8AAAAAAAAA////////AP//////AAAAAAAAAP////8sAAAAAAAc/////wAAAAAAAAD///////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'N' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////AAAAAAAAALD/////////////AAAAAAAAAP//////////AP////////8AAAAAAAAAFOj///////////8AAAAAAAAA//////////8A/////////wAAAAAAAAAASP///////////wAAAAAAAAD//////////wD/////////AAAAAAAAAAAAkP//////////AAAAAAAAAP//////////AP////////8AAAAAAAAAAAAI1P////////8AAAAAAAAA//////////8A/////////wAAAAAAAAAAAAAw+P///////wAAAAAAAAD//////////wD/////////AAAAAAAAAAAAAABw////////AAAAAAAAAP//////////AP////////8AAAAAAAAAAAAAAAC8//////8AAAAAAAAA//////////8A/////////wAAAAAAAAAAAAAAABzs/////wAAAAAAAAD//////////wD/////////AAAAAAAAAAAAAAAAAFD/////AAAAAAAAAP//////////AP////////8AAAAAAAAAAAAAAAAAAJz///8AAAAAAAAA//////////8A/////////wAAAAAAAAAUAAAAAAAADNz//wAAAAAAAAD//////////wD/////////AAAAAAAAALQAAAAAAAAANPz/AAAAAAAAAP//////////AP////////8AAAAAAAAA/2wAAAAAAAAAfP8AAAAAAAAA//////////8A/////////wAAAAAAAAD/+CwAAAAAAAAExAAAAAAAAAD//////////wD/////////AAAAAAAAAP//0AQAAAAAAAAgAAAAAAAAAP//////////AP////////8AAAAAAAAA////jAAAAAAAAAAAAAAAAAAA//////////8A/////////wAAAAAAAAD/////RAAAAAAAAAAAAAAAAAD//////////wD/////////AAAAAAAAAP/////kFAAAAAAAAAAAAAAAAP//////////AP////////8AAAAAAAAA//////+sAAAAAAAAAAAAAAAA//////////8A/////////wAAAAAAAAD///////9kAAAAAAAAAAAAAAD//////////wD/////////AAAAAAAAAP////////QkAAAAAAAAAAAAAP//////////AP////////8AAAAAAAAA/////////8wEAAAAAAAAAAAA//////////8A/////////wAAAAAAAAD//////////4QAAAAAAAAAAAD//////////wD/////////AAAAAAAAAP///////////DwAAAAAAAAAAP//////////AP////////8AAAAAAAAA////////////4BAAAAAAAAAA//////////8A/////////wAAAAAAAAD/////////////qAAAAAAAAAD//////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'O' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A///////////////////0qGw4HAAAABw4aKT0/////////////////wD////////////////wcAwAAAAAAAAAAAAAAAho6P//////////////AP//////////////uBQAAAAAAAAAAAAAAAAAAAAMoP////////////8A/////////////6AEAAAAAAAAAAAAAAAAAAAAAAAAkP///////////wD///////////+4BAAAAAAAAAAAAAAAAAAAAAAAAAAAoP//////////AP//////////8BQAAAAAAAAAAAAAAAAAAAAAAAAAAAAM5P////////8A//////////9wAAAAAAAAAAAsrPD/7KQsAAAAAAAAAABg/////////wD/////////+BAAAAAAAAAAUPj///////hQAAAAAAAAAAjs////////AP////////+sAAAAAAAAABDw//////////AYAAAAAAAAAKD///////8A/////////2wAAAAAAAAAdP///////////3wAAAAAAAAAYP///////wD/////////OAAAAAAAAAC4////////////xAAAAAAAAAAw////////AP////////8cAAAAAAAAAOD////////////oAAAAAAAAABT///////8A/////////wAAAAAAAAAA//////////////8AAAAAAAAAAP///////wD/////////AAAAAAAAAAD//////////////wAAAAAAAAAA////////AP////////8AAAAAAAAAAP/////////////8AAAAAAAAAAD///////8A/////////xwAAAAAAAAA5P///////////+AAAAAAAAAAHP///////wD/////////NAAAAAAAAAC8////////////uAAAAAAAAAA4////////AP////////9oAAAAAAAAAHj///////////98AAAAAAAAAGT///////8A/////////6gAAAAAAAAAGPD/////////+BgAAAAAAAAApP///////wD/////////9AwAAAAAAAAAUPz///////xcAAAAAAAAAAjs////////AP//////////cAAAAAAAAAAALKjs//CwOAAAAAAAAAAAYP////////8A///////////wFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzk/////////wD///////////+4BAAAAAAAAAAAAAAAAAAAAAAAAAAAoP//////////AP////////////+QAAAAAAAAAAAAAAAAAAAAAAAAAJD///////////8A//////////////+sEAAAAAAAAAAAAAAAAAAAAAyg/////////////wD////////////////oZAgAAAAAAAAAAAAAAARg4P//////////////AP//////////////////9KhsOCAAAAAUMFyc7P////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'P' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP///////////wAAAAAAAAAAAAAAAAAACCxguP////////////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAOOD//////////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAGOD/////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAARP////////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAxP///////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAAABo////////////AP///////////wAAAAAAAAAA////6JwMAAAAAAAAADD///////////8A////////////AAAAAAAAAAD//////6AAAAAAAAAADP///////////wD///////////8AAAAAAAAAAP//////9AAAAAAAAAAA////////////AP///////////wAAAAAAAAAA///////0AAAAAAAAAAD///////////8A////////////AAAAAAAAAAD//////5gAAAAAAAAAHP///////////wD///////////8AAAAAAAAAAP///9iICAAAAAAAAABI////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAJD///////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAI6P///////////wD///////////8AAAAAAAAAAAAAAAAAAAAAAAAAAIT/////////////AP///////////wAAAAAAAAAAAAAAAAAAAAAAAABU/P////////////8A////////////AAAAAAAAAAAAAAAAAAAAAAAIhPz//////////////wD///////////8AAAAAAAAAAAAAAAAABCRMkOz/////////////////AP///////////wAAAAAAAAAA//////////////////////////////8A////////////AAAAAAAAAAD//////////////////////////////wD///////////8AAAAAAAAAAP//////////////////////////////AP///////////wAAAAAAAAAA//////////////////////////////8A////////////AAAAAAAAAAD//////////////////////////////wD///////////8AAAAAAAAAAP//////////////////////////////AP///////////wAAAAAAAAAA//////////////////////////////8A////////////AAAAAAAAAAD//////////////////////////////wD///////////8AAAAAAAAAAP//////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'Q' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////SoaDQcAAAAHDhoqPT///////////////////8A//////////////BwDAAAAAAAAAAAAAAACHDo/////////////////wD///////////+4FAAAAAAAAAAAAAAAAAAAABCo////////////////AP//////////nAQAAAAAAAAAAAAAAAAAAAAAAACQ//////////////8A/////////7gEAAAAAAAAAAAAAAAAAAAAAAAAAACg/////////////wD////////wFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzo////////////AP///////3AAAAAAAAAAACyo8P/sqCwAAAAAAAAAAGT///////////8A///////4EAAAAAAAAABM+P///////FQAAAAAAAAACPT//////////wD//////7AAAAAAAAAAFPD/////////9BgAAAAAAAAApP//////////AP//////bAAAAAAAAAB4////////////fAAAAAAAAABk//////////8A//////84AAAAAAAAALz///////////+8AAAAAAAAADT//////////wD//////xwAAAAAAAAA6P///////////+QAAAAAAAAAHP//////////AP//////AAAAAAAAAAD//////////////wAAAAAAAAAA//////////8A//////8AAAAAAAAAAP//////////////AAAAAAAAAAD//////////wD//////wAAAAAAAAAA/P////////////8AAAAAAAAAAP//////////AP//////GAAAAAAAAADg////////////4AAAAAAAAAAc//////////8A//////84AAAAAAAAALT////MJHTo//+8AAAAAAAAADT//////////wD//////2wAAAAAAAAAdP///2AAABCg/3wAAAAAAAAAZP//////////AP//////rAAAAAAAAAAY9P/sCAAAAABMGAAAAAAAAACk//////////8A///////4EAAAAAAAAABU/P+0OAAAAAAAAAAAAAAACPT//////////wD///////94AAAAAAAAAAA4sPD/gAAAAAAAAAAAAABk////////////AP////////AcAAAAAAAAAAAAAAAAAAAAAAAAAAAADOT///////////8A/////////7wEAAAAAAAAAAAAAAAAAAAAAAAAAACQ/////////////wD//////////6wEAAAAAAAAAAAAAAAAAAAAAAAAABSs////////////AP///////////7gUAAAAAAAAAAAAAAAAAAAAAAAAAABAwP////////8A//////////////BwDAAAAAAAAAAAAAAABAgAAAAAAAA8/////////wD////////////////0qGg0GAAAABgwXJjkxBgAAAAAALD/////////AP//////////////////////////////////5DQAAAAk/P////////8A////////////////////////////////////+GwAAJD//////////wD//////////////////////////////////////8A49P//////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'R' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////wAAAAAAAAAAAAAAAAAAAAQgOGSk+P///////////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAcuP//////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAEsP////////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ6P///////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB8////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAADD///////////8A/////////wAAAAAAAAAA///////svDgAAAAAAAAACP///////////wD/////////AAAAAAAAAAD/////////7AAAAAAAAAAA////////////AP////////8AAAAAAAAAAP/////////cAAAAAAAAABD///////////8A/////////wAAAAAAAAAA//////DQoCQAAAAAAAAAQP///////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAACU////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAIPj///////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAzU/////////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAA02P//////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAxctPz///////////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAEDY/////////////////wD/////////AAAAAAAAAAD/9LAsAAAAAAAAAAzc////////////////AP////////8AAAAAAAAAAP///+wkAAAAAAAAADD8//////////////8A/////////wAAAAAAAAAA/////8QAAAAAAAAAAJD//////////////wD/////////AAAAAAAAAAD//////1QAAAAAAAAAFPD/////////////AP////////8AAAAAAAAAAP//////3AQAAAAAAAAAgP////////////8A/////////wAAAAAAAAAA////////aAAAAAAAAAAM6P///////////wD/////////AAAAAAAAAAD////////oCAAAAAAAAABs////////////AP////////8AAAAAAAAAAP////////+AAAAAAAAAAATc//////////8A/////////wAAAAAAAAAA//////////AUAAAAAAAAAFj//////////wD/////////AAAAAAAAAAD//////////5AAAAAAAAAAAND/////////AP////////8AAAAAAAAAAP//////////+CQAAAAAAAAAQP////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'S' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP/////////////////8vHBEIAgAAAQgQHC8/P////////////////8A////////////////pCQAAAAAAAAAAAAAAAAcoP///////////////wD//////////////FwAAAAAAAAAAAAAAAAAAAAAXP//////////////AP////////////9oAAAAAAAAAAAAAAAAAAAAAAAAhP////////////8A////////////zAAAAAAAAAAAAAAAAAAAAAAAAAAI6P///////////wD///////////9cAAAAAAAAAAAAAAAAAAAAAAAAAACA////////////AP///////////xgAAAAAAAAAUOD/8KwkAAAAAAAAADj///////////8A////////////AAAAAAAAAAD0/////8wABCAgICxASP///////////wD///////////8MAAAAAAAAAMz/////////////////////////////AP///////////0AAAAAAAAAACFiQxPT///////////////////////8A////////////oAAAAAAAAAAAAAAAADBwtPT//////////////////wD////////////8QAAAAAAAAAAAAAAAAAAACFTA////////////////AP/////////////oOAAAAAAAAAAAAAAAAAAAAABM6P////////////8A///////////////4fAgAAAAAAAAAAAAAAAAAAAAY2P///////////wD/////////////////7IwwAAAAAAAAAAAAAAAAAAAo+P//////////AP/////////////////////koGw0BAAAAAAAAAAAAACU//////////8A///////////////////////////4uFgAAAAAAAAAADz//////////wD//////////2BgSEA0IBwA6P///////5QAAAAAAAAADP//////////AP//////////JAAAAAAAAACc/////////AAAAAAAAAAA//////////8A//////////9YAAAAAAAAACDo///////AAAAAAAAAABT//////////wD//////////6QAAAAAAAAAACCk7P/snBQAAAAAAAAAUP//////////AP//////////+BAAAAAAAAAAAAAAAAAAAAAAAAAAAACs//////////8A////////////kAAAAAAAAAAAAAAAAAAAAAAAAAAAOP///////////wD////////////8RAAAAAAAAAAAAAAAAAAAAAAAABjc////////////AP/////////////0PAAAAAAAAAAAAAAAAAAAAAAg2P////////////8A///////////////8hBQAAAAAAAAAAAAAAAAMdPT//////////////wD/////////////////+LRwSCAMAAAAHDhoqPT/////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'T' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD///////////////////8AAAAAAAAAAP//////////////////////AP///////////////////wAAAAAAAAAA//////////////////////8A////////////////////AAAAAAAAAAD//////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'U' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////AAAAAAAAAAD///////////8AAAAAAAAAAP//////////AP////////8AAAAAAAAAAP///////////wAAAAAAAAAA//////////8A/////////wAAAAAAAAAA////////////AAAAAAAAAAD//////////wD/////////JAAAAAAAAADk/////////+gAAAAAAAAAHP//////////AP////////9MAAAAAAAAAJz/////////nAAAAAAAAABE//////////8A/////////4gAAAAAAAAAHOj//////+ggAAAAAAAAAHz//////////wD/////////0AAAAAAAAAAAIJzs/+ykIAAAAAAAAAAA0P//////////AP//////////QAAAAAAAAAAAAAAAAAAAAAAAAAAAAED///////////8A///////////IBAAAAAAAAAAAAAAAAAAAAAAAAAAE0P///////////wD///////////+YAAAAAAAAAAAAAAAAAAAAAAAAAJj/////////////AP////////////+UBAAAAAAAAAAAAAAAAAAAAASU//////////////8A///////////////IPAAAAAAAAAAAAAAAAAAwyP///////////////wD/////////////////0IxYOCAIAAAEIEiAyP//////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'V' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD//////zAAAAAAAAAAYP//////////////ZAAAAAAAAAAw////////AP//////kAAAAAAAAAAU/P////////////8UAAAAAAAAAJD///////8A///////oBAAAAAAAAADE////////////xAAAAAAAAAAE7P///////wD///////9MAAAAAAAAAHD///////////94AAAAAAAAAEz/////////AP///////6gAAAAAAAAAJP///////////yQAAAAAAAAArP////////8A////////+BAAAAAAAAAA1P/////////YAAAAAAAAABT4/////////wD/////////aAAAAAAAAACE/////////4QAAAAAAAAAbP//////////AP/////////EAAAAAAAAADT/////////OAAAAAAAAADM//////////8A//////////8kAAAAAAAAAOT//////+QAAAAAAAAAKP///////////wD//////////4QAAAAAAAAAmP//////nAAAAAAAAACI////////////AP//////////5AAAAAAAAABE//////9EAAAAAAAABOT///////////8A////////////QAAAAAAAAAT0////9AgAAAAAAABI/////////////wD///////////+gAAAAAAAAAKT///+kAAAAAAAAAKj/////////////AP////////////QIAAAAAAAAXP///1wAAAAAAAAM+P////////////8A/////////////1wAAAAAAAAM+P/8DAAAAAAAAGT//////////////wD/////////////vAAAAAAAAAC8/7wAAAAAAAAAxP//////////////AP//////////////HAAAAAAAAGj/aAAAAAAAACT///////////////8A//////////////94AAAAAAAAHP8cAAAAAAAAhP///////////////wD//////////////9gAAAAAAAAAkAAAAAAAAADk////////////////AP///////////////zgAAAAAAAAQAAAAAAAAQP////////////////8A////////////////lAAAAAAAAAAAAAAAAACg/////////////////wD////////////////sCAAAAAAAAAAAAAAADPT/////////////////AP////////////////9QAAAAAAAAAAAAAABg//////////////////8A/////////////////7AAAAAAAAAAAAAAAMD//////////////////wD//////////////////BQAAAAAAAAAAAAc////////////////////AP//////////////////cAAAAAAAAAAAAHz///////////////////8A///////////////////MAAAAAAAAAAAA3P///////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'W' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A//8cAAAAAAAAALz/////4AAAAAAAAAAA6P////+8AAAAAAAAABz//wD//1QAAAAAAAAAjP////+gAAAAAAAAAACo/////4wAAAAAAAAAUP//AP//jAAAAAAAAABU/////2AAAAAAAAAAAGj/////VAAAAAAAAACM//8A///EAAAAAAAAACT/////IAAAAAAAAAAAKP////8kAAAAAAAAAMT//wD///gEAAAAAAAAAPD//+AAAAAAAAAAAAAA6P//8AAAAAAAAAAE9P//AP///zAAAAAAAAAAvP//oAAAAAAAAAAAAACo//+8AAAAAAAAADD///8A////bAAAAAAAAACM//9gAAAAAAAAAAAAAGT//4wAAAAAAAAAaP///wD///+kAAAAAAAAAFT//yAAAAAAAAAAAAAAIP//VAAAAAAAAACc////AP///9gAAAAAAAAAJP/gAAAAAAAAAAAAAAAA4P8kAAAAAAAAANT///8A/////xAAAAAAAAAA8KAAAAAAAAAAAAAAAACg8AAAAAAAAAAQ/////wD/////TAAAAAAAAAC8YAAAAAAAAAAAAAAAAGC8AAAAAAAAAET/////AP////+AAAAAAAAAAIwgAAAAAAAAAAAAAAAAIIwAAAAAAAAAfP////8A/////7gAAAAAAAAANAAAAAAAACwwAAAAAAAANAAAAAAAAACw/////wD/////8AAAAAAAAAAAAAAAAAAAdHgAAAAAAAAAAAAAAAAAAOz/////AP//////KAAAAAAAAAAAAAAAAAC4vAAAAAAAAAAAAAAAAAAg//////8A//////9gAAAAAAAAAAAAAAAACPj4CAAAAAAAAAAAAAAAAFj//////wD//////5QAAAAAAAAAAAAAAABE//9IAAAAAAAAAAAAAAAAkP//////AP//////0AAAAAAAAAAAAAAAAIj//4wAAAAAAAAAAAAAAADI//////8A///////8DAAAAAAAAAAAAAAAzP//1AAAAAAAAAAAAAAABPj//////wD///////88AAAAAAAAAAAAABT/////GAAAAAAAAAAAAAA0////////AP///////3QAAAAAAAAAAAAAWP////9gAAAAAAAAAAAAAHD///////8A////////sAAAAAAAAAAAAACg/////6QAAAAAAAAAAAAApP///////wD////////kAAAAAAAAAAAAAOT/////6AAAAAAAAAAAAADc////////AP////////8cAAAAAAAAAAAo////////MAAAAAAAAAAAEP////////8A/////////1QAAAAAAAAAAHD///////94AAAAAAAAAABM/////////wD/////////jAAAAAAAAAAAtP///////7wAAAAAAAAAAID/////////AP/////////EAAAAAAAAAAT0////////+AgAAAAAAAAAuP////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'X' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD///////9UAAAAAAAAAKz///////////+sAAAAAAAAAFD/////////AP///////+QQAAAAAAAAFOT/////////8BwAAAAAAAAM5P////////8A/////////5gAAAAAAAAATP////////9kAAAAAAAAAJD//////////wD//////////0AAAAAAAAAAoP//////wAAAAAAAAAA0/P//////////AP//////////2AgAAAAAAAAQ4P////gkAAAAAAAABMz///////////8A////////////iAAAAAAAAABA////dAAAAAAAAABw/////////////wD////////////8MAAAAAAAAACU/9AEAAAAAAAAHPD/////////////AP/////////////IBAAAAAAAAAzYMAAAAAAAAACs//////////////8A//////////////90AAAAAAAAABAAAAAAAAAATP///////////////wD///////////////QgAAAAAAAAAAAAAAAAAAzg////////////////AP///////////////7wAAAAAAAAAAAAAAAAAjP////////////////8A/////////////////2AAAAAAAAAAAAAAADD8/////////////////wD/////////////////7BQAAAAAAAAAAAAEyP//////////////////AP/////////////////gDAAAAAAAAAAAAAjY//////////////////8A/////////////////0AAAAAAAAAAAAAAADj8/////////////////wD///////////////+UAAAAAAAAAAAAAAAAAJD/////////////////AP//////////////4AwAAAAAAAAAAAAAAAAADOD///////////////8A//////////////9AAAAAAAAAAAAAAAAAAAAAQP///////////////wD/////////////nAAAAAAAAAAAWAAAAAAAAAAAlP//////////////AP///////////+QQAAAAAAAAAGD/YAAAAAAAAAAM4P////////////8A////////////TAAAAAAAAAAs9P/0LAAAAAAAAABM/////////////wD//////////6AAAAAAAAAADNT////UDAAAAAAAAACg////////////AP/////////kEAAAAAAAAACg//////+gAAAAAAAAABDk//////////8A/////////0wAAAAAAAAAYP////////9gAAAAAAAAAEz//////////wD///////+oAAAAAAAAACz0//////////QsAAAAAAAAAKT/////////AP//////7BQAAAAAAAAM1P///////////9QMAAAAAAAAFOz///////8A//////9UAAAAAAAAAKD//////////////6AAAAAAAAAAVP///////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'Y' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP///////1QAAAAAAAAAAGj//////////2gAAAAAAAAAAFT///////8A////////5BAAAAAAAAAAAMT////////EAAAAAAAAAAAQ5P///////wD/////////mAAAAAAAAAAAKPj/////+CgAAAAAAAAAAJj/////////AP//////////PAAAAAAAAAAAgP////+AAAAAAAAAAAA8//////////8A///////////YCAAAAAAAAAAE2P//2AQAAAAAAAAACNj//////////wD///////////+AAAAAAAAAAAA4//84AAAAAAAAAACA////////////AP////////////woAAAAAAAAAACUlAAAAAAAAAAAKPz///////////8A/////////////8gAAAAAAAAAABAQAAAAAAAAAADI/////////////wD//////////////2wAAAAAAAAAAAAAAAAAAAAAbP//////////////AP//////////////8BwAAAAAAAAAAAAAAAAAABzw//////////////8A////////////////tAAAAAAAAAAAAAAAAAAAtP///////////////wD/////////////////VAAAAAAAAAAAAAAAAFT/////////////////AP/////////////////oEAAAAAAAAAAAAAAQ6P////////////////8A//////////////////+cAAAAAAAAAAAAAJz//////////////////wD///////////////////9AAAAAAAAAAABA////////////////////AP///////////////////9gAAAAAAAAAANj///////////////////8A/////////////////////wAAAAAAAAAA/////////////////////wD/////////////////////AAAAAAAAAAD/////////////////////AP////////////////////8AAAAAAAAAAP////////////////////8A/////////////////////wAAAAAAAAAA/////////////////////wD/////////////////////AAAAAAAAAAD/////////////////////AP////////////////////8AAAAAAAAAAP////////////////////8A/////////////////////wAAAAAAAAAA/////////////////////wD/////////////////////AAAAAAAAAAD/////////////////////AP////////////////////8AAAAAAAAAAP////////////////////8A/////////////////////wAAAAAAAAAA/////////////////////wD/////////////////////AAAAAAAAAAD/////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + 'Z' => array( + 'data' => 'AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////8A//////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////////wD//////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAP//////////////AP//////////AAAAAAAAAAAAAAAAAAAAAAAAAAAQ//////////////8A/////////////////////////1AAAAAAAAAABLz//////////////wD///////////////////////98AAAAAAAAAACY////////////////AP//////////////////////pAAAAAAAAAAAaP////////////////8A/////////////////////8QIAAAAAAAAAET8/////////////////wD////////////////////gGAAAAAAAAAAo9P//////////////////AP//////////////////9CwAAAAAAAAAFNz///////////////////8A//////////////////xMAAAAAAAAAATA/////////////////////wD/////////////////eAAAAAAAAAAAnP//////////////////////AP///////////////5wAAAAAAAAAAHT///////////////////////8A///////////////ABAAAAAAAAABM/P///////////////////////wD/////////////3BQAAAAAAAAALPT/////////////////////////AP////////////QoAAAAAAAAABjg//////////////////////////8A///////////8SAAAAAAAAAAExP///////////////////////////wD//////////2wAAAAAAAAAAKD/////////////////////////////AP////////+YAAAAAAAAAAB8//////////////////////////////8A/////////wQAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////wD/////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////AP////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8A/////////////////////////////////////////////////////wD/////////////////////////////////////////////////////AP////////////////////////////////////////////////////8=', + 'width' => 40 + ), + ); + } +} diff --git a/phpBB/phpbb/captcha/plugins/captcha_abstract.php b/phpBB/phpbb/captcha/plugins/captcha_abstract.php new file mode 100644 index 0000000000..24ed7f939d --- /dev/null +++ b/phpBB/phpbb/captcha/plugins/captcha_abstract.php @@ -0,0 +1,390 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha\plugins; + +/** +* This class holds the code shared by the two default 3.0.x CAPTCHAs. +*/ +abstract class captcha_abstract +{ + var $confirm_id; + var $confirm_code; + var $code; + var $seed; + var $attempts = 0; + var $type; + var $solved = 0; + var $captcha_vars = false; + + /** + * @var string name of the service. + */ + protected $service_name; + + function init($type) + { + global $config, $db, $user; + + // read input + $this->confirm_id = request_var('confirm_id', ''); + $this->confirm_code = request_var('confirm_code', ''); + $refresh = request_var('refresh_vc', false) && $config['confirm_refresh']; + + $this->type = (int) $type; + + if (!strlen($this->confirm_id) || !$this->load_code()) + { + // we have no confirm ID, better get ready to display something + $this->generate_code(); + } + else if ($refresh) + { + $this->regenerate_code(); + } + } + + function execute_demo() + { + global $user; + + $this->code = gen_rand_string_friendly(mt_rand(CAPTCHA_MIN_CHARS, CAPTCHA_MAX_CHARS)); + $this->seed = hexdec(substr(unique_id(), 4, 10)); + + // compute $seed % 0x7fffffff + $this->seed -= 0x7fffffff * floor($this->seed / 0x7fffffff); + + $generator = $this->get_generator_class(); + $captcha = new $generator(); + define('IMAGE_OUTPUT', 1); + $captcha->execute($this->code, $this->seed); + } + + function execute() + { + if (empty($this->code)) + { + if (!$this->load_code()) + { + // invalid request, bail out + return false; + } + } + $generator = $this->get_generator_class(); + $captcha = new $generator(); + define('IMAGE_OUTPUT', 1); + $captcha->execute($this->code, $this->seed); + } + + function get_template() + { + global $config, $user, $template, $phpEx, $phpbb_root_path; + + if ($this->is_solved()) + { + return false; + } + else + { + $link = append_sid($phpbb_root_path . 'ucp.' . $phpEx, 'mode=confirm&confirm_id=' . $this->confirm_id . '&type=' . $this->type); + $contact_link = phpbb_get_board_contact_link($config, $phpbb_root_path, $phpEx); + $explain = $user->lang(($this->type != CONFIRM_POST) ? 'CONFIRM_EXPLAIN' : 'POST_CONFIRM_EXPLAIN', '<a href="' . $contact_link . '">', '</a>'); + + $template->assign_vars(array( + 'CONFIRM_IMAGE_LINK' => $link, + 'CONFIRM_IMAGE' => '<img src="' . $link . '" />', + 'CONFIRM_IMG' => '<img src="' . $link . '" />', + 'CONFIRM_ID' => $this->confirm_id, + 'S_CONFIRM_CODE' => true, + 'S_TYPE' => $this->type, + 'S_CONFIRM_REFRESH' => ($config['enable_confirm'] && $config['confirm_refresh'] && $this->type == CONFIRM_REG) ? true : false, + 'L_CONFIRM_EXPLAIN' => $explain, + )); + + return 'captcha_default.html'; + } + } + + function get_demo_template($id) + { + global $config, $user, $template, $phpbb_admin_path, $phpEx; + + $variables = ''; + + if (is_array($this->captcha_vars)) + { + foreach ($this->captcha_vars as $captcha_var => $template_var) + { + $variables .= '&' . rawurlencode($captcha_var) . '=' . request_var($captcha_var, (int) $config[$captcha_var]); + } + } + + // acp_captcha has a delivery function; let's use it + $template->assign_vars(array( + 'CONFIRM_IMAGE' => append_sid($phpbb_admin_path . 'index.' . $phpEx, 'captcha_demo=1&mode=visual&i=' . $id . '&select_captcha=' . $this->get_service_name()) . $variables, + 'CONFIRM_ID' => $this->confirm_id, + )); + + return 'captcha_default_acp_demo.html'; + } + + function get_hidden_fields() + { + $hidden_fields = array(); + + // this is required for posting.php - otherwise we would forget about the captcha being already solved + if ($this->solved) + { + $hidden_fields['confirm_code'] = $this->confirm_code; + } + $hidden_fields['confirm_id'] = $this->confirm_id; + return $hidden_fields; + } + + function garbage_collect($type) + { + global $db, $config; + + $sql = 'SELECT DISTINCT c.session_id + FROM ' . CONFIRM_TABLE . ' c + LEFT JOIN ' . SESSIONS_TABLE . ' s ON (c.session_id = s.session_id) + WHERE s.session_id IS NULL' . + ((empty($type)) ? '' : ' AND c.confirm_type = ' . (int) $type); + $result = $db->sql_query($sql); + + if ($row = $db->sql_fetchrow($result)) + { + $sql_in = array(); + do + { + $sql_in[] = (string) $row['session_id']; + } + while ($row = $db->sql_fetchrow($result)); + + if (sizeof($sql_in)) + { + $sql = 'DELETE FROM ' . CONFIRM_TABLE . ' + WHERE ' . $db->sql_in_set('session_id', $sql_in); + $db->sql_query($sql); + } + } + $db->sql_freeresult($result); + } + + function uninstall() + { + $this->garbage_collect(0); + } + + function install() + { + return; + } + + function validate() + { + global $config, $db, $user; + + if (empty($user->lang)) + { + $user->setup(); + } + + $error = ''; + if (!$this->confirm_id) + { + $error = $user->lang['CONFIRM_CODE_WRONG']; + } + else + { + if ($this->check_code()) + { + $this->solved = true; + } + else + { + $error = $user->lang['CONFIRM_CODE_WRONG']; + } + } + + if (strlen($error)) + { + // okay, incorrect answer. Let's ask a new question. + $this->new_attempt(); + return $error; + } + else + { + return false; + } + } + + /** + * The old way to generate code, suitable for GD and non-GD. Resets the internal state. + */ + function generate_code() + { + global $db, $user; + + $this->code = gen_rand_string_friendly(mt_rand(CAPTCHA_MIN_CHARS, CAPTCHA_MAX_CHARS)); + $this->confirm_id = md5(unique_id($user->ip)); + $this->seed = hexdec(substr(unique_id(), 4, 10)); + $this->solved = 0; + // compute $seed % 0x7fffffff + $this->seed -= 0x7fffffff * floor($this->seed / 0x7fffffff); + + $sql = 'INSERT INTO ' . CONFIRM_TABLE . ' ' . $db->sql_build_array('INSERT', array( + 'confirm_id' => (string) $this->confirm_id, + 'session_id' => (string) $user->session_id, + 'confirm_type' => (int) $this->type, + 'code' => (string) $this->code, + 'seed' => (int) $this->seed) + ); + $db->sql_query($sql); + } + + /** + * New Question, if desired. + */ + function regenerate_code() + { + global $db, $user; + + $this->code = gen_rand_string_friendly(mt_rand(CAPTCHA_MIN_CHARS, CAPTCHA_MAX_CHARS)); + $this->seed = hexdec(substr(unique_id(), 4, 10)); + $this->solved = 0; + // compute $seed % 0x7fffffff + $this->seed -= 0x7fffffff * floor($this->seed / 0x7fffffff); + + $sql = 'UPDATE ' . CONFIRM_TABLE . ' SET ' . $db->sql_build_array('UPDATE', array( + 'code' => (string) $this->code, + 'seed' => (int) $this->seed)) . ' + WHERE + confirm_id = \'' . $db->sql_escape($this->confirm_id) . '\' + AND session_id = \'' . $db->sql_escape($user->session_id) . '\''; + $db->sql_query($sql); + } + + /** + * New Question, if desired. + */ + function new_attempt() + { + global $db, $user; + + $this->code = gen_rand_string_friendly(mt_rand(CAPTCHA_MIN_CHARS, CAPTCHA_MAX_CHARS)); + $this->seed = hexdec(substr(unique_id(), 4, 10)); + $this->solved = 0; + // compute $seed % 0x7fffffff + $this->seed -= 0x7fffffff * floor($this->seed / 0x7fffffff); + + $sql = 'UPDATE ' . CONFIRM_TABLE . ' SET ' . $db->sql_build_array('UPDATE', array( + 'code' => (string) $this->code, + 'seed' => (int) $this->seed)) . ' + , attempts = attempts + 1 + WHERE + confirm_id = \'' . $db->sql_escape($this->confirm_id) . '\' + AND session_id = \'' . $db->sql_escape($user->session_id) . '\''; + $db->sql_query($sql); + } + + /** + * Look up everything we need for painting&checking. + */ + function load_code() + { + global $db, $user; + + $sql = 'SELECT code, seed, attempts + FROM ' . CONFIRM_TABLE . " + WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "' + AND session_id = '" . $db->sql_escape($user->session_id) . "' + AND confirm_type = " . $this->type; + $result = $db->sql_query($sql); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if ($row) + { + $this->code = $row['code']; + $this->seed = $row['seed']; + $this->attempts = $row['attempts']; + return true; + } + + return false; + } + + function check_code() + { + return (strcasecmp($this->code, $this->confirm_code) === 0); + } + + function get_attempt_count() + { + return $this->attempts; + } + + function reset() + { + global $db, $user; + + $sql = 'DELETE FROM ' . CONFIRM_TABLE . " + WHERE session_id = '" . $db->sql_escape($user->session_id) . "' + AND confirm_type = " . (int) $this->type; + $db->sql_query($sql); + + // we leave the class usable by generating a new question + $this->generate_code(); + } + + function is_solved() + { + if (request_var('confirm_code', false) && $this->solved === 0) + { + $this->validate(); + } + return (bool) $this->solved; + } + + /** + * API function + */ + function has_config() + { + return false; + } + + /** + * @return string the name of the service corresponding to the plugin + */ + function get_service_name() + { + return $this->service_name; + } + + /** + * Set the name of the plugin + * + * @param string $name + */ + public function set_name($name) + { + $this->service_name = $name; + } + + /** + * @return string the name of the class used to generate the captcha + */ + abstract function get_generator_class(); +} diff --git a/phpBB/phpbb/captcha/plugins/gd.php b/phpBB/phpbb/captcha/plugins/gd.php new file mode 100644 index 0000000000..f6200b5b2f --- /dev/null +++ b/phpBB/phpbb/captcha/plugins/gd.php @@ -0,0 +1,130 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha\plugins; + +class gd extends captcha_abstract +{ + var $captcha_vars = array( + 'captcha_gd_x_grid' => 'CAPTCHA_GD_X_GRID', + 'captcha_gd_y_grid' => 'CAPTCHA_GD_Y_GRID', + 'captcha_gd_foreground_noise' => 'CAPTCHA_GD_FOREGROUND_NOISE', +// 'captcha_gd' => 'CAPTCHA_GD_PREVIEWED', + 'captcha_gd_wave' => 'CAPTCHA_GD_WAVE', + 'captcha_gd_3d_noise' => 'CAPTCHA_GD_3D_NOISE', + 'captcha_gd_fonts' => 'CAPTCHA_GD_FONTS', + ); + + public function is_available() + { + return @extension_loaded('gd'); + } + + /** + * @return string the name of the class used to generate the captcha + */ + function get_generator_class() + { + return '\\phpbb\\captcha\\gd'; + } + + /** + * API function + */ + function has_config() + { + return true; + } + + public function get_name() + { + return 'CAPTCHA_GD'; + } + + function acp_page($id, &$module) + { + global $db, $user, $auth, $template; + global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx; + + $user->add_lang('acp/board'); + + $config_vars = array( + 'enable_confirm' => 'REG_ENABLE', + 'enable_post_confirm' => 'POST_ENABLE', + 'confirm_refresh' => 'CONFIRM_REFRESH', + 'captcha_gd' => 'CAPTCHA_GD', + ); + + $module->tpl_name = 'captcha_gd_acp'; + $module->page_title = 'ACP_VC_SETTINGS'; + $form_key = 'acp_captcha'; + add_form_key($form_key); + + $submit = request_var('submit', ''); + + if ($submit && check_form_key($form_key)) + { + $captcha_vars = array_keys($this->captcha_vars); + foreach ($captcha_vars as $captcha_var) + { + $value = request_var($captcha_var, 0); + if ($value >= 0) + { + set_config($captcha_var, $value); + } + } + + add_log('admin', 'LOG_CONFIG_VISUAL'); + trigger_error($user->lang['CONFIG_UPDATED'] . adm_back_link($module->u_action)); + } + else if ($submit) + { + trigger_error($user->lang['FORM_INVALID'] . adm_back_link($module->u_action)); + } + else + { + foreach ($this->captcha_vars as $captcha_var => $template_var) + { + $var = (isset($_REQUEST[$captcha_var])) ? request_var($captcha_var, 0) : $config[$captcha_var]; + $template->assign_var($template_var, $var); + } + + $template->assign_vars(array( + 'CAPTCHA_PREVIEW' => $this->get_demo_template($id), + 'CAPTCHA_NAME' => $this->get_service_name(), + 'U_ACTION' => $module->u_action, + )); + } + } + + function execute_demo() + { + global $config; + + $config_old = $config; + + $config = new \phpbb\config\config(array()); + foreach ($config_old as $key => $value) + { + $config->set($key, $value); + } + + foreach ($this->captcha_vars as $captcha_var => $template_var) + { + $config->set($captcha_var, request_var($captcha_var, (int) $config[$captcha_var])); + } + parent::execute_demo(); + $config = $config_old; + } + +} diff --git a/phpBB/phpbb/captcha/plugins/gd_wave.php b/phpBB/phpbb/captcha/plugins/gd_wave.php new file mode 100644 index 0000000000..e1d44df778 --- /dev/null +++ b/phpBB/phpbb/captcha/plugins/gd_wave.php @@ -0,0 +1,42 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha\plugins; + +class gd_wave extends captcha_abstract +{ + public function is_available() + { + return @extension_loaded('gd'); + } + + public function get_name() + { + return 'CAPTCHA_GD_3D'; + } + + /** + * @return string the name of the class used to generate the captcha + */ + function get_generator_class() + { + return '\\phpbb\\captcha\\gd_wave'; + } + + function acp_page($id, &$module) + { + global $config, $db, $template, $user; + + trigger_error($user->lang['CAPTCHA_NO_OPTIONS'] . adm_back_link($module->u_action)); + } +} diff --git a/phpBB/phpbb/captcha/plugins/nogd.php b/phpBB/phpbb/captcha/plugins/nogd.php new file mode 100644 index 0000000000..6845e5935c --- /dev/null +++ b/phpBB/phpbb/captcha/plugins/nogd.php @@ -0,0 +1,42 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha\plugins; + +class nogd extends captcha_abstract +{ + public function is_available() + { + return true; + } + + public function get_name() + { + return 'CAPTCHA_NO_GD'; + } + + /** + * @return string the name of the class used to generate the captcha + */ + function get_generator_class() + { + return '\\phpbb\\captcha\\non_gd'; + } + + function acp_page($id, &$module) + { + global $user; + + trigger_error($user->lang['CAPTCHA_NO_OPTIONS'] . adm_back_link($module->u_action)); + } +} diff --git a/phpBB/phpbb/captcha/plugins/qa.php b/phpBB/phpbb/captcha/plugins/qa.php new file mode 100644 index 0000000000..a9d133d8f2 --- /dev/null +++ b/phpBB/phpbb/captcha/plugins/qa.php @@ -0,0 +1,1039 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha\plugins; + +/** +* And now to something completely different. Let's make a captcha without extending the abstract class. +* QA CAPTCHA sample implementation +*/ +class qa +{ + var $confirm_id; + var $answer; + var $question_ids; + var $question_text; + var $question_lang; + var $question_strict; + var $attempts = 0; + var $type; + // dirty trick: 0 is false, but can still encode that the captcha is not yet validated + var $solved = 0; + + protected $table_captcha_questions; + protected $table_captcha_answers; + protected $table_qa_confirm; + + /** + * @var string name of the service. + */ + protected $service_name; + + /** + * Constructor + * + * @param string $table_captcha_questions + * @param string $table_captcha_answers + * @param string $table_qa_confirm + */ + function __construct($table_captcha_questions, $table_captcha_answers, $table_qa_confirm) + { + $this->table_captcha_questions = $table_captcha_questions; + $this->table_captcha_answers = $table_captcha_answers; + $this->table_qa_confirm = $table_qa_confirm; + } + + /** + * @param int $type as per the CAPTCHA API docs, the type + */ + function init($type) + { + global $config, $db, $user; + + // load our language file + $user->add_lang('captcha_qa'); + + // read input + $this->confirm_id = request_var('qa_confirm_id', ''); + $this->answer = utf8_normalize_nfc(request_var('qa_answer', '', true)); + + $this->type = (int) $type; + $this->question_lang = $user->lang_name; + + // we need all defined questions - shouldn't be too many, so we can just grab them + // try the user's lang first + $sql = 'SELECT question_id + FROM ' . $this->table_captcha_questions . " + WHERE lang_iso = '" . $db->sql_escape($user->lang_name) . "'"; + $result = $db->sql_query($sql, 3600); + + while ($row = $db->sql_fetchrow($result)) + { + $this->question_ids[$row['question_id']] = $row['question_id']; + } + $db->sql_freeresult($result); + + // fallback to the board default lang + if (!sizeof($this->question_ids)) + { + $this->question_lang = $config['default_lang']; + + $sql = 'SELECT question_id + FROM ' . $this->table_captcha_questions . " + WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'"; + $result = $db->sql_query($sql, 7200); + + while ($row = $db->sql_fetchrow($result)) + { + $this->question_ids[$row['question_id']] = $row['question_id']; + } + $db->sql_freeresult($result); + } + + // final fallback to any language + if (!sizeof($this->question_ids)) + { + $this->question_lang = ''; + + $sql = 'SELECT q.question_id, q.lang_iso + FROM ' . $this->table_captcha_questions . ' q, ' . $this->table_captcha_answers . ' a + WHERE q.question_id = a.question_id + GROUP BY lang_iso'; + $result = $db->sql_query($sql, 7200); + + while ($row = $db->sql_fetchrow($result)) + { + if (empty($this->question_lang)) + { + $this->question_lang = $row['lang_iso']; + } + $this->question_ids[$row['question_id']] = $row['question_id']; + } + $db->sql_freeresult($result); + } + + // okay, if there is a confirm_id, we try to load that confirm's state. If not, we try to find one + if (!$this->load_answer() && (!$this->load_confirm_id() || !$this->load_answer())) + { + // we have no valid confirm ID, better get ready to ask something + $this->select_question(); + } + } + + /** + * See if the captcha has created its tables. + */ + public function is_installed() + { + global $db; + + $db_tool = new \phpbb\db\tools($db); + + return $db_tool->sql_table_exists($this->table_captcha_questions); + } + + /** + * API function - for the captcha to be available, it must have installed itself and there has to be at least one question in the board's default lang + */ + public function is_available() + { + global $config, $db, $user; + + // load language file for pretty display in the ACP dropdown + $user->add_lang('captcha_qa'); + + if (!$this->is_installed()) + { + return false; + } + + $sql = 'SELECT COUNT(question_id) AS question_count + FROM ' . $this->table_captcha_questions . " + WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'"; + $result = $db->sql_query($sql); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + return ((bool) $row['question_count']); + } + + /** + * API function + */ + function has_config() + { + return true; + } + + /** + * API function + */ + static public function get_name() + { + return 'CAPTCHA_QA'; + } + + /** + * @return string the name of the service corresponding to the plugin + */ + function get_service_name() + { + return $this->service_name; + } + + /** + * Set the name of the plugin + * + * @param string $name + */ + public function set_name($name) + { + $this->service_name = $name; + } + + /** + * API function - not needed as we don't display an image + */ + function execute_demo() + { + } + + /** + * API function - not needed as we don't display an image + */ + function execute() + { + } + + /** + * API function - send the question to the template + */ + function get_template() + { + global $phpbb_log, $template, $user; + + if ($this->is_solved()) + { + return false; + } + else if (empty($this->question_text) || !count($this->question_ids)) + { + /** @var \phpbb\log\log_interface $phpbb_log */ + $phpbb_log->add('critical', $user->data['user_id'], $user->ip, 'LOG_ERROR_CAPTCHA', time(), array($user->lang('CONFIRM_QUESTION_MISSING'))); + return false; + } + else + { + $template->assign_vars(array( + 'QA_CONFIRM_QUESTION' => $this->question_text, + 'QA_CONFIRM_ID' => $this->confirm_id, + 'S_CONFIRM_CODE' => true, + 'S_TYPE' => $this->type, + )); + + return 'captcha_qa.html'; + } + } + + /** + * API function - we just display a mockup so that the captcha doesn't need to be installed + */ + function get_demo_template() + { + global $config, $db, $template; + + if ($this->is_available()) + { + $sql = 'SELECT question_text + FROM ' . $this->table_captcha_questions . " + WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'"; + $result = $db->sql_query_limit($sql, 1); + if ($row = $db->sql_fetchrow($result)) + { + $template->assign_vars(array( + 'QA_CONFIRM_QUESTION' => $row['question_text'], + )); + } + $db->sql_freeresult($result); + } + return 'captcha_qa_acp_demo.html'; + } + + /** + * API function + */ + function get_hidden_fields() + { + $hidden_fields = array(); + + // this is required - otherwise we would forget about the captcha being already solved + if ($this->solved) + { + $hidden_fields['qa_answer'] = $this->answer; + } + $hidden_fields['qa_confirm_id'] = $this->confirm_id; + + return $hidden_fields; + } + + /** + * API function + */ + function garbage_collect($type = 0) + { + global $db; + + $sql = 'SELECT c.confirm_id + FROM ' . $this->table_qa_confirm . ' c + LEFT JOIN ' . SESSIONS_TABLE . ' s + ON (c.session_id = s.session_id) + WHERE s.session_id IS NULL' . + ((empty($type)) ? '' : ' AND c.confirm_type = ' . (int) $type); + $result = $db->sql_query($sql); + + if ($row = $db->sql_fetchrow($result)) + { + $sql_in = array(); + + do + { + $sql_in[] = (string) $row['confirm_id']; + } + while ($row = $db->sql_fetchrow($result)); + + if (sizeof($sql_in)) + { + $sql = 'DELETE FROM ' . $this->table_qa_confirm . ' + WHERE ' . $db->sql_in_set('confirm_id', $sql_in); + $db->sql_query($sql); + } + } + $db->sql_freeresult($result); + } + + /** + * API function - we don't drop the tables here, as that would cause the loss of all entered questions. + */ + function uninstall() + { + $this->garbage_collect(0); + } + + /** + * API function - set up shop + */ + function install() + { + global $db; + + $db_tool = new \phpbb\db\tools($db); + + $schemas = array( + $this->table_captcha_questions => array ( + 'COLUMNS' => array( + 'question_id' => array('UINT', null, 'auto_increment'), + 'strict' => array('BOOL', 0), + 'lang_id' => array('UINT', 0), + 'lang_iso' => array('VCHAR:30', ''), + 'question_text' => array('TEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'question_id', + 'KEYS' => array( + 'lang' => array('INDEX', 'lang_iso'), + ), + ), + $this->table_captcha_answers => array ( + 'COLUMNS' => array( + 'question_id' => array('UINT', 0), + 'answer_text' => array('STEXT_UNI', ''), + ), + 'KEYS' => array( + 'qid' => array('INDEX', 'question_id'), + ), + ), + $this->table_qa_confirm => array ( + 'COLUMNS' => array( + 'session_id' => array('CHAR:32', ''), + 'confirm_id' => array('CHAR:32', ''), + 'lang_iso' => array('VCHAR:30', ''), + 'question_id' => array('UINT', 0), + 'attempts' => array('UINT', 0), + 'confirm_type' => array('USINT', 0), + ), + 'KEYS' => array( + 'session_id' => array('INDEX', 'session_id'), + 'lookup' => array('INDEX', array('confirm_id', 'session_id', 'lang_iso')), + ), + 'PRIMARY_KEY' => 'confirm_id', + ), + ); + + foreach ($schemas as $table => $schema) + { + if (!$db_tool->sql_table_exists($table)) + { + $db_tool->sql_create_table($table, $schema); + } + } + } + + /** + * API function - see what has to be done to validate + */ + function validate() + { + global $phpbb_log, $user; + + $error = ''; + + if (!sizeof($this->question_ids)) + { + /** @var \phpbb\log\log_interface $phpbb_log */ + $phpbb_log->add('critical', $user->data['user_id'], $user->ip, 'LOG_ERROR_CAPTCHA', time(), array($user->lang('CONFIRM_QUESTION_MISSING'))); + return $user->lang('CONFIRM_QUESTION_MISSING'); + } + + if (!$this->confirm_id) + { + $error = $user->lang['CONFIRM_QUESTION_WRONG']; + } + else + { + if ($this->check_answer()) + { + $this->solved = true; + } + else + { + $error = $user->lang['CONFIRM_QUESTION_WRONG']; + } + } + + if (strlen($error)) + { + // okay, incorrect answer. Let's ask a new question. + $this->new_attempt(); + $this->solved = false; + + return $error; + } + else + { + return false; + } + } + + /** + * Select a question + */ + function select_question() + { + global $db, $user; + + if (!sizeof($this->question_ids)) + { + return; + } + $this->confirm_id = md5(unique_id($user->ip)); + $this->question = (int) array_rand($this->question_ids); + + $sql = 'INSERT INTO ' . $this->table_qa_confirm . ' ' . $db->sql_build_array('INSERT', array( + 'confirm_id' => (string) $this->confirm_id, + 'session_id' => (string) $user->session_id, + 'lang_iso' => (string) $this->question_lang, + 'confirm_type' => (int) $this->type, + 'question_id' => (int) $this->question, + )); + $db->sql_query($sql); + + $this->load_answer(); + } + + /** + * New Question, if desired. + */ + function reselect_question() + { + global $db, $user; + + if (!sizeof($this->question_ids)) + { + return; + } + + $this->question = (int) array_rand($this->question_ids); + $this->solved = 0; + + $sql = 'UPDATE ' . $this->table_qa_confirm . ' + SET question_id = ' . (int) $this->question . " + WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "' + AND session_id = '" . $db->sql_escape($user->session_id) . "'"; + $db->sql_query($sql); + + $this->load_answer(); + } + + /** + * Wrong answer, so we increase the attempts and use a different question. + */ + function new_attempt() + { + global $db, $user; + + // yah, I would prefer a stronger rand, but this should work + $this->question = (int) array_rand($this->question_ids); + $this->solved = 0; + + $sql = 'UPDATE ' . $this->table_qa_confirm . ' + SET question_id = ' . (int) $this->question . ", + attempts = attempts + 1 + WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "' + AND session_id = '" . $db->sql_escape($user->session_id) . "'"; + $db->sql_query($sql); + + $this->load_answer(); + } + + + /** + * See if there is already an entry for the current session. + */ + function load_confirm_id() + { + global $db, $user; + + $sql = 'SELECT confirm_id + FROM ' . $this->table_qa_confirm . " + WHERE + session_id = '" . $db->sql_escape($user->session_id) . "' + AND lang_iso = '" . $db->sql_escape($this->question_lang) . "' + AND confirm_type = " . $this->type; + $result = $db->sql_query_limit($sql, 1); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if ($row) + { + $this->confirm_id = $row['confirm_id']; + return true; + } + return false; + } + + /** + * Look up everything we need and populate the instance variables. + */ + function load_answer() + { + global $db, $user; + + if (!strlen($this->confirm_id) || !sizeof($this->question_ids)) + { + return false; + } + + $sql = 'SELECT con.question_id, attempts, question_text, strict + FROM ' . $this->table_qa_confirm . ' con, ' . $this->table_captcha_questions . " qes + WHERE con.question_id = qes.question_id + AND confirm_id = '" . $db->sql_escape($this->confirm_id) . "' + AND session_id = '" . $db->sql_escape($user->session_id) . "' + AND qes.lang_iso = '" . $db->sql_escape($this->question_lang) . "' + AND confirm_type = " . $this->type; + $result = $db->sql_query($sql); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if ($row) + { + $this->question = $row['question_id']; + + $this->attempts = $row['attempts']; + $this->question_strict = $row['strict']; + $this->question_text = $row['question_text']; + + return true; + } + + return false; + } + + /** + * The actual validation + */ + function check_answer() + { + global $db; + + $answer = ($this->question_strict) ? utf8_normalize_nfc(request_var('qa_answer', '', true)) : utf8_clean_string(utf8_normalize_nfc(request_var('qa_answer', '', true))); + + $sql = 'SELECT answer_text + FROM ' . $this->table_captcha_answers . ' + WHERE question_id = ' . (int) $this->question; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $solution = ($this->question_strict) ? $row['answer_text'] : utf8_clean_string($row['answer_text']); + + if ($solution === $answer) + { + $this->solved = true; + + break; + } + } + $db->sql_freeresult($result); + + return $this->solved; + } + + /** + * API function + */ + function get_attempt_count() + { + return $this->attempts; + } + + /** + * API function + */ + function reset() + { + global $db, $user; + + $sql = 'DELETE FROM ' . $this->table_qa_confirm . " + WHERE session_id = '" . $db->sql_escape($user->session_id) . "' + AND confirm_type = " . (int) $this->type; + $db->sql_query($sql); + + // we leave the class usable by generating a new question + $this->select_question(); + } + + /** + * API function + */ + function is_solved() + { + if (request_var('qa_answer', false) && $this->solved === 0) + { + $this->validate(); + } + + return (bool) $this->solved; + } + + /** + * API function - The ACP backend, this marks the end of the easy methods + */ + function acp_page($id, &$module) + { + global $user, $template; + global $config; + + $user->add_lang('acp/board'); + $user->add_lang('captcha_qa'); + + if (!self::is_installed()) + { + $this->install(); + } + + $module->tpl_name = 'captcha_qa_acp'; + $module->page_title = 'ACP_VC_SETTINGS'; + $form_key = 'acp_captcha'; + add_form_key($form_key); + + $submit = request_var('submit', false); + $question_id = request_var('question_id', 0); + $action = request_var('action', ''); + + // we have two pages, so users might want to navigate from one to the other + $list_url = $module->u_action . "&configure=1&select_captcha=" . $this->get_service_name(); + + $template->assign_vars(array( + 'U_ACTION' => $module->u_action, + 'QUESTION_ID' => $question_id , + 'CLASS' => $this->get_service_name(), + )); + + // show the list? + if (!$question_id && $action != 'add') + { + $this->acp_question_list($module); + } + else if ($question_id && $action == 'delete') + { + if ($this->get_service_name() !== $config['captcha_plugin'] || !$this->acp_is_last($question_id)) + { + if (confirm_box(true)) + { + $this->acp_delete_question($question_id); + + trigger_error($user->lang['QUESTION_DELETED'] . adm_back_link($list_url)); + } + else + { + confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array( + 'question_id' => $question_id, + 'action' => $action, + 'configure' => 1, + 'select_captcha' => $this->get_service_name(), + )) + ); + } + } + else + { + trigger_error($user->lang['QA_LAST_QUESTION'] . adm_back_link($list_url), E_USER_WARNING); + } + } + else + { + // okay, show the editor + $question_input = $this->acp_get_question_input(); + $langs = $this->get_languages(); + + foreach ($langs as $lang => $entry) + { + $template->assign_block_vars('langs', array( + 'ISO' => $lang, + 'NAME' => $entry['name'], + )); + } + + $template->assign_vars(array( + 'U_LIST' => $list_url, + )); + + if ($question_id) + { + if ($question = $this->acp_get_question_data($question_id)) + { + $template->assign_vars(array( + 'QUESTION_TEXT' => ($question_input['question_text']) ? $question_input['question_text'] : $question['question_text'], + 'LANG_ISO' => ($question_input['lang_iso']) ? $question_input['lang_iso'] : $question['lang_iso'], + 'STRICT' => (isset($_REQUEST['strict'])) ? $question_input['strict'] : $question['strict'], + 'ANSWERS' => implode("\n", $question['answers']), + )); + } + else + { + trigger_error($user->lang['FORM_INVALID'] . adm_back_link($list_url)); + } + } + else + { + $template->assign_vars(array( + 'QUESTION_TEXT' => $question_input['question_text'], + 'LANG_ISO' => $question_input['lang_iso'], + 'STRICT' => $question_input['strict'], + 'ANSWERS' => (is_array($question_input['answers'])) ? implode("\n", $question_input['answers']) : '', + )); + } + + if ($submit && check_form_key($form_key)) + { + if (!$this->validate_input($question_input)) + { + $template->assign_vars(array( + 'S_ERROR' => true, + )); + } + else + { + if ($question_id) + { + $this->acp_update_question($question_input, $question_id); + } + else + { + $this->acp_add_question($question_input); + } + + add_log('admin', 'LOG_CONFIG_VISUAL'); + trigger_error($user->lang['CONFIG_UPDATED'] . adm_back_link($list_url)); + } + } + else if ($submit) + { + trigger_error($user->lang['FORM_INVALID'] . adm_back_link($list_url), E_USER_WARNING); + } + } + } + + /** + * This handles the list overview + */ + function acp_question_list(&$module) + { + global $db, $template; + + $sql = 'SELECT * + FROM ' . $this->table_captcha_questions; + $result = $db->sql_query($sql); + + $template->assign_vars(array( + 'S_LIST' => true, + )); + + while ($row = $db->sql_fetchrow($result)) + { + $url = $module->u_action . "&question_id={$row['question_id']}&configure=1&select_captcha=" . $this->get_service_name() . '&'; + + $template->assign_block_vars('questions', array( + 'QUESTION_TEXT' => $row['question_text'], + 'QUESTION_ID' => $row['question_id'], + 'QUESTION_LANG' => $row['lang_iso'], + 'U_DELETE' => "{$url}action=delete", + 'U_EDIT' => "{$url}action=edit", + )); + } + $db->sql_freeresult($result); + } + + /** + * Grab a question and bring it into a format the editor understands + */ + function acp_get_question_data($question_id) + { + global $db; + + if ($question_id) + { + $sql = 'SELECT * + FROM ' . $this->table_captcha_questions . ' + WHERE question_id = ' . $question_id; + $result = $db->sql_query($sql); + $question = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if (!$question) + { + return false; + } + + $question['answers'] = array(); + + $sql = 'SELECT * + FROM ' . $this->table_captcha_answers . ' + WHERE question_id = ' . $question_id; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $question['answers'][] = $row['answer_text']; + } + $db->sql_freeresult($result); + + return $question; + } + + return false; + } + + /** + * Grab a question from input and bring it into a format the editor understands + */ + function acp_get_question_input() + { + $answers = utf8_normalize_nfc(request_var('answers', '', true)); + + // Convert answers into array and filter if answers are set + if (strlen($answers)) + { + $answers = array_filter(array_map('trim', explode("\n", $answers)), function ($value) { + return $value !== ''; + }); + } + + $question = array( + 'question_text' => request_var('question_text', '', true), + 'strict' => request_var('strict', false), + 'lang_iso' => request_var('lang_iso', ''), + 'answers' => $answers, + ); + return $question; + } + + /** + * Update a question. + * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data + */ + function acp_update_question($data, $question_id) + { + global $db, $cache; + + // easier to delete all answers than to figure out which to update + $sql = 'DELETE FROM ' . $this->table_captcha_answers . " WHERE question_id = $question_id"; + $db->sql_query($sql); + + $langs = $this->get_languages(); + $question_ary = $data; + $question_ary['lang_id'] = $langs[$question_ary['lang_iso']]['id']; + unset($question_ary['answers']); + + $sql = 'UPDATE ' . $this->table_captcha_questions . ' + SET ' . $db->sql_build_array('UPDATE', $question_ary) . " + WHERE question_id = $question_id"; + $db->sql_query($sql); + + $this->acp_insert_answers($data, $question_id); + + $cache->destroy('sql', $this->table_captcha_questions); + } + + /** + * Insert a question. + * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data + */ + function acp_add_question($data) + { + global $db, $cache; + + $langs = $this->get_languages(); + $question_ary = $data; + + $question_ary['lang_id'] = $langs[$data['lang_iso']]['id']; + unset($question_ary['answers']); + + $sql = 'INSERT INTO ' . $this->table_captcha_questions . ' ' . $db->sql_build_array('INSERT', $question_ary); + $db->sql_query($sql); + + $question_id = $db->sql_nextid(); + + $this->acp_insert_answers($data, $question_id); + + $cache->destroy('sql', $this->table_captcha_questions); + } + + /** + * Insert the answers. + * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data + */ + function acp_insert_answers($data, $question_id) + { + global $db, $cache; + + foreach ($data['answers'] as $answer) + { + $answer_ary = array( + 'question_id' => $question_id, + 'answer_text' => $answer, + ); + + $sql = 'INSERT INTO ' . $this->table_captcha_answers . ' ' . $db->sql_build_array('INSERT', $answer_ary); + $db->sql_query($sql); + } + + $cache->destroy('sql', $this->table_captcha_answers); + } + + /** + * Delete a question. + */ + function acp_delete_question($question_id) + { + global $db, $cache; + + $tables = array($this->table_captcha_questions, $this->table_captcha_answers); + + foreach ($tables as $table) + { + $sql = "DELETE FROM $table + WHERE question_id = $question_id"; + $db->sql_query($sql); + } + + $cache->destroy('sql', $tables); + } + + /** + * Check if the entered data can be inserted/used + * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data + */ + function validate_input($question_data) + { + $langs = $this->get_languages(); + + if (!isset($question_data['lang_iso']) || + !isset($question_data['question_text']) || + !isset($question_data['strict']) || + !isset($question_data['answers'])) + { + return false; + } + + if (!isset($langs[$question_data['lang_iso']]) || + !strlen($question_data['question_text']) || + !sizeof($question_data['answers']) || + !is_array($question_data['answers'])) + { + return false; + } + + return true; + } + + /** + * List the installed language packs + */ + function get_languages() + { + global $db; + + $sql = 'SELECT * + FROM ' . LANG_TABLE; + $result = $db->sql_query($sql); + + $langs = array(); + while ($row = $db->sql_fetchrow($result)) + { + $langs[$row['lang_iso']] = array( + 'name' => $row['lang_local_name'], + 'id' => (int) $row['lang_id'], + ); + } + $db->sql_freeresult($result); + + return $langs; + } + + + + /** + * See if there is a question other than the one we have + */ + function acp_is_last($question_id) + { + global $config, $db; + + if ($question_id) + { + $sql = 'SELECT question_id + FROM ' . $this->table_captcha_questions . " + WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "' + AND question_id <> " . (int) $question_id; + $result = $db->sql_query_limit($sql, 1); + $question = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if (!$question) + { + return true; + } + return false; + } + } +} diff --git a/phpBB/phpbb/captcha/plugins/recaptcha.php b/phpBB/phpbb/captcha/plugins/recaptcha.php new file mode 100644 index 0000000000..584f3afec1 --- /dev/null +++ b/phpBB/phpbb/captcha/plugins/recaptcha.php @@ -0,0 +1,332 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\captcha\plugins; + +class recaptcha extends captcha_abstract +{ + var $recaptcha_server = 'http://www.google.com/recaptcha/api'; + var $recaptcha_server_secure = 'https://www.google.com/recaptcha/api'; // class constants :( + + // We are opening a socket to port 80 of this host and send + // the POST request asking for verification to the path specified here. + var $recaptcha_verify_server = 'www.google.com'; + var $recaptcha_verify_path = '/recaptcha/api/verify'; + + var $challenge; + var $response; + + /** + * Constructor + */ + public function __construct() + { + global $request; + $this->recaptcha_server = $request->is_secure() ? $this->recaptcha_server_secure : $this->recaptcha_server; + } + + function init($type) + { + global $config, $db, $user; + + $user->add_lang('captcha_recaptcha'); + parent::init($type); + $this->challenge = request_var('recaptcha_challenge_field', ''); + $this->response = request_var('recaptcha_response_field', ''); + } + + public function is_available() + { + global $config, $user; + $user->add_lang('captcha_recaptcha'); + return (isset($config['recaptcha_pubkey']) && !empty($config['recaptcha_pubkey'])); + } + + /** + * API function + */ + function has_config() + { + return true; + } + + static public function get_name() + { + return 'CAPTCHA_RECAPTCHA'; + } + + /** + * This function is implemented because required by the upper class, but is never used for reCaptcha. + */ + function get_generator_class() + { + throw new \Exception('No generator class given.'); + } + + function acp_page($id, &$module) + { + global $config, $db, $template, $user; + + $captcha_vars = array( + 'recaptcha_pubkey' => 'RECAPTCHA_PUBKEY', + 'recaptcha_privkey' => 'RECAPTCHA_PRIVKEY', + ); + + $module->tpl_name = 'captcha_recaptcha_acp'; + $module->page_title = 'ACP_VC_SETTINGS'; + $form_key = 'acp_captcha'; + add_form_key($form_key); + + $submit = request_var('submit', ''); + + if ($submit && check_form_key($form_key)) + { + $captcha_vars = array_keys($captcha_vars); + foreach ($captcha_vars as $captcha_var) + { + $value = request_var($captcha_var, ''); + if ($value) + { + set_config($captcha_var, $value); + } + } + + add_log('admin', 'LOG_CONFIG_VISUAL'); + trigger_error($user->lang['CONFIG_UPDATED'] . adm_back_link($module->u_action)); + } + else if ($submit) + { + trigger_error($user->lang['FORM_INVALID'] . adm_back_link($module->u_action)); + } + else + { + foreach ($captcha_vars as $captcha_var => $template_var) + { + $var = (isset($_REQUEST[$captcha_var])) ? request_var($captcha_var, '') : ((isset($config[$captcha_var])) ? $config[$captcha_var] : ''); + $template->assign_var($template_var, $var); + } + + $template->assign_vars(array( + 'CAPTCHA_PREVIEW' => $this->get_demo_template($id), + 'CAPTCHA_NAME' => $this->get_service_name(), + 'U_ACTION' => $module->u_action, + )); + + } + } + + // not needed + function execute_demo() + { + } + + // not needed + function execute() + { + } + + function get_template() + { + global $config, $user, $template, $phpbb_root_path, $phpEx; + + if ($this->is_solved()) + { + return false; + } + else + { + $contact_link = phpbb_get_board_contact_link($config, $phpbb_root_path, $phpEx); + $explain = $user->lang(($this->type != CONFIRM_POST) ? 'CONFIRM_EXPLAIN' : 'POST_CONFIRM_EXPLAIN', '<a href="' . $contact_link . '">', '</a>'); + + $template->assign_vars(array( + 'RECAPTCHA_SERVER' => $this->recaptcha_server, + 'RECAPTCHA_PUBKEY' => isset($config['recaptcha_pubkey']) ? $config['recaptcha_pubkey'] : '', + 'RECAPTCHA_ERRORGET' => '', + 'S_RECAPTCHA_AVAILABLE' => self::is_available(), + 'S_CONFIRM_CODE' => true, + 'S_TYPE' => $this->type, + 'L_CONFIRM_EXPLAIN' => $explain, + )); + + return 'captcha_recaptcha.html'; + } + } + + function get_demo_template($id) + { + return $this->get_template(); + } + + function get_hidden_fields() + { + $hidden_fields = array(); + + // this is required for posting.php - otherwise we would forget about the captcha being already solved + if ($this->solved) + { + $hidden_fields['confirm_code'] = $this->code; + } + $hidden_fields['confirm_id'] = $this->confirm_id; + return $hidden_fields; + } + + function uninstall() + { + $this->garbage_collect(0); + } + + function install() + { + return; + } + + function validate() + { + if (!parent::validate()) + { + return false; + } + else + { + return $this->recaptcha_check_answer(); + } + } + +// Code from here on is based on recaptchalib.php +/* + * This is a PHP library that handles calling reCAPTCHA. + * - Documentation and latest version + * http://recaptcha.net/plugins/php/ + * - Get a reCAPTCHA API Key + * http://recaptcha.net/api/getkey + * - Discussion group + * http://groups.google.com/group/recaptcha + * + * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net + * AUTHORS: + * Mike Crawford + * Ben Maurer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + /** + * Submits an HTTP POST to a reCAPTCHA server + * @param string $host + * @param string $path + * @param array $data + * @param int port + * @return array response + */ + function _recaptcha_http_post($host, $path, $data, $port = 80) + { + $req = $this->_recaptcha_qsencode ($data); + + $http_request = "POST $path HTTP/1.0\r\n"; + $http_request .= "Host: $host\r\n"; + $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; + $http_request .= "Content-Length: " . strlen($req) . "\r\n"; + $http_request .= "User-Agent: reCAPTCHA/PHP/phpBB\r\n"; + $http_request .= "\r\n"; + $http_request .= $req; + + $response = ''; + if (false == ($fs = @fsockopen($host, $port, $errno, $errstr, 10))) + { + trigger_error('RECAPTCHA_SOCKET_ERROR', E_USER_ERROR); + } + + fwrite($fs, $http_request); + + while (!feof($fs)) + { + // One TCP-IP packet + $response .= fgets($fs, 1160); + } + fclose($fs); + $response = explode("\r\n\r\n", $response, 2); + + return $response; + } + + /** + * Calls an HTTP POST function to verify if the user's guess was correct + * @param array $extra_params an array of extra variables to post to the server + * @return ReCaptchaResponse + */ + function recaptcha_check_answer($extra_params = array()) + { + global $config, $user; + + //discard spam submissions + if ($this->challenge == null || strlen($this->challenge) == 0 || $this->response == null || strlen($this->response) == 0) + { + return $user->lang['RECAPTCHA_INCORRECT']; + } + + $response = $this->_recaptcha_http_post($this->recaptcha_verify_server, $this->recaptcha_verify_path, + array( + 'privatekey' => $config['recaptcha_privkey'], + 'remoteip' => $user->ip, + 'challenge' => $this->challenge, + 'response' => $this->response + ) + $extra_params + ); + + $answers = explode("\n", $response[1]); + + if (trim($answers[0]) === 'true') + { + $this->solved = true; + return false; + } + else + { + return $user->lang['RECAPTCHA_INCORRECT']; + } + } + + /** + * Encodes the given data into a query string format + * @param $data - array of string elements to be encoded + * @return string - encoded request + */ + function _recaptcha_qsencode($data) + { + $req = ''; + foreach ($data as $key => $value) + { + $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; + } + + // Cut the last '&' + $req = substr($req, 0, strlen($req) - 1); + return $req; + } +} diff --git a/phpBB/phpbb/class_loader.php b/phpBB/phpbb/class_loader.php new file mode 100644 index 0000000000..cfdcc2af0b --- /dev/null +++ b/phpBB/phpbb/class_loader.php @@ -0,0 +1,164 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* The class loader resolves class names to file system paths and loads them if +* necessary. +* +* Classes have to be of the form phpbb_(dir_)*(classpart_)*, so directory names +* must never contain underscores. Example: phpbb_dir_subdir_class_name is a +* valid class name, while phpbb_dir_sub_dir_class_name is not. +* +* If every part of the class name is a directory, the last directory name is +* also used as the filename, e.g. phpbb_dir would resolve to dir/dir.php. +*/ +class class_loader +{ + private $namespace; + private $path; + private $php_ext; + private $cache; + + /** + * A map of looked up class names to paths relative to $this->path. + * This map is stored in cache and looked up if the cache is available. + * + * @var array + */ + private $cached_paths = array(); + + /** + * Creates a new \phpbb\class_loader, which loads files with the given + * file extension from the given path. + * + * @param string $namespace Required namespace for files to be loaded + * @param string $path Directory to load files from + * @param string $php_ext The file extension for PHP files + * @param \phpbb\cache\driver\driver_interface $cache An implementation of the phpBB cache interface. + */ + public function __construct($namespace, $path, $php_ext = 'php', \phpbb\cache\driver\driver_interface $cache = null) + { + if ($namespace[0] !== '\\') + { + $namespace = '\\' . $namespace; + } + + $this->namespace = $namespace; + $this->path = $path; + $this->php_ext = $php_ext; + + $this->set_cache($cache); + } + + /** + * Provide the class loader with a cache to store paths. If set to null, the + * the class loader will resolve paths by checking for the existance of every + * directory in the class name every time. + * + * @param \phpbb\cache\driver\driver_interface $cache An implementation of the phpBB cache interface. + */ + public function set_cache(\phpbb\cache\driver\driver_interface $cache = null) + { + if ($cache) + { + $this->cached_paths = $cache->get('class_loader_' . str_replace('\\', '__', $this->namespace)); + + if ($this->cached_paths === false) + { + $this->cached_paths = array(); + } + } + + $this->cache = $cache; + } + + /** + * Registers the class loader as an autoloader using SPL. + */ + public function register() + { + spl_autoload_register(array($this, 'load_class')); + } + + /** + * Removes the class loader from the SPL autoloader stack. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'load_class')); + } + + /** + * Resolves a phpBB class name to a relative path which can be included. + * + * @param string $class The class name to resolve, must be in the + * namespace the loader was constructed with. + * Has to begin with \ + * @return string|bool A relative path to the file containing the + * class or false if looking it up failed. + */ + public function resolve_path($class) + { + if (isset($this->cached_paths[$class])) + { + return $this->path . $this->cached_paths[$class] . '.' . $this->php_ext; + } + + if (!preg_match('/^' . preg_quote($this->namespace, '/') . '[a-zA-Z0-9_\\\\]+$/', $class)) + { + return false; + } + + $relative_path = str_replace('\\', '/', substr($class, strlen($this->namespace))); + + if (!file_exists($this->path . $relative_path . '.' . $this->php_ext)) + { + return false; + } + + if ($this->cache) + { + $this->cached_paths[$class] = $relative_path; + $this->cache->put('class_loader_' . str_replace('\\', '__', $this->namespace), $this->cached_paths); + } + + return $this->path . $relative_path . '.' . $this->php_ext; + } + + /** + * Resolves a class name to a path and then includes it. + * + * @param string $class The class name which is being loaded. + */ + public function load_class($class) + { + // In general $class is not supposed to contain a leading backslash, + // but sometimes it does. See tickets PHP-50731 and HHVM-1840. + if ($class[0] !== '\\') + { + $class = '\\' . $class; + } + + if (substr($class, 0, strlen($this->namespace)) === $this->namespace) + { + $path = $this->resolve_path($class); + + if ($path) + { + require $path; + } + } + } +} diff --git a/phpBB/phpbb/composer.json b/phpBB/phpbb/composer.json new file mode 100644 index 0000000000..6b3888ef64 --- /dev/null +++ b/phpBB/phpbb/composer.json @@ -0,0 +1,32 @@ +{ + "name": "phpbb/phpbb-core", + "description": "Collection of core phpBB libraries", + "type": "library", + "keywords": ["phpbb", "forum"], + "homepage": "https://www.phpbb.com", + "license": "GPL-2.0", + "authors": [ + { + "name": "phpBB Limited", + "email": "operations@phpbb.com", + "homepage": "https://www.phpbb.com/go/authors" + } + ], + "support": { + "issues": "https://tracker.phpbb.com", + "forum": "https://www.phpbb.com/community/", + "wiki": "https://wiki.phpbb.com", + "irc": "irc://irc.freenode.org/phpbb" + }, + "autoload": { + "classmap": [""] + }, + "require": { + "php": ">=5.3.3" + }, + "extra": { + "branch-alias": { + "dev-master": "3.1.x-dev" + } + } +} diff --git a/phpBB/phpbb/config/config.php b/phpBB/phpbb/config/config.php new file mode 100644 index 0000000000..aaad333006 --- /dev/null +++ b/phpBB/phpbb/config/config.php @@ -0,0 +1,167 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\config; + +/** +* Configuration container class +*/ +class config implements \ArrayAccess, \IteratorAggregate, \Countable +{ + /** + * The configuration data + * @var array(string => string) + */ + protected $config; + + /** + * Creates a configuration container with a default set of values + * + * @param array(string => string) $config The configuration data. + */ + public function __construct(array $config) + { + $this->config = $config; + } + + /** + * Retrieves an ArrayIterator over the configuration values. + * + * @return \ArrayIterator An iterator over all config data + */ + public function getIterator() + { + return new \ArrayIterator($this->config); + } + + /** + * Checks if the specified config value exists. + * + * @param string $key The configuration option's name. + * @return bool Whether the configuration option exists. + */ + public function offsetExists($key) + { + return isset($this->config[$key]); + } + + /** + * Retrieves a configuration value. + * + * @param string $key The configuration option's name. + * @return string The configuration value + */ + public function offsetGet($key) + { + return (isset($this->config[$key])) ? $this->config[$key] : ''; + } + + /** + * Temporarily overwrites the value of a configuration variable. + * + * The configuration change will not persist. It will be lost + * after the request. + * + * @param string $key The configuration option's name. + * @param string $value The temporary value. + */ + public function offsetSet($key, $value) + { + $this->config[$key] = $value; + } + + /** + * Called when deleting a configuration value directly, triggers an error. + * + * @param string $key The configuration option's name. + */ + public function offsetUnset($key) + { + trigger_error('Config values have to be deleted explicitly with the \phpbb\config\config::delete($key) method.', E_USER_ERROR); + } + + /** + * Retrieves the number of configuration options currently set. + * + * @return int Number of config options + */ + public function count() + { + return count($this->config); + } + + /** + * Removes a configuration option + * + * @param String $key The configuration option's name + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached + * @return null + */ + public function delete($key, $use_cache = true) + { + unset($this->config[$key]); + } + + /** + * Sets a configuration option's value + * + * @param string $key The configuration option's name + * @param string $value New configuration value + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached. + */ + public function set($key, $value, $use_cache = true) + { + $this->config[$key] = $value; + } + + /** + * Sets a configuration option's value only if the old_value matches the + * current configuration value or the configuration value does not exist yet. + * + * @param string $key The configuration option's name + * @param string $old_value Current configuration value + * @param string $new_value New configuration value + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached. + * @return bool True if the value was changed, false otherwise. + */ + public function set_atomic($key, $old_value, $new_value, $use_cache = true) + { + if (!isset($this->config[$key]) || $this->config[$key] == $old_value) + { + $this->config[$key] = $new_value; + return true; + } + return false; + } + + /** + * Increments an integer configuration value. + * + * @param string $key The configuration option's name + * @param int $increment Amount to increment by + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached. + */ + function increment($key, $increment, $use_cache = true) + { + if (!isset($this->config[$key])) + { + $this->config[$key] = 0; + } + + $this->config[$key] += $increment; + } +} diff --git a/phpBB/phpbb/config/db.php b/phpBB/phpbb/config/db.php new file mode 100644 index 0000000000..26489bdd34 --- /dev/null +++ b/phpBB/phpbb/config/db.php @@ -0,0 +1,204 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\config; + +/** +* Configuration container class +*/ +class db extends \phpbb\config\config +{ + /** + * Cache instance + * @var \phpbb\cache\driver\driver_interface + */ + protected $cache; + + /** + * Database connection + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * Name of the database table used for configuration. + * @var string + */ + protected $table; + + /** + * Creates a configuration container with a default set of values + * + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param \phpbb\cache\driver\driver_interface $cache Cache instance + * @param string $table Configuration table name + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\cache\driver\driver_interface $cache, $table) + { + $this->db = $db; + $this->cache = $cache; + $this->table = $table; + + if (($config = $cache->get('config')) !== false) + { + $sql = 'SELECT config_name, config_value + FROM ' . $this->table . ' + WHERE is_dynamic = 1'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $config[$row['config_name']] = $row['config_value']; + } + $this->db->sql_freeresult($result); + } + else + { + $config = $cached_config = array(); + + $sql = 'SELECT config_name, config_value, is_dynamic + FROM ' . $this->table; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + if (!$row['is_dynamic']) + { + $cached_config[$row['config_name']] = $row['config_value']; + } + + $config[$row['config_name']] = $row['config_value']; + } + $this->db->sql_freeresult($result); + + $cache->put('config', $cached_config); + } + + parent::__construct($config); + } + + /** + * Removes a configuration option + * + * @param String $key The configuration option's name + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached + * @return null + */ + public function delete($key, $use_cache = true) + { + $sql = 'DELETE FROM ' . $this->table . " + WHERE config_name = '" . $this->db->sql_escape($key) . "'"; + $this->db->sql_query($sql); + + unset($this->config[$key]); + + if ($use_cache) + { + $this->cache->destroy('config'); + } + } + + /** + * Sets a configuration option's value + * + * @param string $key The configuration option's name + * @param string $value New configuration value + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached. + */ + public function set($key, $value, $use_cache = true) + { + $this->set_atomic($key, false, $value, $use_cache); + } + + /** + * Sets a configuration option's value only if the old_value matches the + * current configuration value or the configuration value does not exist yet. + * + * @param string $key The configuration option's name + * @param mixed $old_value Current configuration value or false to ignore + * the old value + * @param string $new_value New configuration value + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached + * @return bool True if the value was changed, false otherwise + */ + public function set_atomic($key, $old_value, $new_value, $use_cache = true) + { + $sql = 'UPDATE ' . $this->table . " + SET config_value = '" . $this->db->sql_escape($new_value) . "' + WHERE config_name = '" . $this->db->sql_escape($key) . "'"; + + if ($old_value !== false) + { + $sql .= " AND config_value = '" . $this->db->sql_escape($old_value) . "'"; + } + + $this->db->sql_query($sql); + + if (!$this->db->sql_affectedrows() && isset($this->config[$key])) + { + return false; + } + + if (!isset($this->config[$key])) + { + $sql = 'INSERT INTO ' . $this->table . ' ' . $this->db->sql_build_array('INSERT', array( + 'config_name' => $key, + 'config_value' => $new_value, + 'is_dynamic' => ($use_cache) ? 0 : 1)); + $this->db->sql_query($sql); + } + + if ($use_cache) + { + $this->cache->destroy('config'); + } + + $this->config[$key] = $new_value; + return true; + } + + /** + * Increments an integer config value directly in the database. + * + * Using this method instead of setting the new value directly avoids race + * conditions and unlike set_atomic it cannot fail. + * + * @param string $key The configuration option's name + * @param int $increment Amount to increment by + * @param bool $use_cache Whether this variable should be cached or if it + * changes too frequently to be efficiently cached. + */ + function increment($key, $increment, $use_cache = true) + { + if (!isset($this->config[$key])) + { + $this->set($key, '0', $use_cache); + } + + $sql_update = $this->db->cast_expr_to_string($this->db->cast_expr_to_bigint('config_value') . ' + ' . (int) $increment); + + $this->db->sql_query('UPDATE ' . $this->table . ' + SET config_value = ' . $sql_update . " + WHERE config_name = '" . $this->db->sql_escape($key) . "'"); + + if ($use_cache) + { + $this->cache->destroy('config'); + } + + $this->config[$key] += $increment; + } +} diff --git a/phpBB/phpbb/config/db_text.php b/phpBB/phpbb/config/db_text.php new file mode 100644 index 0000000000..818f6bdcc9 --- /dev/null +++ b/phpBB/phpbb/config/db_text.php @@ -0,0 +1,159 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\config; + +/** +* Manages configuration options with an arbitrary length value stored in a TEXT +* column. In constrast to class \phpbb\config\db, values are never cached and +* prefetched, but every get operation sends a query to the database. +*/ +class db_text +{ + /** + * Database connection + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * Name of the database table used. + * @var string + */ + protected $table; + + /** + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param string $table Table name + */ + public function __construct(\phpbb\db\driver\driver_interface $db, $table) + { + $this->db = $db; + $this->table = $this->db->sql_escape($table); + } + + /** + * Sets the configuration option with the name $key to $value. + * + * @param string $key The configuration option's name + * @param string $value New configuration value + * + * @return null + */ + public function set($key, $value) + { + $this->set_array(array($key => $value)); + } + + /** + * Gets the configuration value for the name $key. + * + * @param string $key The configuration option's name + * + * @return string|null String result on success + * null if there is no such option + */ + public function get($key) + { + $map = $this->get_array(array($key)); + + return isset($map[$key]) ? $map[$key] : null; + } + + /** + * Removes the configuration option with the name $key. + * + * @param string $key The configuration option's name + * + * @return null + */ + public function delete($key) + { + $this->delete_array(array($key)); + } + + /** + * Mass set configuration options: Receives an associative array, + * treats array keys as configuration option names and associated + * array values as their configuration option values. + * + * @param array $map Map from configuration names to values + * + * @return null + */ + public function set_array(array $map) + { + $this->db->sql_transaction('begin'); + + foreach ($map as $key => $value) + { + $sql = 'UPDATE ' . $this->table . " + SET config_value = '" . $this->db->sql_escape($value) . "' + WHERE config_name = '" . $this->db->sql_escape($key) . "'"; + $this->db->sql_query($sql); + + if (!$this->db->sql_affectedrows()) + { + $sql = 'INSERT INTO ' . $this->table . ' ' . $this->db->sql_build_array('INSERT', array( + 'config_name' => (string) $key, + 'config_value' => (string) $value, + )); + $this->db->sql_query($sql); + } + } + + $this->db->sql_transaction('commit'); + } + + /** + * Mass get configuration options: Receives a set of configuration + * option names and returns the result as a key => value map where + * array keys are configuration option names and array values are + * associated config option values. + * + * @param array $keys Set of configuration option names + * + * @return array Map from configuration names to values + */ + public function get_array(array $keys) + { + $sql = 'SELECT * + FROM ' . $this->table . ' + WHERE ' . $this->db->sql_in_set('config_name', $keys, false, true); + $result = $this->db->sql_query($sql); + + $map = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $map[$row['config_name']] = $row['config_value']; + } + $this->db->sql_freeresult($result); + + return $map; + } + + /** + * Mass delete configuration options. + * + * @param array $keys Set of configuration option names + * + * @return null + */ + public function delete_array(array $keys) + { + $sql = 'DELETE + FROM ' . $this->table . ' + WHERE ' . $this->db->sql_in_set('config_name', $keys, false, true); + $this->db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/config_php_file.php b/phpBB/phpbb/config_php_file.php new file mode 100644 index 0000000000..7445e7df22 --- /dev/null +++ b/phpBB/phpbb/config_php_file.php @@ -0,0 +1,160 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +class config_php_file +{ + /** @var string phpBB Root Path */ + protected $phpbb_root_path; + + /** @var string php file extension */ + protected $php_ext; + + /** + * Indicates whether the php config file has been loaded. + * + * @var bool + */ + protected $config_loaded = false; + + /** + * The content of the php config file + * + * @var array + */ + protected $config_data = array(); + + /** + * The path to the config file. (Default: $phpbb_root_path . 'config.' . $php_ext) + * + * @var string + */ + protected $config_file; + + private $defined_vars; + + /** + * Constructor + * + * @param string $phpbb_root_path phpBB Root Path + * @param string $php_ext php file extension + */ + function __construct($phpbb_root_path, $php_ext) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config_file = $this->phpbb_root_path . 'config.' . $this->php_ext; + } + + /** + * Set the path to the config file. + * + * @param string $config_file + */ + public function set_config_file($config_file) + { + $this->config_file = $config_file; + $this->config_loaded = false; + } + + /** + * Returns an associative array containing the variables defined by the config file. + * + * @return array Return the content of the config file or an empty array if the file does not exists. + */ + public function get_all() + { + $this->load_config_file(); + + return $this->config_data; + } + + /** + * Return the value of a variable defined into the config.php file or null if the variable does not exist. + * + * @param string $variable The name of the variable + * @return mixed Value of the variable or null if the variable is not defined. + */ + public function get($variable) + { + $this->load_config_file(); + + return isset($this->config_data[$variable]) ? $this->config_data[$variable] : null; + } + + /** + * Load the config file and store the information. + * + * @return null + */ + protected function load_config_file() + { + if (!$this->config_loaded && file_exists($this->config_file)) + { + $this->defined_vars = get_defined_vars(); + + require($this->config_file); + $this->config_data = array_diff_key(get_defined_vars(), $this->defined_vars); + + $this->config_loaded = true; + } + } + + /** + * Convert either 3.0 dbms or 3.1 db driver class name to 3.1 db driver class name. + * + * If $dbms is a valid 3.1 db driver class name, returns it unchanged. + * Otherwise prepends phpbb\db\driver\ to the dbms to convert a 3.0 dbms + * to 3.1 db driver class name. + * + * @param string $dbms dbms parameter + * @return string driver class + * @throws \RuntimeException + */ + public function convert_30_dbms_to_31($dbms) + { + // Note: this check is done first because mysqli extension + // supplies a mysqli class, and class_exists($dbms) would return + // true for mysqli class. + // However, per the docblock any valid 3.1 driver name should be + // recognized by this function, and have priority over 3.0 dbms. + if (strpos($dbms, 'phpbb\db\driver') === false && class_exists('phpbb\db\driver\\' . $dbms)) + { + return 'phpbb\db\driver\\' . $dbms; + } + + if (class_exists($dbms)) + { + // Additionally we could check that $dbms extends phpbb\db\driver\driver. + // http://php.net/manual/en/class.reflectionclass.php + // Beware of possible performance issues: + // http://stackoverflow.com/questions/294582/php-5-reflection-api-performance + // We could check for interface implementation in all paths or + // only when we do not prepend phpbb\db\driver\. + + /* + $reflection = new \ReflectionClass($dbms); + + if ($reflection->isSubclassOf('phpbb\db\driver\driver')) + { + return $dbms; + } + */ + + return $dbms; + } + + throw new \RuntimeException("You have specified an invalid dbms driver: $dbms"); + } +} diff --git a/phpBB/phpbb/console/application.php b/phpBB/phpbb/console/application.php new file mode 100644 index 0000000000..bc4897af18 --- /dev/null +++ b/phpBB/phpbb/console/application.php @@ -0,0 +1,120 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\console; + +use Symfony\Component\Console\Shell; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +class application extends \Symfony\Component\Console\Application +{ + /** + * @var bool Indicates whether or not we are in a shell + */ + protected $in_shell = false; + + /** + * @var \phpbb\user User object + */ + protected $user; + + /** + * @param string $name The name of the application + * @param string $version The version of the application + * @param \phpbb\user $user The user which runs the application (used for translation) + */ + public function __construct($name, $version, \phpbb\user $user) + { + $this->user = $user; + + parent::__construct($name, $version); + } + + /** + * {@inheritdoc} + */ + protected function getDefaultInputDefinition() + { + $input_definition = parent::getDefaultInputDefinition(); + + $input_definition->addOption(new InputOption( + 'safe-mode', + null, + InputOption::VALUE_NONE, + $this->user->lang('CLI_DESCRIPTION_OPTION_SAFE_MODE') + )); + + return $input_definition; + } + + /** + * Gets the help message. + * + * It's a hack of the default help message to display the --shell + * option only for the application and not for all the commands. + * + * @return string A help message. + */ + public function getHelp() + { + // If we are already in a shell + // we do not want to have the --shell option available + if ($this->in_shell) + { + return parent::getHelp(); + } + + $this->getDefinition()->addOption(new InputOption( + '--shell', + '-s', + InputOption::VALUE_NONE, + $this->user->lang('CLI_DESCRIPTION_OPTION_SHELL') + )); + + return parent::getHelp(); + } + + /** + * Register a set of commands from the container + * + * @param \phpbb\di\service_collection $command_collection The console service collection + */ + public function register_container_commands(\phpbb\di\service_collection $command_collection) + { + foreach ($command_collection as $service_command) + { + $this->add($service_command); + } + } + + /** + * {@inheritdoc} + */ + public function doRun(InputInterface $input, OutputInterface $output) + { + // Run a shell if the --shell (or -s) option is set and if no command name is specified + // Also, we do not want to have the --shell option available if we are already in a shell + if (!$this->in_shell && $this->getCommandName($input) === null && $input->hasParameterOption(array('--shell', '-s'))) + { + $shell = new Shell($this); + $this->in_shell = true; + $shell->run(); + + return 0; + } + + return parent::doRun($input, $output); + } +} diff --git a/phpBB/phpbb/console/command/cache/purge.php b/phpBB/phpbb/console/command/cache/purge.php new file mode 100644 index 0000000000..d0c2ef6f72 --- /dev/null +++ b/phpBB/phpbb/console/command/cache/purge.php @@ -0,0 +1,89 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\cache; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class purge extends \phpbb\console\command\command +{ + /** @var \phpbb\cache\driver\driver_interface */ + protected $cache; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\auth\auth */ + protected $auth; + + /** @var \phpbb\log\log_interface */ + protected $log; + + /** @var \phpbb\config\config */ + protected $config; + + /** + * Constructor + * + * @param \phpbb\user $user User instance + * @param \phpbb\cache\driver\driver_interface $cache Cache instance + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param \phpbb\auth\auth $auth Auth instance + * @param \phpbb\log\log $log Logger instance + * @param \phpbb\config\config $config Config instance + */ + public function __construct(\phpbb\user $user, \phpbb\cache\driver\driver_interface $cache, \phpbb\db\driver\driver_interface $db, \phpbb\auth\auth $auth, \phpbb\log\log_interface $log, \phpbb\config\config $config) + { + $this->cache = $cache; + $this->db = $db; + $this->auth = $auth; + $this->log = $log; + $this->config = $config; + parent::__construct($user); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('cache:purge') + ->setDescription($this->user->lang('PURGE_CACHE')) + ; + } + + /** + * Executes the command cache:purge. + * + * Purge the cache (including permissions) and increment the asset_version number + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return null + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $this->config->increment('assets_version', 1); + $this->cache->purge(); + + // Clear permissions + $this->auth->acl_clear_prefetch(); + phpbb_cache_moderators($this->db, $this->cache, $this->auth); + + $this->log->add('admin', ANONYMOUS, '', 'LOG_PURGE_CACHE', time(), array()); + + $output->writeln($this->user->lang('PURGE_CACHE_SUCCESS')); + } +} diff --git a/phpBB/phpbb/console/command/command.php b/phpBB/phpbb/console/command/command.php new file mode 100644 index 0000000000..638c989da2 --- /dev/null +++ b/phpBB/phpbb/console/command/command.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\console\command; + +abstract class command extends \Symfony\Component\Console\Command\Command +{ + /** @var \phpbb\user */ + protected $user; + + /** + * Constructor + * + * @param \phpbb\user $user User instance (mostly for translation) + */ + public function __construct(\phpbb\user $user) + { + $this->user = $user; + parent::__construct(); + } +} diff --git a/phpBB/phpbb/console/command/config/command.php b/phpBB/phpbb/console/command/config/command.php new file mode 100644 index 0000000000..f0ad5d4d19 --- /dev/null +++ b/phpBB/phpbb/console/command/config/command.php @@ -0,0 +1,26 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\config; + +abstract class command extends \phpbb\console\command\command +{ + /** @var \phpbb\config\config */ + protected $config; + + function __construct(\phpbb\user $user, \phpbb\config\config $config) + { + $this->config = $config; + + parent::__construct($user); + } +} diff --git a/phpBB/phpbb/console/command/config/delete.php b/phpBB/phpbb/console/command/config/delete.php new file mode 100644 index 0000000000..efd276d7e3 --- /dev/null +++ b/phpBB/phpbb/console/command/config/delete.php @@ -0,0 +1,63 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\config; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class delete extends command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('config:delete') + ->setDescription($this->user->lang('CLI_DESCRIPTION_DELETE_CONFIG')) + ->addArgument( + 'key', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_OPTION_NAME') + ) + ; + } + + /** + * Executes the command config:delete. + * + * Removes a configuration option + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return null + * @see \phpbb\config\config::delete() + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $key = $input->getArgument('key'); + + if (isset($this->config[$key])) + { + $this->config->delete($key); + + $output->writeln('<info>' . $this->user->lang('CLI_CONFIG_DELETE_SUCCESS', $key) . '</info>'); + } + else + { + $output->writeln('<error>' . $this->user->lang('CLI_CONFIG_NOT_EXISTS', $key) . '</error>'); + } + } +} diff --git a/phpBB/phpbb/console/command/config/get.php b/phpBB/phpbb/console/command/config/get.php new file mode 100644 index 0000000000..9c03b49a3d --- /dev/null +++ b/phpBB/phpbb/console/command/config/get.php @@ -0,0 +1,72 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\config; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +class get extends command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('config:get') + ->setDescription($this->user->lang('CLI_DESCRIPTION_GET_CONFIG')) + ->addArgument( + 'key', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_OPTION_NAME') + ) + ->addOption( + 'no-newline', + null, + InputOption::VALUE_NONE, + $this->user->lang('CLI_CONFIG_PRINT_WITHOUT_NEWLINE') + ) + ; + } + + /** + * Executes the command config:get. + * + * Retrieves a configuration value. + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return null + * @see \phpbb\config\config::offsetGet() + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $key = $input->getArgument('key'); + + if (isset($this->config[$key]) && $input->getOption('no-newline')) + { + $output->write($this->config[$key]); + } + else if (isset($this->config[$key])) + { + $output->writeln($this->config[$key]); + } + else + { + $output->writeln('<error>' . $this->user->lang('CLI_CONFIG_NOT_EXISTS', $key) . '</error>'); + } + } +} diff --git a/phpBB/phpbb/console/command/config/increment.php b/phpBB/phpbb/console/command/config/increment.php new file mode 100644 index 0000000000..b4d7438b66 --- /dev/null +++ b/phpBB/phpbb/console/command/config/increment.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\config; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +class increment extends command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('config:increment') + ->setDescription($this->user->lang('CLI_DESCRIPTION_INCREMENT_CONFIG')) + ->addArgument( + 'key', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_OPTION_NAME') + ) + ->addArgument( + 'increment', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_INCREMENT_BY') + ) + ->addOption( + 'dynamic', + 'd', + InputOption::VALUE_NONE, + $this->user->lang('CLI_CONFIG_CANNOT_CACHED') + ) + ; + } + + /** + * Executes the command config:increment. + * + * Increments an integer configuration value. + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return null + * @see \phpbb\config\config::increment() + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $key = $input->getArgument('key'); + $increment = $input->getArgument('increment'); + $use_cache = !$input->getOption('dynamic'); + + $this->config->increment($key, $increment, $use_cache); + + $output->writeln('<info>' . $this->user->lang('CLI_CONFIG_INCREMENT_SUCCESS', $key) . '</info>'); + } +} diff --git a/phpBB/phpbb/console/command/config/set.php b/phpBB/phpbb/console/command/config/set.php new file mode 100644 index 0000000000..695de31013 --- /dev/null +++ b/phpBB/phpbb/console/command/config/set.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\config; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +class set extends command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('config:set') + ->setDescription($this->user->lang('CLI_DESCRIPTION_SET_CONFIG')) + ->addArgument( + 'key', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_OPTION_NAME') + ) + ->addArgument( + 'value', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_NEW') + ) + ->addOption( + 'dynamic', + 'd', + InputOption::VALUE_NONE, + $this->user->lang('CLI_CONFIG_CANNOT_CACHED') + ) + ; + } + + /** + * Executes the command config:set. + * + * Sets a configuration option's value. + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return null + * @see \phpbb\config\config::set() + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $key = $input->getArgument('key'); + $value = $input->getArgument('value'); + $use_cache = !$input->getOption('dynamic'); + + $this->config->set($key, $value, $use_cache); + + $output->writeln('<info>' . $this->user->lang('CLI_CONFIG_SET_SUCCESS', $key) . '</info>'); + } +} diff --git a/phpBB/phpbb/console/command/config/set_atomic.php b/phpBB/phpbb/console/command/config/set_atomic.php new file mode 100644 index 0000000000..e8c69a0885 --- /dev/null +++ b/phpBB/phpbb/console/command/config/set_atomic.php @@ -0,0 +1,84 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\config; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +class set_atomic extends command +{ + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('config:set-atomic') + ->setDescription($this->user->lang('CLI_DESCRIPTION_SET_ATOMIC_CONFIG')) + ->addArgument( + 'key', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_OPTION_NAME') + ) + ->addArgument( + 'old', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_CURRENT') + ) + ->addArgument( + 'new', + InputArgument::REQUIRED, + $this->user->lang('CLI_CONFIG_NEW') + ) + ->addOption( + 'dynamic', + 'd', + InputOption::VALUE_NONE, + $this->user->lang('CLI_CONFIG_CANNOT_CACHED') + ) + ; + } + + /** + * Executes the command config:set-atomic. + * + * Sets a configuration option's value only if the old_value matches the + * current configuration value or the configuration value does not exist yet. + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return bool True if the value was changed, false otherwise. + * @see \phpbb\config\config::set_atomic() + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $key = $input->getArgument('key'); + $old_value = $input->getArgument('old'); + $new_value = $input->getArgument('new'); + $use_cache = !$input->getOption('dynamic'); + + if ($this->config->set_atomic($key, $old_value, $new_value, $use_cache)) + { + $output->writeln('<info>' . $this->user->lang('CLI_CONFIG_SET_SUCCESS', $key) . '</info>'); + return 0; + } + else + { + $output->writeln('<error>' . $this->user->lang('CLI_CONFIG_SET_FAILURE', $key) . '</error>'); + return 1; + } + } +} diff --git a/phpBB/phpbb/console/command/cron/cron_list.php b/phpBB/phpbb/console/command/cron/cron_list.php new file mode 100644 index 0000000000..c515fd9e80 --- /dev/null +++ b/phpBB/phpbb/console/command/cron/cron_list.php @@ -0,0 +1,111 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\cron; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class cron_list extends \phpbb\console\command\command +{ + /** @var \phpbb\cron\manager */ + protected $cron_manager; + + /** + * Constructor + * + * @param \phpbb\user $user User instance + * @param \phpbb\cron\manager $cron_manager Cron manager + */ + public function __construct(\phpbb\user $user, \phpbb\cron\manager $cron_manager) + { + $this->cron_manager = $cron_manager; + parent::__construct($user); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('cron:list') + ->setDescription($this->user->lang('CLI_DESCRIPTION_CRON_LIST')) + ; + } + + /** + * Executes the command cron:list. + * + * Prints a list of ready and unready cron jobs. + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return null + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $tasks = $this->cron_manager->get_tasks(); + + if (empty($tasks)) + { + $output->writeln($this->user->lang('CRON_NO_TASKS')); + return; + } + + $ready_tasks = array(); + $not_ready_tasks = array(); + foreach ($tasks as $task) + { + if ($task->is_ready()) + { + $ready_tasks[] = $task; + } + else + { + $not_ready_tasks[] = $task; + } + } + + if (!empty($ready_tasks)) + { + $output->writeln('<info>' . $this->user->lang('TASKS_READY') . '</info>'); + $this->print_tasks_names($ready_tasks, $output); + } + + if (!empty($ready_tasks) && !empty($not_ready_tasks)) + { + $output->writeln(''); + } + + if (!empty($not_ready_tasks)) + { + $output->writeln('<info>' . $this->user->lang('TASKS_NOT_READY') . '</info>'); + $this->print_tasks_names($not_ready_tasks, $output); + } + } + + /** + * Print a list of cron jobs + * + * @param array $tasks A list of task to display + * @param OutputInterface $output An OutputInterface instance + */ + protected function print_tasks_names(array $tasks, OutputInterface $output) + { + foreach ($tasks as $task) + { + $output->writeln($task->get_name()); + } + } +} diff --git a/phpBB/phpbb/console/command/cron/run.php b/phpBB/phpbb/console/command/cron/run.php new file mode 100644 index 0000000000..a9648fcd41 --- /dev/null +++ b/phpBB/phpbb/console/command/cron/run.php @@ -0,0 +1,172 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\console\command\cron; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Output\OutputInterface; + +class run extends \phpbb\console\command\command +{ + /** @var \phpbb\cron\manager */ + protected $cron_manager; + + /** @var \phpbb\lock\db */ + protected $lock_db; + + /** + * Construct method + * + * @param \phpbb\user $user The user object (used to get language information) + * @param \phpbb\cron\manager $cron_manager The cron manager containing + * the cron tasks to be executed. + * @param \phpbb\lock\db $lock_db The lock for accessing database. + */ + public function __construct(\phpbb\user $user, \phpbb\cron\manager $cron_manager, \phpbb\lock\db $lock_db) + { + $this->cron_manager = $cron_manager; + $this->lock_db = $lock_db; + parent::__construct($user); + } + + /** + * Sets the command name and description + * + * @return null + */ + protected function configure() + { + $this + ->setName('cron:run') + ->setDescription($this->user->lang('CLI_DESCRIPTION_CRON_RUN')) + ->setHelp($this->user->lang('CLI_HELP_CRON_RUN')) + ->addArgument('name', InputArgument::OPTIONAL, $this->user->lang('CLI_DESCRIPTION_CRON_RUN_ARGUMENT_1')) + ; + } + + /** + * Executes the command cron:run. + * + * Tries to acquire the cron lock, then if no argument has been given runs all ready cron tasks. + * If the cron lock can not be obtained, an error message is printed + * and the exit status is set to 1. + * If the verbose option is specified, each start of a task is printed. + * Otherwise there is no output. + * If an argument is given to the command, only the task whose name matches the + * argument will be started. If verbose option is specified, + * an info message containing the name of the task is printed. + * If no task matches the argument given, an error message is printed + * and the exit status is set to 2. + * + * @param InputInterface $input The input stream used to get the argument and verboe option. + * @param OutputInterface $output The output stream, used for printing verbose-mode and error information. + * + * @return int 0 if all is ok, 1 if a lock error occured and 2 if no task matching the argument was found. + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + if ($this->lock_db->acquire()) + { + $task_name = $input->getArgument('name'); + if ($task_name) + { + $exit_status = $this->run_one($input, $output, $task_name); + } + else + { + $exit_status = $this->run_all($input, $output); + } + + $this->lock_db->release(); + return $exit_status; + } + else + { + $output->writeln('<error>' . $this->user->lang('CRON_LOCK_ERROR') . '</error>'); + return 1; + } + } + + /** + * Executes all ready cron tasks. + * + * If verbose mode is set, an info message will be printed if there is no task to + * be run, or else for each starting task. + * + * @see execute + * @param InputInterface $input The input stream used to get the argument and verbose option. + * @param OutputInterface $output The output stream, used for printing verbose-mode and error information. + * @return int 0 + */ + protected function run_all(InputInterface $input, OutputInterface $output) + { + $run_tasks = $this->cron_manager->find_all_ready_tasks(); + + if ($run_tasks) + { + foreach ($run_tasks as $task) + { + if ($input->getOption('verbose')) + { + $output->writeln('<info>' . $this->user->lang('RUNNING_TASK', $task->get_name()) . '</info>'); + } + + $task->run(); + } + } + else + { + if ($input->getOption('verbose')) + { + $output->writeln('<info>' . $this->user->lang('CRON_NO_TASK') . '</info>'); + } + } + + return 0; + } + + /** + * Executes a given cron task, if it is ready. + * + * If there is a task whose name matches $task_name, it is run and 0 is returned. + * and if verbose mode is set, print an info message with the name of the task. + * If there is no task matching $task_name, the function prints an error message + * and returns with status 2. + * + * @see execute + * @param string $task_name The name of the task that should be run. + * @param InputInterface $input The input stream used to get the argument and verbose option. + * @param OutputInterface $output The output stream, used for printing verbose-mode and error information. + * @return int 0 if all is well, 2 if no task matches $task_name. + */ + protected function run_one(InputInterface $input, OutputInterface $output, $task_name) + { + $task = $this->cron_manager->find_task($task_name); + if ($task) + { + if ($input->getOption('verbose')) + { + $output->writeln('<info>' . $this->user->lang('RUNNING_TASK', $task_name) . '</info>'); + } + + $task->run(); + return 0; + } + else + { + $output->writeln('<error>' . $this->user->lang('CRON_NO_SUCH_TASK', $task_name) . '</error>'); + return 2; + } + } +} diff --git a/phpBB/phpbb/console/command/db/console_migrator_output_handler.php b/phpBB/phpbb/console/command/db/console_migrator_output_handler.php new file mode 100644 index 0000000000..b9741a3838 --- /dev/null +++ b/phpBB/phpbb/console/command/db/console_migrator_output_handler.php @@ -0,0 +1,69 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\console\command\db; + +use phpbb\user; +use phpbb\db\migrator_output_handler_interface; +use Symfony\Component\Console\Output\OutputInterface; + +class console_migrator_output_handler implements migrator_output_handler_interface +{ + /** + * User object. + * + * @var user + */ + private $user; + + /** + * Console output object. + * + * @var OutputInterface + */ + private $output; + + /** + * Constructor + * + * @param user $user User object + * @param OutputInterface $output Console output object + */ + public function __construct(user $user, OutputInterface $output) + { + $this->user = $user; + $this->output = $output; + } + + /** + * {@inheritdoc} + */ + public function write($message, $verbosity) + { + if ($verbosity <= $this->output->getVerbosity()) + { + $translated_message = call_user_func_array(array($this->user, 'lang'), $message); + + if ($verbosity === migrator_output_handler_interface::VERBOSITY_NORMAL) + { + $translated_message = '<info>' . $translated_message . '</info>'; + } + else if ($verbosity === migrator_output_handler_interface::VERBOSITY_VERBOSE) + { + $translated_message = '<comment>' . $translated_message . '</comment>'; + } + + $this->output->writeln($translated_message); + } + } +} diff --git a/phpBB/phpbb/console/command/db/migrate.php b/phpBB/phpbb/console/command/db/migrate.php new file mode 100644 index 0000000000..87c2a057d1 --- /dev/null +++ b/phpBB/phpbb/console/command/db/migrate.php @@ -0,0 +1,107 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\db; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class migrate extends \phpbb\console\command\command +{ + /** @var \phpbb\db\migrator */ + protected $migrator; + + /** @var \phpbb\extension\manager */ + protected $extension_manager; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\cache\service */ + protected $cache; + + /** @var \phpbb\log\log */ + protected $log; + + /** @var string phpBB root path */ + protected $phpbb_root_path; + + function __construct(\phpbb\user $user, \phpbb\db\migrator $migrator, \phpbb\extension\manager $extension_manager, \phpbb\config\config $config, \phpbb\cache\service $cache, \phpbb\log\log $log, $phpbb_root_path) + { + $this->migrator = $migrator; + $this->extension_manager = $extension_manager; + $this->config = $config; + $this->cache = $cache; + $this->log = $log; + $this->phpbb_root_path = $phpbb_root_path; + parent::__construct($user); + $this->user->add_lang(array('common', 'install', 'migrator')); + } + + protected function configure() + { + $this + ->setName('db:migrate') + ->setDescription($this->user->lang('CLI_DESCRIPTION_DB_MIGRATE')) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $this->migrator->set_output_handler(new \phpbb\db\log_wrapper_migrator_output_handler($this->user, new console_migrator_output_handler($this->user, $output), $this->phpbb_root_path . 'store/migrations_' . time() . '.log')); + + $this->migrator->create_migrations_table(); + + $this->cache->purge(); + + $this->load_migrations(); + $orig_version = $this->config['version']; + while (!$this->migrator->finished()) + { + try + { + $this->migrator->update(); + } + catch (\phpbb\db\migration\exception $e) + { + $output->writeln('<error>' . $e->getLocalisedMessage($this->user) . '</error>'); + $this->finalise_update(); + return 1; + } + } + + if ($orig_version != $this->config['version']) + { + $this->log->add('admin', ANONYMOUS, '', 'LOG_UPDATE_DATABASE', time(), array($orig_version, $this->config['version'])); + } + + $this->finalise_update(); + $output->writeln($this->user->lang['DATABASE_UPDATE_COMPLETE']); + } + + protected function load_migrations() + { + $migrations = $this->extension_manager + ->get_finder() + ->core_path('phpbb/db/migration/data/') + ->extension_directory('/migrations') + ->get_classes(); + + $this->migrator->set_migrations($migrations); + } + + protected function finalise_update() + { + $this->cache->purge(); + $this->config->increment('assets_version', 1); + } +} diff --git a/phpBB/phpbb/console/command/dev/migration_tips.php b/phpBB/phpbb/console/command/dev/migration_tips.php new file mode 100644 index 0000000000..f9047bdac8 --- /dev/null +++ b/phpBB/phpbb/console/command/dev/migration_tips.php @@ -0,0 +1,64 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\dev; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class migration_tips extends \phpbb\console\command\command +{ + /** @var \phpbb\extension\manager */ + protected $extension_manager; + + function __construct(\phpbb\user $user, \phpbb\extension\manager $extension_manager) + { + $this->extension_manager = $extension_manager; + parent::__construct($user); + } + + protected function configure() + { + $this + ->setName('dev:migration-tips') + ->setDescription($this->user->lang('CLI_DESCRIPTION_FIND_MIGRATIONS')) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $migrations = $this->extension_manager->get_finder() + ->set_extensions(array()) + ->core_path('phpbb/db/migration/data/') + ->get_classes(); + $tips = $migrations; + + foreach ($migrations as $migration_class) + { + foreach ($migration_class::depends_on() as $dependency) + { + $tips_key = array_search($dependency, $tips); + if ($tips_key !== false) + { + unset($tips[$tips_key]); + } + } + } + + $output->writeln("\t\tarray("); + foreach ($tips as $migration) + { + $output->writeln("\t\t\t'{$migration}',"); + } + $output->writeln("\t\t);"); + } +} diff --git a/phpBB/phpbb/console/command/extension/command.php b/phpBB/phpbb/console/command/extension/command.php new file mode 100644 index 0000000000..364d954082 --- /dev/null +++ b/phpBB/phpbb/console/command/extension/command.php @@ -0,0 +1,30 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\extension; + +abstract class command extends \phpbb\console\command\command +{ + /** @var \phpbb\extension\manager */ + protected $manager; + + /** @var \phpbb\log\log */ + protected $log; + + public function __construct(\phpbb\user $user, \phpbb\extension\manager $manager, \phpbb\log\log $log) + { + $this->manager = $manager; + $this->log = $log; + + parent::__construct($user); + } +} diff --git a/phpBB/phpbb/console/command/extension/disable.php b/phpBB/phpbb/console/command/extension/disable.php new file mode 100644 index 0000000000..1eee16cbd9 --- /dev/null +++ b/phpBB/phpbb/console/command/extension/disable.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\extension; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class disable extends command +{ + protected function configure() + { + $this + ->setName('extension:disable') + ->setDescription($this->user->lang('CLI_DESCRIPTION_DISABLE_EXTENSION')) + ->addArgument( + 'extension-name', + InputArgument::REQUIRED, + $this->user->lang('CLI_EXTENSION_NAME') + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $name = $input->getArgument('extension-name'); + $this->manager->disable($name); + $this->manager->load_extensions(); + + if ($this->manager->is_enabled($name)) + { + $output->writeln('<error>' . $this->user->lang('CLI_EXTENSION_DISABLE_FAILURE', $name) . '</error>'); + return 1; + } + else + { + $this->log->add('admin', ANONYMOUS, '', 'LOG_EXT_DISABLE', time(), array($name)); + $output->writeln('<info>' . $this->user->lang('CLI_EXTENSION_DISABLE_SUCCESS', $name) . '</info>'); + return 0; + } + } +} diff --git a/phpBB/phpbb/console/command/extension/enable.php b/phpBB/phpbb/console/command/extension/enable.php new file mode 100644 index 0000000000..59ff11e9b7 --- /dev/null +++ b/phpBB/phpbb/console/command/extension/enable.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\extension; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class enable extends command +{ + protected function configure() + { + $this + ->setName('extension:enable') + ->setDescription($this->user->lang('CLI_DESCRIPTION_ENABLE_EXTENSION')) + ->addArgument( + 'extension-name', + InputArgument::REQUIRED, + $this->user->lang('CLI_EXTENSION_NAME') + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $name = $input->getArgument('extension-name'); + $this->manager->enable($name); + $this->manager->load_extensions(); + + if ($this->manager->is_enabled($name)) + { + $this->log->add('admin', ANONYMOUS, '', 'LOG_EXT_ENABLE', time(), array($name)); + $output->writeln('<info>' . $this->user->lang('CLI_EXTENSION_ENABLE_SUCCESS', $name) . '</info>'); + return 0; + } + else + { + $output->writeln('<error>' . $this->user->lang('CLI_EXTENSION_ENABLE_FAILURE', $name) . '</error>'); + return 1; + } + } +} diff --git a/phpBB/phpbb/console/command/extension/purge.php b/phpBB/phpbb/console/command/extension/purge.php new file mode 100644 index 0000000000..517e9a74c9 --- /dev/null +++ b/phpBB/phpbb/console/command/extension/purge.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\extension; + +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class purge extends command +{ + protected function configure() + { + $this + ->setName('extension:purge') + ->setDescription($this->user->lang('CLI_DESCRIPTION_PURGE_EXTENSION')) + ->addArgument( + 'extension-name', + InputArgument::REQUIRED, + $this->user->lang('CLI_EXTENSION_NAME') + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $name = $input->getArgument('extension-name'); + $this->manager->purge($name); + $this->manager->load_extensions(); + + if ($this->manager->is_enabled($name)) + { + $output->writeln('<error>' . $this->user->lang('CLI_EXTENSION_PURGE_FAILURE', $name) . '</error>'); + return 1; + } + else + { + $this->log->add('admin', ANONYMOUS, '', 'LOG_EXT_PURGE', time(), array($name)); + $output->writeln('<info>' . $this->user->lang('CLI_EXTENSION_PURGE_SUCCESS', $name) . '</info>'); + return 0; + } + } +} diff --git a/phpBB/phpbb/console/command/extension/show.php b/phpBB/phpbb/console/command/extension/show.php new file mode 100644 index 0000000000..f9322034d7 --- /dev/null +++ b/phpBB/phpbb/console/command/extension/show.php @@ -0,0 +1,62 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\extension; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class show extends command +{ + protected function configure() + { + $this + ->setName('extension:show') + ->setDescription($this->user->lang('CLI_DESCRIPTION_LIST_EXTENSIONS')) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $this->manager->load_extensions(); + $all = array_keys($this->manager->all_available()); + + if (empty($all)) + { + $output->writeln('<comment>' . $this->user->lang('CLI_EXTENSION_NOT_FOUND') . '</comment>'); + return 3; + } + + $enabled = array_keys($this->manager->all_enabled()); + $this->print_extension_list($output, $this->user->lang('CLI_EXTENSIONS_ENABLED') . $this->user->lang('COLON'), $enabled); + + $output->writeln(''); + + $disabled = array_keys($this->manager->all_disabled()); + $this->print_extension_list($output, $this->user->lang('CLI_EXTENSIONS_DISABLED') . $this->user->lang('COLON'), $disabled); + + $output->writeln(''); + + $purged = array_diff($all, $enabled, $disabled); + $this->print_extension_list($output, $this->user->lang('CLI_EXTENSIONS_AVAILABLE') . $this->user->lang('COLON'), $purged); + } + + protected function print_extension_list(OutputInterface $output, $type, array $extensions) + { + $output->writeln("<info>$type</info>"); + + foreach ($extensions as $extension) + { + $output->writeln(" - $extension"); + } + } +} diff --git a/phpBB/phpbb/console/command/fixup/fix_left_right_ids.php b/phpBB/phpbb/console/command/fixup/fix_left_right_ids.php new file mode 100644 index 0000000000..f55e1761bc --- /dev/null +++ b/phpBB/phpbb/console/command/fixup/fix_left_right_ids.php @@ -0,0 +1,134 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\console\command\fixup; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class fix_left_right_ids extends \phpbb\console\command\command +{ + /** @var \phpbb\user */ + protected $user; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\cache\driver\driver_interface */ + protected $cache; + + /** + * Constructor + * + * @param \phpbb\user $user User instance + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param \phpbb\cache\driver\driver_interface $cache Cache instance + */ + public function __construct(\phpbb\user $user, \phpbb\db\driver\driver_interface $db, \phpbb\cache\driver\driver_interface $cache) + { + $this->user = $user; + $this->db = $db; + $this->cache = $cache; + + parent::__construct($user); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('fixup:fix-left-right-ids') + ->setDescription($this->user->lang('CLI_DESCRIPTION_FIX_LEFT_RIGHT_IDS')) + ; + } + + /** + * Executes the command fixup:fix-left-right-ids. + * + * Repairs the tree structure of the forums and modules. + * The code is mainly borrowed from Support toolkit for phpBB Olympus + * + * @param InputInterface $input An InputInterface instance + * @param OutputInterface $output An OutputInterface instance + * + * @return void + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + // Fix Left/Right IDs for the modules table + $result = $this->db->sql_query('SELECT DISTINCT(module_class) FROM ' . MODULES_TABLE); + while ($row = $this->db->sql_fetchrow($result)) + { + $i = 1; + $where = array("module_class = '" . $this->db->sql_escape($row['module_class']) . "'"); + $this->fix_ids_tree($i, 'module_id', MODULES_TABLE, 0, $where); + } + $this->db->sql_freeresult($result); + + // Fix the Left/Right IDs for the forums table + $i = 1; + $this->fix_ids_tree($i, 'forum_id', FORUMS_TABLE); + + $this->cache->purge(); + + $output->writeln('<info>' . $this->user->lang('CLI_FIXUP_FIX_LEFT_RIGHT_IDS_SUCCESS') . '</info>'); + } + + /** + * Item's tree structure rebuild helper + * The item is either forum or ACP/MCP/UCP module + * + * @param int $i Item id offset index + * @param string $field The key field to fix, forum_id|module_id + * @param string $table The table name to perform, FORUMS_TABLE|MODULES_TABLE + * @param int $parent_id Parent item id + * @param array $where Additional WHERE clause condition + * + * @return bool True on rebuild success, false otherwise + */ + protected function fix_ids_tree(&$i, $field, $table, $parent_id = 0, $where = array()) + { + $changes_made = false; + $sql = 'SELECT * FROM ' . $table . ' + WHERE parent_id = ' . (int) $parent_id . + ((!empty($where)) ? ' AND ' . implode(' AND ', $where) : '') . ' + ORDER BY left_id ASC'; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + // Update the left_id for the item + if ($row['left_id'] != $i) + { + $this->db->sql_query('UPDATE ' . $table . ' SET ' . $this->db->sql_build_array('UPDATE', array('left_id' => $i)) . " WHERE $field = " . (int) $row[$field]); + $changes_made = true; + } + $i++; + + // Go through children and update their left/right IDs + $changes_made = (($this->fix_ids_tree($i, $field, $table, $row[$field], $where)) || $changes_made) ? true : false; + + // Update the right_id for the item + if ($row['right_id'] != $i) + { + $this->db->sql_query('UPDATE ' . $table . ' SET ' . $this->db->sql_build_array('UPDATE', array('right_id' => $i)) . " WHERE $field = " . (int) $row[$field]); + $changes_made = true; + } + $i++; + } + $this->db->sql_freeresult($result); + + return $changes_made; + } +} diff --git a/phpBB/phpbb/console/command/fixup/recalculate_email_hash.php b/phpBB/phpbb/console/command/fixup/recalculate_email_hash.php new file mode 100644 index 0000000000..ec4e1b0ee7 --- /dev/null +++ b/phpBB/phpbb/console/command/fixup/recalculate_email_hash.php @@ -0,0 +1,75 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\fixup; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class recalculate_email_hash extends \phpbb\console\command\command +{ + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + function __construct(\phpbb\user $user, \phpbb\db\driver\driver_interface $db) + { + $this->db = $db; + + parent::__construct($user); + } + + protected function configure() + { + $this + ->setName('fixup:recalculate-email-hash') + ->setDescription($this->user->lang('CLI_DESCRIPTION_RECALCULATE_EMAIL_HASH')) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $sql = 'SELECT user_id, user_email, user_email_hash + FROM ' . USERS_TABLE . ' + WHERE user_type <> ' . USER_IGNORE . " + AND user_email <> ''"; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $user_email_hash = phpbb_email_hash($row['user_email']); + if ($user_email_hash !== $row['user_email_hash']) + { + $sql_ary = array( + 'user_email_hash' => $user_email_hash, + ); + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' + WHERE user_id = ' . (int) $row['user_id']; + $this->db->sql_query($sql); + + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) + { + $output->writeln(sprintf( + 'user_id %d, email %s => %s', + $row['user_id'], + $row['user_email'], + $user_email_hash + )); + } + } + } + $this->db->sql_freeresult($result); + + $output->writeln('<info>' . $this->user->lang('CLI_FIXUP_RECALCULATE_EMAIL_HASH_SUCCESS') . '</info>'); + } +} diff --git a/phpBB/phpbb/console/command/fixup/update_hashes.php b/phpBB/phpbb/console/command/fixup/update_hashes.php new file mode 100644 index 0000000000..4bcc3b5d19 --- /dev/null +++ b/phpBB/phpbb/console/command/fixup/update_hashes.php @@ -0,0 +1,117 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ +namespace phpbb\console\command\fixup; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Helper\ProgressBar; + +class update_hashes extends \phpbb\console\command\command +{ + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\passwords\manager */ + protected $passwords_manager; + + /** @var string Default hashing type */ + protected $default_type; + + /** + * Update_hashes constructor + * + * @param \phpbb\config\config $config + * @param \phpbb\user $user + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\passwords\manager $passwords_manager + * @param array $hashing_algorithms Hashing driver + * service collection + * @param array $defaults Default password types + */ + public function __construct(\phpbb\config\config $config, \phpbb\user $user, + \phpbb\db\driver\driver_interface $db, \phpbb\passwords\manager $passwords_manager, + $hashing_algorithms, $defaults) + { + $this->config = $config; + $this->db = $db; + + $this->passwords_manager = $passwords_manager; + + foreach ($defaults as $type) + { + if ($hashing_algorithms[$type]->is_supported()) + { + $this->default_type = $type; + break; + } + } + + parent::__construct($user); + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('fixup:update-hashes') + ->setDescription($this->user->lang('CLI_DESCRIPTION_UPDATE_HASH_BCRYPT')) + ; + } + + /** + * {@inheritdoc} + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + // Get count to be able to display progress + $sql = 'SELECT COUNT(user_id) AS count + FROM ' . USERS_TABLE . ' + WHERE user_password ' . $this->db->sql_like_expression('$H$' . $this->db->get_any_char()) . ' + OR user_password ' . $this->db->sql_like_expression('$CP$' . $this->db->get_any_char()); + $result = $this->db->sql_query($sql); + $total_update_passwords = $this->db->sql_fetchfield('count'); + $this->db->sql_freeresult($result); + + // Create progress bar + $progress_bar = new ProgressBar($output, $total_update_passwords); + $progress_bar->start(); + + $sql = 'SELECT user_id, user_password + FROM ' . USERS_TABLE . ' + WHERE user_password ' . $this->db->sql_like_expression('$H$' . $this->db->get_any_char()) . ' + OR user_password ' . $this->db->sql_like_expression('$CP$' . $this->db->get_any_char()); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $new_hash = $this->passwords_manager->hash($row['user_password'], array($this->default_type)); + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_password = "' . $this->db->sql_escape($new_hash) . '" + WHERE user_id = ' . (int) $row['user_id']; + $this->db->sql_query($sql); + $progress_bar->advance(); + } + + $this->config->set('update_hashes_last_cron', time()); + + $progress_bar->finish(); + + $output->writeln('<info>' . $this->user->lang('CLI_FIXUP_UPDATE_HASH_BCRYPT_SUCCESS') . '</info>'); + } +} diff --git a/phpBB/phpbb/content_visibility.php b/phpBB/phpbb/content_visibility.php new file mode 100644 index 0000000000..bf7dc2c703 --- /dev/null +++ b/phpBB/phpbb/content_visibility.php @@ -0,0 +1,863 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* phpbb_visibility +* Handle fetching and setting the visibility for topics and posts +*/ +class content_visibility +{ + /** + * Database object + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Auth object + * @var \phpbb\auth\auth + */ + protected $auth; + + /** + * config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $phpbb_dispatcher; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP Extension + * @var string + */ + protected $php_ext; + + /** + * Constructor + * + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\config\config $config Config object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\user $user User object + * @param string $phpbb_root_path Root path + * @param string $php_ext PHP Extension + * @param string $forums_table Forums table name + * @param string $posts_table Posts table name + * @param string $topics_table Topics table name + * @param string $users_table Users table name + */ + public function __construct(\phpbb\auth\auth $auth, \phpbb\config\config $config, \phpbb\event\dispatcher_interface $phpbb_dispatcher, \phpbb\db\driver\driver_interface $db, \phpbb\user $user, $phpbb_root_path, $php_ext, $forums_table, $posts_table, $topics_table, $users_table) + { + $this->auth = $auth; + $this->config = $config; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->db = $db; + $this->user = $user; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->forums_table = $forums_table; + $this->posts_table = $posts_table; + $this->topics_table = $topics_table; + $this->users_table = $users_table; + } + + /** + * Can the current logged-in user soft-delete posts? + * + * @param $forum_id int Forum ID whose permissions to check + * @param $poster_id int Poster ID of the post in question + * @param $post_locked bool Is the post locked? + * @return bool + */ + public function can_soft_delete($forum_id, $poster_id, $post_locked) + { + if ($this->auth->acl_get('m_softdelete', $forum_id)) + { + return true; + } + else if ($this->auth->acl_get('f_softdelete', $forum_id) && $poster_id == $this->user->data['user_id'] && !$post_locked) + { + return true; + } + + return false; + } + + /** + * Get the topics post count or the forums post/topic count based on permissions + * + * @param $mode string One of topic_posts, forum_posts or forum_topics + * @param $data array Array with the topic/forum data to calculate from + * @param $forum_id int The forum id is used for permission checks + * @return int Number of posts/topics the user can see in the topic/forum + */ + public function get_count($mode, $data, $forum_id) + { + if (!$this->auth->acl_get('m_approve', $forum_id)) + { + return (int) $data[$mode . '_approved']; + } + + return (int) $data[$mode . '_approved'] + (int) $data[$mode . '_unapproved'] + (int) $data[$mode . '_softdeleted']; + } + + /** + * Create topic/post visibility SQL for a given forum ID + * + * Note: Read permissions are not checked. + * + * @param $mode string Either "topic" or "post" + * @param $forum_id int The forum id is used for permission checks + * @param $table_alias string Table alias to prefix in SQL queries + * @return string The appropriate combination SQL logic for topic/post_visibility + */ + public function get_visibility_sql($mode, $forum_id, $table_alias = '') + { + $where_sql = ''; + + $get_visibility_sql_overwrite = false; + + /** + * Allow changing the result of calling get_visibility_sql + * + * @event core.phpbb_content_visibility_get_visibility_sql_before + * @var string where_sql Extra visibility conditions. It must end with either an SQL "AND" or an "OR" + * @var string mode Either "topic" or "post" depending on the query this is being used in + * @var array forum_id The forum id in which the search is made. + * @var string table_alias Table alias to prefix in SQL queries + * @var mixed get_visibility_sql_overwrite If a string, forces the function to return get_forums_visibility_sql_overwrite after executing the event + * If false, get_visibility_sql continues normally + * It must be either boolean or string + * @since 3.1.4-RC1 + */ + $vars = array( + 'where_sql', + 'mode', + 'forum_id', + 'table_alias', + 'get_visibility_sql_overwrite', + ); + extract($this->phpbb_dispatcher->trigger_event('core.phpbb_content_visibility_get_visibility_sql_before', compact($vars))); + + if ($get_visibility_sql_overwrite !== false) + { + return $get_visibility_sql_overwrite; + } + + if ($this->auth->acl_get('m_approve', $forum_id)) + { + return $where_sql . '1 = 1'; + } + + return $where_sql . $table_alias . $mode . '_visibility = ' . ITEM_APPROVED; + } + + /** + * Create topic/post visibility SQL for a set of forums + * + * Note: Read permissions are not checked. Forums without read permissions + * should not be in $forum_ids + * + * @param $mode string Either "topic" or "post" + * @param $forum_ids array Array of forum ids which the posts/topics are limited to + * @param $table_alias string Table alias to prefix in SQL queries + * @return string The appropriate combination SQL logic for topic/post_visibility + */ + public function get_forums_visibility_sql($mode, $forum_ids = array(), $table_alias = '') + { + $where_sql = '('; + + $approve_forums = array_intersect($forum_ids, array_keys($this->auth->acl_getf('m_approve', true))); + + $get_forums_visibility_sql_overwrite = false; + /** + * Allow changing the result of calling get_forums_visibility_sql + * + * @event core.phpbb_content_visibility_get_forums_visibility_before + * @var string where_sql The action the user tried to execute + * @var string mode Either "topic" or "post" depending on the query this is being used in + * @var array forum_ids Array of forum ids which the posts/topics are limited to + * @var string table_alias Table alias to prefix in SQL queries + * @var array approve_forums Array of forums where the user has m_approve permissions + * @var mixed get_forums_visibility_sql_overwrite If a string, forces the function to return get_forums_visibility_sql_overwrite after executing the event + * If false, get_forums_visibility_sql continues normally + * It must be either boolean or string + * @since 3.1.3-RC1 + */ + $vars = array( + 'where_sql', + 'mode', + 'forum_ids', + 'table_alias', + 'approve_forums', + 'get_forums_visibility_sql_overwrite', + ); + extract($this->phpbb_dispatcher->trigger_event('core.phpbb_content_visibility_get_forums_visibility_before', compact($vars))); + + if ($get_forums_visibility_sql_overwrite !== false) + { + return $get_forums_visibility_sql_overwrite; + } + + if (sizeof($approve_forums)) + { + // Remove moderator forums from the rest + $forum_ids = array_diff($forum_ids, $approve_forums); + + if (!sizeof($forum_ids)) + { + // The user can see all posts/topics in all specified forums + return $where_sql . $this->db->sql_in_set($table_alias . 'forum_id', $approve_forums) . ')'; + } + else + { + // Moderator can view all posts/topics in some forums + $where_sql .= $this->db->sql_in_set($table_alias . 'forum_id', $approve_forums) . ' OR '; + } + } + else + { + // The user is just a normal user + return $where_sql . $table_alias . $mode . '_visibility = ' . ITEM_APPROVED . ' + AND ' . $this->db->sql_in_set($table_alias . 'forum_id', $forum_ids, false, true) . ')'; + } + + $where_sql .= '(' . $table_alias . $mode . '_visibility = ' . ITEM_APPROVED . ' + AND ' . $this->db->sql_in_set($table_alias . 'forum_id', $forum_ids) . '))'; + + return $where_sql; + } + + /** + * Create topic/post visibility SQL for all forums on the board + * + * Note: Read permissions are not checked. Forums without read permissions + * should be in $exclude_forum_ids + * + * @param $mode string Either "topic" or "post" + * @param $exclude_forum_ids array Array of forum ids which are excluded + * @param $table_alias string Table alias to prefix in SQL queries + * @return string The appropriate combination SQL logic for topic/post_visibility + */ + public function get_global_visibility_sql($mode, $exclude_forum_ids = array(), $table_alias = '') + { + $where_sqls = array(); + + $approve_forums = array_diff(array_keys($this->auth->acl_getf('m_approve', true)), $exclude_forum_ids); + + $visibility_sql_overwrite = null; + + /** + * Allow changing the result of calling get_global_visibility_sql + * + * @event core.phpbb_content_visibility_get_global_visibility_before + * @var array where_sqls The action the user tried to execute + * @var string mode Either "topic" or "post" depending on the query this is being used in + * @var array exclude_forum_ids Array of forum ids the current user doesn't have access to + * @var string table_alias Table alias to prefix in SQL queries + * @var array approve_forums Array of forums where the user has m_approve permissions + * @var string visibility_sql_overwrite Forces the function to return an implosion of where_sqls (joined by "OR") + * @since 3.1.3-RC1 + */ + $vars = array( + 'where_sqls', + 'mode', + 'exclude_forum_ids', + 'table_alias', + 'approve_forums', + 'visibility_sql_overwrite', + ); + extract($this->phpbb_dispatcher->trigger_event('core.phpbb_content_visibility_get_global_visibility_before', compact($vars))); + + if ($visibility_sql_overwrite) + { + return $visibility_sql_overwrite; + } + + if (sizeof($exclude_forum_ids)) + { + $where_sqls[] = '(' . $this->db->sql_in_set($table_alias . 'forum_id', $exclude_forum_ids, true) . ' + AND ' . $table_alias . $mode . '_visibility = ' . ITEM_APPROVED . ')'; + } + else + { + $where_sqls[] = $table_alias . $mode . '_visibility = ' . ITEM_APPROVED; + } + + if (sizeof($approve_forums)) + { + $where_sqls[] = $this->db->sql_in_set($table_alias . 'forum_id', $approve_forums); + return '(' . implode(' OR ', $where_sqls) . ')'; + } + + // There is only one element, so we just return that one + return $where_sqls[0]; + } + + /** + * Change visibility status of one post or all posts of a topic + * + * @param $visibility int Element of {ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE} + * @param $post_id mixed Post ID or array of post IDs to act on, + * if it is empty, all posts of topic_id will be modified + * @param $topic_id int Topic where $post_id is found + * @param $forum_id int Forum where $topic_id is found + * @param $user_id int User performing the action + * @param $time int Timestamp when the action is performed + * @param $reason string Reason why the visibility was changed. + * @param $is_starter bool Is this the first post of the topic changed? + * @param $is_latest bool Is this the last post of the topic changed? + * @param $limit_visibility mixed Limit updating per topic_id to a certain visibility + * @param $limit_delete_time mixed Limit updating per topic_id to a certain deletion time + * @return array Changed post data, empty array if an error occurred. + */ + public function set_post_visibility($visibility, $post_id, $topic_id, $forum_id, $user_id, $time, $reason, $is_starter, $is_latest, $limit_visibility = false, $limit_delete_time = false) + { + if (!in_array($visibility, array(ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE))) + { + return array(); + } + + if ($post_id) + { + if (is_array($post_id)) + { + $where_sql = $this->db->sql_in_set('post_id', array_map('intval', $post_id)); + } + else + { + $where_sql = 'post_id = ' . (int) $post_id; + } + $where_sql .= ' AND topic_id = ' . (int) $topic_id; + } + else + { + $where_sql = 'topic_id = ' . (int) $topic_id; + + // Limit the posts to a certain visibility and deletion time + // This allows us to only restore posts, that were approved + // when the topic got soft deleted. So previous soft deleted + // and unapproved posts are still soft deleted/unapproved + if ($limit_visibility !== false) + { + $where_sql .= ' AND post_visibility = ' . (int) $limit_visibility; + } + + if ($limit_delete_time !== false) + { + $where_sql .= ' AND post_delete_time = ' . (int) $limit_delete_time; + } + } + + $sql = 'SELECT poster_id, post_id, post_postcount, post_visibility + FROM ' . $this->posts_table . ' + WHERE ' . $where_sql; + $result = $this->db->sql_query($sql); + + $post_ids = $poster_postcounts = $postcounts = $postcount_visibility = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $post_ids[] = (int) $row['post_id']; + + if ($row['post_visibility'] != $visibility) + { + if ($row['post_postcount'] && !isset($poster_postcounts[(int) $row['poster_id']])) + { + $poster_postcounts[(int) $row['poster_id']] = 1; + } + else if ($row['post_postcount']) + { + $poster_postcounts[(int) $row['poster_id']]++; + } + + if (!isset($postcount_visibility[$row['post_visibility']])) + { + $postcount_visibility[$row['post_visibility']] = 1; + } + else + { + $postcount_visibility[$row['post_visibility']]++; + } + } + } + $this->db->sql_freeresult($result); + + if (empty($post_ids)) + { + return array(); + } + + if (!function_exists('truncate_string')) + { + include($this->phpbb_root_path . 'includes/functions_content.' . $this->php_ext); + } + + $data = array( + 'post_visibility' => (int) $visibility, + 'post_delete_user' => (int) $user_id, + 'post_delete_time' => ((int) $time) ?: time(), + 'post_delete_reason' => truncate_string($reason, 255, 255, false), + ); + /** + * Perform actions right before the query to change post visibility + * + * @event core.set_post_visibility_before_sql + * @var int visibility Element of {ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE} + * @var array post_id Array containing all post IDs to be modified. If blank, all posts within the topic are modified. + * @var int topic_id Topic of the post IDs to be modified. + * @var int forum_id Forum ID that the topic_id resides in. + * @var int user_id User ID doing this action. + * @var int timestamp Timestamp of this action. + * @var string reason Reason specified by the user for this change. + * @var bool is_starter Are we changing the topic's starter? + * @var bool is_latest Are we changing the topic's latest post? + * @var array data The data array for this action. + * @since 3.1.10-RC1 + */ + $vars = array( + 'visibility', + 'post_id', + 'topic_id', + 'forum_id', + 'user_id', + 'timestamp', + 'reason', + 'is_starter', + 'is_latest', + 'data', + ); + extract($this->phpbb_dispatcher->trigger_event('core.set_post_visibility_before_sql', compact($vars))); + $sql = 'UPDATE ' . $this->posts_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $data) . ' + WHERE ' . $this->db->sql_in_set('post_id', $post_ids); + $this->db->sql_query($sql); + + // Group the authors by post count, to reduce the number of queries + foreach ($poster_postcounts as $poster_id => $num_posts) + { + $postcounts[$num_posts][] = $poster_id; + } + + // Update users postcounts + foreach ($postcounts as $num_posts => $poster_ids) + { + if (in_array($visibility, array(ITEM_REAPPROVE, ITEM_DELETED))) + { + $sql = 'UPDATE ' . $this->users_table . ' + SET user_posts = 0 + WHERE ' . $this->db->sql_in_set('user_id', $poster_ids) . ' + AND user_posts < ' . $num_posts; + $this->db->sql_query($sql); + + $sql = 'UPDATE ' . $this->users_table . ' + SET user_posts = user_posts - ' . $num_posts . ' + WHERE ' . $this->db->sql_in_set('user_id', $poster_ids) . ' + AND user_posts >= ' . $num_posts; + $this->db->sql_query($sql); + } + else + { + $sql = 'UPDATE ' . $this->users_table . ' + SET user_posts = user_posts + ' . $num_posts . ' + WHERE ' . $this->db->sql_in_set('user_id', $poster_ids); + $this->db->sql_query($sql); + } + } + + $update_topic_postcount = true; + + // Sync the first/last topic information if needed + if (!$is_starter && $is_latest) + { + if (!function_exists('update_post_information')) + { + include($this->phpbb_root_path . 'includes/functions_posting.' . $this->php_ext); + } + + // update_post_information can only update the last post info ... + if ($topic_id) + { + update_post_information('topic', $topic_id, false); + } + if ($forum_id) + { + update_post_information('forum', $forum_id, false); + } + } + else if ($is_starter && $topic_id) + { + if (!function_exists('sync')) + { + include($this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext); + } + + // ... so we need to use sync, if the first post is changed. + // The forum is resynced recursive by sync() itself. + sync('topic', 'topic_id', $topic_id, true); + + // sync recalculates the topic replies and forum posts by itself, so we don't do that. + $update_topic_postcount = false; + } + + $topic_update_array = array(); + // Update the topic's reply count and the forum's post count + if ($update_topic_postcount) + { + $field_alias = array( + ITEM_APPROVED => 'posts_approved', + ITEM_UNAPPROVED => 'posts_unapproved', + ITEM_DELETED => 'posts_softdeleted', + ITEM_REAPPROVE => 'posts_unapproved', + ); + $cur_posts = array_fill_keys($field_alias, 0); + + foreach ($postcount_visibility as $post_visibility => $visibility_posts) + { + $cur_posts[$field_alias[(int) $post_visibility]] += $visibility_posts; + } + + $sql_ary = array(); + $recipient_field = $field_alias[$visibility]; + + foreach ($cur_posts as $field => $count) + { + // Decrease the count for the old statuses. + if ($count && $field != $recipient_field) + { + $sql_ary[$field] = " - $count"; + } + } + // Add up the count from all statuses excluding the recipient status. + $count_increase = array_sum(array_diff($cur_posts, array($recipient_field))); + + if ($count_increase) + { + $sql_ary[$recipient_field] = " + $count_increase"; + } + + if (sizeof($sql_ary)) + { + $forum_sql = array(); + + foreach ($sql_ary as $field => $value_change) + { + $topic_update_array[] = 'topic_' . $field . ' = topic_' . $field . $value_change; + $forum_sql[] = 'forum_' . $field . ' = forum_' . $field . $value_change; + } + + $sql = 'UPDATE ' . $this->forums_table . ' + SET ' . implode(', ', $forum_sql) . ' + WHERE forum_id = ' . (int) $forum_id; + $this->db->sql_query($sql); + } + } + + if ($post_id) + { + $sql = 'SELECT 1 AS has_attachments + FROM ' . POSTS_TABLE . ' + WHERE topic_id = ' . (int) $topic_id . ' + AND post_attachment = 1 + AND post_visibility = ' . ITEM_APPROVED . ' + AND ' . $this->db->sql_in_set('post_id', $post_id, true); + $result = $this->db->sql_query_limit($sql, 1); + + $has_attachment = (bool) $this->db->sql_fetchfield('has_attachments'); + $this->db->sql_freeresult($result); + + if ($has_attachment && $visibility == ITEM_APPROVED) + { + $topic_update_array[] = 'topic_attachment = 1'; + } + else if (!$has_attachment && $visibility != ITEM_APPROVED) + { + $topic_update_array[] = 'topic_attachment = 0'; + } + } + + if (!empty($topic_update_array)) + { + // Update the number for replies and posts, and update the attachments flag + $sql = 'UPDATE ' . $this->topics_table . ' + SET ' . implode(', ', $topic_update_array) . ' + WHERE topic_id = ' . (int) $topic_id; + $this->db->sql_query($sql); + } + /** + * Perform actions after all steps to changing post visibility + * + * @event core.set_post_visibility_after + * @var int visibility Element of {ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE} + * @var array post_id Array containing all post IDs to be modified. If blank, all posts within the topic are modified. + * @var int topic_id Topic of the post IDs to be modified. + * @var int forum_id Forum ID that the topic_id resides in. + * @var int user_id User ID doing this action. + * @var int timestamp Timestamp of this action. + * @var string reason Reason specified by the user for this change. + * @var bool is_starter Are we changing the topic's starter? + * @var bool is_latest Are we changing the topic's latest post? + * @var array data The data array for this action. + * @since 3.1.10-RC1 + */ + $vars = array( + 'visibility', + 'post_id', + 'topic_id', + 'forum_id', + 'user_id', + 'timestamp', + 'reason', + 'is_starter', + 'is_latest', + 'data', + ); + extract($this->phpbb_dispatcher->trigger_event('core.set_post_visibility_after', compact($vars))); + return $data; + } + + /** + * Set topic visibility + * + * Allows approving (which is akin to undeleting/restore) or soft deleting an entire topic. + * Calls set_post_visibility as needed. + * + * Note: By default, when a soft deleted topic is restored. Only posts that + * were approved at the time of soft deleting, are being restored. + * Same applies to soft deleting. Only approved posts will be marked + * as soft deleted. + * If you want to update all posts, use the force option. + * + * @param $visibility int Element of {ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE} + * @param $topic_id mixed Topic ID to act on + * @param $forum_id int Forum where $topic_id is found + * @param $user_id int User performing the action + * @param $time int Timestamp when the action is performed + * @param $reason string Reason why the visibilty was changed. + * @param $force_update_all bool Force to update all posts within the topic + * @return array Changed topic data, empty array if an error occured. + */ + public function set_topic_visibility($visibility, $topic_id, $forum_id, $user_id, $time, $reason, $force_update_all = false) + { + if (!in_array($visibility, array(ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE))) + { + return array(); + } + + if (!$force_update_all) + { + $sql = 'SELECT topic_visibility, topic_delete_time + FROM ' . $this->topics_table . ' + WHERE topic_id = ' . (int) $topic_id; + $result = $this->db->sql_query($sql); + $original_topic_data = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$original_topic_data) + { + // The topic does not exist... + return array(); + } + } + + if (!function_exists('truncate_string')) + { + include($this->phpbb_root_path . 'includes/functions_content.' . $this->php_ext); + } + + // Note, we do not set a reason for the posts, just for the topic + $data = array( + 'topic_visibility' => (int) $visibility, + 'topic_delete_user' => (int) $user_id, + 'topic_delete_time' => ((int) $time) ?: time(), + 'topic_delete_reason' => truncate_string($reason, 255, 255, false), + ); + /** + * Perform actions right before the query to change topic visibility + * + * @event core.set_topic_visibility_before_sql + * @var int visibility Element of {ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE} + * @var int topic_id Topic of the post IDs to be modified. + * @var int forum_id Forum ID that the topic_id resides in. + * @var int user_id User ID doing this action. + * @var int timestamp Timestamp of this action. + * @var string reason Reason specified by the user for this change. + * @var bool force_update_all Force an update on all posts within the topic, regardless of their current approval state. + * @var array data The data array for this action. + * @since 3.1.10-RC1 + */ + $vars = array( + 'visibility', + 'topic_id', + 'forum_id', + 'user_id', + 'timestamp', + 'reason', + 'force_update_all', + 'data', + ); + extract($this->phpbb_dispatcher->trigger_event('core.set_topic_visibility_before_sql', compact($vars))); + $sql = 'UPDATE ' . $this->topics_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $data) . ' + WHERE topic_id = ' . (int) $topic_id; + $this->db->sql_query($sql); + + if (!$this->db->sql_affectedrows()) + { + return array(); + } + + if (!$force_update_all && $original_topic_data['topic_delete_time'] && $original_topic_data['topic_visibility'] == ITEM_DELETED && $visibility == ITEM_APPROVED) + { + // If we're restoring a topic we only restore posts, that were soft deleted through the topic soft deletion. + $this->set_post_visibility($visibility, false, $topic_id, $forum_id, $user_id, $time, '', true, true, $original_topic_data['topic_visibility'], $original_topic_data['topic_delete_time']); + } + else if (!$force_update_all && $original_topic_data['topic_visibility'] == ITEM_APPROVED && $visibility == ITEM_DELETED) + { + // If we're soft deleting a topic we only mark approved posts as soft deleted. + $this->set_post_visibility($visibility, false, $topic_id, $forum_id, $user_id, $time, '', true, true, $original_topic_data['topic_visibility']); + } + else + { + $this->set_post_visibility($visibility, false, $topic_id, $forum_id, $user_id, $time, '', true, true); + } + /** + * Perform actions after all steps to changing topic visibility + * + * @event core.set_topic_visibility_after + * @var int visibility Element of {ITEM_APPROVED, ITEM_DELETED, ITEM_REAPPROVE} + * @var int topic_id Topic of the post IDs to be modified. + * @var int forum_id Forum ID that the topic_id resides in. + * @var int user_id User ID doing this action. + * @var int timestamp Timestamp of this action. + * @var string reason Reason specified by the user for this change. + * @var bool force_update_all Force an update on all posts within the topic, regardless of their current approval state. + * @var array data The data array for this action. + * @since 3.1.10-RC1 + */ + $vars = array( + 'visibility', + 'topic_id', + 'forum_id', + 'user_id', + 'timestamp', + 'reason', + 'force_update_all', + 'data', + ); + extract($this->phpbb_dispatcher->trigger_event('core.set_topic_visibility_after', compact($vars))); + return $data; + } + + /** + * Add post to topic and forum statistics + * + * @param $data array Contains information from the topics table about given topic + * @param &$sql_data array Populated with the SQL changes, may be empty at call time + * @return null + */ + public function add_post_to_statistic($data, &$sql_data) + { + $sql_data[$this->topics_table] = (($sql_data[$this->topics_table]) ? $sql_data[$this->topics_table] . ', ' : '') . 'topic_posts_approved = topic_posts_approved + 1'; + + $sql_data[$this->forums_table] = (($sql_data[$this->forums_table]) ? $sql_data[$this->forums_table] . ', ' : '') . 'forum_posts_approved = forum_posts_approved + 1'; + + if ($data['post_postcount']) + { + $sql_data[$this->users_table] = (($sql_data[$this->users_table]) ? $sql_data[$this->users_table] . ', ' : '') . 'user_posts = user_posts + 1'; + } + + $this->config->increment('num_posts', 1, false); + } + + /** + * Remove post from topic and forum statistics + * + * @param $data array Contains information from the topics table about given topic + * @param &$sql_data array Populated with the SQL changes, may be empty at call time + * @return null + */ + public function remove_post_from_statistic($data, &$sql_data) + { + if ($data['post_visibility'] == ITEM_APPROVED) + { + $sql_data[$this->topics_table] = ((!empty($sql_data[$this->topics_table])) ? $sql_data[$this->topics_table] . ', ' : '') . 'topic_posts_approved = topic_posts_approved - 1'; + $sql_data[$this->forums_table] = ((!empty($sql_data[$this->forums_table])) ? $sql_data[$this->forums_table] . ', ' : '') . 'forum_posts_approved = forum_posts_approved - 1'; + + if ($data['post_postcount']) + { + $sql_data[$this->users_table] = ((!empty($sql_data[$this->users_table])) ? $sql_data[$this->users_table] . ', ' : '') . 'user_posts = user_posts - 1'; + } + + $this->config->increment('num_posts', -1, false); + } + else if ($data['post_visibility'] == ITEM_UNAPPROVED || $data['post_visibility'] == ITEM_REAPPROVE) + { + $sql_data[FORUMS_TABLE] = (($sql_data[FORUMS_TABLE]) ? $sql_data[FORUMS_TABLE] . ', ' : '') . 'forum_posts_unapproved = forum_posts_unapproved - 1'; + $sql_data[TOPICS_TABLE] = (($sql_data[TOPICS_TABLE]) ? $sql_data[TOPICS_TABLE] . ', ' : '') . 'topic_posts_unapproved = topic_posts_unapproved - 1'; + } + else if ($data['post_visibility'] == ITEM_DELETED) + { + $sql_data[FORUMS_TABLE] = (($sql_data[FORUMS_TABLE]) ? $sql_data[FORUMS_TABLE] . ', ' : '') . 'forum_posts_softdeleted = forum_posts_softdeleted - 1'; + $sql_data[TOPICS_TABLE] = (($sql_data[TOPICS_TABLE]) ? $sql_data[TOPICS_TABLE] . ', ' : '') . 'topic_posts_softdeleted = topic_posts_softdeleted - 1'; + } + } + + /** + * Remove topic from forum statistics + * + * @param $data array Post and topic data + * @param &$sql_data array Populated with the SQL changes, may be empty at call time + * @return null + */ + public function remove_topic_from_statistic($data, &$sql_data) + { + if ($data['topic_visibility'] == ITEM_APPROVED) + { + $sql_data[FORUMS_TABLE] .= 'forum_posts_approved = forum_posts_approved - 1, forum_topics_approved = forum_topics_approved - 1'; + + if ($data['post_postcount']) + { + $sql_data[$this->users_table] = ((!empty($sql_data[$this->users_table])) ? $sql_data[$this->users_table] . ', ' : '') . 'user_posts = user_posts - 1'; + } + } + else if ($data['topic_visibility'] == ITEM_UNAPPROVED || $data['post_visibility'] == ITEM_REAPPROVE) + { + $sql_data[FORUMS_TABLE] .= 'forum_posts_unapproved = forum_posts_unapproved - 1, forum_topics_unapproved = forum_topics_unapproved - 1'; + } + else if ($data['topic_visibility'] == ITEM_DELETED) + { + $sql_data[FORUMS_TABLE] .= 'forum_posts_softdeleted = forum_posts_softdeleted - 1, forum_topics_softdeleted = forum_topics_softdeleted - 1'; + } + + } +} diff --git a/phpBB/phpbb/controller/exception.php b/phpBB/phpbb/controller/exception.php new file mode 100644 index 0000000000..437558b06a --- /dev/null +++ b/phpBB/phpbb/controller/exception.php @@ -0,0 +1,21 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\controller; + +/** +* Controller exception class +*/ +class exception extends \RuntimeException +{ +} diff --git a/phpBB/phpbb/controller/helper.php b/phpBB/phpbb/controller/helper.php new file mode 100644 index 0000000000..ce6bfba981 --- /dev/null +++ b/phpBB/phpbb/controller/helper.php @@ -0,0 +1,267 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\controller; + +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Routing\Generator\UrlGenerator; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use Symfony\Component\Routing\RequestContext; + +/** +* Controller helper class, contains methods that do things for controllers +*/ +class helper +{ + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * config object + * @var \phpbb\config\config + */ + protected $config; + + /* @var \phpbb\symfony_request */ + protected $symfony_request; + + /* @var \phpbb\request\request_interface */ + protected $request; + + /** + * @var \phpbb\filesystem The filesystem object + */ + protected $filesystem; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP file extension + * @var string + */ + protected $php_ext; + + /** + * Constructor + * + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + * @param \phpbb\config\config $config Config object + * + * @param \phpbb\controller\provider $provider Path provider + * @param \phpbb\extension\manager $manager Extension manager object + * @param \phpbb\symfony_request $symfony_request Symfony Request object + * @param \phpbb\request\request_interface $request phpBB request object + * @param \phpbb\filesystem $filesystem The filesystem object + * @param string $phpbb_root_path phpBB root path + * @param string $php_ext PHP file extension + */ + public function __construct(\phpbb\template\template $template, \phpbb\user $user, \phpbb\config\config $config, \phpbb\controller\provider $provider, \phpbb\extension\manager $manager, \phpbb\symfony_request $symfony_request, \phpbb\request\request_interface $request, \phpbb\filesystem $filesystem, $phpbb_root_path, $php_ext) + { + $this->template = $template; + $this->user = $user; + $this->config = $config; + $this->symfony_request = $symfony_request; + $this->request = $request; + $this->filesystem = $filesystem; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $provider->find_routing_files($manager->get_finder()); + $this->route_collection = $provider->find($phpbb_root_path)->get_routes(); + } + + /** + * Automate setting up the page and creating the response object. + * + * @param string $template_file The template handle to render + * @param string $page_title The title of the page to output + * @param int $status_code The status code to be sent to the page header + * @param bool $display_online_list Do we display online users list + * @param int $item_id Restrict online users to item id + * @param string $item Restrict online users to a certain session item, e.g. forum for session_forum_id + * @param bool $send_headers Whether headers should be sent by page_header(). Defaults to false for controllers. + * + * @return Response object containing rendered page + */ + public function render($template_file, $page_title = '', $status_code = 200, $display_online_list = false, $item_id = 0, $item = 'forum', $send_headers = false) + { + page_header($page_title, $display_online_list, $item_id, $item, $send_headers); + + $this->template->set_filenames(array( + 'body' => $template_file, + )); + + page_footer(true, false, false); + + $headers = !empty($this->user->data['is_bot']) ? array('X-PHPBB-IS-BOT' => 'yes') : array(); + + return new Response($this->template->assign_display('body'), $status_code, $headers); + } + + /** + * Generate a URL to a route + * + * @param string $route Name of the route to travel + * @param array $params String or array of additional url parameters + * @param bool $is_amp Is url using & (true) or & (false) + * @param string|bool $session_id Possibility to use a custom session id instead of the global one + * @param bool|string $reference_type The type of reference to be generated (one of the constants) + * @return string The URL already passed through append_sid() + */ + public function route($route, array $params = array(), $is_amp = true, $session_id = false, $reference_type = UrlGeneratorInterface::ABSOLUTE_PATH) + { + $anchor = ''; + if (isset($params['#'])) + { + $anchor = '#' . $params['#']; + unset($params['#']); + } + + $context = new RequestContext(); + $context->fromRequest($this->symfony_request); + + if ($this->config['force_server_vars']) + { + $context->setHost($this->config['server_name']); + $context->setScheme(substr($this->config['server_protocol'], 0, -3)); + $context->setHttpPort($this->config['server_port']); + $context->setHttpsPort($this->config['server_port']); + $context->setBaseUrl(rtrim($this->config['script_path'], '/')); + } + + $script_name = $this->symfony_request->getScriptName(); + $page_name = substr($script_name, -1, 1) == '/' ? '' : utf8_basename($script_name); + + $base_url = $context->getBaseUrl(); + + // Append page name if base URL does not contain it + if (!empty($page_name) && strpos($base_url, '/' . $page_name) === false) + { + $base_url .= '/' . $page_name; + } + + // If enable_mod_rewrite is false we need to replace the current front-end by app.php, otherwise we need to remove it. + $base_url = str_replace('/' . $page_name, empty($this->config['enable_mod_rewrite']) ? '/app.' . $this->php_ext : '', $base_url); + + // We need to update the base url to move to the directory of the app.php file if the current script is not app.php + if ($page_name !== 'app.php' && !$this->config['force_server_vars']) + { + if (empty($this->config['enable_mod_rewrite'])) + { + $base_url = str_replace('/app.' . $this->php_ext, '/' . $this->phpbb_root_path . 'app.' . $this->php_ext, $base_url); + } + else + { + $base_url .= preg_replace(get_preg_expression('path_remove_dot_trailing_slash'), '$2', $this->phpbb_root_path); + } + } + + $base_url = $this->request->escape($this->filesystem->clean_path($base_url), true); + + $context->setBaseUrl($base_url); + + $url_generator = new UrlGenerator($this->route_collection, $context); + $route_url = $url_generator->generate($route, $params, $reference_type); + + if ($is_amp) + { + $route_url = str_replace(array('&', '&'), array('&', '&'), $route_url); + } + + if ($reference_type === UrlGeneratorInterface::RELATIVE_PATH && empty($this->config['enable_mod_rewrite'])) + { + $route_url = 'app.' . $this->php_ext . '/' . $route_url; + } + + return append_sid($route_url . $anchor, false, $is_amp, $session_id, true); + } + + /** + * Output an error, effectively the same thing as trigger_error + * + * @param string $message The error message + * @param int $code The error code (e.g. 404, 500, 503, etc.) + * @return Response A Response instance + * + * @deprecated 3.1.3 (To be removed: 3.3.0) Use exceptions instead. + */ + public function error($message, $code = 500) + { + return $this->message($message, array(), 'INFORMATION', $code); + } + + /** + * Output a message + * + * In case of an error, please throw an exception instead + * + * @param string $message The message to display (must be a language variable) + * @param array $parameters The parameters to use with the language var + * @param string $title Title for the message (must be a language variable) + * @param int $code The HTTP status code (e.g. 404, 500, 503, etc.) + * @return Response A Response instance + */ + public function message($message, array $parameters = array(), $title = 'INFORMATION', $code = 200) + { + array_unshift($parameters, $message); + $message_text = call_user_func_array(array($this->user, 'lang'), $parameters); + $message_title = $this->user->lang($title); + + if ($this->request->is_ajax()) + { + global $refresh_data; + + return new JsonResponse( + array( + 'MESSAGE_TITLE' => $message_title, + 'MESSAGE_TEXT' => $message_text, + 'S_USER_WARNING' => false, + 'S_USER_NOTICE' => false, + 'REFRESH_DATA' => (!empty($refresh_data)) ? $refresh_data : null + ), + $code + ); + } + + $this->template->assign_vars(array( + 'MESSAGE_TEXT' => $message_text, + 'MESSAGE_TITLE' => $message_title, + )); + + return $this->render('message_body.html', $message_title, $code); + } + + /** + * Return the current url + * + * @return string + */ + public function get_current_url() + { + return generate_board_url(true) . $this->request->escape($this->symfony_request->getRequestUri(), true); + } +} diff --git a/phpBB/phpbb/controller/provider.php b/phpBB/phpbb/controller/provider.php new file mode 100644 index 0000000000..7e26848290 --- /dev/null +++ b/phpBB/phpbb/controller/provider.php @@ -0,0 +1,92 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\controller; + +use Symfony\Component\Routing\RouteCollection; +use Symfony\Component\Routing\Loader\YamlFileLoader; +use Symfony\Component\Config\FileLocator; + +/** +* Controller interface +*/ +class provider +{ + /** + * YAML file(s) containing route information + * @var array + */ + protected $routing_files; + + /** + * Collection of the routes in phpBB and all found extensions + * @var RouteCollection + */ + protected $routes; + + /** + * Construct method + * + * @param array $routing_files Array of strings containing paths + * to YAML files holding route information + */ + public function __construct($routing_files = array()) + { + $this->routing_files = $routing_files; + } + + /** + * Find the list of routing files + * + * @param \phpbb\finder $finder + * @return null + */ + public function find_routing_files(\phpbb\finder $finder) + { + // We hardcode the path to the core config directory + // because the finder cannot find it + $this->routing_files = array_merge($this->routing_files, array('config/routing.yml'), array_keys($finder + ->directory('/config') + ->suffix('routing.yml') + ->find() + )); + } + + /** + * Find a list of controllers + * + * @param string $base_path Base path to prepend to file paths + * @return provider + */ + public function find($base_path = '') + { + $this->routes = new RouteCollection; + foreach ($this->routing_files as $file_path) + { + $loader = new YamlFileLoader(new FileLocator(phpbb_realpath($base_path))); + $this->routes->addCollection($loader->load($file_path)); + } + + return $this; + } + + /** + * Get the list of routes + * + * @return RouteCollection Get the route collection + */ + public function get_routes() + { + return $this->routes; + } +} diff --git a/phpBB/phpbb/controller/resolver.php b/phpBB/phpbb/controller/resolver.php new file mode 100644 index 0000000000..948a6a218c --- /dev/null +++ b/phpBB/phpbb/controller/resolver.php @@ -0,0 +1,175 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\controller; + +use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\Request; + +/** +* Controller manager class +*/ +class resolver implements ControllerResolverInterface +{ + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * ContainerInterface object + * @var ContainerInterface + */ + protected $container; + + /** + * phpbb\template\template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * Request type cast helper object + * @var \phpbb\request\type_cast_helper + */ + protected $type_cast_helper; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * Construct method + * + * @param \phpbb\user $user User Object + * @param ContainerInterface $container ContainerInterface object + * @param string $phpbb_root_path Relative path to phpBB root + * @param \phpbb\template\template $template + */ + public function __construct(\phpbb\user $user, ContainerInterface $container, $phpbb_root_path, \phpbb\template\template $template = null) + { + $this->user = $user; + $this->container = $container; + $this->template = $template; + $this->type_cast_helper = new \phpbb\request\type_cast_helper(); + $this->phpbb_root_path = $phpbb_root_path; + } + + /** + * Load a controller callable + * + * @param \Symfony\Component\HttpFoundation\Request $request Symfony Request object + * @return bool|Callable Callable or false + * @throws \phpbb\controller\exception + */ + public function getController(Request $request) + { + $controller = $request->attributes->get('_controller'); + + if (!$controller) + { + throw new \phpbb\controller\exception($this->user->lang['CONTROLLER_NOT_SPECIFIED']); + } + + // Require a method name along with the service name + if (stripos($controller, ':') === false) + { + throw new \phpbb\controller\exception($this->user->lang['CONTROLLER_METHOD_NOT_SPECIFIED']); + } + + list($service, $method) = explode(':', $controller); + + if (!$this->container->has($service)) + { + throw new \phpbb\controller\exception($this->user->lang('CONTROLLER_SERVICE_UNDEFINED', $service)); + } + + $controller_object = $this->container->get($service); + + /* + * If this is an extension controller, we'll try to automatically set + * the style paths for the extension (the ext author can change them + * if necessary). + */ + $controller_dir = explode('\\', get_class($controller_object)); + + // 0 vendor, 1 extension name, ... + if (!is_null($this->template) && isset($controller_dir[1])) + { + $controller_style_dir = 'ext/' . $controller_dir[0] . '/' . $controller_dir[1] . '/styles'; + + if (is_dir($this->phpbb_root_path . $controller_style_dir)) + { + $this->template->set_style(array($controller_style_dir, 'styles')); + } + } + + return array($controller_object, $method); + } + + /** + * Dependencies should be specified in the service definition and can be + * then accessed in __construct(). Arguments are sent through the URL path + * and should match the parameters of the method you are using as your + * controller. + * + * @param \Symfony\Component\HttpFoundation\Request $request Symfony Request object + * @param mixed $controller A callable (controller class, method) + * @return array An array of arguments to pass to the controller + * @throws \phpbb\controller\exception + */ + public function getArguments(Request $request, $controller) + { + // At this point, $controller contains the object and method name + list($object, $method) = $controller; + $mirror = new \ReflectionMethod($object, $method); + + $arguments = array(); + $parameters = $mirror->getParameters(); + $attributes = $request->attributes->all(); + foreach ($parameters as $param) + { + if (array_key_exists($param->name, $attributes)) + { + if (is_string($attributes[$param->name])) + { + $value = $attributes[$param->name]; + $this->type_cast_helper->set_var($value, $attributes[$param->name], 'string', true, false); + $arguments[] = $value; + } + else + { + $arguments[] = $attributes[$param->name]; + } + } + else if ($param->getClass() && $param->getClass()->isInstance($request)) + { + $arguments[] = $request; + } + else if ($param->isDefaultValueAvailable()) + { + $arguments[] = $param->getDefaultValue(); + } + else + { + throw new \phpbb\controller\exception($this->user->lang('CONTROLLER_ARGUMENT_VALUE_MISSING', $param->getPosition() + 1, get_class($object) . ':' . $method, $param->name)); + } + } + + return $arguments; + } +} diff --git a/phpBB/phpbb/cron/manager.php b/phpBB/phpbb/cron/manager.php new file mode 100644 index 0000000000..9bd30a0a5b --- /dev/null +++ b/phpBB/phpbb/cron/manager.php @@ -0,0 +1,147 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron; + +/** +* Cron manager class. +* +* Finds installed cron tasks, stores task objects, provides task selection. +*/ +class manager +{ + /** + * Set of \phpbb\cron\task\wrapper objects. + * Array holding all tasks that have been found. + * + * @var array + */ + protected $tasks = array(); + + protected $phpbb_root_path; + protected $php_ext; + + /** + * Constructor. Loads all available tasks. + * + * @param array|\Traversable $tasks Provides an iterable set of task names + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $php_ext PHP file extension + */ + public function __construct($tasks, $phpbb_root_path, $php_ext) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + + $this->load_tasks($tasks); + } + + /** + * Loads tasks given by name, wraps them + * and puts them into $this->tasks. + * + * @param array|\Traversable $tasks Array of instances of \phpbb\cron\task\task + * + * @return null + */ + public function load_tasks($tasks) + { + foreach ($tasks as $task) + { + $this->tasks[] = $this->wrap_task($task); + } + } + + /** + * Finds a task that is ready to run. + * + * If several tasks are ready, any one of them could be returned. + * + * If no tasks are ready, null is returned. + * + * @return \phpbb\cron\task\wrapper|null + */ + public function find_one_ready_task() + { + shuffle($this->tasks); + foreach ($this->tasks as $task) + { + if ($task->is_ready()) + { + return $task; + } + } + return null; + } + + /** + * Finds all tasks that are ready to run. + * + * @return array List of tasks which are ready to run (wrapped in \phpbb\cron\task\wrapper). + */ + public function find_all_ready_tasks() + { + $tasks = array(); + foreach ($this->tasks as $task) + { + if ($task->is_ready()) + { + $tasks[] = $task; + } + } + return $tasks; + } + + /** + * Finds a task by name. + * + * If there is no task with the specified name, null is returned. + * + * Web runner uses this method to resolve names to tasks. + * + * @param string $name Name of the task to look up. + * @return \phpbb\cron\task\wrapper A wrapped task corresponding to the given name, or null. + */ + public function find_task($name) + { + foreach ($this->tasks as $task) + { + if ($task->get_name() == $name) + { + return $task; + } + } + return null; + } + + /** + * Find all tasks and return them. + * + * @return array List of all tasks. + */ + public function get_tasks() + { + return $this->tasks; + } + + /** + * Wraps a task inside an instance of \phpbb\cron\task\wrapper. + * + * @param \phpbb\cron\task\task $task The task. + * @return \phpbb\cron\task\wrapper The wrapped task. + */ + public function wrap_task(\phpbb\cron\task\task $task) + { + return new \phpbb\cron\task\wrapper($task, $this->phpbb_root_path, $this->php_ext); + } +} diff --git a/phpBB/phpbb/cron/task/base.php b/phpBB/phpbb/cron/task/base.php new file mode 100644 index 0000000000..57c9912d31 --- /dev/null +++ b/phpBB/phpbb/cron/task/base.php @@ -0,0 +1,72 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task; + +/** +* Cron task base class. Provides sensible defaults for cron tasks +* and partially implements cron task interface, making writing cron tasks easier. +* +* At a minimum, subclasses must override the run() method. +* +* Cron tasks need not inherit from this base class. If desired, +* they may implement cron task interface directly. +*/ +abstract class base implements \phpbb\cron\task\task +{ + private $name; + + /** + * Returns the name of the task. + * + * @return string Name of wrapped task. + */ + public function get_name() + { + return $this->name; + } + + /** + * Sets the name of the task. + * + * @param string $name The task name + */ + public function set_name($name) + { + $this->name = $name; + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * For example, a cron task that prunes forums can only run when + * forum pruning is enabled. + * + * @return bool + */ + public function is_runnable() + { + return true; + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * @return bool + */ + public function should_run() + { + return true; + } +} diff --git a/phpBB/phpbb/cron/task/core/prune_all_forums.php b/phpBB/phpbb/cron/task/core/prune_all_forums.php new file mode 100644 index 0000000000..b47939ccbe --- /dev/null +++ b/phpBB/phpbb/cron/task/core/prune_all_forums.php @@ -0,0 +1,89 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Prune all forums cron task. +* +* It is intended to be invoked from system cron. +* This task will find all forums for which pruning is enabled, and will +* prune all forums as necessary. +*/ +class prune_all_forums extends \phpbb\cron\task\base +{ + protected $phpbb_root_path; + protected $php_ext; + protected $config; + protected $db; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param string $php_ext The PHP file extension + * @param \phpbb\config\config $config The config + * @param \phpbb\db\driver\driver_interface $db The db connection + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config = $config; + $this->db = $db; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + if (!function_exists('auto_prune')) + { + include($this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext); + } + + $sql = 'SELECT forum_id, prune_next, enable_prune, prune_days, prune_viewed, forum_flags, prune_freq + FROM ' . FORUMS_TABLE . " + WHERE enable_prune = 1 + AND prune_next < " . time(); + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if ($row['prune_days']) + { + auto_prune($row['forum_id'], 'posted', $row['forum_flags'], $row['prune_days'], $row['prune_freq']); + } + + if ($row['prune_viewed']) + { + auto_prune($row['forum_id'], 'viewed', $row['forum_flags'], $row['prune_viewed'], $row['prune_freq']); + } + } + $this->db->sql_freeresult($result); + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * This cron task will only run when system cron is utilised. + * + * @return bool + */ + public function is_runnable() + { + return (bool) $this->config['use_system_cron']; + } +} diff --git a/phpBB/phpbb/cron/task/core/prune_forum.php b/phpBB/phpbb/cron/task/core/prune_forum.php new file mode 100644 index 0000000000..ba68565197 --- /dev/null +++ b/phpBB/phpbb/cron/task/core/prune_forum.php @@ -0,0 +1,159 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Prune one forum cron task. +* +* It is intended to be used when cron is invoked via web. +* This task can decide whether it should be run using data obtained by viewforum +* code, without making additional database queries. +*/ +class prune_forum extends \phpbb\cron\task\base implements \phpbb\cron\task\parametrized +{ + protected $phpbb_root_path; + protected $php_ext; + protected $config; + protected $db; + + /** + * If $forum_data is given, it is assumed to contain necessary information + * about a single forum that is to be pruned. + * + * If $forum_data is not given, forum id will be retrieved via request_var + * and a database query will be performed to load the necessary information + * about the forum. + */ + protected $forum_data; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param string $php_ext PHP file extension + * @param \phpbb\config\config $config The config + * @param \phpbb\db\driver\driver_interface $db The db connection + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config = $config; + $this->db = $db; + } + + /** + * Manually set forum data. + * + * @param array $forum_data Information about a forum to be pruned. + */ + public function set_forum_data($forum_data) + { + $this->forum_data = $forum_data; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + if (!function_exists('auto_prune')) + { + include($this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext); + } + + if ($this->forum_data['prune_days']) + { + auto_prune($this->forum_data['forum_id'], 'posted', $this->forum_data['forum_flags'], $this->forum_data['prune_days'], $this->forum_data['prune_freq']); + } + + if ($this->forum_data['prune_viewed']) + { + auto_prune($this->forum_data['forum_id'], 'viewed', $this->forum_data['forum_flags'], $this->forum_data['prune_viewed'], $this->forum_data['prune_freq']); + } + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * This cron task will not run when system cron is utilised, as in + * such cases prune_all_forums task would run instead. + * + * Additionally, this task must be given the forum data, either via + * the constructor or parse_parameters method. + * + * @return bool + */ + public function is_runnable() + { + return !$this->config['use_system_cron'] && $this->forum_data; + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * Forum pruning interval is specified in the forum data. + * + * @return bool + */ + public function should_run() + { + return $this->forum_data['enable_prune'] && $this->forum_data['prune_next'] < time(); + } + + /** + * Returns parameters of this cron task as an array. + * The array has one key, f, whose value is id of the forum to be pruned. + * + * @return array + */ + public function get_parameters() + { + return array('f' => $this->forum_data['forum_id']); + } + + /** + * Parses parameters found in $request, which is an instance of + * \phpbb\request\request_interface. + * + * It is expected to have a key f whose value is id of the forum to be pruned. + * + * @param \phpbb\request\request_interface $request Request object. + * + * @return null + */ + public function parse_parameters(\phpbb\request\request_interface $request) + { + $this->forum_data = null; + if ($request->is_set('f')) + { + $forum_id = $request->variable('f', 0); + + $sql = 'SELECT forum_id, prune_next, enable_prune, prune_days, prune_viewed, forum_flags, prune_freq + FROM ' . FORUMS_TABLE . " + WHERE forum_id = $forum_id"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + $this->forum_data = $row; + } + } + } +} diff --git a/phpBB/phpbb/cron/task/core/prune_notifications.php b/phpBB/phpbb/cron/task/core/prune_notifications.php new file mode 100644 index 0000000000..ffa7e17970 --- /dev/null +++ b/phpBB/phpbb/cron/task/core/prune_notifications.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Prune notifications cron task. +*/ +class prune_notifications extends \phpbb\cron\task\base +{ + protected $config; + protected $notification_manager; + + /** + * Constructor. + * + * @param \phpbb\config\config $config The config + * @param \phpbb\notification\manager $notification_manager Notification manager + */ + public function __construct(\phpbb\config\config $config, \phpbb\notification\manager $notification_manager) + { + $this->config = $config; + $this->notification_manager = $notification_manager; + } + + /** + * {@inheritdoc} + */ + public function run() + { + // time minus expire days in seconds + $timestamp = time() - ($this->config['read_notification_expire_days'] * 60 * 60 * 24); + $this->notification_manager->prune_notifications($timestamp); + } + + /** + * {@inheritdoc} + */ + public function is_runnable() + { + return (bool) $this->config['read_notification_expire_days']; + } + + /** + * {@inheritdoc} + */ + public function should_run() + { + return $this->config['read_notification_last_gc'] < time() - $this->config['read_notification_gc']; + } +} diff --git a/phpBB/phpbb/cron/task/core/prune_shadow_topics.php b/phpBB/phpbb/cron/task/core/prune_shadow_topics.php new file mode 100644 index 0000000000..97a4b0ea86 --- /dev/null +++ b/phpBB/phpbb/cron/task/core/prune_shadow_topics.php @@ -0,0 +1,200 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Prune one forum of its shadow topics cron task. +* +* It is intended to be used when cron is invoked via web. +* This task can decide whether it should be run using data obtained by viewforum +* code, without making additional database queries. +*/ +class prune_shadow_topics extends \phpbb\cron\task\base implements \phpbb\cron\task\parametrized +{ + protected $phpbb_root_path; + protected $php_ext; + protected $config; + protected $db; + protected $log; + protected $user; + + /** + * If $forum_data is given, it is assumed to contain necessary information + * about a single forum that is to be pruned. + * + * If $forum_data is not given, forum id will be retrieved via request_var + * and a database query will be performed to load the necessary information + * about the forum. + */ + protected $forum_data; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param string $php_ext PHP file extension + * @param \phpbb\config\config $config The config + * @param \phpbb\db\driver\driver_interface $db The db connection + * @param \phpbb\log\log $log The phpBB log system + * @param \phpbb\user $user The phpBB user object + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\log\log $log, \phpbb\user $user) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config = $config; + $this->db = $db; + $this->log = $log; + $this->user = $user; + } + + /** + * Manually set forum data. + * + * @param array $forum_data Information about a forum to be pruned. + */ + public function set_forum_data($forum_data) + { + $this->forum_data = $forum_data; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + if (!function_exists('auto_prune')) + { + include($this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext); + } + + if ($this->forum_data['prune_shadow_days']) + { + $this->auto_prune_shadow_topics($this->forum_data['forum_id'], 'shadow', $this->forum_data['forum_flags'], $this->forum_data['prune_shadow_days'], $this->forum_data['prune_shadow_freq']); + } + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * This cron task will not run when system cron is utilised, as in + * such cases prune_all_forums task would run instead. + * + * Additionally, this task must be given the forum data, either via + * the constructor or parse_parameters method. + * + * @return bool + */ + public function is_runnable() + { + return !$this->config['use_system_cron'] && $this->forum_data; + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * Forum pruning interval is specified in the forum data. + * + * @return bool + */ + public function should_run() + { + return $this->forum_data['enable_shadow_prune'] && $this->forum_data['prune_shadow_next'] < time(); + } + + /** + * Returns parameters of this cron task as an array. + * The array has one key, f, whose value is id of the forum to be pruned. + * + * @return array + */ + public function get_parameters() + { + return array('f' => $this->forum_data['forum_id']); + } + + /** + * Parses parameters found in $request, which is an instance of + * \phpbb\request\request_interface. + * + * It is expected to have a key f whose value is id of the forum to be pruned. + * + * @param \phpbb\request\request_interface $request Request object. + * + * @return null + */ + public function parse_parameters(\phpbb\request\request_interface $request) + { + $this->forum_data = null; + if ($request->is_set('f')) + { + $forum_id = $request->variable('f', 0); + + $sql = 'SELECT forum_id, prune_shadow_next, enable_shadow_prune, prune_shadow_days, forum_flags, prune_shadow_freq + FROM ' . FORUMS_TABLE . " + WHERE forum_id = $forum_id"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + $this->forum_data = $row; + } + } + } + + /** + * Automatically prune shadow topics + * Based on fuunction auto_prune() + * @param int $forum_id Forum ID of forum that should be pruned + * @param string $prune_mode Prune mode + * @param int $prune_flags Prune flags + * @param int $prune_days Prune date in days + * @param int $prune_freq Prune frequency + * @return null + */ + protected function auto_prune_shadow_topics($forum_id, $prune_mode, $prune_flags, $prune_days, $prune_freq) + { + $sql = 'SELECT forum_name + FROM ' . FORUMS_TABLE . " + WHERE forum_id = $forum_id"; + $result = $this->db->sql_query($sql, 3600); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + $prune_date = time() - ($prune_days * 86400); + $next_prune = time() + ($prune_freq * 86400); + + prune($forum_id, $prune_mode, $prune_date, $prune_flags, true); + + $sql = 'UPDATE ' . FORUMS_TABLE . " + SET prune_shadow_next = $next_prune + WHERE forum_id = $forum_id"; + $this->db->sql_query($sql); + + $user_id = (empty($this->user->data)) ? ANONYMOUS : $this->user->data['user_id']; + $user_ip = (empty($this->user->ip)) ? '' : $this->user->ip; + + $this->log->add('admin', $user_id, $user_ip, 'LOG_PRUNE_SHADOW', false, array($row['forum_name'])); + } + + return; + } +} diff --git a/phpBB/phpbb/cron/task/core/queue.php b/phpBB/phpbb/cron/task/core/queue.php new file mode 100644 index 0000000000..a9345a44df --- /dev/null +++ b/phpBB/phpbb/cron/task/core/queue.php @@ -0,0 +1,78 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Queue cron task. Sends email and jabber messages queued by other scripts. +*/ +class queue extends \phpbb\cron\task\base +{ + protected $phpbb_root_path; + protected $php_ext; + protected $config; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param string $php_ext PHP file extension + * @param \phpbb\config\config $config The config + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\config\config $config) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config = $config; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + if (!class_exists('queue')) + { + include($this->phpbb_root_path . 'includes/functions_messenger.' . $this->php_ext); + } + $queue = new \queue(); + $queue->process(); + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * Queue task is only run if the email queue (file) exists. + * + * @return bool + */ + public function is_runnable() + { + return file_exists($this->phpbb_root_path . 'cache/queue.' . $this->php_ext); + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * The interval between queue runs is specified in board configuration. + * + * @return bool + */ + public function should_run() + { + return $this->config['last_queue_run'] < time() - $this->config['queue_interval']; + } +} diff --git a/phpBB/phpbb/cron/task/core/tidy_cache.php b/phpBB/phpbb/cron/task/core/tidy_cache.php new file mode 100644 index 0000000000..506a245f0f --- /dev/null +++ b/phpBB/phpbb/cron/task/core/tidy_cache.php @@ -0,0 +1,72 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Tidy cache cron task. +*/ +class tidy_cache extends \phpbb\cron\task\base +{ + protected $config; + protected $cache; + + /** + * Constructor. + * + * @param \phpbb\config\config $config The config + * @param \phpbb\cache\driver\driver_interface $cache The cache driver + */ + public function __construct(\phpbb\config\config $config, \phpbb\cache\driver\driver_interface $cache) + { + $this->config = $config; + $this->cache = $cache; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + $this->cache->tidy(); + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * Tidy cache cron task runs if the cache implementation in use + * supports tidying. + * + * @return bool + */ + public function is_runnable() + { + return true; + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * The interval between cache tidying is specified in board + * configuration. + * + * @return bool + */ + public function should_run() + { + return $this->config['cache_last_gc'] < time() - $this->config['cache_gc']; + } +} diff --git a/phpBB/phpbb/cron/task/core/tidy_database.php b/phpBB/phpbb/cron/task/core/tidy_database.php new file mode 100644 index 0000000000..949bba8012 --- /dev/null +++ b/phpBB/phpbb/cron/task/core/tidy_database.php @@ -0,0 +1,66 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Tidy database cron task. +*/ +class tidy_database extends \phpbb\cron\task\base +{ + protected $phpbb_root_path; + protected $php_ext; + protected $config; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param string $php_ext The PHP file extension + * @param \phpbb\config\config $config The config + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\config\config $config) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config = $config; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + if (!function_exists('tidy_database')) + { + include($this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext); + } + tidy_database(); + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * The interval between database tidying is specified in board + * configuration. + * + * @return bool + */ + public function should_run() + { + return $this->config['database_last_gc'] < time() - $this->config['database_gc']; + } +} diff --git a/phpBB/phpbb/cron/task/core/tidy_plupload.php b/phpBB/phpbb/cron/task/core/tidy_plupload.php new file mode 100644 index 0000000000..b6aeecf4b4 --- /dev/null +++ b/phpBB/phpbb/cron/task/core/tidy_plupload.php @@ -0,0 +1,118 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Cron task for cleaning plupload's temporary upload directory. +*/ +class tidy_plupload extends \phpbb\cron\task\base +{ + /** + * How old a file must be (in seconds) before it is deleted. + * @var int + */ + protected $max_file_age = 86400; + + /** + * How often we run the cron (in seconds). + * @var int + */ + protected $cron_frequency = 86400; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * Config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Directory where plupload stores temporary files. + * @var string + */ + protected $plupload_upload_path; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param \phpbb\config\config $config The config + */ + public function __construct($phpbb_root_path, \phpbb\config\config $config) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->config = $config; + + $this->plupload_upload_path = $this->phpbb_root_path . $this->config['upload_path'] . '/plupload'; + } + + /** + * {@inheritDoc} + */ + public function run() + { + // Remove old temporary file (perhaps failed uploads?) + $last_valid_timestamp = time() - $this->max_file_age; + try + { + $iterator = new \DirectoryIterator($this->plupload_upload_path); + foreach ($iterator as $file) + { + if (strpos($file->getBasename(), $this->config['plupload_salt']) !== 0) + { + // Skip over any non-plupload files. + continue; + } + + if ($file->getMTime() < $last_valid_timestamp) + { + @unlink($file->getPathname()); + } + } + } + catch (\UnexpectedValueException $e) + { + add_log( + 'critical', + 'LOG_PLUPLOAD_TIDY_FAILED', + $this->plupload_upload_path, + $e->getMessage(), + $e->getTraceAsString() + ); + } + + $this->config->set('plupload_last_gc', time(), true); + } + + /** + * {@inheritDoc} + */ + public function is_runnable() + { + return !empty($this->config['plupload_salt']) && is_dir($this->plupload_upload_path); + } + + /** + * {@inheritDoc} + */ + public function should_run() + { + return $this->config['plupload_last_gc'] < time() - $this->cron_frequency; + } +} diff --git a/phpBB/phpbb/cron/task/core/tidy_search.php b/phpBB/phpbb/cron/task/core/tidy_search.php new file mode 100644 index 0000000000..eb3970254f --- /dev/null +++ b/phpBB/phpbb/cron/task/core/tidy_search.php @@ -0,0 +1,133 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Tidy search cron task. +* +* Will only run when the currently selected search backend supports tidying. +*/ +class tidy_search extends \phpbb\cron\task\base +{ + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP file extension + * @var string + */ + protected $php_ext; + + /** + * Auth object + * @var \phpbb\auth\auth + */ + protected $auth; + + /** + * Config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Database object + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $phpbb_dispatcher; + + /** + * Constructor. + * + * @param string $phpbb_root_path The phpBB root path + * @param string $php_ext The PHP file extension + * @param \phpbb\auth\auth $auth The auth object + * @param \phpbb\config\config $config The config object + * @param \phpbb\db\driver\driver_interface $db The database object + * @param \phpbb\user $user The user object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher The event dispatcher object + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\auth\auth $auth, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\user $user, \phpbb\event\dispatcher_interface $phpbb_dispatcher) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->auth = $auth; + $this->config = $config; + $this->db = $db; + $this->user = $user; + $this->phpbb_dispatcher = $phpbb_dispatcher; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + $search_type = $this->config['search_type']; + + // We do some additional checks in the module to ensure it can actually be utilised + $error = false; + $search = new $search_type($error, $this->phpbb_root_path, $this->php_ext, $this->auth, $this->config, $this->db, $this->user, $this->phpbb_dispatcher); + + if (!$error) + { + $search->tidy(); + } + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * Search cron task is runnable in all normal use. It may not be + * runnable if the search backend implementation selected in board + * configuration does not exist. + * + * @return bool + */ + public function is_runnable() + { + return class_exists($this->config['search_type']); + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * The interval between search tidying is specified in board + * configuration. + * + * @return bool + */ + public function should_run() + { + return $this->config['search_last_gc'] < time() - $this->config['search_gc']; + } +} diff --git a/phpBB/phpbb/cron/task/core/tidy_sessions.php b/phpBB/phpbb/cron/task/core/tidy_sessions.php new file mode 100644 index 0000000000..5e6dabdabf --- /dev/null +++ b/phpBB/phpbb/cron/task/core/tidy_sessions.php @@ -0,0 +1,59 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Tidy sessions cron task. +*/ +class tidy_sessions extends \phpbb\cron\task\base +{ + protected $config; + protected $user; + + /** + * Constructor. + * + * @param \phpbb\config\config $config The config + * @param \phpbb\user $user The user + */ + public function __construct(\phpbb\config\config $config, \phpbb\user $user) + { + $this->config = $config; + $this->user = $user; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + $this->user->session_gc(); + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * The interval between session tidying is specified in board + * configuration. + * + * @return bool + */ + public function should_run() + { + return $this->config['session_last_gc'] < time() - $this->config['session_gc']; + } +} diff --git a/phpBB/phpbb/cron/task/core/tidy_warnings.php b/phpBB/phpbb/cron/task/core/tidy_warnings.php new file mode 100644 index 0000000000..7b67eae6ef --- /dev/null +++ b/phpBB/phpbb/cron/task/core/tidy_warnings.php @@ -0,0 +1,80 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task\core; + +/** +* Tidy warnings cron task. +* +* Will only run when warnings are configured to expire. +*/ +class tidy_warnings extends \phpbb\cron\task\base +{ + protected $phpbb_root_path; + protected $php_ext; + protected $config; + + /** + * Constructor. + * + * @param string $phpbb_root_path The root path + * @param string $php_ext PHP file extension + * @param \phpbb\config\config $config The config + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\config\config $config) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->config = $config; + } + + /** + * Runs this cron task. + * + * @return null + */ + public function run() + { + if (!function_exists('tidy_warnings')) + { + include($this->phpbb_root_path . 'includes/functions_admin.' . $this->php_ext); + } + tidy_warnings(); + } + + /** + * Returns whether this cron task can run, given current board configuration. + * + * If warnings are set to never expire, this cron task will not run. + * + * @return bool + */ + public function is_runnable() + { + return (bool) $this->config['warnings_expire_days']; + } + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * The interval between warnings tidying is specified in board + * configuration. + * + * @return bool + */ + public function should_run() + { + return $this->config['warnings_last_gc'] < time() - $this->config['warnings_gc']; + } +} diff --git a/phpBB/phpbb/cron/task/core/update_hashes.php b/phpBB/phpbb/cron/task/core/update_hashes.php new file mode 100644 index 0000000000..a4fe477d99 --- /dev/null +++ b/phpBB/phpbb/cron/task/core/update_hashes.php @@ -0,0 +1,130 @@ +<?php +/** + * + * This file is part of the phpBB Forum Software package. + * + * @copyright (c) phpBB Limited <https://www.phpbb.com> + * @license GNU General Public License, version 2 (GPL-2.0) + * + * For full copyright and license information, please see + * the docs/CREDITS.txt file. + * + */ + +namespace phpbb\cron\task\core; + +/** + * Update old hashes to the current default hashing algorithm + * + * It is intended to gradually update all "old" style hashes to the + * current default hashing algorithm. + */ +class update_hashes extends \phpbb\cron\task\base +{ + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\lock\db */ + protected $update_lock; + + /** @var \phpbb\passwords\manager */ + protected $passwords_manager; + + /** @var string Default hashing type */ + protected $default_type; + + /** + * Constructor. + * + * @param \phpbb\config\config $config + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\lock\db $update_lock + * @param \phpbb\passwords\manager $passwords_manager + * @param array $hashing_algorithms Hashing driver + * service collection + * @param array $defaults Default password types + */ + public function __construct(\phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\lock\db $update_lock, \phpbb\passwords\manager $passwords_manager, $hashing_algorithms, $defaults) + { + $this->config = $config; + $this->db = $db; + $this->passwords_manager = $passwords_manager; + $this->update_lock = $update_lock; + + foreach ($defaults as $type) + { + if ($hashing_algorithms[$type]->is_supported()) + { + $this->default_type = $type; + break; + } + } + } + + /** + * {@inheritdoc} + */ + public function is_runnable() + { + return !$this->config['use_system_cron']; + } + + /** + * {@inheritdoc} + */ + public function should_run() + { + if (!empty($this->config['update_hashes_lock'])) + { + $last_run = explode(' ', $this->config['update_hashes_lock']); + if ($last_run[0] + 60 >= time()) + { + return false; + } + } + + return $this->config['enable_update_hashes'] && $this->config['update_hashes_last_cron'] < (time() - 60); + } + + /** + * {@inheritdoc} + */ + public function run() + { + if ($this->update_lock->acquire()) + { + $sql = 'SELECT user_id, user_password + FROM ' . USERS_TABLE . ' + WHERE user_password ' . $this->db->sql_like_expression('$H$' . $this->db->get_any_char()) . ' + OR user_password ' . $this->db->sql_like_expression('$CP$' . $this->db->get_any_char()); + $result = $this->db->sql_query_limit($sql, 20); + + $affected_rows = 0; + + while ($row = $this->db->sql_fetchrow($result)) + { + $new_hash = $this->passwords_manager->hash($row['user_password'], array($this->default_type)); + + // Increase number so we know that users were selected from the database + $affected_rows++; + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_password = "' . $this->db->sql_escape($new_hash) . '" + WHERE user_id = ' . (int) $row['user_id']; + $this->db->sql_query($sql); + } + + $this->config->set('update_hashes_last_cron', time()); + $this->update_lock->release(); + + // Stop cron for good once all hashes are converted + if ($affected_rows === 0) + { + $this->config->set('enable_update_hashes', '0'); + } + } + } +} diff --git a/phpBB/phpbb/cron/task/parametrized.php b/phpBB/phpbb/cron/task/parametrized.php new file mode 100644 index 0000000000..7e190b9b86 --- /dev/null +++ b/phpBB/phpbb/cron/task/parametrized.php @@ -0,0 +1,48 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task; + +/** +* Parametrized cron task interface. +* +* Parametrized cron tasks are somewhat of a cross between regular cron tasks and +* delayed jobs. Whereas regular cron tasks perform some action globally, +* parametrized cron tasks perform actions on a particular object (or objects). +* Parametrized cron tasks do not make sense and are not usable without +* specifying these objects. +*/ +interface parametrized extends \phpbb\cron\task\task +{ + /** + * Returns parameters of this cron task as an array. + * + * The array must map string keys to string values. + * + * @return array + */ + public function get_parameters(); + + /** + * Parses parameters found in $request, which is an instance of + * \phpbb\request\request_interface. + * + * $request contains user input and must not be trusted. + * Cron task must validate all data before using it. + * + * @param \phpbb\request\request_interface $request Request object. + * + * @return null + */ + public function parse_parameters(\phpbb\request\request_interface $request); +} diff --git a/phpBB/phpbb/cron/task/task.php b/phpBB/phpbb/cron/task/task.php new file mode 100644 index 0000000000..6d5a383d2d --- /dev/null +++ b/phpBB/phpbb/cron/task/task.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task; + +/** +* Cron task interface +*/ +interface task +{ + /** + * Returns the name of the task. + * + * @return string Name of wrapped task. + */ + public function get_name(); + + /** + * Runs this cron task. + * + * @return null + */ + public function run(); + + /** + * Returns whether this cron task can run, given current board configuration. + * + * For example, a cron task that prunes forums can only run when + * forum pruning is enabled. + * + * @return bool + */ + public function is_runnable(); + + /** + * Returns whether this cron task should run now, because enough time + * has passed since it was last run. + * + * @return bool + */ + public function should_run(); +} diff --git a/phpBB/phpbb/cron/task/wrapper.php b/phpBB/phpbb/cron/task/wrapper.php new file mode 100644 index 0000000000..8a4a8b1f0c --- /dev/null +++ b/phpBB/phpbb/cron/task/wrapper.php @@ -0,0 +1,106 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\cron\task; + +/** +* Cron task wrapper class. +* Enhances cron tasks with convenience methods that work identically for all tasks. +*/ +class wrapper +{ + protected $task; + protected $phpbb_root_path; + protected $php_ext; + + /** + * Constructor. + * + * Wraps a task $task, which must implement cron_task interface. + * + * @param \phpbb\cron\task\task $task The cron task to wrap. + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $php_ext PHP file extension + */ + public function __construct(\phpbb\cron\task\task $task, $phpbb_root_path, $php_ext) + { + $this->task = $task; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * Returns whether the wrapped task is parametrised. + * + * Parametrized tasks accept parameters during initialization and must + * normally be scheduled with parameters. + * + * @return bool Whether or not this task is parametrized. + */ + public function is_parametrized() + { + return $this->task instanceof \phpbb\cron\task\parametrized; + } + + /** + * Returns whether the wrapped task is ready to run. + * + * A task is ready to run when it is runnable according to current configuration + * and enough time has passed since it was last run. + * + * @return bool Whether the wrapped task is ready to run. + */ + public function is_ready() + { + return $this->task->is_runnable() && $this->task->should_run(); + } + + /** + * Returns a url through which this task may be invoked via web. + * + * When system cron is not in use, running a cron task is accomplished + * by outputting an image with the url returned by this function as + * source. + * + * @return string URL through which this task may be invoked. + */ + public function get_url() + { + $name = $this->get_name(); + if ($this->is_parametrized()) + { + $params = $this->task->get_parameters(); + $extra = ''; + foreach ($params as $key => $value) + { + $extra .= '&' . $key . '=' . urlencode($value); + } + } + else + { + $extra = ''; + } + $url = append_sid($this->phpbb_root_path . 'cron.' . $this->php_ext, 'cron_type=' . $name . $extra); + return $url; + } + + /** + * Forwards all other method calls to the wrapped task implementation. + * + * @return mixed + */ + public function __call($name, $args) + { + return call_user_func_array(array($this->task, $name), $args); + } +} diff --git a/phpBB/phpbb/datetime.php b/phpBB/phpbb/datetime.php new file mode 100644 index 0000000000..63cdba90fd --- /dev/null +++ b/phpBB/phpbb/datetime.php @@ -0,0 +1,168 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* phpBB custom extensions to the PHP DateTime class +* This handles the relative formats phpBB employs +*/ +class datetime extends \DateTime +{ + /** + * String used to wrap the date segment which should be replaced by today/tomorrow/yesterday + */ + const RELATIVE_WRAPPER = '|'; + + /** + * @var user User who is the context for this DateTime instance + */ + protected $user; + + /** + * @var array Date formats are preprocessed by phpBB, to save constant recalculation they are cached. + */ + static protected $format_cache = array(); + + /** + * Constructs a new instance of \phpbb\datetime, expanded to include an argument to inject + * the user context and modify the timezone to the users selected timezone if one is not set. + * + * @param user $user object for context. + * @param string $time String in a format accepted by strtotime(). + * @param \DateTimeZone $timezone Time zone of the time. + */ + public function __construct($user, $time = 'now', \DateTimeZone $timezone = null) + { + $this->user = $user; + $timezone = $timezone ?: $this->user->timezone; + + parent::__construct($time, $timezone); + } + + /** + * Formats the current date time into the specified format + * + * @param string $format Optional format to use for output, defaults to users chosen format + * @param boolean $force_absolute Force output of a non relative date + * @return string Formatted date time + */ + public function format($format = '', $force_absolute = false) + { + $format = $format ? $format : $this->user->date_format; + $format = self::format_cache($format, $this->user); + $relative = ($format['is_short'] && !$force_absolute); + $now = new self($this->user, 'now', $this->user->timezone); + + $timestamp = $this->getTimestamp(); + $now_ts = $now->getTimeStamp(); + + $delta = $now_ts - $timestamp; + + if ($relative) + { + /* + * Check the delta is less than or equal to 1 hour + * and the delta not more than a minute in the past + * and the delta is either greater than -5 seconds or timestamp + * and current time are of the same minute (they must be in the same hour already) + * finally check that relative dates are supported by the language pack + */ + if ($delta <= 3600 && $delta > -60 && + ($delta >= -5 || (($now_ts / 60) % 60) == (($timestamp / 60) % 60)) + && isset($this->user->lang['datetime']['AGO'])) + { + return $this->user->lang(array('datetime', 'AGO'), max(0, (int) floor($delta / 60))); + } + else + { + $midnight = clone $now; + $midnight->setTime(0, 0, 0); + + $midnight = $midnight->getTimestamp(); + + if ($timestamp <= $midnight + 2 * 86400) + { + $day = false; + + if ($timestamp > $midnight + 86400) + { + $day = 'TOMORROW'; + } + else if ($timestamp > $midnight) + { + $day = 'TODAY'; + } + else if ($timestamp > $midnight - 86400) + { + $day = 'YESTERDAY'; + } + + if ($day !== false) + { + // Format using the short formatting and finally swap out the relative token placeholder with the correct value + return str_replace(self::RELATIVE_WRAPPER . self::RELATIVE_WRAPPER, $this->user->lang['datetime'][$day], strtr(parent::format($format['format_short']), $format['lang'])); + } + } + } + } + + return strtr(parent::format($format['format_long']), $format['lang']); + } + + /** + * Magic method to convert DateTime object to string + * + * @return string Formatted date time, according to the users default settings. + */ + public function __toString() + { + return $this->format(); + } + + /** + * Pre-processes the specified date format + * + * @param string $format Output format + * @param user $user User object to use for localisation + * @return array Processed date format + */ + static protected function format_cache($format, $user) + { + $lang = $user->lang_name; + + if (!isset(self::$format_cache[$lang])) + { + self::$format_cache[$lang] = array(); + } + + if (!isset(self::$format_cache[$lang][$format])) + { + // Is the user requesting a friendly date format (i.e. 'Today 12:42')? + self::$format_cache[$lang][$format] = array( + 'is_short' => strpos($format, self::RELATIVE_WRAPPER) !== false, + 'format_short' => substr($format, 0, strpos($format, self::RELATIVE_WRAPPER)) . self::RELATIVE_WRAPPER . self::RELATIVE_WRAPPER . substr(strrchr($format, self::RELATIVE_WRAPPER), 1), + 'format_long' => str_replace(self::RELATIVE_WRAPPER, '', $format), + 'lang' => array_filter($user->lang['datetime'], 'is_string'), + ); + + // Short representation of month in format? Some languages use different terms for the long and short format of May + if ((strpos($format, '\M') === false && strpos($format, 'M') !== false) || (strpos($format, '\r') === false && strpos($format, 'r') !== false)) + { + self::$format_cache[$lang][$format]['lang']['May'] = $user->lang['datetime']['May_short']; + } + } + + return self::$format_cache[$lang][$format]; + } +} diff --git a/phpBB/phpbb/db/driver/driver.php b/phpBB/phpbb/db/driver/driver.php new file mode 100644 index 0000000000..01dd66cd6e --- /dev/null +++ b/phpBB/phpbb/db/driver/driver.php @@ -0,0 +1,1078 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* Database Abstraction Layer +*/ +abstract class driver implements driver_interface +{ + var $db_connect_id; + var $query_result; + var $return_on_error = false; + var $transaction = false; + var $sql_time = 0; + var $num_queries = array(); + var $open_queries = array(); + + var $curtime = 0; + var $query_hold = ''; + var $html_hold = ''; + var $sql_report = ''; + + var $persistency = false; + var $user = ''; + var $server = ''; + var $dbname = ''; + + // Set to true if error triggered + var $sql_error_triggered = false; + + // Holding the last sql query on sql error + var $sql_error_sql = ''; + // Holding the error information - only populated if sql_error_triggered is set + var $sql_error_returned = array(); + + // Holding transaction count + var $transactions = 0; + + // Supports multi inserts? + var $multi_insert = false; + + /** + * Current sql layer + */ + var $sql_layer = ''; + + /** + * Wildcards for matching any (%) or exactly one (_) character within LIKE expressions + */ + var $any_char; + var $one_char; + + /** + * Exact version of the DBAL, directly queried + */ + var $sql_server_version = false; + + /** + * Constructor + */ + function __construct() + { + $this->num_queries = array( + 'cached' => 0, + 'normal' => 0, + 'total' => 0, + ); + + // Fill default sql layer based on the class being called. + // This can be changed by the specified layer itself later if needed. + $this->sql_layer = substr(get_class($this), strlen('phpbb\db\driver\\')); + + // Do not change this please! This variable is used to easy the use of it - and is hardcoded. + $this->any_char = chr(0) . '%'; + $this->one_char = chr(0) . '_'; + } + + /** + * {@inheritdoc} + */ + public function get_sql_layer() + { + return $this->sql_layer; + } + + /** + * {@inheritdoc} + */ + public function get_db_name() + { + return $this->dbname; + } + + /** + * {@inheritdoc} + */ + public function get_any_char() + { + return $this->any_char; + } + + /** + * {@inheritdoc} + */ + public function get_one_char() + { + return $this->one_char; + } + + /** + * {@inheritdoc} + */ + public function get_db_connect_id() + { + return $this->db_connect_id; + } + + /** + * {@inheritdoc} + */ + public function get_sql_error_triggered() + { + return $this->sql_error_triggered; + } + + /** + * {@inheritdoc} + */ + public function get_sql_error_sql() + { + return $this->sql_error_sql; + } + + /** + * {@inheritdoc} + */ + public function get_transaction() + { + return $this->transaction; + } + + /** + * {@inheritdoc} + */ + public function get_sql_time() + { + return $this->sql_time; + } + + /** + * {@inheritdoc} + */ + public function get_sql_error_returned() + { + return $this->sql_error_returned; + } + + /** + * {@inheritdoc} + */ + public function get_multi_insert() + { + return $this->multi_insert; + } + + /** + * {@inheritdoc} + */ + public function set_multi_insert($multi_insert) + { + $this->multi_insert = $multi_insert; + } + + /** + * {@inheritDoc} + */ + function sql_return_on_error($fail = false) + { + $this->sql_error_triggered = false; + $this->sql_error_sql = ''; + + $this->return_on_error = $fail; + } + + /** + * {@inheritDoc} + */ + function sql_num_queries($cached = false) + { + return ($cached) ? $this->num_queries['cached'] : $this->num_queries['normal']; + } + + /** + * {@inheritDoc} + */ + function sql_add_num_queries($cached = false) + { + $this->num_queries['cached'] += ($cached !== false) ? 1 : 0; + $this->num_queries['normal'] += ($cached !== false) ? 0 : 1; + $this->num_queries['total'] += 1; + } + + /** + * {@inheritDoc} + */ + function sql_close() + { + if (!$this->db_connect_id) + { + return false; + } + + if ($this->transaction) + { + do + { + $this->sql_transaction('commit'); + } + while ($this->transaction); + } + + foreach ($this->open_queries as $query_id) + { + $this->sql_freeresult($query_id); + } + + // Connection closed correctly. Set db_connect_id to false to prevent errors + if ($result = $this->_sql_close()) + { + $this->db_connect_id = false; + } + + return $result; + } + + /** + * {@inheritDoc} + */ + function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + if (empty($query)) + { + return false; + } + + // Never use a negative total or offset + $total = ($total < 0) ? 0 : $total; + $offset = ($offset < 0) ? 0 : $offset; + + return $this->_sql_query_limit($query, $total, $offset, $cache_ttl); + } + + /** + * {@inheritDoc} + */ + function sql_fetchrowset($query_id = false) + { + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($query_id !== false) + { + $result = array(); + while ($row = $this->sql_fetchrow($query_id)) + { + $result[] = $row; + } + + return $result; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + if ($query_id === false) + { + return false; + } + + $this->sql_freeresult($query_id); + $query_id = $this->sql_query($this->last_query_text); + + if ($query_id === false) + { + return false; + } + + // We do not fetch the row for rownum == 0 because then the next resultset would be the second row + for ($i = 0; $i < $rownum; $i++) + { + if (!$this->sql_fetchrow($query_id)) + { + return false; + } + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_fetchfield($field, $rownum = false, $query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($query_id !== false) + { + if ($rownum !== false) + { + $this->sql_rowseek($rownum, $query_id); + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchfield($query_id, $field); + } + + $row = $this->sql_fetchrow($query_id); + return (isset($row[$field])) ? $row[$field] : false; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_like_expression($expression) + { + $expression = utf8_str_replace(array('_', '%'), array("\_", "\%"), $expression); + $expression = utf8_str_replace(array(chr(0) . "\_", chr(0) . "\%"), array('_', '%'), $expression); + + return $this->_sql_like_expression('LIKE \'' . $this->sql_escape($expression) . '\''); + } + + /** + * {@inheritDoc} + */ + function sql_not_like_expression($expression) + { + $expression = utf8_str_replace(array('_', '%'), array("\_", "\%"), $expression); + $expression = utf8_str_replace(array(chr(0) . "\_", chr(0) . "\%"), array('_', '%'), $expression); + + return $this->_sql_not_like_expression('NOT LIKE \'' . $this->sql_escape($expression) . '\''); + } + + /** + * {@inheritDoc} + */ + public function sql_case($condition, $action_true, $action_false = false) + { + $sql_case = 'CASE WHEN ' . $condition; + $sql_case .= ' THEN ' . $action_true; + $sql_case .= ($action_false !== false) ? ' ELSE ' . $action_false : ''; + $sql_case .= ' END'; + return $sql_case; + } + + /** + * {@inheritDoc} + */ + public function sql_concatenate($expr1, $expr2) + { + return $expr1 . ' || ' . $expr2; + } + + /** + * {@inheritDoc} + */ + function sql_buffer_nested_transactions() + { + return false; + } + + /** + * {@inheritDoc} + */ + function sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + // If we are within a transaction we will not open another one, but enclose the current one to not loose data (preventing auto commit) + if ($this->transaction) + { + $this->transactions++; + return true; + } + + $result = $this->_sql_transaction('begin'); + + if (!$result) + { + $this->sql_error(); + } + + $this->transaction = true; + break; + + case 'commit': + // If there was a previously opened transaction we do not commit yet... + // but count back the number of inner transactions + if ($this->transaction && $this->transactions) + { + $this->transactions--; + return true; + } + + // Check if there is a transaction (no transaction can happen if + // there was an error, with a combined rollback and error returning enabled) + // This implies we have transaction always set for autocommit db's + if (!$this->transaction) + { + return false; + } + + $result = $this->_sql_transaction('commit'); + + if (!$result) + { + $this->sql_error(); + } + + $this->transaction = false; + $this->transactions = 0; + break; + + case 'rollback': + $result = $this->_sql_transaction('rollback'); + $this->transaction = false; + $this->transactions = 0; + break; + + default: + $result = $this->_sql_transaction($status); + break; + } + + return $result; + } + + /** + * {@inheritDoc} + */ + function sql_build_array($query, $assoc_ary = false) + { + if (!is_array($assoc_ary)) + { + return false; + } + + $fields = $values = array(); + + if ($query == 'INSERT' || $query == 'INSERT_SELECT') + { + foreach ($assoc_ary as $key => $var) + { + $fields[] = $key; + + if (is_array($var) && is_string($var[0])) + { + // This is used for INSERT_SELECT(s) + $values[] = $var[0]; + } + else + { + $values[] = $this->_sql_validate_value($var); + } + } + + $query = ($query == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' '; + } + else if ($query == 'MULTI_INSERT') + { + trigger_error('The MULTI_INSERT query value is no longer supported. Please use sql_multi_insert() instead.', E_USER_ERROR); + } + else if ($query == 'UPDATE' || $query == 'SELECT' || $query == 'DELETE') + { + $values = array(); + foreach ($assoc_ary as $key => $var) + { + $values[] = "$key = " . $this->_sql_validate_value($var); + } + $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values); + } + + return $query; + } + + /** + * {@inheritDoc} + */ + function sql_in_set($field, $array, $negate = false, $allow_empty_set = false) + { + if (!sizeof($array)) + { + if (!$allow_empty_set) + { + // Print the backtrace to help identifying the location of the problematic code + $this->sql_error('No values specified for SQL IN comparison'); + } + else + { + // NOT IN () actually means everything so use a tautology + if ($negate) + { + return '1=1'; + } + // IN () actually means nothing so use a contradiction + else + { + return '1=0'; + } + } + } + + if (!is_array($array)) + { + $array = array($array); + } + + if (sizeof($array) == 1) + { + @reset($array); + $var = current($array); + + return $field . ($negate ? ' <> ' : ' = ') . $this->_sql_validate_value($var); + } + else + { + return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', array_map(array($this, '_sql_validate_value'), $array)) . ')'; + } + } + + /** + * {@inheritDoc} + */ + function sql_bit_and($column_name, $bit, $compare = '') + { + if (method_exists($this, '_sql_bit_and')) + { + return $this->_sql_bit_and($column_name, $bit, $compare); + } + + return $column_name . ' & ' . (1 << $bit) . (($compare) ? ' ' . $compare : ''); + } + + /** + * {@inheritDoc} + */ + function sql_bit_or($column_name, $bit, $compare = '') + { + if (method_exists($this, '_sql_bit_or')) + { + return $this->_sql_bit_or($column_name, $bit, $compare); + } + + return $column_name . ' | ' . (1 << $bit) . (($compare) ? ' ' . $compare : ''); + } + + /** + * {@inheritDoc} + */ + function cast_expr_to_bigint($expression) + { + return $expression; + } + + /** + * {@inheritDoc} + */ + function cast_expr_to_string($expression) + { + return $expression; + } + + /** + * {@inheritDoc} + */ + function sql_lower_text($column_name) + { + return "LOWER($column_name)"; + } + + /** + * {@inheritDoc} + */ + function sql_multi_insert($table, $sql_ary) + { + if (!sizeof($sql_ary)) + { + return false; + } + + if ($this->multi_insert) + { + $ary = array(); + foreach ($sql_ary as $id => $_sql_ary) + { + // If by accident the sql array is only one-dimensional we build a normal insert statement + if (!is_array($_sql_ary)) + { + return $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $sql_ary)); + } + + $values = array(); + foreach ($_sql_ary as $key => $var) + { + $values[] = $this->_sql_validate_value($var); + } + $ary[] = '(' . implode(', ', $values) . ')'; + } + + return $this->sql_query('INSERT INTO ' . $table . ' ' . ' (' . implode(', ', array_keys($sql_ary[0])) . ') VALUES ' . implode(', ', $ary)); + } + else + { + foreach ($sql_ary as $ary) + { + if (!is_array($ary)) + { + return false; + } + + $result = $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $ary)); + + if (!$result) + { + return false; + } + } + } + + return true; + } + + /** + * Function for validating values + * @access private + */ + function _sql_validate_value($var) + { + if (is_null($var)) + { + return 'NULL'; + } + else if (is_string($var)) + { + return "'" . $this->sql_escape($var) . "'"; + } + else + { + return (is_bool($var)) ? intval($var) : $var; + } + } + + /** + * {@inheritDoc} + */ + function sql_build_query($query, $array) + { + $sql = ''; + switch ($query) + { + case 'SELECT': + case 'SELECT_DISTINCT'; + + $sql = str_replace('_', ' ', $query) . ' ' . $array['SELECT'] . ' FROM '; + + // Build table array. We also build an alias array for later checks. + $table_array = $aliases = array(); + $used_multi_alias = false; + + foreach ($array['FROM'] as $table_name => $alias) + { + if (is_array($alias)) + { + $used_multi_alias = true; + + foreach ($alias as $multi_alias) + { + $table_array[] = $table_name . ' ' . $multi_alias; + $aliases[] = $multi_alias; + } + } + else + { + $table_array[] = $table_name . ' ' . $alias; + $aliases[] = $alias; + } + } + + // We run the following code to determine if we need to re-order the table array. ;) + // The reason for this is that for multi-aliased tables (two equal tables) in the FROM statement the last table need to match the first comparison. + // DBMS who rely on this: Oracle, PostgreSQL and MSSQL. For all other DBMS it makes absolutely no difference in which order the table is. + if (!empty($array['LEFT_JOIN']) && sizeof($array['FROM']) > 1 && $used_multi_alias !== false) + { + // Take first LEFT JOIN + $join = current($array['LEFT_JOIN']); + + // Determine the table used there (even if there are more than one used, we only want to have one + preg_match('/(' . implode('|', $aliases) . ')\.[^\s]+/U', str_replace(array('(', ')', 'AND', 'OR', ' '), '', $join['ON']), $matches); + + // If there is a first join match, we need to make sure the table order is correct + if (!empty($matches[1])) + { + $first_join_match = trim($matches[1]); + $table_array = $last = array(); + + foreach ($array['FROM'] as $table_name => $alias) + { + if (is_array($alias)) + { + foreach ($alias as $multi_alias) + { + ($multi_alias === $first_join_match) ? $last[] = $table_name . ' ' . $multi_alias : $table_array[] = $table_name . ' ' . $multi_alias; + } + } + else + { + ($alias === $first_join_match) ? $last[] = $table_name . ' ' . $alias : $table_array[] = $table_name . ' ' . $alias; + } + } + + $table_array = array_merge($table_array, $last); + } + } + + $sql .= $this->_sql_custom_build('FROM', implode(' CROSS JOIN ', $table_array)); + + if (!empty($array['LEFT_JOIN'])) + { + foreach ($array['LEFT_JOIN'] as $join) + { + $sql .= ' LEFT JOIN ' . key($join['FROM']) . ' ' . current($join['FROM']) . ' ON (' . $join['ON'] . ')'; + } + } + + if (!empty($array['WHERE'])) + { + $sql .= ' WHERE ' . $this->_sql_custom_build('WHERE', $array['WHERE']); + } + + if (!empty($array['GROUP_BY'])) + { + $sql .= ' GROUP BY ' . $array['GROUP_BY']; + } + + if (!empty($array['ORDER_BY'])) + { + $sql .= ' ORDER BY ' . $array['ORDER_BY']; + } + + break; + } + + return $sql; + } + + /** + * {@inheritDoc} + */ + function sql_error($sql = '') + { + global $auth, $user, $config; + + // Set var to retrieve errored status + $this->sql_error_triggered = true; + $this->sql_error_sql = $sql; + + $this->sql_error_returned = $this->_sql_error(); + + if (!$this->return_on_error) + { + $message = 'SQL ERROR [ ' . $this->sql_layer . ' ]<br /><br />' . $this->sql_error_returned['message'] . ' [' . $this->sql_error_returned['code'] . ']'; + + // Show complete SQL error and path to administrators only + // Additionally show complete error on installation or if extended debug mode is enabled + // The DEBUG constant is for development only! + if ((isset($auth) && $auth->acl_get('a_')) || defined('IN_INSTALL') || defined('DEBUG')) + { + $message .= ($sql) ? '<br /><br />SQL<br /><br />' . htmlspecialchars($sql) : ''; + } + else + { + // If error occurs in initiating the session we need to use a pre-defined language string + // This could happen if the connection could not be established for example (then we are not able to grab the default language) + if (!isset($user->lang['SQL_ERROR_OCCURRED'])) + { + $message .= '<br /><br />An sql error occurred while fetching this page. Please contact an administrator if this problem persists.'; + } + else + { + if (!empty($config['board_contact'])) + { + $message .= '<br /><br />' . sprintf($user->lang['SQL_ERROR_OCCURRED'], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>'); + } + else + { + $message .= '<br /><br />' . sprintf($user->lang['SQL_ERROR_OCCURRED'], '', ''); + } + } + } + + if ($this->transaction) + { + $this->sql_transaction('rollback'); + } + + if (strlen($message) > 1024) + { + // We need to define $msg_long_text here to circumvent text stripping. + global $msg_long_text; + $msg_long_text = $message; + + trigger_error(false, E_USER_ERROR); + } + + trigger_error($message, E_USER_ERROR); + } + + if ($this->transaction) + { + $this->sql_transaction('rollback'); + } + + return $this->sql_error_returned; + } + + /** + * {@inheritDoc} + */ + function sql_report($mode, $query = '') + { + global $cache, $starttime, $phpbb_root_path, $phpbb_path_helper, $user; + global $request; + + if (is_object($request) && !$request->variable('explain', false)) + { + return false; + } + + if (!$query && $this->query_hold != '') + { + $query = $this->query_hold; + } + + switch ($mode) + { + case 'display': + if (!empty($cache)) + { + $cache->unload(); + } + $this->sql_close(); + + $mtime = explode(' ', microtime()); + $totaltime = $mtime[0] + $mtime[1] - $starttime; + + echo '<!DOCTYPE html> + <html dir="ltr"> + <head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <title>SQL Report</title> + <link href="' . htmlspecialchars($phpbb_path_helper->update_web_root_path($phpbb_root_path) . $phpbb_path_helper->get_adm_relative_path()) . 'style/admin.css" rel="stylesheet" type="text/css" media="screen" /> + </head> + <body id="errorpage"> + <div id="wrap"> + <div id="page-header"> + <a href="' . build_url('explain') . '">Return to previous page</a> + </div> + <div id="page-body"> + <div id="acp"> + <div class="panel"> + <span class="corners-top"><span></span></span> + <div id="content"> + <h1>SQL Report</h1> + <br /> + <p><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries['normal']} queries" . (($this->num_queries['cached']) ? " + {$this->num_queries['cached']} " . (($this->num_queries['cached'] == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></p> + + <p>Time spent on ' . $this->sql_layer . ' queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></p> + + <br /><br /> + ' . $this->sql_report . ' + </div> + <span class="corners-bottom"><span></span></span> + </div> + </div> + </div> + <div id="page-footer"> + Powered by <a href="https://www.phpbb.com/">phpBB</a>® Forum Software © phpBB Limited + </div> + </div> + </body> + </html>'; + + exit_handler(); + + break; + + case 'stop': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $this->sql_report .= ' + + <table cellspacing="1"> + <thead> + <tr> + <th>Query #' . $this->num_queries['total'] . '</th> + </tr> + </thead> + <tbody> + <tr> + <td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td> + </tr> + </tbody> + </table> + + ' . $this->html_hold . ' + + <p style="text-align: center;"> + '; + + if ($this->query_result) + { + if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query)) + { + $this->sql_report .= 'Affected rows: <b>' . $this->sql_affectedrows() . '</b> | '; + } + $this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $this->curtime) . 's</b>'; + } + else + { + $error = $this->sql_error(); + $this->sql_report .= '<b style="color: red">FAILED</b> - ' . $this->sql_layer . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']); + } + + $this->sql_report .= '</p><br /><br />'; + + $this->sql_time += $endtime - $this->curtime; + break; + + case 'start': + $this->query_hold = $query; + $this->html_hold = ''; + + $this->_sql_report($mode, $query); + + $this->curtime = explode(' ', microtime()); + $this->curtime = $this->curtime[0] + $this->curtime[1]; + + break; + + case 'add_select_row': + + $html_table = func_get_arg(2); + $row = func_get_arg(3); + + if (!$html_table && sizeof($row)) + { + $html_table = true; + $this->html_hold .= '<table cellspacing="1"><tr>'; + + foreach (array_keys($row) as $val) + { + $this->html_hold .= '<th>' . (($val) ? ucwords(str_replace('_', ' ', $val)) : ' ') . '</th>'; + } + $this->html_hold .= '</tr>'; + } + $this->html_hold .= '<tr>'; + + $class = 'row1'; + foreach (array_values($row) as $val) + { + $class = ($class == 'row1') ? 'row2' : 'row1'; + $this->html_hold .= '<td class="' . $class . '">' . (($val) ? $val : ' ') . '</td>'; + } + $this->html_hold .= '</tr>'; + + return $html_table; + + break; + + case 'fromcache': + + $this->_sql_report($mode, $query); + + break; + + case 'record_fromcache': + + $endtime = func_get_arg(2); + $splittime = func_get_arg(3); + + $time_cache = $endtime - $this->curtime; + $time_db = $splittime - $endtime; + $color = ($time_db > $time_cache) ? 'green' : 'red'; + + $this->sql_report .= '<table cellspacing="1"><thead><tr><th>Query results obtained from the cache</th></tr></thead><tbody><tr>'; + $this->sql_report .= '<td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></tbody></table>'; + $this->sql_report .= '<p style="text-align: center;">'; + $this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p><br /><br />'; + + // Pad the start time to not interfere with page timing + $starttime += $time_db; + + break; + + default: + + $this->_sql_report($mode, $query); + + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function get_estimated_row_count($table_name) + { + return $this->get_row_count($table_name); + } + + /** + * {@inheritDoc} + */ + function get_row_count($table_name) + { + $sql = 'SELECT COUNT(*) AS rows_total + FROM ' . $this->sql_escape($table_name); + $result = $this->sql_query($sql); + $rows_total = $this->sql_fetchfield('rows_total'); + $this->sql_freeresult($result); + + return $rows_total; + } +} diff --git a/phpBB/phpbb/db/driver/driver_interface.php b/phpBB/phpbb/db/driver/driver_interface.php new file mode 100644 index 0000000000..8b487c5d42 --- /dev/null +++ b/phpBB/phpbb/db/driver/driver_interface.php @@ -0,0 +1,453 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +interface driver_interface +{ + /** + * Gets the name of the sql layer. + * + * @return string + */ + public function get_sql_layer(); + + /** + * Gets the name of the database. + * + * @return string + */ + public function get_db_name(); + + /** + * Wildcards for matching any (%) character within LIKE expressions + * + * @return string + */ + public function get_any_char(); + + /** + * Wildcards for matching exactly one (_) character within LIKE expressions + * + * @return string + */ + public function get_one_char(); + + /** + * Gets the time spent into the queries + * + * @return int + */ + public function get_sql_time(); + + /** + * Gets the connect ID. + * + * @return mixed + */ + public function get_db_connect_id(); + + /** + * Indicates if an error was triggered. + * + * @return bool + */ + public function get_sql_error_triggered(); + + /** + * Gets the last faulty query + * + * @return string + */ + public function get_sql_error_sql(); + + /** + * Indicates if we are in a transaction. + * + * @return bool + */ + public function get_transaction(); + + /** + * Gets the returned error. + * + * @return array + */ + public function get_sql_error_returned(); + + /** + * Indicates if multiple insertion can be used + * + * @return bool + */ + public function get_multi_insert(); + + /** + * Set if multiple insertion can be used + * + * @param bool $multi_insert + */ + public function set_multi_insert($multi_insert); + + /** + * Gets the exact number of rows in a specified table. + * + * @param string $table_name Table name + * @return string Exact number of rows in $table_name. + */ + public function get_row_count($table_name); + + /** + * Gets the estimated number of rows in a specified table. + * + * @param string $table_name Table name + * @return string Number of rows in $table_name. + * Prefixed with ~ if estimated (otherwise exact). + */ + public function get_estimated_row_count($table_name); + + /** + * Run LOWER() on DB column of type text (i.e. neither varchar nor char). + * + * @param string $column_name The column name to use + * @return string A SQL statement like "LOWER($column_name)" + */ + public function sql_lower_text($column_name); + + /** + * Display sql error page + * + * @param string $sql The SQL query causing the error + * @return mixed Returns the full error message, if $this->return_on_error + * is set, null otherwise + */ + public function sql_error($sql = ''); + + /** + * Returns whether results of a query need to be buffered to run a + * transaction while iterating over them. + * + * @return bool Whether buffering is required. + */ + public function sql_buffer_nested_transactions(); + + /** + * Run binary OR operator on DB column. + * + * @param string $column_name The column name to use + * @param int $bit The value to use for the OR operator, + * will be converted to (1 << $bit). Is used by options, + * using the number schema... 0, 1, 2...29 + * @param string $compare Any custom SQL code after the check (e.g. "= 0") + * @return string A SQL statement like "$column | (1 << $bit) {$compare}" + */ + public function sql_bit_or($column_name, $bit, $compare = ''); + + /** + * Version information about used database + * + * @param bool $raw Only return the fetched sql_server_version + * @param bool $use_cache Is it safe to retrieve the value from the cache + * @return string sql server version + */ + public function sql_server_info($raw = false, $use_cache = true); + + /** + * Return on error or display error message + * + * @param bool $fail Should we return on errors, or stop + * @return null + */ + public function sql_return_on_error($fail = false); + + /** + * Build sql statement from an array + * + * @param string $query Should be on of the following strings: + * INSERT, INSERT_SELECT, UPDATE, SELECT, DELETE + * @param array $assoc_ary Array with "column => value" pairs + * @return string A SQL statement like "c1 = 'a' AND c2 = 'b'" + */ + public function sql_build_array($query, $assoc_ary = array()); + + /** + * Fetch all rows + * + * @param mixed $query_id Already executed query to get the rows from, + * if false, the last query will be used. + * @return mixed Nested array if the query had rows, false otherwise + */ + public function sql_fetchrowset($query_id = false); + + /** + * SQL Transaction + * + * @param string $status Should be one of the following strings: + * begin, commit, rollback + * @return mixed Buffered, seekable result handle, false on error + */ + public function sql_transaction($status = 'begin'); + + /** + * Build a concatenated expression + * + * @param string $expr1 Base SQL expression where we append the second one + * @param string $expr2 SQL expression that is appended to the first expression + * @return string Concatenated string + */ + public function sql_concatenate($expr1, $expr2); + + /** + * Build a case expression + * + * Note: The two statements action_true and action_false must have the same + * data type (int, vchar, ...) in the database! + * + * @param string $condition The condition which must be true, + * to use action_true rather then action_else + * @param string $action_true SQL expression that is used, if the condition is true + * @param mixed $action_false SQL expression that is used, if the condition is false + * @return string CASE expression including the condition and statements + */ + public function sql_case($condition, $action_true, $action_false = false); + + /** + * Build sql statement from array for select and select distinct statements + * + * Possible query values: SELECT, SELECT_DISTINCT + * + * @param string $query Should be one of: SELECT, SELECT_DISTINCT + * @param array $array Array with the query data: + * SELECT A comma imploded list of columns to select + * FROM Array with "table => alias" pairs, + * (alias can also be an array) + * Optional: LEFT_JOIN Array of join entries: + * FROM Table that should be joined + * ON Condition for the join + * Optional: WHERE Where SQL statement + * Optional: GROUP_BY Group by SQL statement + * Optional: ORDER_BY Order by SQL statement + * @return string A SQL statement ready for execution + */ + public function sql_build_query($query, $array); + + /** + * Fetch field + * if rownum is false, the current row is used, else it is pointing to the row (zero-based) + * + * @param string $field Name of the column + * @param mixed $rownum Row number, if false the current row will be used + * and the row curser will point to the next row + * Note: $rownum is 0 based + * @param mixed $query_id Already executed query to get the rows from, + * if false, the last query will be used. + * @return mixed String value of the field in the selected row, + * false, if the row does not exist + */ + public function sql_fetchfield($field, $rownum = false, $query_id = false); + + /** + * Fetch current row + * + * @param mixed $query_id Already executed query to get the rows from, + * if false, the last query will be used. + * @return mixed Array with the current row, + * false, if the row does not exist + */ + public function sql_fetchrow($query_id = false); + + /** + * Returns SQL string to cast a string expression to an int. + * + * @param string $expression An expression evaluating to string + * @return string Expression returning an int + */ + public function cast_expr_to_bigint($expression); + + /** + * Get last inserted id after insert statement + * + * @return string Autoincrement value of the last inserted row + */ + public function sql_nextid(); + + /** + * Add to query count + * + * @param bool $cached Is this query cached? + * @return null + */ + public function sql_add_num_queries($cached = false); + + /** + * Build LIMIT query + * + * @param string $query The SQL query to execute + * @param int $total The number of rows to select + * @param int $offset + * @param int $cache_ttl Either 0 to avoid caching or + * the time in seconds which the result shall be kept in cache + * @return mixed Buffered, seekable result handle, false on error + */ + public function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0); + + /** + * Base query method + * + * @param string $query The SQL query to execute + * @param int $cache_ttl Either 0 to avoid caching or + * the time in seconds which the result shall be kept in cache + * @return mixed Buffered, seekable result handle, false on error + */ + public function sql_query($query = '', $cache_ttl = 0); + + /** + * Returns SQL string to cast an integer expression to a string. + * + * @param string $expression An expression evaluating to int + * @return string Expression returning a string + */ + public function cast_expr_to_string($expression); + + /** + * Connect to server + * + * @param string $sqlserver Address of the database server + * @param string $sqluser User name of the SQL user + * @param string $sqlpassword Password of the SQL user + * @param string $database Name of the database + * @param mixed $port Port of the database server + * @param bool $persistency + * @param bool $new_link Should a new connection be established + * @return mixed Connection ID on success, string error message otherwise + */ + public function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false); + + /** + * Run binary AND operator on DB column. + * Results in sql statement: "{$column_name} & (1 << {$bit}) {$compare}" + * + * @param string $column_name The column name to use + * @param int $bit The value to use for the AND operator, + * will be converted to (1 << $bit). Is used by + * options, using the number schema: 0, 1, 2...29 + * @param string $compare Any custom SQL code after the check (for example "= 0") + * @return string A SQL statement like: "{$column} & (1 << {$bit}) {$compare}" + */ + public function sql_bit_and($column_name, $bit, $compare = ''); + + /** + * Free sql result + * + * @param mixed $query_id Already executed query result, + * if false, the last query will be used. + * @return null + */ + public function sql_freeresult($query_id = false); + + /** + * Return number of sql queries and cached sql queries used + * + * @param bool $cached Should we return the number of cached or normal queries? + * @return int Number of queries that have been executed + */ + public function sql_num_queries($cached = false); + + /** + * Run more than one insert statement. + * + * @param string $table Table name to run the statements on + * @param array $sql_ary Multi-dimensional array holding the statement data + * @return bool false if no statements were executed. + */ + public function sql_multi_insert($table, $sql_ary); + + /** + * Return number of affected rows + * + * @return mixed Number of the affected rows by the last query + * false if no query has been run before + */ + public function sql_affectedrows(); + + /** + * DBAL garbage collection, close SQL connection + * + * @return mixed False if no connection was opened before, + * Server response otherwise + */ + public function sql_close(); + + /** + * Seek to given row number + * + * @param mixed $rownum Row number the curser should point to + * Note: $rownum is 0 based + * @param mixed $query_id ID of the query to set the row cursor on + * if false, the last query will be used. + * $query_id will then be set correctly + * @return bool False if something went wrong + */ + public function sql_rowseek($rownum, &$query_id); + + /** + * Escape string used in sql query + * + * @param string $msg String to be escaped + * @return string Escaped version of $msg + */ + public function sql_escape($msg); + + /** + * Correctly adjust LIKE expression for special characters + * Some DBMS are handling them in a different way + * + * @param string $expression The expression to use. Every wildcard is + * escaped, except $this->any_char and $this->one_char + * @return string A SQL statement like: "LIKE 'bertie_%'" + */ + public function sql_like_expression($expression); + + /** + * Correctly adjust NOT LIKE expression for special characters + * Some DBMS are handling them in a different way + * + * @param string $expression The expression to use. Every wildcard is + * escaped, except $this->any_char and $this->one_char + * @return string A SQL statement like: "NOT LIKE 'bertie_%'" + */ + public function sql_not_like_expression($expression); + + /** + * Explain queries + * + * @param string $mode Available modes: display, start, stop, + * add_select_row, fromcache, record_fromcache + * @param string $query The Query that should be explained + * @return mixed Either a full HTML page, boolean or null + */ + public function sql_report($mode, $query = ''); + + /** + * Build IN or NOT IN sql comparison string, uses <> or = on single element + * arrays to improve comparison speed + * + * @param string $field Name of the sql column that shall be compared + * @param array $array Array of values that are (not) allowed + * @param bool $negate true for NOT IN (), false for IN () + * @param bool $allow_empty_set If true, allow $array to be empty, + * this function will return 1=1 or 1=0 then. + * @return string A SQL statement like: "IN (1, 2, 3, 4)" or "= 1" + */ + public function sql_in_set($field, $array, $negate = false, $allow_empty_set = false); +} diff --git a/phpBB/phpbb/db/driver/factory.php b/phpBB/phpbb/db/driver/factory.php new file mode 100644 index 0000000000..fb3a826254 --- /dev/null +++ b/phpBB/phpbb/db/driver/factory.php @@ -0,0 +1,443 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +use \Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* Database Abstraction Layer +*/ +class factory implements driver_interface +{ + /** + * @var driver_interface + */ + protected $driver = null; + + /** + * @var ContainerInterface + */ + protected $container; + + /** + * Constructor. + * + * @param ContainerInterface $container A ContainerInterface instance + */ + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + /** + * Return the current driver (and retrieved it from the container if necessary) + * + * @return driver_interface + */ + protected function get_driver() + { + if ($this->driver === null) + { + $this->driver = $this->container->get('dbal.conn.driver'); + } + + return $this->driver; + } + + /** + * Set the current driver + * + * @param driver_interface $driver + */ + public function set_driver(driver_interface $driver) + { + $this->driver = $driver; + } + + /** + * {@inheritdoc} + */ + public function get_sql_layer() + { + return $this->get_driver()->get_sql_layer(); + } + + /** + * {@inheritdoc} + */ + public function get_db_name() + { + return $this->get_driver()->get_db_name(); + } + + /** + * {@inheritdoc} + */ + public function get_any_char() + { + return $this->get_driver()->get_any_char(); + } + + /** + * {@inheritdoc} + */ + public function get_one_char() + { + return $this->get_driver()->get_one_char(); + } + + /** + * {@inheritdoc} + */ + public function get_db_connect_id() + { + return $this->get_driver()->get_db_connect_id(); + } + + /** + * {@inheritdoc} + */ + public function get_sql_error_triggered() + { + return $this->get_driver()->get_sql_error_triggered(); + } + + /** + * {@inheritdoc} + */ + public function get_sql_error_sql() + { + return $this->get_driver()->get_sql_error_sql(); + } + + /** + * {@inheritdoc} + */ + public function get_transaction() + { + return $this->get_driver()->get_transaction(); + } + + /** + * {@inheritdoc} + */ + public function get_sql_time() + { + return $this->get_driver()->get_sql_time(); + } + + /** + * {@inheritdoc} + */ + public function get_sql_error_returned() + { + return $this->get_driver()->get_sql_error_returned(); + } + + /** + * {@inheritdoc} + */ + public function get_multi_insert() + { + return $this->get_driver()->get_multi_insert(); + } + + /** + * {@inheritdoc} + */ + public function set_multi_insert($multi_insert) + { + $this->get_driver()->set_multi_insert($multi_insert); + } + + /** + * {@inheritdoc} + */ + public function get_row_count($table_name) + { + return $this->get_driver()->get_row_count($table_name); + } + + /** + * {@inheritdoc} + */ + public function get_estimated_row_count($table_name) + { + return $this->get_driver()->get_estimated_row_count($table_name); + } + + /** + * {@inheritdoc} + */ + public function sql_lower_text($column_name) + { + return $this->get_driver()->sql_lower_text($column_name); + } + + /** + * {@inheritdoc} + */ + public function sql_error($sql = '') + { + return $this->get_driver()->sql_error($sql); + } + + /** + * {@inheritdoc} + */ + public function sql_buffer_nested_transactions() + { + return $this->get_driver()->sql_buffer_nested_transactions(); + } + + /** + * {@inheritdoc} + */ + public function sql_bit_or($column_name, $bit, $compare = '') + { + return $this->get_driver()->sql_bit_or($column_name, $bit, $compare); + } + + /** + * {@inheritdoc} + */ + public function sql_server_info($raw = false, $use_cache = true) + { + return $this->get_driver()->sql_server_info($raw, $use_cache); + } + + /** + * {@inheritdoc} + */ + public function sql_return_on_error($fail = false) + { + return $this->get_driver()->sql_return_on_error($fail); + } + + /** + * {@inheritdoc} + */ + public function sql_build_array($query, $assoc_ary = array()) + { + return $this->get_driver()->sql_build_array($query, $assoc_ary); + } + + /** + * {@inheritdoc} + */ + public function sql_fetchrowset($query_id = false) + { + return $this->get_driver()->sql_fetchrowset($query_id); + } + + /** + * {@inheritdoc} + */ + public function sql_transaction($status = 'begin') + { + return $this->get_driver()->sql_transaction($status); + } + + /** + * {@inheritdoc} + */ + public function sql_concatenate($expr1, $expr2) + { + return $this->get_driver()->sql_concatenate($expr1, $expr2); + } + + /** + * {@inheritdoc} + */ + public function sql_case($condition, $action_true, $action_false = false) + { + return $this->get_driver()->sql_case($condition, $action_true, $action_false); + } + + /** + * {@inheritdoc} + */ + public function sql_build_query($query, $array) + { + return $this->get_driver()->sql_build_query($query, $array); + } + + /** + * {@inheritdoc} + */ + public function sql_fetchfield($field, $rownum = false, $query_id = false) + { + return $this->get_driver()->sql_fetchfield($field, $rownum, $query_id); + } + + /** + * {@inheritdoc} + */ + public function sql_fetchrow($query_id = false) + { + return $this->get_driver()->sql_fetchrow($query_id); + } + + /** + * {@inheritdoc} + */ + public function cast_expr_to_bigint($expression) + { + return $this->get_driver()->cast_expr_to_bigint($expression); + } + + /** + * {@inheritdoc} + */ + public function sql_nextid() + { + return $this->get_driver()->sql_nextid(); + } + + /** + * {@inheritdoc} + */ + public function sql_add_num_queries($cached = false) + { + return $this->get_driver()->sql_add_num_queries($cached); + } + + /** + * {@inheritdoc} + */ + public function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + return $this->get_driver()->sql_query_limit($query, $total, $offset, $cache_ttl); + } + + /** + * {@inheritdoc} + */ + public function sql_query($query = '', $cache_ttl = 0) + { + return $this->get_driver()->sql_query($query, $cache_ttl); + } + + /** + * {@inheritdoc} + */ + public function cast_expr_to_string($expression) + { + return $this->get_driver()->cast_expr_to_string($expression); + } + + /** + * {@inheritdoc} + */ + public function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + throw new \Exception('Disabled method.'); + } + + /** + * {@inheritdoc} + */ + public function sql_bit_and($column_name, $bit, $compare = '') + { + return $this->get_driver()->sql_bit_and($column_name, $bit, $compare); + } + + /** + * {@inheritdoc} + */ + public function sql_freeresult($query_id = false) + { + return $this->get_driver()->sql_freeresult($query_id); + } + + /** + * {@inheritdoc} + */ + public function sql_num_queries($cached = false) + { + return $this->get_driver()->sql_num_queries($cached); + } + + /** + * {@inheritdoc} + */ + public function sql_multi_insert($table, $sql_ary) + { + return $this->get_driver()->sql_multi_insert($table, $sql_ary); + } + + /** + * {@inheritdoc} + */ + public function sql_affectedrows() + { + return $this->get_driver()->sql_affectedrows(); + } + + /** + * {@inheritdoc} + */ + public function sql_close() + { + return $this->get_driver()->sql_close(); + } + + /** + * {@inheritdoc} + */ + public function sql_rowseek($rownum, &$query_id) + { + return $this->get_driver()->sql_rowseek($rownum, $query_id); + } + + /** + * {@inheritdoc} + */ + public function sql_escape($msg) + { + return $this->get_driver()->sql_escape($msg); + } + + /** + * {@inheritdoc} + */ + public function sql_like_expression($expression) + { + return $this->get_driver()->sql_like_expression($expression); + } + + /** + * {@inheritdoc} + */ + public function sql_not_like_expression($expression) + { + return $this->get_driver()->sql_not_like_expression($expression); + } + + /** + * {@inheritdoc} + */ + public function sql_report($mode, $query = '') + { + return $this->get_driver()->sql_report($mode, $query); + } + + /** + * {@inheritdoc} + */ + public function sql_in_set($field, $array, $negate = false, $allow_empty_set = false) + { + return $this->get_driver()->sql_in_set($field, $array, $negate, $allow_empty_set); + } +} diff --git a/phpBB/phpbb/db/driver/mssql.php b/phpBB/phpbb/db/driver/mssql.php new file mode 100644 index 0000000000..f9ea884ce2 --- /dev/null +++ b/phpBB/phpbb/db/driver/mssql.php @@ -0,0 +1,476 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* MSSQL Database Abstraction Layer +* Minimum Requirement is MSSQL 2000+ +*/ +class mssql extends \phpbb\db\driver\driver +{ + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + if (!function_exists('mssql_connect')) + { + $this->connect_error = 'mssql_connect function does not exist, is mssql extension installed?'; + return $this->sql_error(''); + } + + $this->persistency = $persistency; + $this->user = $sqluser; + $this->dbname = $database; + + $port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':'; + $this->server = $sqlserver . (($port) ? $port_delimiter . $port : ''); + + @ini_set('mssql.charset', 'UTF-8'); + @ini_set('mssql.textlimit', 2147483647); + @ini_set('mssql.textsize', 2147483647); + + $this->db_connect_id = ($this->persistency) ? @mssql_pconnect($this->server, $this->user, $sqlpassword, $new_link) : @mssql_connect($this->server, $this->user, $sqlpassword, $new_link); + + if ($this->db_connect_id && $this->dbname != '') + { + if (!@mssql_select_db($this->dbname, $this->db_connect_id)) + { + @mssql_close($this->db_connect_id); + return false; + } + } + + return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mssql_version')) === false) + { + $result_id = @mssql_query("SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition')", $this->db_connect_id); + + $row = false; + if ($result_id) + { + $row = @mssql_fetch_assoc($result_id); + @mssql_free_result($result_id); + } + + $this->sql_server_version = ($row) ? trim(implode(' ', $row)) : 0; + + if (!empty($cache) && $use_cache) + { + $cache->put('mssql_version', $this->sql_server_version); + } + } + + if ($raw) + { + return $this->sql_server_version; + } + + return ($this->sql_server_version) ? 'MSSQL<br />' . $this->sql_server_version : 'MSSQL'; + } + + /** + * {@inheritDoc} + */ + public function sql_concatenate($expr1, $expr2) + { + return $expr1 . ' + ' . $expr2; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return @mssql_query('BEGIN TRANSACTION', $this->db_connect_id); + break; + + case 'commit': + return @mssql_query('COMMIT TRANSACTION', $this->db_connect_id); + break; + + case 'rollback': + return @mssql_query('ROLLBACK TRANSACTION', $this->db_connect_id); + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @mssql_query($query, $this->db_connect_id)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // Since TOP is only returning a set number of rows we won't need it if total is set to 0 (return all rows) + if ($total) + { + // We need to grab the total number of rows + the offset number of rows to get the correct result + if (strpos($query, 'SELECT DISTINCT') === 0) + { + $query = 'SELECT DISTINCT TOP ' . ($total + $offset) . ' ' . substr($query, 15); + } + else + { + $query = 'SELECT TOP ' . ($total + $offset) . ' ' . substr($query, 6); + } + } + + $result = $this->sql_query($query, $cache_ttl); + + // Seek by $offset rows + if ($offset) + { + $this->sql_rowseek($offset, $result); + } + + return $result; + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->db_connect_id) ? @mssql_rows_affected($this->db_connect_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + if ($query_id === false) + { + return false; + } + + $row = @mssql_fetch_assoc($query_id); + + // I hope i am able to remove this later... hopefully only a PHP or MSSQL bug + if ($row) + { + foreach ($row as $key => $value) + { + $row[$key] = ($value === ' ' || $value === null) ? '' : $value; + } + } + + return $row; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + return ($query_id !== false) ? @mssql_data_seek($query_id, $rownum) : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + $result_id = @mssql_query('SELECT SCOPE_IDENTITY()', $this->db_connect_id); + if ($result_id) + { + if ($row = @mssql_fetch_assoc($result_id)) + { + @mssql_free_result($result_id); + return $row['computed']; + } + @mssql_free_result($result_id); + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if (isset($this->open_queries[(int) $query_id])) + { + unset($this->open_queries[(int) $query_id]); + return @mssql_free_result($query_id); + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + return str_replace(array("'", "\0"), array("''", ''), $msg); + } + + /** + * {@inheritDoc} + */ + function sql_lower_text($column_name) + { + return "LOWER(SUBSTRING($column_name, 1, DATALENGTH($column_name)))"; + } + + /** + * Build LIKE expression + * @access private + */ + function _sql_like_expression($expression) + { + return $expression . " ESCAPE '\\'"; + } + + /** + * Build NOT LIKE expression + * @access private + */ + function _sql_not_like_expression($expression) + { + return $expression . " ESCAPE '\\'"; + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if (function_exists('mssql_get_last_message')) + { + $error = array( + 'message' => @mssql_get_last_message(), + 'code' => '', + ); + + // Get error code number + $result_id = @mssql_query('SELECT @@ERROR as code', $this->db_connect_id); + if ($result_id) + { + $row = @mssql_fetch_assoc($result_id); + $error['code'] = $row['code']; + @mssql_free_result($result_id); + } + + // Get full error message if possible + $sql = 'SELECT CAST(description as varchar(255)) as message + FROM master.dbo.sysmessages + WHERE error = ' . $error['code']; + $result_id = @mssql_query($sql); + + if ($result_id) + { + $row = @mssql_fetch_assoc($result_id); + if (!empty($row['message'])) + { + $error['message'] .= '<br />' . $row['message']; + } + @mssql_free_result($result_id); + } + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Build db-specific query data + * @access private + */ + function _sql_custom_build($stage, $data) + { + return $data; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @mssql_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + $html_table = false; + @mssql_query('SET SHOWPLAN_TEXT ON;', $this->db_connect_id); + if ($result = @mssql_query($query, $this->db_connect_id)) + { + @mssql_next_result($result); + while ($row = @mssql_fetch_row($result)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @mssql_query('SET SHOWPLAN_TEXT OFF;', $this->db_connect_id); + @mssql_free_result($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @mssql_query($query, $this->db_connect_id); + while ($void = @mssql_fetch_assoc($result)) + { + // Take the time spent on parsing rows into account + } + @mssql_free_result($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/mssql_base.php b/phpBB/phpbb/db/driver/mssql_base.php new file mode 100644 index 0000000000..514df9eaca --- /dev/null +++ b/phpBB/phpbb/db/driver/mssql_base.php @@ -0,0 +1,71 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* MSSQL Database Base Abstraction Layer + */ +abstract class mssql_base extends \phpbb\db\driver\driver +{ + /** + * {@inheritDoc} + */ + public function sql_concatenate($expr1, $expr2) + { + return $expr1 . ' + ' . $expr2; + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + return str_replace(array("'", "\0"), array("''", ''), $msg); + } + + /** + * {@inheritDoc} + */ + function sql_lower_text($column_name) + { + return "LOWER(SUBSTRING($column_name, 1, DATALENGTH($column_name)))"; + } + + /** + * Build LIKE expression + * @access private + */ + function _sql_like_expression($expression) + { + return $expression . " ESCAPE '\\'"; + } + + /** + * Build NOT LIKE expression + * @access private + */ + function _sql_not_like_expression($expression) + { + return $expression . " ESCAPE '\\'"; + } + + /** + * Build db-specific query data + * @access private + */ + function _sql_custom_build($stage, $data) + { + return $data; + } +} diff --git a/phpBB/phpbb/db/driver/mssql_odbc.php b/phpBB/phpbb/db/driver/mssql_odbc.php new file mode 100644 index 0000000000..8e5d4c7a4c --- /dev/null +++ b/phpBB/phpbb/db/driver/mssql_odbc.php @@ -0,0 +1,377 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* Unified ODBC functions +* Unified ODBC functions support any database having ODBC driver, for example Adabas D, IBM DB2, iODBC, Solid, Sybase SQL Anywhere... +* Here we only support MSSQL Server 2000+ because of the provided schema +* +* @note number of bytes returned for returning data depends on odbc.defaultlrl php.ini setting. +* If it is limited to 4K for example only 4K of data is returned max, resulting in incomplete theme data for example. +* @note odbc.defaultbinmode may affect UTF8 characters +*/ +class mssql_odbc extends \phpbb\db\driver\mssql_base +{ + var $last_query_text = ''; + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + $this->persistency = $persistency; + $this->user = $sqluser; + $this->dbname = $database; + + $port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':'; + $this->server = $sqlserver . (($port) ? $port_delimiter . $port : ''); + + $max_size = @ini_get('odbc.defaultlrl'); + if (!empty($max_size)) + { + $unit = strtolower(substr($max_size, -1, 1)); + $max_size = (int) $max_size; + + if ($unit == 'k') + { + $max_size = floor($max_size / 1024); + } + else if ($unit == 'g') + { + $max_size *= 1024; + } + else if (is_numeric($unit)) + { + $max_size = floor((int) ($max_size . $unit) / 1048576); + } + $max_size = max(8, $max_size) . 'M'; + + @ini_set('odbc.defaultlrl', $max_size); + } + + if ($this->persistency) + { + if (!function_exists('odbc_pconnect')) + { + $this->connect_error = 'odbc_pconnect function does not exist, is odbc extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @odbc_pconnect($this->server, $this->user, $sqlpassword); + } + else + { + if (!function_exists('odbc_connect')) + { + $this->connect_error = 'odbc_connect function does not exist, is odbc extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @odbc_connect($this->server, $this->user, $sqlpassword); + } + + return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mssqlodbc_version')) === false) + { + $result_id = @odbc_exec($this->db_connect_id, "SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition')"); + + $row = false; + if ($result_id) + { + $row = @odbc_fetch_array($result_id); + @odbc_free_result($result_id); + } + + $this->sql_server_version = ($row) ? trim(implode(' ', $row)) : 0; + + if (!empty($cache) && $use_cache) + { + $cache->put('mssqlodbc_version', $this->sql_server_version); + } + } + + if ($raw) + { + return $this->sql_server_version; + } + + return ($this->sql_server_version) ? 'MSSQL (ODBC)<br />' . $this->sql_server_version : 'MSSQL (ODBC)'; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return @odbc_exec($this->db_connect_id, 'BEGIN TRANSACTION'); + break; + + case 'commit': + return @odbc_exec($this->db_connect_id, 'COMMIT TRANSACTION'); + break; + + case 'rollback': + return @odbc_exec($this->db_connect_id, 'ROLLBACK TRANSACTION'); + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->last_query_text = $query; + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @odbc_exec($this->db_connect_id, $query)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // Since TOP is only returning a set number of rows we won't need it if total is set to 0 (return all rows) + if ($total) + { + // We need to grab the total number of rows + the offset number of rows to get the correct result + if (strpos($query, 'SELECT DISTINCT') === 0) + { + $query = 'SELECT DISTINCT TOP ' . ($total + $offset) . ' ' . substr($query, 15); + } + else + { + $query = 'SELECT TOP ' . ($total + $offset) . ' ' . substr($query, 6); + } + } + + $result = $this->sql_query($query, $cache_ttl); + + // Seek by $offset rows + if ($offset) + { + $this->sql_rowseek($offset, $result); + } + + return $result; + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->db_connect_id) ? @odbc_num_rows($this->query_result) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + return ($query_id !== false) ? @odbc_fetch_array($query_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + $result_id = @odbc_exec($this->db_connect_id, 'SELECT @@IDENTITY'); + + if ($result_id) + { + if (@odbc_fetch_array($result_id)) + { + $id = @odbc_result($result_id, 1); + @odbc_free_result($result_id); + return $id; + } + @odbc_free_result($result_id); + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if (isset($this->open_queries[(int) $query_id])) + { + unset($this->open_queries[(int) $query_id]); + return @odbc_free_result($query_id); + } + + return false; + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if (function_exists('odbc_errormsg')) + { + $error = array( + 'message' => @odbc_errormsg(), + 'code' => @odbc_error(), + ); + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @odbc_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @odbc_exec($this->db_connect_id, $query); + while ($void = @odbc_fetch_array($result)) + { + // Take the time spent on parsing rows into account + } + @odbc_free_result($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/mssqlnative.php b/phpBB/phpbb/db/driver/mssqlnative.php new file mode 100644 index 0000000000..46a9b3a477 --- /dev/null +++ b/phpBB/phpbb/db/driver/mssqlnative.php @@ -0,0 +1,442 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +/** +* This is the MS SQL Server Native database abstraction layer. +* PHP mssql native driver required. +* @author Chris Pucci +* +*/ + +namespace phpbb\db\driver; + +class mssqlnative extends \phpbb\db\driver\mssql_base +{ + var $m_insert_id = null; + var $last_query_text = ''; + var $query_options = array(); + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + // Test for driver support, to avoid suppressed fatal error + if (!function_exists('sqlsrv_connect')) + { + $this->connect_error = 'Native MS SQL Server driver for PHP is missing or needs to be updated. Version 1.1 or later is required to install phpBB3. You can download the driver from: http://www.microsoft.com/sqlserver/2005/en/us/PHP-Driver.aspx'; + return $this->sql_error(''); + } + + //set up connection variables + $this->persistency = $persistency; + $this->user = $sqluser; + $this->dbname = $database; + $port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':'; + $this->server = $sqlserver . (($port) ? $port_delimiter . $port : ''); + + //connect to database + $this->db_connect_id = sqlsrv_connect($this->server, array( + 'Database' => $this->dbname, + 'UID' => $this->user, + 'PWD' => $sqlpassword + )); + + return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mssql_version')) === false) + { + $arr_server_info = sqlsrv_server_info($this->db_connect_id); + $this->sql_server_version = $arr_server_info['SQLServerVersion']; + + if (!empty($cache) && $use_cache) + { + $cache->put('mssql_version', $this->sql_server_version); + } + } + + if ($raw) + { + return $this->sql_server_version; + } + + return ($this->sql_server_version) ? 'MSSQL<br />' . $this->sql_server_version : 'MSSQL'; + } + + /** + * {@inheritDoc} + */ + function sql_buffer_nested_transactions() + { + return true; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return sqlsrv_begin_transaction($this->db_connect_id); + break; + + case 'commit': + return sqlsrv_commit($this->db_connect_id); + break; + + case 'rollback': + return sqlsrv_rollback($this->db_connect_id); + break; + } + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->last_query_text = $query; + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @sqlsrv_query($this->db_connect_id, $query, array(), $this->query_options)) === false) + { + $this->sql_error($query); + } + // reset options for next query + $this->query_options = array(); + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + return $this->query_result; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // total == 0 means all results - not zero results + if ($offset == 0 && $total !== 0) + { + if (strpos($query, "SELECT") === false) + { + $query = "TOP {$total} " . $query; + } + else + { + $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP '.$total, $query); + } + } + else if ($offset > 0) + { + $query = preg_replace('/SELECT(\s*DISTINCT)?/Dsi', 'SELECT$1 TOP(10000000) ', $query); + $query = 'SELECT * + FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3 + FROM (SELECT 1 AS line2, sub1.* FROM (' . $query . ') AS sub1) as sub2) AS sub3'; + + if ($total > 0) + { + $query .= ' WHERE line3 BETWEEN ' . ($offset+1) . ' AND ' . ($offset + $total); + } + else + { + $query .= ' WHERE line3 > ' . $offset; + } + } + + $result = $this->sql_query($query, $cache_ttl); + + return $result; + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->db_connect_id) ? @sqlsrv_rows_affected($this->query_result) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + if ($query_id === false) + { + return false; + } + + $row = @sqlsrv_fetch_array($query_id, SQLSRV_FETCH_ASSOC); + + if ($row) + { + foreach ($row as $key => $value) + { + $row[$key] = ($value === ' ' || $value === null) ? '' : $value; + } + + // remove helper values from LIMIT queries + if (isset($row['line2'])) + { + unset($row['line2'], $row['line3']); + } + } + return (sizeof($row)) ? $row : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + $result_id = @sqlsrv_query($this->db_connect_id, 'SELECT @@IDENTITY'); + + if ($result_id !== false) + { + $row = @sqlsrv_fetch_array($result_id); + $id = $row[0]; + @sqlsrv_free_stmt($result_id); + return $id; + } + else + { + return false; + } + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if (isset($this->open_queries[(int) $query_id])) + { + unset($this->open_queries[(int) $query_id]); + return @sqlsrv_free_stmt($query_id); + } + + return false; + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if (function_exists('sqlsrv_errors')) + { + $errors = @sqlsrv_errors(SQLSRV_ERR_ERRORS); + $error_message = ''; + $code = 0; + + if ($errors != null) + { + foreach ($errors as $error) + { + $error_message .= "SQLSTATE: " . $error['SQLSTATE'] . "\n"; + $error_message .= "code: " . $error['code'] . "\n"; + $code = $error['code']; + $error_message .= "message: " . $error['message'] . "\n"; + } + $this->last_error_result = $error_message; + $error = $this->last_error_result; + } + else + { + $error = (isset($this->last_error_result) && $this->last_error_result) ? $this->last_error_result : array(); + } + + $error = array( + 'message' => $error, + 'code' => $code, + ); + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @sqlsrv_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + $html_table = false; + @sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT ON;'); + if ($result = @sqlsrv_query($this->db_connect_id, $query)) + { + @sqlsrv_next_result($result); + while ($row = @sqlsrv_fetch_array($result)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @sqlsrv_query($this->db_connect_id, 'SET SHOWPLAN_TEXT OFF;'); + @sqlsrv_free_stmt($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @sqlsrv_query($this->db_connect_id, $query); + while ($void = @sqlsrv_fetch_array($result)) + { + // Take the time spent on parsing rows into account + } + @sqlsrv_free_stmt($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } + + /** + * Utility method used to retrieve number of rows + * Emulates mysql_num_rows + * Used in acp_database.php -> write_data_mssqlnative() + * Requires a static or keyset cursor to be definde via + * mssqlnative_set_query_options() + */ + function mssqlnative_num_rows($res) + { + if ($res !== false) + { + return sqlsrv_num_rows($res); + } + else + { + return false; + } + } + + /** + * Allows setting mssqlnative specific query options passed to sqlsrv_query as 4th parameter. + */ + function mssqlnative_set_query_options($options) + { + $this->query_options = $options; + } +} diff --git a/phpBB/phpbb/db/driver/mysql.php b/phpBB/phpbb/db/driver/mysql.php new file mode 100644 index 0000000000..e93c7239e8 --- /dev/null +++ b/phpBB/phpbb/db/driver/mysql.php @@ -0,0 +1,485 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* MySQL4 Database Abstraction Layer +* Compatible with: +* MySQL 3.23+ +* MySQL 4.0+ +* MySQL 4.1+ +* MySQL 5.0+ +*/ +class mysql extends \phpbb\db\driver\mysql_base +{ + var $multi_insert = true; + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + $this->persistency = $persistency; + $this->user = $sqluser; + $this->server = $sqlserver . (($port) ? ':' . $port : ''); + $this->dbname = $database; + + $this->sql_layer = 'mysql4'; + + if ($this->persistency) + { + if (!function_exists('mysql_pconnect')) + { + $this->connect_error = 'mysql_pconnect function does not exist, is mysql extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @mysql_pconnect($this->server, $this->user, $sqlpassword); + } + else + { + if (!function_exists('mysql_connect')) + { + $this->connect_error = 'mysql_connect function does not exist, is mysql extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @mysql_connect($this->server, $this->user, $sqlpassword, $new_link); + } + + if ($this->db_connect_id && $this->dbname != '') + { + if (@mysql_select_db($this->dbname, $this->db_connect_id)) + { + // Determine what version we are using and if it natively supports UNICODE + if (version_compare($this->sql_server_info(true), '4.1.0', '>=')) + { + @mysql_query("SET NAMES 'utf8'", $this->db_connect_id); + + // enforce strict mode on databases that support it + if (version_compare($this->sql_server_info(true), '5.0.2', '>=')) + { + $result = @mysql_query('SELECT @@session.sql_mode AS sql_mode', $this->db_connect_id); + $row = @mysql_fetch_assoc($result); + @mysql_free_result($result); + $modes = array_map('trim', explode(',', $row['sql_mode'])); + + // TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES + if (!in_array('TRADITIONAL', $modes)) + { + if (!in_array('STRICT_ALL_TABLES', $modes)) + { + $modes[] = 'STRICT_ALL_TABLES'; + } + + if (!in_array('STRICT_TRANS_TABLES', $modes)) + { + $modes[] = 'STRICT_TRANS_TABLES'; + } + } + + $mode = implode(',', $modes); + @mysql_query("SET SESSION sql_mode='{$mode}'", $this->db_connect_id); + } + } + else if (version_compare($this->sql_server_info(true), '4.0.0', '<')) + { + $this->sql_layer = 'mysql'; + } + + return $this->db_connect_id; + } + } + + return $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mysql_version')) === false) + { + $result = @mysql_query('SELECT VERSION() AS version', $this->db_connect_id); + $row = @mysql_fetch_assoc($result); + @mysql_free_result($result); + + $this->sql_server_version = $row['version']; + + if (!empty($cache) && $use_cache) + { + $cache->put('mysql_version', $this->sql_server_version); + } + } + + return ($raw) ? $this->sql_server_version : 'MySQL ' . $this->sql_server_version; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return @mysql_query('BEGIN', $this->db_connect_id); + break; + + case 'commit': + return @mysql_query('COMMIT', $this->db_connect_id); + break; + + case 'rollback': + return @mysql_query('ROLLBACK', $this->db_connect_id); + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @mysql_query($query, $this->db_connect_id)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + if ($this->db_connect_id) + { + // We always want the number of matched rows + // instead of changed rows, when running an update. + // So when mysql_info() returns the number of matched rows + // we return that one instead of mysql_affected_rows() + $mysql_info = @mysql_info($this->db_connect_id); + if ($mysql_info !== false) + { + $match = array(); + preg_match('#^Rows matched: (\d)+ Changed: (\d)+ Warnings: (\d)+$#', $mysql_info, $match); + if (isset($match[1])) + { + return $match[1]; + } + } + + return @mysql_affected_rows($this->db_connect_id); + } + return false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + return ($query_id !== false) ? @mysql_fetch_assoc($query_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + return ($query_id !== false) ? @mysql_data_seek($query_id, $rownum) : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + return ($this->db_connect_id) ? @mysql_insert_id($this->db_connect_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if (isset($this->open_queries[(int) $query_id])) + { + unset($this->open_queries[(int) $query_id]); + return @mysql_free_result($query_id); + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + if (!$this->db_connect_id) + { + return @mysql_real_escape_string($msg); + } + + return @mysql_real_escape_string($msg, $this->db_connect_id); + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if ($this->db_connect_id) + { + $error = array( + 'message' => @mysql_error($this->db_connect_id), + 'code' => @mysql_errno($this->db_connect_id), + ); + } + else if (function_exists('mysql_error')) + { + $error = array( + 'message' => @mysql_error(), + 'code' => @mysql_errno(), + ); + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @mysql_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + static $test_prof; + + // current detection method, might just switch to see the existance of INFORMATION_SCHEMA.PROFILING + if ($test_prof === null) + { + $test_prof = false; + if (version_compare($this->sql_server_info(true), '5.0.37', '>=') && version_compare($this->sql_server_info(true), '5.1', '<')) + { + $test_prof = true; + } + } + + switch ($mode) + { + case 'start': + + $explain_query = $query; + if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + + if (preg_match('/^SELECT/', $explain_query)) + { + $html_table = false; + + // begin profiling + if ($test_prof) + { + @mysql_query('SET profiling = 1;', $this->db_connect_id); + } + + if ($result = @mysql_query("EXPLAIN $explain_query", $this->db_connect_id)) + { + while ($row = @mysql_fetch_assoc($result)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @mysql_free_result($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + + if ($test_prof) + { + $html_table = false; + + // get the last profile + if ($result = @mysql_query('SHOW PROFILE ALL;', $this->db_connect_id)) + { + $this->html_hold .= '<br />'; + while ($row = @mysql_fetch_assoc($result)) + { + // make <unknown> HTML safe + if (!empty($row['Source_function'])) + { + $row['Source_function'] = str_replace(array('<', '>'), array('<', '>'), $row['Source_function']); + } + + // remove unsupported features + foreach ($row as $key => $val) + { + if ($val === null) + { + unset($row[$key]); + } + } + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @mysql_free_result($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + + @mysql_query('SET profiling = 0;', $this->db_connect_id); + } + } + + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @mysql_query($query, $this->db_connect_id); + while ($void = @mysql_fetch_assoc($result)) + { + // Take the time spent on parsing rows into account + } + @mysql_free_result($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/mysql_base.php b/phpBB/phpbb/db/driver/mysql_base.php new file mode 100644 index 0000000000..5e0b359134 --- /dev/null +++ b/phpBB/phpbb/db/driver/mysql_base.php @@ -0,0 +1,138 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* Abstract MySQL Database Base Abstraction Layer +*/ +abstract class mysql_base extends \phpbb\db\driver\driver +{ + /** + * {@inheritDoc} + */ + public function sql_concatenate($expr1, $expr2) + { + return 'CONCAT(' . $expr1 . ', ' . $expr2 . ')'; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // if $total is set to 0 we do not want to limit the number of rows + if ($total == 0) + { + // MySQL 4.1+ no longer supports -1 in limit queries + $total = '18446744073709551615'; + } + + $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total); + + return $this->sql_query($query, $cache_ttl); + } + + /** + * {@inheritDoc} + */ + function get_estimated_row_count($table_name) + { + $table_status = $this->get_table_status($table_name); + + if (isset($table_status['Engine'])) + { + if ($table_status['Engine'] === 'MyISAM') + { + return $table_status['Rows']; + } + else if ($table_status['Engine'] === 'InnoDB' && $table_status['Rows'] > 100000) + { + return '~' . $table_status['Rows']; + } + } + + return parent::get_row_count($table_name); + } + + /** + * {@inheritDoc} + */ + function get_row_count($table_name) + { + $table_status = $this->get_table_status($table_name); + + if (isset($table_status['Engine']) && $table_status['Engine'] === 'MyISAM') + { + return $table_status['Rows']; + } + + return parent::get_row_count($table_name); + } + + /** + * Gets some information about the specified table. + * + * @param string $table_name Table name + * + * @return array + * + * @access protected + */ + function get_table_status($table_name) + { + $sql = "SHOW TABLE STATUS + LIKE '" . $this->sql_escape($table_name) . "'"; + $result = $this->sql_query($sql); + $table_status = $this->sql_fetchrow($result); + $this->sql_freeresult($result); + + return $table_status; + } + + /** + * Build LIKE expression + * @access private + */ + function _sql_like_expression($expression) + { + return $expression; + } + + /** + * Build NOT LIKE expression + * @access private + */ + function _sql_not_like_expression($expression) + { + return $expression; + } + + /** + * Build db-specific query data + * @access private + */ + function _sql_custom_build($stage, $data) + { + switch ($stage) + { + case 'FROM': + $data = '(' . $data . ')'; + break; + } + + return $data; + } +} diff --git a/phpBB/phpbb/db/driver/mysqli.php b/phpBB/phpbb/db/driver/mysqli.php new file mode 100644 index 0000000000..c0ddfbf76c --- /dev/null +++ b/phpBB/phpbb/db/driver/mysqli.php @@ -0,0 +1,475 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* MySQLi Database Abstraction Layer +* mysqli-extension has to be compiled with: +* MySQL 4.1+ or MySQL 5.0+ +*/ +class mysqli extends \phpbb\db\driver\mysql_base +{ + var $multi_insert = true; + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + if (!function_exists('mysqli_connect')) + { + $this->connect_error = 'mysqli_connect function does not exist, is mysqli extension installed?'; + return $this->sql_error(''); + } + + $this->persistency = $persistency; + $this->user = $sqluser; + + // If persistent connection, set dbhost to localhost when empty and prepend it with 'p:' prefix + $this->server = ($this->persistency) ? 'p:' . (($sqlserver) ? $sqlserver : 'localhost') : $sqlserver; + + $this->dbname = $database; + $port = (!$port) ? null : $port; + + // If port is set and it is not numeric, most likely mysqli socket is set. + // Try to map it to the $socket parameter. + $socket = null; + if ($port) + { + if (is_numeric($port)) + { + $port = (int) $port; + } + else + { + $socket = $port; + $port = null; + } + } + + $this->db_connect_id = mysqli_init(); + + if (!@mysqli_real_connect($this->db_connect_id, $this->server, $this->user, $sqlpassword, $this->dbname, $port, $socket, MYSQLI_CLIENT_FOUND_ROWS)) + { + $this->db_connect_id = ''; + } + + if ($this->db_connect_id && $this->dbname != '') + { + @mysqli_query($this->db_connect_id, "SET NAMES 'utf8'"); + + // enforce strict mode on databases that support it + if (version_compare($this->sql_server_info(true), '5.0.2', '>=')) + { + $result = @mysqli_query($this->db_connect_id, 'SELECT @@session.sql_mode AS sql_mode'); + if ($result !== null) + { + $row = @mysqli_fetch_assoc($result); + + $modes = array_map('trim', explode(',', $row['sql_mode'])); + } + else + { + $modes = array(); + } + @mysqli_free_result($result); + + // TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES + if (!in_array('TRADITIONAL', $modes)) + { + if (!in_array('STRICT_ALL_TABLES', $modes)) + { + $modes[] = 'STRICT_ALL_TABLES'; + } + + if (!in_array('STRICT_TRANS_TABLES', $modes)) + { + $modes[] = 'STRICT_TRANS_TABLES'; + } + } + + $mode = implode(',', $modes); + @mysqli_query($this->db_connect_id, "SET SESSION sql_mode='{$mode}'"); + } + return $this->db_connect_id; + } + + return $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mysqli_version')) === false) + { + $result = @mysqli_query($this->db_connect_id, 'SELECT VERSION() AS version'); + if ($result !== null) + { + $row = @mysqli_fetch_assoc($result); + + $this->sql_server_version = $row['version']; + + if (!empty($cache) && $use_cache) + { + $cache->put('mysqli_version', $this->sql_server_version); + } + } + @mysqli_free_result($result); + } + + return ($raw) ? $this->sql_server_version : 'MySQL(i) ' . $this->sql_server_version; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return @mysqli_autocommit($this->db_connect_id, false); + break; + + case 'commit': + $result = @mysqli_commit($this->db_connect_id); + @mysqli_autocommit($this->db_connect_id, true); + return $result; + break; + + case 'rollback': + $result = @mysqli_rollback($this->db_connect_id); + @mysqli_autocommit($this->db_connect_id, true); + return $result; + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @mysqli_query($this->db_connect_id, $query)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->db_connect_id) ? @mysqli_affected_rows($this->db_connect_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + if ($query_id !== false && $query_id !== null) + { + $result = @mysqli_fetch_assoc($query_id); + return $result !== null ? $result : false; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + return ($query_id !== false) ? @mysqli_data_seek($query_id, $rownum) : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + return ($this->db_connect_id) ? @mysqli_insert_id($this->db_connect_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + return @mysqli_free_result($query_id); + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + return @mysqli_real_escape_string($this->db_connect_id, $msg); + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if ($this->db_connect_id) + { + $error = array( + 'message' => @mysqli_error($this->db_connect_id), + 'code' => @mysqli_errno($this->db_connect_id) + ); + } + else if (function_exists('mysqli_connect_error')) + { + $error = array( + 'message' => @mysqli_connect_error(), + 'code' => @mysqli_connect_errno(), + ); + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @mysqli_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + static $test_prof; + + // current detection method, might just switch to see the existance of INFORMATION_SCHEMA.PROFILING + if ($test_prof === null) + { + $test_prof = false; + if (strpos(mysqli_get_server_info($this->db_connect_id), 'community') !== false) + { + $ver = mysqli_get_server_version($this->db_connect_id); + if ($ver >= 50037 && $ver < 50100) + { + $test_prof = true; + } + } + } + + switch ($mode) + { + case 'start': + + $explain_query = $query; + if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + + if (preg_match('/^SELECT/', $explain_query)) + { + $html_table = false; + + // begin profiling + if ($test_prof) + { + @mysqli_query($this->db_connect_id, 'SET profiling = 1;'); + } + + if ($result = @mysqli_query($this->db_connect_id, "EXPLAIN $explain_query")) + { + while ($row = @mysqli_fetch_assoc($result)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @mysqli_free_result($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + + if ($test_prof) + { + $html_table = false; + + // get the last profile + if ($result = @mysqli_query($this->db_connect_id, 'SHOW PROFILE ALL;')) + { + $this->html_hold .= '<br />'; + while ($row = @mysqli_fetch_assoc($result)) + { + // make <unknown> HTML safe + if (!empty($row['Source_function'])) + { + $row['Source_function'] = str_replace(array('<', '>'), array('<', '>'), $row['Source_function']); + } + + // remove unsupported features + foreach ($row as $key => $val) + { + if ($val === null) + { + unset($row[$key]); + } + } + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @mysqli_free_result($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + + @mysqli_query($this->db_connect_id, 'SET profiling = 0;'); + } + } + + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @mysqli_query($this->db_connect_id, $query); + if ($result !== null) + { + while ($void = @mysqli_fetch_assoc($result)) + { + // Take the time spent on parsing rows into account + } + } + @mysqli_free_result($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/oracle.php b/phpBB/phpbb/db/driver/oracle.php new file mode 100644 index 0000000000..6dcab5dd7d --- /dev/null +++ b/phpBB/phpbb/db/driver/oracle.php @@ -0,0 +1,807 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* Oracle Database Abstraction Layer +*/ +class oracle extends \phpbb\db\driver\driver +{ + var $last_query_text = ''; + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + $this->persistency = $persistency; + $this->user = $sqluser; + $this->server = $sqlserver . (($port) ? ':' . $port : ''); + $this->dbname = $database; + + $connect = $database; + + // support for "easy connect naming" + if ($sqlserver !== '' && $sqlserver !== '/') + { + if (substr($sqlserver, -1, 1) == '/') + { + $sqlserver == substr($sqlserver, 0, -1); + } + $connect = $sqlserver . (($port) ? ':' . $port : '') . '/' . $database; + } + + if ($new_link) + { + if (!function_exists('ocinlogon')) + { + $this->connect_error = 'ocinlogon function does not exist, is oci extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @ocinlogon($this->user, $sqlpassword, $connect, 'UTF8'); + } + else if ($this->persistency) + { + if (!function_exists('ociplogon')) + { + $this->connect_error = 'ociplogon function does not exist, is oci extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @ociplogon($this->user, $sqlpassword, $connect, 'UTF8'); + } + else + { + if (!function_exists('ocilogon')) + { + $this->connect_error = 'ocilogon function does not exist, is oci extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @ocilogon($this->user, $sqlpassword, $connect, 'UTF8'); + } + + return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + /** + * force $use_cache false. I didn't research why the caching code below is commented out + * but I assume its because the Oracle extension provides a direct method to access it + * without a query. + */ + + $use_cache = false; +/* + global $cache; + + if (empty($cache) || ($this->sql_server_version = $cache->get('oracle_version')) === false) + { + $result = @ociparse($this->db_connect_id, 'SELECT * FROM v$version WHERE banner LIKE \'Oracle%\''); + @ociexecute($result, OCI_DEFAULT); + @ocicommit($this->db_connect_id); + + $row = array(); + @ocifetchinto($result, $row, OCI_ASSOC + OCI_RETURN_NULLS); + @ocifreestatement($result); + $this->sql_server_version = trim($row['BANNER']); + + $cache->put('oracle_version', $this->sql_server_version); + } +*/ + $this->sql_server_version = @ociserverversion($this->db_connect_id); + + return $this->sql_server_version; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return true; + break; + + case 'commit': + return @ocicommit($this->db_connect_id); + break; + + case 'rollback': + return @ocirollback($this->db_connect_id); + break; + } + + return true; + } + + /** + * Oracle specific code to handle the fact that it does not compare columns properly + * @access private + */ + function _rewrite_col_compare($args) + { + if (sizeof($args) == 4) + { + if ($args[2] == '=') + { + return '(' . $args[0] . ' OR (' . $args[1] . ' is NULL AND ' . $args[3] . ' is NULL))'; + } + else if ($args[2] == '<>') + { + // really just a fancy way of saying foo <> bar or (foo is NULL XOR bar is NULL) but SQL has no XOR :P + return '(' . $args[0] . ' OR ((' . $args[1] . ' is NULL AND ' . $args[3] . ' is NOT NULL) OR (' . $args[1] . ' is NOT NULL AND ' . $args[3] . ' is NULL)))'; + } + } + else + { + return $this->_rewrite_where($args[0]); + } + } + + /** + * Oracle specific code to handle it's lack of sanity + * @access private + */ + function _rewrite_where($where_clause) + { + preg_match_all('/\s*(AND|OR)?\s*([\w_.()]++)\s*(?:(=|<[=>]?|>=?|LIKE)\s*((?>\'(?>[^\']++|\'\')*+\'|[\d-.()]+))|((NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]+,? ?)*+\)))/', $where_clause, $result, PREG_SET_ORDER); + $out = ''; + foreach ($result as $val) + { + if (!isset($val[5])) + { + if ($val[4] !== "''") + { + $out .= $val[0]; + } + else + { + $out .= ' ' . $val[1] . ' ' . $val[2]; + if ($val[3] == '=') + { + $out .= ' is NULL'; + } + else if ($val[3] == '<>') + { + $out .= ' is NOT NULL'; + } + } + } + else + { + $in_clause = array(); + $sub_exp = substr($val[5], strpos($val[5], '(') + 1, -1); + $extra = false; + preg_match_all('/\'(?>[^\']++|\'\')*+\'|[\d-.]++/', $sub_exp, $sub_vals, PREG_PATTERN_ORDER); + $i = 0; + foreach ($sub_vals[0] as $sub_val) + { + // two things: + // 1) This determines if an empty string was in the IN clausing, making us turn it into a NULL comparison + // 2) This fixes the 1000 list limit that Oracle has (ORA-01795) + if ($sub_val !== "''") + { + $in_clause[(int) $i++/1000][] = $sub_val; + } + else + { + $extra = true; + } + } + if (!$extra && $i < 1000) + { + $out .= $val[0]; + } + else + { + $out .= ' ' . $val[1] . '('; + $in_array = array(); + + // constuct each IN() clause + foreach ($in_clause as $in_values) + { + $in_array[] = $val[2] . ' ' . (isset($val[6]) ? $val[6] : '') . 'IN(' . implode(', ', $in_values) . ')'; + } + + // Join the IN() clauses against a few ORs (IN is just a nicer OR anyway) + $out .= implode(' OR ', $in_array); + + // handle the empty string case + if ($extra) + { + $out .= ' OR ' . $val[2] . ' is ' . (isset($val[6]) ? $val[6] : '') . 'NULL'; + } + $out .= ')'; + + unset($in_array, $in_clause); + } + } + } + + return $out; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->last_query_text = $query; + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + $in_transaction = false; + if (!$this->transaction) + { + $this->sql_transaction('begin'); + } + else + { + $in_transaction = true; + } + + $array = array(); + + // We overcome Oracle's 4000 char limit by binding vars + if (strlen($query) > 4000) + { + if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/sU', $query, $regs)) + { + if (strlen($regs[3]) > 4000) + { + $cols = explode(', ', $regs[2]); + + preg_match_all('/\'(?:[^\']++|\'\')*+\'|[\d-.]+/', $regs[3], $vals, PREG_PATTERN_ORDER); + +/* The code inside this comment block breaks clob handling, but does allow the + database restore script to work. If you want to allow no posts longer than 4KB + and/or need the db restore script, uncomment this. + + + if (sizeof($cols) !== sizeof($vals)) + { + // Try to replace some common data we know is from our restore script or from other sources + $regs[3] = str_replace("'||chr(47)||'", '/', $regs[3]); + $_vals = explode(', ', $regs[3]); + + $vals = array(); + $is_in_val = false; + $i = 0; + $string = ''; + + foreach ($_vals as $value) + { + if (strpos($value, "'") === false && !$is_in_val) + { + $vals[$i++] = $value; + continue; + } + + if (substr($value, -1) === "'") + { + $vals[$i] = $string . (($is_in_val) ? ', ' : '') . $value; + $string = ''; + $is_in_val = false; + + if ($vals[$i][0] !== "'") + { + $vals[$i] = "''" . $vals[$i]; + } + $i++; + continue; + } + else + { + $string .= (($is_in_val) ? ', ' : '') . $value; + $is_in_val = true; + } + } + + if ($string) + { + // New value if cols != value + $vals[(sizeof($cols) !== sizeof($vals)) ? $i : $i - 1] .= $string; + } + + $vals = array(0 => $vals); + } +*/ + + $inserts = $vals[0]; + unset($vals); + + foreach ($inserts as $key => $value) + { + if (!empty($value) && $value[0] === "'" && strlen($value) > 4002) // check to see if this thing is greater than the max + 'x2 + { + $inserts[$key] = ':' . strtoupper($cols[$key]); + $array[$inserts[$key]] = str_replace("''", "'", substr($value, 1, -1)); + } + } + + $query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')'; + } + } + else if (preg_match_all('/^(UPDATE [\\w_]++\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data, PREG_SET_ORDER)) + { + if (strlen($data[0][2]) > 4000) + { + $update = $data[0][1]; + $where = $data[0][3]; + preg_match_all('/([\\w_]++)\\s*=\\s*(\'(?:[^\']++|\'\')*+\'|[\d-.]++)/', $data[0][2], $temp, PREG_SET_ORDER); + unset($data); + + $cols = array(); + foreach ($temp as $value) + { + if (!empty($value[2]) && $value[2][0] === "'" && strlen($value[2]) > 4002) // check to see if this thing is greater than the max + 'x2 + { + $cols[] = $value[1] . '=:' . strtoupper($value[1]); + $array[$value[1]] = str_replace("''", "'", substr($value[2], 1, -1)); + } + else + { + $cols[] = $value[1] . '=' . $value[2]; + } + } + + $query = $update . implode(', ', $cols) . ' ' . $where; + unset($cols); + } + } + } + + switch (substr($query, 0, 6)) + { + case 'DELETE': + if (preg_match('/^(DELETE FROM [\w_]++ WHERE)((?:\s*(?:AND|OR)?\s*[\w_]+\s*(?:(?:=|<>)\s*(?>\'(?>[^\']++|\'\')*+\'|[\d-.]+)|(?:NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]+,? ?)*+\)))*+)$/', $query, $regs)) + { + $query = $regs[1] . $this->_rewrite_where($regs[2]); + unset($regs); + } + break; + + case 'UPDATE': + if (preg_match('/^(UPDATE [\\w_]++\\s+SET [\\w_]+\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]++|:\w++)(?:, [\\w_]+\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]++|:\w++))*+\\s+WHERE)(.*)$/s', $query, $regs)) + { + $query = $regs[1] . $this->_rewrite_where($regs[2]); + unset($regs); + } + break; + + case 'SELECT': + $query = preg_replace_callback('/([\w_.]++)\s*(?:(=|<>)\s*(?>\'(?>[^\']++|\'\')*+\'|[\d-.]++|([\w_.]++))|(?:NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]++,? ?)*+\))/', array($this, '_rewrite_col_compare'), $query); + break; + } + + $this->query_result = @ociparse($this->db_connect_id, $query); + + foreach ($array as $key => $value) + { + @ocibindbyname($this->query_result, $key, $array[$key], -1); + } + + $success = @ociexecute($this->query_result, OCI_DEFAULT); + + if (!$success) + { + $this->sql_error($query); + $this->query_result = false; + } + else + { + if (!$in_transaction) + { + $this->sql_transaction('commit'); + } + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + $query = 'SELECT * FROM (SELECT /*+ FIRST_ROWS */ rownum AS xrownum, a.* FROM (' . $query . ') a WHERE rownum <= ' . ($offset + $total) . ') WHERE xrownum >= ' . $offset; + + return $this->sql_query($query, $cache_ttl); + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->query_result) ? @ocirowcount($this->query_result) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + if ($query_id !== false) + { + $row = array(); + $result = @ocifetchinto($query_id, $row, OCI_ASSOC + OCI_RETURN_NULLS); + + if (!$result || !$row) + { + return false; + } + + $result_row = array(); + foreach ($row as $key => $value) + { + // Oracle treats empty strings as null + if (is_null($value)) + { + $value = ''; + } + + // OCI->CLOB? + if (is_object($value)) + { + $value = $value->load(); + } + + $result_row[strtolower($key)] = $value; + } + + return $result_row; + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + if ($query_id === false) + { + return false; + } + + // Reset internal pointer + @ociexecute($query_id, OCI_DEFAULT); + + // We do not fetch the row for rownum == 0 because then the next resultset would be the second row + for ($i = 0; $i < $rownum; $i++) + { + if (!$this->sql_fetchrow($query_id)) + { + return false; + } + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + $query_id = $this->query_result; + + if ($query_id !== false && $this->last_query_text != '') + { + if (preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#is', $this->last_query_text, $tablename)) + { + $query = 'SELECT ' . $tablename[1] . '_seq.currval FROM DUAL'; + $stmt = @ociparse($this->db_connect_id, $query); + @ociexecute($stmt, OCI_DEFAULT); + + $temp_result = @ocifetchinto($stmt, $temp_array, OCI_ASSOC + OCI_RETURN_NULLS); + @ocifreestatement($stmt); + + if ($temp_result) + { + return $temp_array['CURRVAL']; + } + else + { + return false; + } + } + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if (isset($this->open_queries[(int) $query_id])) + { + unset($this->open_queries[(int) $query_id]); + return @ocifreestatement($query_id); + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + return str_replace(array("'", "\0"), array("''", ''), $msg); + } + + /** + * Build LIKE expression + * @access private + */ + function _sql_like_expression($expression) + { + return $expression . " ESCAPE '\\'"; + } + + /** + * Build NOT LIKE expression + * @access private + */ + function _sql_not_like_expression($expression) + { + return $expression . " ESCAPE '\\'"; + } + + function _sql_custom_build($stage, $data) + { + return $data; + } + + function _sql_bit_and($column_name, $bit, $compare = '') + { + return 'BITAND(' . $column_name . ', ' . (1 << $bit) . ')' . (($compare) ? ' ' . $compare : ''); + } + + function _sql_bit_or($column_name, $bit, $compare = '') + { + return 'BITOR(' . $column_name . ', ' . (1 << $bit) . ')' . (($compare) ? ' ' . $compare : ''); + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if (function_exists('ocierror')) + { + $error = @ocierror(); + $error = (!$error) ? @ocierror($this->query_result) : $error; + $error = (!$error) ? @ocierror($this->db_connect_id) : $error; + + if ($error) + { + $this->last_error_result = $error; + } + else + { + $error = (isset($this->last_error_result) && $this->last_error_result) ? $this->last_error_result : array(); + } + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @ocilogoff($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + + $html_table = false; + + // Grab a plan table, any will do + $sql = "SELECT table_name + FROM USER_TABLES + WHERE table_name LIKE '%PLAN_TABLE%'"; + $stmt = ociparse($this->db_connect_id, $sql); + ociexecute($stmt); + $result = array(); + + if (ocifetchinto($stmt, $result, OCI_ASSOC + OCI_RETURN_NULLS)) + { + $table = $result['TABLE_NAME']; + + // This is the statement_id that will allow us to track the plan + $statement_id = substr(md5($query), 0, 30); + + // Remove any stale plans + $stmt2 = ociparse($this->db_connect_id, "DELETE FROM $table WHERE statement_id='$statement_id'"); + ociexecute($stmt2); + ocifreestatement($stmt2); + + // Explain the plan + $sql = "EXPLAIN PLAN + SET STATEMENT_ID = '$statement_id' + FOR $query"; + $stmt2 = ociparse($this->db_connect_id, $sql); + ociexecute($stmt2); + ocifreestatement($stmt2); + + // Get the data from the plan + $sql = "SELECT operation, options, object_name, object_type, cardinality, cost + FROM plan_table + START WITH id = 0 AND statement_id = '$statement_id' + CONNECT BY PRIOR id = parent_id + AND statement_id = '$statement_id'"; + $stmt2 = ociparse($this->db_connect_id, $sql); + ociexecute($stmt2); + + $row = array(); + while (ocifetchinto($stmt2, $row, OCI_ASSOC + OCI_RETURN_NULLS)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + + ocifreestatement($stmt2); + + // Remove the plan we just made, we delete them on request anyway + $stmt2 = ociparse($this->db_connect_id, "DELETE FROM $table WHERE statement_id='$statement_id'"); + ociexecute($stmt2); + ocifreestatement($stmt2); + } + + ocifreestatement($stmt); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @ociparse($this->db_connect_id, $query); + $success = @ociexecute($result, OCI_DEFAULT); + $row = array(); + + while (@ocifetchinto($result, $row, OCI_ASSOC + OCI_RETURN_NULLS)) + { + // Take the time spent on parsing rows into account + } + @ocifreestatement($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/postgres.php b/phpBB/phpbb/db/driver/postgres.php new file mode 100644 index 0000000000..a3b9aa4c6b --- /dev/null +++ b/phpBB/phpbb/db/driver/postgres.php @@ -0,0 +1,490 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* PostgreSQL Database Abstraction Layer +* Minimum Requirement is Version 8.3+ +*/ +class postgres extends \phpbb\db\driver\driver +{ + var $multi_insert = true; + var $last_query_text = ''; + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + $connect_string = ''; + + if ($sqluser) + { + $connect_string .= "user=$sqluser "; + } + + if ($sqlpassword) + { + $connect_string .= "password=$sqlpassword "; + } + + if ($sqlserver) + { + // $sqlserver can carry a port separated by : for compatibility reasons + // If $sqlserver has more than one : it's probably an IPv6 address. + // In this case we only allow passing a port via the $port variable. + if (substr_count($sqlserver, ':') === 1) + { + list($sqlserver, $port) = explode(':', $sqlserver); + } + + if ($sqlserver !== 'localhost') + { + $connect_string .= "host=$sqlserver "; + } + + if ($port) + { + $connect_string .= "port=$port "; + } + } + + $schema = ''; + + if ($database) + { + $this->dbname = $database; + if (strpos($database, '.') !== false) + { + list($database, $schema) = explode('.', $database); + } + $connect_string .= "dbname=$database"; + } + + $this->persistency = $persistency; + + if ($this->persistency) + { + if (!function_exists('pg_pconnect')) + { + $this->connect_error = 'pg_pconnect function does not exist, is pgsql extension installed?'; + return $this->sql_error(''); + } + $collector = new \phpbb\error_collector; + $collector->install(); + $this->db_connect_id = (!$new_link) ? @pg_pconnect($connect_string) : @pg_pconnect($connect_string, PGSQL_CONNECT_FORCE_NEW); + } + else + { + if (!function_exists('pg_connect')) + { + $this->connect_error = 'pg_connect function does not exist, is pgsql extension installed?'; + return $this->sql_error(''); + } + $collector = new \phpbb\error_collector; + $collector->install(); + $this->db_connect_id = (!$new_link) ? @pg_connect($connect_string) : @pg_connect($connect_string, PGSQL_CONNECT_FORCE_NEW); + } + + $collector->uninstall(); + + if ($this->db_connect_id) + { + if ($schema !== '') + { + @pg_query($this->db_connect_id, 'SET search_path TO ' . $schema); + } + return $this->db_connect_id; + } + + $this->connect_error = $collector->format_errors(); + return $this->sql_error(''); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('pgsql_version')) === false) + { + $query_id = @pg_query($this->db_connect_id, 'SELECT VERSION() AS version'); + $row = @pg_fetch_assoc($query_id, null); + @pg_free_result($query_id); + + $this->sql_server_version = (!empty($row['version'])) ? trim(substr($row['version'], 10)) : 0; + + if (!empty($cache) && $use_cache) + { + $cache->put('pgsql_version', $this->sql_server_version); + } + } + + return ($raw) ? $this->sql_server_version : 'PostgreSQL ' . $this->sql_server_version; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return @pg_query($this->db_connect_id, 'BEGIN'); + break; + + case 'commit': + return @pg_query($this->db_connect_id, 'COMMIT'); + break; + + case 'rollback': + return @pg_query($this->db_connect_id, 'ROLLBACK'); + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->last_query_text = $query; + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @pg_query($this->db_connect_id, $query)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * Build db-specific query data + * @access private + */ + function _sql_custom_build($stage, $data) + { + return $data; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // if $total is set to 0 we do not want to limit the number of rows + if ($total == 0) + { + $total = 'ALL'; + } + + $query .= "\n LIMIT $total OFFSET $offset"; + + return $this->sql_query($query, $cache_ttl); + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->query_result) ? @pg_affected_rows($this->query_result) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + return ($query_id !== false) ? @pg_fetch_assoc($query_id, null) : false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + return ($query_id !== false) ? @pg_result_seek($query_id, $rownum) : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + $query_id = $this->query_result; + + if ($query_id !== false && $this->last_query_text != '') + { + if (preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $this->last_query_text, $tablename)) + { + $query = "SELECT currval('" . $tablename[1] . "_seq') AS last_value"; + $temp_q_id = @pg_query($this->db_connect_id, $query); + + if (!$temp_q_id) + { + return false; + } + + $temp_result = @pg_fetch_assoc($temp_q_id, null); + @pg_free_result($query_id); + + return ($temp_result) ? $temp_result['last_value'] : false; + } + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if (isset($this->open_queries[(int) $query_id])) + { + unset($this->open_queries[(int) $query_id]); + return @pg_free_result($query_id); + } + + return false; + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + return @pg_escape_string($msg); + } + + /** + * Build LIKE expression + * @access private + */ + function _sql_like_expression($expression) + { + return $expression; + } + + /** + * Build NOT LIKE expression + * @access private + */ + function _sql_not_like_expression($expression) + { + return $expression; + } + + /** + * {@inheritDoc} + */ + function cast_expr_to_bigint($expression) + { + return 'CAST(' . $expression . ' as DECIMAL(255, 0))'; + } + + /** + * {@inheritDoc} + */ + function cast_expr_to_string($expression) + { + return 'CAST(' . $expression . ' as VARCHAR(255))'; + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + // pg_last_error only works when there is an established connection. + // Connection errors have to be tracked by us manually. + if ($this->db_connect_id) + { + $message = @pg_last_error($this->db_connect_id); + } + else + { + $message = $this->connect_error; + } + + return array( + 'message' => $message, + 'code' => '' + ); + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @pg_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + + $explain_query = $query; + if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + + if (preg_match('/^SELECT/', $explain_query)) + { + $html_table = false; + + if ($result = @pg_query($this->db_connect_id, "EXPLAIN $explain_query")) + { + while ($row = @pg_fetch_assoc($result, null)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + @pg_free_result($result); + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + } + + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @pg_query($this->db_connect_id, $query); + while ($void = @pg_fetch_assoc($result, null)) + { + // Take the time spent on parsing rows into account + } + @pg_free_result($result); + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/sqlite.php b/phpBB/phpbb/db/driver/sqlite.php new file mode 100644 index 0000000000..d5da0e2438 --- /dev/null +++ b/phpBB/phpbb/db/driver/sqlite.php @@ -0,0 +1,378 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* Sqlite Database Abstraction Layer +* Minimum Requirement: 2.8.2+ +*/ +class sqlite extends \phpbb\db\driver\driver +{ + var $connect_error = ''; + + /** + * {@inheritDoc} + */ + function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + $this->persistency = $persistency; + $this->user = $sqluser; + $this->server = $sqlserver . (($port) ? ':' . $port : ''); + $this->dbname = $database; + + $error = ''; + if ($this->persistency) + { + if (!function_exists('sqlite_popen')) + { + $this->connect_error = 'sqlite_popen function does not exist, is sqlite extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @sqlite_popen($this->server, 0666, $error); + } + else + { + if (!function_exists('sqlite_open')) + { + $this->connect_error = 'sqlite_open function does not exist, is sqlite extension installed?'; + return $this->sql_error(''); + } + $this->db_connect_id = @sqlite_open($this->server, 0666, $error); + } + + if ($this->db_connect_id) + { + @sqlite_query('PRAGMA short_column_names = 1', $this->db_connect_id); +// @sqlite_query('PRAGMA encoding = "UTF-8"', $this->db_connect_id); + } + + return ($this->db_connect_id) ? true : array('message' => $error); + } + + /** + * {@inheritDoc} + */ + function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('sqlite_version')) === false) + { + $result = @sqlite_query('SELECT sqlite_version() AS version', $this->db_connect_id); + $row = @sqlite_fetch_array($result, SQLITE_ASSOC); + + $this->sql_server_version = (!empty($row['version'])) ? $row['version'] : 0; + + if (!empty($cache) && $use_cache) + { + $cache->put('sqlite_version', $this->sql_server_version); + } + } + + return ($raw) ? $this->sql_server_version : 'SQLite ' . $this->sql_server_version; + } + + /** + * SQL Transaction + * @access private + */ + function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return @sqlite_query('BEGIN', $this->db_connect_id); + break; + + case 'commit': + return @sqlite_query('COMMIT', $this->db_connect_id); + break; + + case 'rollback': + return @sqlite_query('ROLLBACK', $this->db_connect_id); + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @sqlite_query($query, $this->db_connect_id)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + else if (strpos($query, 'SELECT') === 0 && $this->query_result) + { + $this->open_queries[(int) $this->query_result] = $this->query_result; + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * Build LIMIT query + */ + function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // if $total is set to 0 we do not want to limit the number of rows + if ($total == 0) + { + $total = -1; + } + + $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total); + + return $this->sql_query($query, $cache_ttl); + } + + /** + * {@inheritDoc} + */ + function sql_affectedrows() + { + return ($this->db_connect_id) ? @sqlite_changes($this->db_connect_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + return ($query_id !== false) ? @sqlite_fetch_array($query_id, SQLITE_ASSOC) : false; + } + + /** + * {@inheritDoc} + */ + function sql_rowseek($rownum, &$query_id) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && $cache->sql_exists($query_id)) + { + return $cache->sql_rowseek($rownum, $query_id); + } + + return ($query_id !== false) ? @sqlite_seek($query_id, $rownum) : false; + } + + /** + * {@inheritDoc} + */ + function sql_nextid() + { + return ($this->db_connect_id) ? @sqlite_last_insert_rowid($this->db_connect_id) : false; + } + + /** + * {@inheritDoc} + */ + function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + return true; + } + + /** + * {@inheritDoc} + */ + function sql_escape($msg) + { + return @sqlite_escape_string($msg); + } + + /** + * {@inheritDoc} + * + * For SQLite an underscore is a not-known character... this may change with SQLite3 + */ + function sql_like_expression($expression) + { + // Unlike LIKE, GLOB is unfortunately case sensitive. + // We only catch * and ? here, not the character map possible on file globbing. + $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression); + + $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression); + $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression); + + return 'GLOB \'' . $this->sql_escape($expression) . '\''; + } + + /** + * {@inheritDoc} + * + * For SQLite an underscore is a not-known character... + */ + function sql_not_like_expression($expression) + { + // Unlike NOT LIKE, NOT GLOB is unfortunately case sensitive. + // We only catch * and ? here, not the character map possible on file globbing. + $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression); + + $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression); + $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression); + + return 'NOT GLOB \'' . $this->sql_escape($expression) . '\''; + } + + /** + * return sql error array + * @access private + */ + function _sql_error() + { + if (function_exists('sqlite_error_string')) + { + $error = array( + 'message' => @sqlite_error_string(@sqlite_last_error($this->db_connect_id)), + 'code' => @sqlite_last_error($this->db_connect_id), + ); + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Build db-specific query data + * @access private + */ + function _sql_custom_build($stage, $data) + { + return $data; + } + + /** + * Close sql connection + * @access private + */ + function _sql_close() + { + return @sqlite_close($this->db_connect_id); + } + + /** + * Build db-specific report + * @access private + */ + function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = @sqlite_query($query, $this->db_connect_id); + while ($void = @sqlite_fetch_array($result, SQLITE_ASSOC)) + { + // Take the time spent on parsing rows into account + } + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/driver/sqlite3.php b/phpBB/phpbb/db/driver/sqlite3.php new file mode 100644 index 0000000000..cc3352af34 --- /dev/null +++ b/phpBB/phpbb/db/driver/sqlite3.php @@ -0,0 +1,405 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\driver; + +/** +* SQLite3 Database Abstraction Layer +* Minimum Requirement: 3.6.15+ +*/ +class sqlite3 extends \phpbb\db\driver\driver +{ + /** + * @var string Stores errors during connection setup in case the driver is not available + */ + protected $connect_error = ''; + + /** + * @var \SQLite3 The SQLite3 database object to operate against + */ + protected $dbo = null; + + /** + * {@inheritDoc} + */ + public function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) + { + $this->persistency = false; + $this->user = $sqluser; + $this->server = $sqlserver . (($port) ? ':' . $port : ''); + $this->dbname = $database; + + if (!class_exists('SQLite3', false)) + { + $this->connect_error = 'SQLite3 not found, is the extension installed?'; + return $this->sql_error(''); + } + + try + { + $this->dbo = new \SQLite3($this->server, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); + $this->dbo->busyTimeout(60000); + $this->db_connect_id = true; + } + catch (\Exception $e) + { + $this->connect_error = $e->getMessage(); + return array('message' => $this->connect_error); + } + + return true; + } + + /** + * {@inheritDoc} + */ + public function sql_server_info($raw = false, $use_cache = true) + { + global $cache; + + if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('sqlite_version')) === false) + { + $version = \SQLite3::version(); + + $this->sql_server_version = $version['versionString']; + + if (!empty($cache) && $use_cache) + { + $cache->put('sqlite_version', $this->sql_server_version); + } + } + + return ($raw) ? $this->sql_server_version : 'SQLite ' . $this->sql_server_version; + } + + /** + * SQL Transaction + * + * @param string $status Should be one of the following strings: + * begin, commit, rollback + * @return bool Success/failure of the transaction query + */ + protected function _sql_transaction($status = 'begin') + { + switch ($status) + { + case 'begin': + return $this->dbo->exec('BEGIN IMMEDIATE'); + break; + + case 'commit': + return $this->dbo->exec('COMMIT'); + break; + + case 'rollback': + return $this->dbo->exec('ROLLBACK'); + break; + } + + return true; + } + + /** + * {@inheritDoc} + */ + public function sql_query($query = '', $cache_ttl = 0) + { + if ($query != '') + { + global $cache; + + // EXPLAIN only in extra debug mode + if (defined('DEBUG')) + { + $this->sql_report('start', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->curtime = microtime(true); + } + + $this->last_query_text = $query; + $this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false; + $this->sql_add_num_queries($this->query_result); + + if ($this->query_result === false) + { + if (($this->query_result = @$this->dbo->query($query)) === false) + { + $this->sql_error($query); + } + + if (defined('DEBUG')) + { + $this->sql_report('stop', $query); + } + else if (defined('PHPBB_DISPLAY_LOAD_TIME')) + { + $this->sql_time += microtime(true) - $this->curtime; + } + + if ($cache && $cache_ttl) + { + $this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl); + } + } + else if (defined('DEBUG')) + { + $this->sql_report('fromcache', $query); + } + } + else + { + return false; + } + + return $this->query_result; + } + + /** + * Build LIMIT query + * + * @param string $query The SQL query to execute + * @param int $total The number of rows to select + * @param int $offset + * @param int $cache_ttl Either 0 to avoid caching or + * the time in seconds which the result shall be kept in cache + * @return mixed Buffered, seekable result handle, false on error + */ + protected function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) + { + $this->query_result = false; + + // if $total is set to 0 we do not want to limit the number of rows + if ($total == 0) + { + $total = -1; + } + + $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total); + + return $this->sql_query($query, $cache_ttl); + } + + /** + * {@inheritDoc} + */ + public function sql_affectedrows() + { + return ($this->db_connect_id) ? $this->dbo->changes() : false; + } + + /** + * {@inheritDoc} + */ + public function sql_fetchrow($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_fetchrow($query_id); + } + + return is_object($query_id) ? $query_id->fetchArray(SQLITE3_ASSOC) : false; + } + + /** + * {@inheritDoc} + */ + public function sql_nextid() + { + return ($this->db_connect_id) ? $this->dbo->lastInsertRowID() : false; + } + + /** + * {@inheritDoc} + */ + public function sql_freeresult($query_id = false) + { + global $cache; + + if ($query_id === false) + { + $query_id = $this->query_result; + } + + if ($cache && !is_object($query_id) && $cache->sql_exists($query_id)) + { + return $cache->sql_freeresult($query_id); + } + + if ($query_id) + { + return @$query_id->finalize(); + } + } + + /** + * {@inheritDoc} + */ + public function sql_escape($msg) + { + return \SQLite3::escapeString($msg); + } + + /** + * {@inheritDoc} + * + * For SQLite an underscore is an unknown character. + */ + public function sql_like_expression($expression) + { + // Unlike LIKE, GLOB is unfortunately case sensitive. + // We only catch * and ? here, not the character map possible on file globbing. + $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression); + + $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression); + $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression); + + return 'GLOB \'' . $this->sql_escape($expression) . '\''; + } + + /** + * {@inheritDoc} + * + * For SQLite an underscore is an unknown character. + */ + public function sql_not_like_expression($expression) + { + // Unlike NOT LIKE, NOT GLOB is unfortunately case sensitive + // We only catch * and ? here, not the character map possible on file globbing. + $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression); + + $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression); + $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression); + + return 'NOT GLOB \'' . $this->sql_escape($expression) . '\''; + } + + /** + * return sql error array + * + * @return array + */ + protected function _sql_error() + { + if (class_exists('SQLite3', false) && isset($this->dbo)) + { + $error = array( + 'message' => $this->dbo->lastErrorMsg(), + 'code' => $this->dbo->lastErrorCode(), + ); + } + else + { + $error = array( + 'message' => $this->connect_error, + 'code' => '', + ); + } + + return $error; + } + + /** + * Build db-specific query data + * + * @param string $stage Available stages: FROM, WHERE + * @param mixed $data A string containing the CROSS JOIN query or an array of WHERE clauses + * + * @return string The db-specific query fragment + */ + protected function _sql_custom_build($stage, $data) + { + return $data; + } + + /** + * Close sql connection + * + * @return bool False if failure + */ + protected function _sql_close() + { + return $this->dbo->close(); + } + + /** + * Build db-specific report + * + * @param string $mode Available modes: display, start, stop, + * add_select_row, fromcache, record_fromcache + * @param string $query The Query that should be explained + * @return mixed Either a full HTML page, boolean or null + */ + protected function _sql_report($mode, $query = '') + { + switch ($mode) + { + case 'start': + + $explain_query = $query; + if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) + { + $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; + } + + if (preg_match('/^SELECT/', $explain_query)) + { + $html_table = false; + + if ($result = $this->dbo->query("EXPLAIN QUERY PLAN $explain_query")) + { + while ($row = $result->fetchArray(SQLITE3_ASSOC)) + { + $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); + } + } + + if ($html_table) + { + $this->html_hold .= '</table>'; + } + } + + break; + + case 'fromcache': + $endtime = explode(' ', microtime()); + $endtime = $endtime[0] + $endtime[1]; + + $result = $this->dbo->query($query); + while ($void = $result->fetchArray(SQLITE3_ASSOC)) + { + // Take the time spent on parsing rows into account + } + + $splittime = explode(' ', microtime()); + $splittime = $splittime[0] + $splittime[1]; + + $this->sql_report('record_fromcache', $query, $endtime, $splittime); + + break; + } + } +} diff --git a/phpBB/phpbb/db/html_migrator_output_handler.php b/phpBB/phpbb/db/html_migrator_output_handler.php new file mode 100644 index 0000000000..e37c667463 --- /dev/null +++ b/phpBB/phpbb/db/html_migrator_output_handler.php @@ -0,0 +1,48 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +use phpbb\user; + +class html_migrator_output_handler implements migrator_output_handler_interface +{ + /** + * User object. + * + * @var user + */ + private $user; + + /** + * Constructor + * + * @param user $user User object + */ + public function __construct(user $user) + { + $this->user = $user; + } + + /** + * {@inheritdoc} + */ + public function write($message, $verbosity) + { + if ($verbosity <= migrator_output_handler_interface::VERBOSITY_VERBOSE) + { + $final_message = call_user_func_array(array($this->user, 'lang'), $message); + echo $final_message . "<br />\n"; + } + } +} diff --git a/phpBB/phpbb/db/log_wrapper_migrator_output_handler.php b/phpBB/phpbb/db/log_wrapper_migrator_output_handler.php new file mode 100644 index 0000000000..94c293dc45 --- /dev/null +++ b/phpBB/phpbb/db/log_wrapper_migrator_output_handler.php @@ -0,0 +1,95 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +use phpbb\user; + +class log_wrapper_migrator_output_handler implements migrator_output_handler_interface +{ + /** + * User object. + * + * @var user + */ + protected $user; + + /** + * A migrator output handler + * + * @var migrator_output_handler_interface + */ + protected $migrator; + + /** + * Log file handle + * @var resource + */ + protected $file_handle = false; + + /** + * Constructor + * + * @param user $user User object + * @param migrator_output_handler_interface $migrator Migrator output handler + * @param string $log_file File to log to + */ + public function __construct(user $user, migrator_output_handler_interface $migrator, $log_file) + { + $this->user = $user; + $this->migrator = $migrator; + $this->file_open($log_file); + } + + /** + * Open file for logging + * + * @param string $file File to open + */ + protected function file_open($file) + { + if (phpbb_is_writable(dirname($file))) + { + $this->file_handle = fopen($file, 'w'); + } + else + { + throw new \RuntimeException('Unable to write to migrator log file'); + } + } + + /** + * {@inheritdoc} + */ + public function write($message, $verbosity) + { + $this->migrator->write($message, $verbosity); + + if ($this->file_handle !== false) + { + $translated_message = call_user_func_array(array($this->user, 'lang'), $message) . "\n"; + + if ($verbosity <= migrator_output_handler_interface::VERBOSITY_NORMAL) + { + $translated_message = '[INFO] ' . $translated_message; + } + else + { + $translated_message = '[DEBUG] ' . $translated_message; + } + + fwrite($this->file_handle, $translated_message); + fflush($this->file_handle); + } + } +} diff --git a/phpBB/phpbb/db/migration/container_aware_migration.php b/phpBB/phpbb/db/migration/container_aware_migration.php new file mode 100644 index 0000000000..3b4b49b04b --- /dev/null +++ b/phpBB/phpbb/db/migration/container_aware_migration.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration; + +use Symfony\Component\DependencyInjection\ContainerAwareInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* Abstract base class for container aware database migrations. +*/ +abstract class container_aware_migration extends migration implements ContainerAwareInterface +{ + /** + * @var ContainerInterface + */ + protected $container; + + /** + * {@inheritdoc} + */ + public function setContainer(ContainerInterface $container = null) + { + $this->container = $container; + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/.htaccess b/phpBB/phpbb/db/migration/data/v30x/.htaccess new file mode 100644 index 0000000000..44242b5418 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/.htaccess @@ -0,0 +1,33 @@ +# With Apache 2.4 the "Order, Deny" syntax has been deprecated and moved from +# module mod_authz_host to a new module called mod_access_compat (which may be +# disabled) and a new "Require" syntax has been introduced to mod_authz_host. +# We could just conditionally provide both versions, but unfortunately Apache +# does not explicitly tell us its version if the module mod_version is not +# available. In this case, we check for the availability of module +# mod_authz_core (which should be on 2.4 or higher only) as a best guess. +<IfModule mod_version.c> + <IfVersion < 2.4> + <Files "*"> + Order Allow,Deny + Deny from All + </Files> + </IfVersion> + <IfVersion >= 2.4> + <Files "*"> + Require all denied + </Files> + </IfVersion> +</IfModule> +<IfModule !mod_version.c> + <IfModule !mod_authz_core.c> + <Files "*"> + Order Allow,Deny + Deny from All + </Files> + </IfModule> + <IfModule mod_authz_core.c> + <Files "*"> + Require all denied + </Files> + </IfModule> +</IfModule> diff --git a/phpBB/phpbb/db/migration/data/v30x/local_url_bbcode.php b/phpBB/phpbb/db/migration/data/v30x/local_url_bbcode.php new file mode 100644 index 0000000000..648ae9ce96 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/local_url_bbcode.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class local_url_bbcode extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_12_rc1'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_local_url_bbcode'))), + ); + } + + /** + * Update BBCodes that currently use the LOCAL_URL tag + * + * To fix http://tracker.phpbb.com/browse/PHPBB3-8319 we changed + * the second_pass_replace value, so that needs updating for existing ones + */ + public function update_local_url_bbcode() + { + $sql = 'SELECT * + FROM ' . BBCODES_TABLE . ' + WHERE bbcode_match ' . $this->db->sql_like_expression($this->db->get_any_char() . 'LOCAL_URL' . $this->db->get_any_char()); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + if (!class_exists('acp_bbcodes')) + { + if (function_exists('phpbb_require_updated')) + { + phpbb_require_updated('includes/acp/acp_bbcodes.' . $this->php_ext); + } + else + { + require($this->phpbb_root_path . 'includes/acp/acp_bbcodes.' . $this->php_ext); + } + } + + $bbcode_match = $row['bbcode_match']; + $bbcode_tpl = $row['bbcode_tpl']; + + $acp_bbcodes = new \acp_bbcodes(); + $sql_ary = $acp_bbcodes->build_regexp($bbcode_match, $bbcode_tpl); + + $sql = 'UPDATE ' . BBCODES_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' + WHERE bbcode_id = ' . (int) $row['bbcode_id']; + $this->sql_query($sql); + } + $this->db->sql_freeresult($result); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_0.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_0.php new file mode 100644 index 0000000000..26937d6d80 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_0.php @@ -0,0 +1,1181 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_0 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.0', '>='); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'attachments' => array( + 'COLUMNS' => array( + 'attach_id' => array('UINT', NULL, 'auto_increment'), + 'post_msg_id' => array('UINT', 0), + 'topic_id' => array('UINT', 0), + 'in_message' => array('BOOL', 0), + 'poster_id' => array('UINT', 0), + 'is_orphan' => array('BOOL', 1), + 'physical_filename' => array('VCHAR', ''), + 'real_filename' => array('VCHAR', ''), + 'download_count' => array('UINT', 0), + 'attach_comment' => array('TEXT_UNI', ''), + 'extension' => array('VCHAR:100', ''), + 'mimetype' => array('VCHAR:100', ''), + 'filesize' => array('UINT:20', 0), + 'filetime' => array('TIMESTAMP', 0), + 'thumbnail' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'attach_id', + 'KEYS' => array( + 'filetime' => array('INDEX', 'filetime'), + 'post_msg_id' => array('INDEX', 'post_msg_id'), + 'topic_id' => array('INDEX', 'topic_id'), + 'poster_id' => array('INDEX', 'poster_id'), + 'is_orphan' => array('INDEX', 'is_orphan'), + ), + ), + + $this->table_prefix . 'acl_groups' => array( + 'COLUMNS' => array( + 'group_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'auth_option_id' => array('UINT', 0), + 'auth_role_id' => array('UINT', 0), + 'auth_setting' => array('TINT:2', 0), + ), + 'KEYS' => array( + 'group_id' => array('INDEX', 'group_id'), + 'auth_opt_id' => array('INDEX', 'auth_option_id'), + 'auth_role_id' => array('INDEX', 'auth_role_id'), + ), + ), + + $this->table_prefix . 'acl_options' => array( + 'COLUMNS' => array( + 'auth_option_id' => array('UINT', NULL, 'auto_increment'), + 'auth_option' => array('VCHAR:50', ''), + 'is_global' => array('BOOL', 0), + 'is_local' => array('BOOL', 0), + 'founder_only' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'auth_option_id', + 'KEYS' => array( + 'auth_option' => array('INDEX', 'auth_option'), + ), + ), + + $this->table_prefix . 'acl_roles' => array( + 'COLUMNS' => array( + 'role_id' => array('UINT', NULL, 'auto_increment'), + 'role_name' => array('VCHAR_UNI', ''), + 'role_description' => array('TEXT_UNI', ''), + 'role_type' => array('VCHAR:10', ''), + 'role_order' => array('USINT', 0), + ), + 'PRIMARY_KEY' => 'role_id', + 'KEYS' => array( + 'role_type' => array('INDEX', 'role_type'), + 'role_order' => array('INDEX', 'role_order'), + ), + ), + + $this->table_prefix . 'acl_roles_data' => array( + 'COLUMNS' => array( + 'role_id' => array('UINT', 0), + 'auth_option_id' => array('UINT', 0), + 'auth_setting' => array('TINT:2', 0), + ), + 'PRIMARY_KEY' => array('role_id', 'auth_option_id'), + 'KEYS' => array( + 'ath_op_id' => array('INDEX', 'auth_option_id'), + ), + ), + + $this->table_prefix . 'acl_users' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'auth_option_id' => array('UINT', 0), + 'auth_role_id' => array('UINT', 0), + 'auth_setting' => array('TINT:2', 0), + ), + 'KEYS' => array( + 'user_id' => array('INDEX', 'user_id'), + 'auth_option_id' => array('INDEX', 'auth_option_id'), + 'auth_role_id' => array('INDEX', 'auth_role_id'), + ), + ), + + $this->table_prefix . 'banlist' => array( + 'COLUMNS' => array( + 'ban_id' => array('UINT', NULL, 'auto_increment'), + 'ban_userid' => array('UINT', 0), + 'ban_ip' => array('VCHAR:40', ''), + 'ban_email' => array('VCHAR_UNI:100', ''), + 'ban_start' => array('TIMESTAMP', 0), + 'ban_end' => array('TIMESTAMP', 0), + 'ban_exclude' => array('BOOL', 0), + 'ban_reason' => array('VCHAR_UNI', ''), + 'ban_give_reason' => array('VCHAR_UNI', ''), + ), + 'PRIMARY_KEY' => 'ban_id', + 'KEYS' => array( + 'ban_end' => array('INDEX', 'ban_end'), + 'ban_user' => array('INDEX', array('ban_userid', 'ban_exclude')), + 'ban_email' => array('INDEX', array('ban_email', 'ban_exclude')), + 'ban_ip' => array('INDEX', array('ban_ip', 'ban_exclude')), + ), + ), + + $this->table_prefix . 'bbcodes' => array( + 'COLUMNS' => array( + 'bbcode_id' => array('TINT:3', 0), + 'bbcode_tag' => array('VCHAR:16', ''), + 'bbcode_helpline' => array('VCHAR_UNI', ''), + 'display_on_posting' => array('BOOL', 0), + 'bbcode_match' => array('TEXT_UNI', ''), + 'bbcode_tpl' => array('MTEXT_UNI', ''), + 'first_pass_match' => array('MTEXT_UNI', ''), + 'first_pass_replace' => array('MTEXT_UNI', ''), + 'second_pass_match' => array('MTEXT_UNI', ''), + 'second_pass_replace' => array('MTEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'bbcode_id', + 'KEYS' => array( + 'display_on_post' => array('INDEX', 'display_on_posting'), + ), + ), + + $this->table_prefix . 'bookmarks' => array( + 'COLUMNS' => array( + 'topic_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + ), + 'PRIMARY_KEY' => array('topic_id', 'user_id'), + ), + + $this->table_prefix . 'bots' => array( + 'COLUMNS' => array( + 'bot_id' => array('UINT', NULL, 'auto_increment'), + 'bot_active' => array('BOOL', 1), + 'bot_name' => array('STEXT_UNI', ''), + 'user_id' => array('UINT', 0), + 'bot_agent' => array('VCHAR', ''), + 'bot_ip' => array('VCHAR', ''), + ), + 'PRIMARY_KEY' => 'bot_id', + 'KEYS' => array( + 'bot_active' => array('INDEX', 'bot_active'), + ), + ), + + $this->table_prefix . 'config' => array( + 'COLUMNS' => array( + 'config_name' => array('VCHAR', ''), + 'config_value' => array('VCHAR_UNI', ''), + 'is_dynamic' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'config_name', + 'KEYS' => array( + 'is_dynamic' => array('INDEX', 'is_dynamic'), + ), + ), + + $this->table_prefix . 'confirm' => array( + 'COLUMNS' => array( + 'confirm_id' => array('CHAR:32', ''), + 'session_id' => array('CHAR:32', ''), + 'confirm_type' => array('TINT:3', 0), + 'code' => array('VCHAR:8', ''), + 'seed' => array('UINT:10', 0), + ), + 'PRIMARY_KEY' => array('session_id', 'confirm_id'), + 'KEYS' => array( + 'confirm_type' => array('INDEX', 'confirm_type'), + ), + ), + + $this->table_prefix . 'disallow' => array( + 'COLUMNS' => array( + 'disallow_id' => array('UINT', NULL, 'auto_increment'), + 'disallow_username' => array('VCHAR_UNI:255', ''), + ), + 'PRIMARY_KEY' => 'disallow_id', + ), + + $this->table_prefix . 'drafts' => array( + 'COLUMNS' => array( + 'draft_id' => array('UINT', NULL, 'auto_increment'), + 'user_id' => array('UINT', 0), + 'topic_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'save_time' => array('TIMESTAMP', 0), + 'draft_subject' => array('XSTEXT_UNI', ''), + 'draft_message' => array('MTEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'draft_id', + 'KEYS' => array( + 'save_time' => array('INDEX', 'save_time'), + ), + ), + + $this->table_prefix . 'extensions' => array( + 'COLUMNS' => array( + 'extension_id' => array('UINT', NULL, 'auto_increment'), + 'group_id' => array('UINT', 0), + 'extension' => array('VCHAR:100', ''), + ), + 'PRIMARY_KEY' => 'extension_id', + ), + + $this->table_prefix . 'extension_groups' => array( + 'COLUMNS' => array( + 'group_id' => array('UINT', NULL, 'auto_increment'), + 'group_name' => array('VCHAR_UNI', ''), + 'cat_id' => array('TINT:2', 0), + 'allow_group' => array('BOOL', 0), + 'download_mode' => array('BOOL', 1), + 'upload_icon' => array('VCHAR', ''), + 'max_filesize' => array('UINT:20', 0), + 'allowed_forums' => array('TEXT', ''), + 'allow_in_pm' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'group_id', + ), + + $this->table_prefix . 'forums' => array( + 'COLUMNS' => array( + 'forum_id' => array('UINT', NULL, 'auto_increment'), + 'parent_id' => array('UINT', 0), + 'left_id' => array('UINT', 0), + 'right_id' => array('UINT', 0), + 'forum_parents' => array('MTEXT', ''), + 'forum_name' => array('STEXT_UNI', ''), + 'forum_desc' => array('TEXT_UNI', ''), + 'forum_desc_bitfield' => array('VCHAR:255', ''), + 'forum_desc_options' => array('UINT:11', 7), + 'forum_desc_uid' => array('VCHAR:8', ''), + 'forum_link' => array('VCHAR_UNI', ''), + 'forum_password' => array('VCHAR_UNI:40', ''), + 'forum_style' => array('USINT', 0), + 'forum_image' => array('VCHAR', ''), + 'forum_rules' => array('TEXT_UNI', ''), + 'forum_rules_link' => array('VCHAR_UNI', ''), + 'forum_rules_bitfield' => array('VCHAR:255', ''), + 'forum_rules_options' => array('UINT:11', 7), + 'forum_rules_uid' => array('VCHAR:8', ''), + 'forum_topics_per_page' => array('TINT:4', 0), + 'forum_type' => array('TINT:4', 0), + 'forum_status' => array('TINT:4', 0), + 'forum_posts' => array('UINT', 0), + 'forum_topics' => array('UINT', 0), + 'forum_topics_real' => array('UINT', 0), + 'forum_last_post_id' => array('UINT', 0), + 'forum_last_poster_id' => array('UINT', 0), + 'forum_last_post_subject' => array('XSTEXT_UNI', ''), + 'forum_last_post_time' => array('TIMESTAMP', 0), + 'forum_last_poster_name'=> array('VCHAR_UNI', ''), + 'forum_last_poster_colour'=> array('VCHAR:6', ''), + 'forum_flags' => array('TINT:4', 32), + 'display_on_index' => array('BOOL', 1), + 'enable_indexing' => array('BOOL', 1), + 'enable_icons' => array('BOOL', 1), + 'enable_prune' => array('BOOL', 0), + 'prune_next' => array('TIMESTAMP', 0), + 'prune_days' => array('UINT', 0), + 'prune_viewed' => array('UINT', 0), + 'prune_freq' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'forum_id', + 'KEYS' => array( + 'left_right_id' => array('INDEX', array('left_id', 'right_id')), + 'forum_lastpost_id' => array('INDEX', 'forum_last_post_id'), + ), + ), + + $this->table_prefix . 'forums_access' => array( + 'COLUMNS' => array( + 'forum_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'session_id' => array('CHAR:32', ''), + ), + 'PRIMARY_KEY' => array('forum_id', 'user_id', 'session_id'), + ), + + $this->table_prefix . 'forums_track' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'mark_time' => array('TIMESTAMP', 0), + ), + 'PRIMARY_KEY' => array('user_id', 'forum_id'), + ), + + $this->table_prefix . 'forums_watch' => array( + 'COLUMNS' => array( + 'forum_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'notify_status' => array('BOOL', 0), + ), + 'KEYS' => array( + 'forum_id' => array('INDEX', 'forum_id'), + 'user_id' => array('INDEX', 'user_id'), + 'notify_stat' => array('INDEX', 'notify_status'), + ), + ), + + $this->table_prefix . 'groups' => array( + 'COLUMNS' => array( + 'group_id' => array('UINT', NULL, 'auto_increment'), + 'group_type' => array('TINT:4', 1), + 'group_founder_manage' => array('BOOL', 0), + 'group_name' => array('VCHAR_CI', ''), + 'group_desc' => array('TEXT_UNI', ''), + 'group_desc_bitfield' => array('VCHAR:255', ''), + 'group_desc_options' => array('UINT:11', 7), + 'group_desc_uid' => array('VCHAR:8', ''), + 'group_display' => array('BOOL', 0), + 'group_avatar' => array('VCHAR', ''), + 'group_avatar_type' => array('TINT:2', 0), + 'group_avatar_width' => array('USINT', 0), + 'group_avatar_height' => array('USINT', 0), + 'group_rank' => array('UINT', 0), + 'group_colour' => array('VCHAR:6', ''), + 'group_sig_chars' => array('UINT', 0), + 'group_receive_pm' => array('BOOL', 0), + 'group_message_limit' => array('UINT', 0), + 'group_legend' => array('BOOL', 1), + ), + 'PRIMARY_KEY' => 'group_id', + 'KEYS' => array( + 'group_legend' => array('INDEX', 'group_legend'), + ), + ), + + $this->table_prefix . 'icons' => array( + 'COLUMNS' => array( + 'icons_id' => array('UINT', NULL, 'auto_increment'), + 'icons_url' => array('VCHAR', ''), + 'icons_width' => array('TINT:4', 0), + 'icons_height' => array('TINT:4', 0), + 'icons_order' => array('UINT', 0), + 'display_on_posting' => array('BOOL', 1), + ), + 'PRIMARY_KEY' => 'icons_id', + 'KEYS' => array( + 'display_on_posting' => array('INDEX', 'display_on_posting'), + ), + ), + + $this->table_prefix . 'lang' => array( + 'COLUMNS' => array( + 'lang_id' => array('TINT:4', NULL, 'auto_increment'), + 'lang_iso' => array('VCHAR:30', ''), + 'lang_dir' => array('VCHAR:30', ''), + 'lang_english_name' => array('VCHAR_UNI:100', ''), + 'lang_local_name' => array('VCHAR_UNI:255', ''), + 'lang_author' => array('VCHAR_UNI:255', ''), + ), + 'PRIMARY_KEY' => 'lang_id', + 'KEYS' => array( + 'lang_iso' => array('INDEX', 'lang_iso'), + ), + ), + + $this->table_prefix . 'log' => array( + 'COLUMNS' => array( + 'log_id' => array('UINT', NULL, 'auto_increment'), + 'log_type' => array('TINT:4', 0), + 'user_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'topic_id' => array('UINT', 0), + 'reportee_id' => array('UINT', 0), + 'log_ip' => array('VCHAR:40', ''), + 'log_time' => array('TIMESTAMP', 0), + 'log_operation' => array('TEXT_UNI', ''), + 'log_data' => array('MTEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'log_id', + 'KEYS' => array( + 'log_type' => array('INDEX', 'log_type'), + 'forum_id' => array('INDEX', 'forum_id'), + 'topic_id' => array('INDEX', 'topic_id'), + 'reportee_id' => array('INDEX', 'reportee_id'), + 'user_id' => array('INDEX', 'user_id'), + ), + ), + + $this->table_prefix . 'moderator_cache' => array( + 'COLUMNS' => array( + 'forum_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'username' => array('VCHAR_UNI:255', ''), + 'group_id' => array('UINT', 0), + 'group_name' => array('VCHAR_UNI', ''), + 'display_on_index' => array('BOOL', 1), + ), + 'KEYS' => array( + 'disp_idx' => array('INDEX', 'display_on_index'), + 'forum_id' => array('INDEX', 'forum_id'), + ), + ), + + $this->table_prefix . 'modules' => array( + 'COLUMNS' => array( + 'module_id' => array('UINT', NULL, 'auto_increment'), + 'module_enabled' => array('BOOL', 1), + 'module_display' => array('BOOL', 1), + 'module_basename' => array('VCHAR', ''), + 'module_class' => array('VCHAR:10', ''), + 'parent_id' => array('UINT', 0), + 'left_id' => array('UINT', 0), + 'right_id' => array('UINT', 0), + 'module_langname' => array('VCHAR', ''), + 'module_mode' => array('VCHAR', ''), + 'module_auth' => array('VCHAR', ''), + ), + 'PRIMARY_KEY' => 'module_id', + 'KEYS' => array( + 'left_right_id' => array('INDEX', array('left_id', 'right_id')), + 'module_enabled' => array('INDEX', 'module_enabled'), + 'class_left_id' => array('INDEX', array('module_class', 'left_id')), + ), + ), + + $this->table_prefix . 'poll_options' => array( + 'COLUMNS' => array( + 'poll_option_id' => array('TINT:4', 0), + 'topic_id' => array('UINT', 0), + 'poll_option_text' => array('TEXT_UNI', ''), + 'poll_option_total' => array('UINT', 0), + ), + 'KEYS' => array( + 'poll_opt_id' => array('INDEX', 'poll_option_id'), + 'topic_id' => array('INDEX', 'topic_id'), + ), + ), + + $this->table_prefix . 'poll_votes' => array( + 'COLUMNS' => array( + 'topic_id' => array('UINT', 0), + 'poll_option_id' => array('TINT:4', 0), + 'vote_user_id' => array('UINT', 0), + 'vote_user_ip' => array('VCHAR:40', ''), + ), + 'KEYS' => array( + 'topic_id' => array('INDEX', 'topic_id'), + 'vote_user_id' => array('INDEX', 'vote_user_id'), + 'vote_user_ip' => array('INDEX', 'vote_user_ip'), + ), + ), + + $this->table_prefix . 'posts' => array( + 'COLUMNS' => array( + 'post_id' => array('UINT', NULL, 'auto_increment'), + 'topic_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'poster_id' => array('UINT', 0), + 'icon_id' => array('UINT', 0), + 'poster_ip' => array('VCHAR:40', ''), + 'post_time' => array('TIMESTAMP', 0), + 'post_approved' => array('BOOL', 1), + 'post_reported' => array('BOOL', 0), + 'enable_bbcode' => array('BOOL', 1), + 'enable_smilies' => array('BOOL', 1), + 'enable_magic_url' => array('BOOL', 1), + 'enable_sig' => array('BOOL', 1), + 'post_username' => array('VCHAR_UNI:255', ''), + 'post_subject' => array('XSTEXT_UNI', '', 'true_sort'), + 'post_text' => array('MTEXT_UNI', ''), + 'post_checksum' => array('VCHAR:32', ''), + 'post_attachment' => array('BOOL', 0), + 'bbcode_bitfield' => array('VCHAR:255', ''), + 'bbcode_uid' => array('VCHAR:8', ''), + 'post_postcount' => array('BOOL', 1), + 'post_edit_time' => array('TIMESTAMP', 0), + 'post_edit_reason' => array('STEXT_UNI', ''), + 'post_edit_user' => array('UINT', 0), + 'post_edit_count' => array('USINT', 0), + 'post_edit_locked' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'post_id', + 'KEYS' => array( + 'forum_id' => array('INDEX', 'forum_id'), + 'topic_id' => array('INDEX', 'topic_id'), + 'poster_ip' => array('INDEX', 'poster_ip'), + 'poster_id' => array('INDEX', 'poster_id'), + 'post_approved' => array('INDEX', 'post_approved'), + 'tid_post_time' => array('INDEX', array('topic_id', 'post_time')), + ), + ), + + $this->table_prefix . 'privmsgs' => array( + 'COLUMNS' => array( + 'msg_id' => array('UINT', NULL, 'auto_increment'), + 'root_level' => array('UINT', 0), + 'author_id' => array('UINT', 0), + 'icon_id' => array('UINT', 0), + 'author_ip' => array('VCHAR:40', ''), + 'message_time' => array('TIMESTAMP', 0), + 'enable_bbcode' => array('BOOL', 1), + 'enable_smilies' => array('BOOL', 1), + 'enable_magic_url' => array('BOOL', 1), + 'enable_sig' => array('BOOL', 1), + 'message_subject' => array('XSTEXT_UNI', ''), + 'message_text' => array('MTEXT_UNI', ''), + 'message_edit_reason' => array('STEXT_UNI', ''), + 'message_edit_user' => array('UINT', 0), + 'message_attachment' => array('BOOL', 0), + 'bbcode_bitfield' => array('VCHAR:255', ''), + 'bbcode_uid' => array('VCHAR:8', ''), + 'message_edit_time' => array('TIMESTAMP', 0), + 'message_edit_count' => array('USINT', 0), + 'to_address' => array('TEXT_UNI', ''), + 'bcc_address' => array('TEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'msg_id', + 'KEYS' => array( + 'author_ip' => array('INDEX', 'author_ip'), + 'message_time' => array('INDEX', 'message_time'), + 'author_id' => array('INDEX', 'author_id'), + 'root_level' => array('INDEX', 'root_level'), + ), + ), + + $this->table_prefix . 'privmsgs_folder' => array( + 'COLUMNS' => array( + 'folder_id' => array('UINT', NULL, 'auto_increment'), + 'user_id' => array('UINT', 0), + 'folder_name' => array('VCHAR_UNI', ''), + 'pm_count' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'folder_id', + 'KEYS' => array( + 'user_id' => array('INDEX', 'user_id'), + ), + ), + + $this->table_prefix . 'privmsgs_rules' => array( + 'COLUMNS' => array( + 'rule_id' => array('UINT', NULL, 'auto_increment'), + 'user_id' => array('UINT', 0), + 'rule_check' => array('UINT', 0), + 'rule_connection' => array('UINT', 0), + 'rule_string' => array('VCHAR_UNI', ''), + 'rule_user_id' => array('UINT', 0), + 'rule_group_id' => array('UINT', 0), + 'rule_action' => array('UINT', 0), + 'rule_folder_id' => array('INT:11', 0), + ), + 'PRIMARY_KEY' => 'rule_id', + 'KEYS' => array( + 'user_id' => array('INDEX', 'user_id'), + ), + ), + + $this->table_prefix . 'privmsgs_to' => array( + 'COLUMNS' => array( + 'msg_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'author_id' => array('UINT', 0), + 'pm_deleted' => array('BOOL', 0), + 'pm_new' => array('BOOL', 1), + 'pm_unread' => array('BOOL', 1), + 'pm_replied' => array('BOOL', 0), + 'pm_marked' => array('BOOL', 0), + 'pm_forwarded' => array('BOOL', 0), + 'folder_id' => array('INT:11', 0), + ), + 'KEYS' => array( + 'msg_id' => array('INDEX', 'msg_id'), + 'author_id' => array('INDEX', 'author_id'), + 'usr_flder_id' => array('INDEX', array('user_id', 'folder_id')), + ), + ), + + $this->table_prefix . 'profile_fields' => array( + 'COLUMNS' => array( + 'field_id' => array('UINT', NULL, 'auto_increment'), + 'field_name' => array('VCHAR_UNI', ''), + 'field_type' => array('TINT:4', 0), + 'field_ident' => array('VCHAR:20', ''), + 'field_length' => array('VCHAR:20', ''), + 'field_minlen' => array('VCHAR', ''), + 'field_maxlen' => array('VCHAR', ''), + 'field_novalue' => array('VCHAR_UNI', ''), + 'field_default_value' => array('VCHAR_UNI', ''), + 'field_validation' => array('VCHAR_UNI:20', ''), + 'field_required' => array('BOOL', 0), + 'field_show_on_reg' => array('BOOL', 0), + 'field_hide' => array('BOOL', 0), + 'field_no_view' => array('BOOL', 0), + 'field_active' => array('BOOL', 0), + 'field_order' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'field_id', + 'KEYS' => array( + 'fld_type' => array('INDEX', 'field_type'), + 'fld_ordr' => array('INDEX', 'field_order'), + ), + ), + + $this->table_prefix . 'profile_fields_data' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'user_id', + ), + + $this->table_prefix . 'profile_fields_lang' => array( + 'COLUMNS' => array( + 'field_id' => array('UINT', 0), + 'lang_id' => array('UINT', 0), + 'option_id' => array('UINT', 0), + 'field_type' => array('TINT:4', 0), + 'lang_value' => array('VCHAR_UNI', ''), + ), + 'PRIMARY_KEY' => array('field_id', 'lang_id', 'option_id'), + ), + + $this->table_prefix . 'profile_lang' => array( + 'COLUMNS' => array( + 'field_id' => array('UINT', 0), + 'lang_id' => array('UINT', 0), + 'lang_name' => array('VCHAR_UNI', ''), + 'lang_explain' => array('TEXT_UNI', ''), + 'lang_default_value' => array('VCHAR_UNI', ''), + ), + 'PRIMARY_KEY' => array('field_id', 'lang_id'), + ), + + $this->table_prefix . 'ranks' => array( + 'COLUMNS' => array( + 'rank_id' => array('UINT', NULL, 'auto_increment'), + 'rank_title' => array('VCHAR_UNI', ''), + 'rank_min' => array('UINT', 0), + 'rank_special' => array('BOOL', 0), + 'rank_image' => array('VCHAR', ''), + ), + 'PRIMARY_KEY' => 'rank_id', + ), + + $this->table_prefix . 'reports' => array( + 'COLUMNS' => array( + 'report_id' => array('UINT', NULL, 'auto_increment'), + 'reason_id' => array('USINT', 0), + 'post_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'user_notify' => array('BOOL', 0), + 'report_closed' => array('BOOL', 0), + 'report_time' => array('TIMESTAMP', 0), + 'report_text' => array('MTEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'report_id', + ), + + $this->table_prefix . 'reports_reasons' => array( + 'COLUMNS' => array( + 'reason_id' => array('USINT', NULL, 'auto_increment'), + 'reason_title' => array('VCHAR_UNI', ''), + 'reason_description' => array('MTEXT_UNI', ''), + 'reason_order' => array('USINT', 0), + ), + 'PRIMARY_KEY' => 'reason_id', + ), + + $this->table_prefix . 'search_results' => array( + 'COLUMNS' => array( + 'search_key' => array('VCHAR:32', ''), + 'search_time' => array('TIMESTAMP', 0), + 'search_keywords' => array('MTEXT_UNI', ''), + 'search_authors' => array('MTEXT', ''), + ), + 'PRIMARY_KEY' => 'search_key', + ), + + $this->table_prefix . 'search_wordlist' => array( + 'COLUMNS' => array( + 'word_id' => array('UINT', NULL, 'auto_increment'), + 'word_text' => array('VCHAR_UNI', ''), + 'word_common' => array('BOOL', 0), + 'word_count' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'word_id', + 'KEYS' => array( + 'wrd_txt' => array('UNIQUE', 'word_text'), + 'wrd_cnt' => array('INDEX', 'word_count'), + ), + ), + + $this->table_prefix . 'search_wordmatch' => array( + 'COLUMNS' => array( + 'post_id' => array('UINT', 0), + 'word_id' => array('UINT', 0), + 'title_match' => array('BOOL', 0), + ), + 'KEYS' => array( + 'unq_mtch' => array('UNIQUE', array('word_id', 'post_id', 'title_match')), + 'word_id' => array('INDEX', 'word_id'), + 'post_id' => array('INDEX', 'post_id'), + ), + ), + + $this->table_prefix . 'sessions' => array( + 'COLUMNS' => array( + 'session_id' => array('CHAR:32', ''), + 'session_user_id' => array('UINT', 0), + 'session_last_visit' => array('TIMESTAMP', 0), + 'session_start' => array('TIMESTAMP', 0), + 'session_time' => array('TIMESTAMP', 0), + 'session_ip' => array('VCHAR:40', ''), + 'session_browser' => array('VCHAR:150', ''), + 'session_forwarded_for' => array('VCHAR:255', ''), + 'session_page' => array('VCHAR_UNI', ''), + 'session_viewonline' => array('BOOL', 1), + 'session_autologin' => array('BOOL', 0), + 'session_admin' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'session_id', + 'KEYS' => array( + 'session_time' => array('INDEX', 'session_time'), + 'session_user_id' => array('INDEX', 'session_user_id'), + ), + ), + + $this->table_prefix . 'sessions_keys' => array( + 'COLUMNS' => array( + 'key_id' => array('CHAR:32', ''), + 'user_id' => array('UINT', 0), + 'last_ip' => array('VCHAR:40', ''), + 'last_login' => array('TIMESTAMP', 0), + ), + 'PRIMARY_KEY' => array('key_id', 'user_id'), + 'KEYS' => array( + 'last_login' => array('INDEX', 'last_login'), + ), + ), + + $this->table_prefix . 'sitelist' => array( + 'COLUMNS' => array( + 'site_id' => array('UINT', NULL, 'auto_increment'), + 'site_ip' => array('VCHAR:40', ''), + 'site_hostname' => array('VCHAR', ''), + 'ip_exclude' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'site_id', + ), + + $this->table_prefix . 'smilies' => array( + 'COLUMNS' => array( + 'smiley_id' => array('UINT', NULL, 'auto_increment'), +// We may want to set 'code' to VCHAR:50 or check if unicode support is possible... at the moment only ASCII characters are allowed. + 'code' => array('VCHAR_UNI:50', ''), + 'emotion' => array('VCHAR_UNI:50', ''), + 'smiley_url' => array('VCHAR:50', ''), + 'smiley_width' => array('USINT', 0), + 'smiley_height' => array('USINT', 0), + 'smiley_order' => array('UINT', 0), + 'display_on_posting'=> array('BOOL', 1), + ), + 'PRIMARY_KEY' => 'smiley_id', + 'KEYS' => array( + 'display_on_post' => array('INDEX', 'display_on_posting'), + ), + ), + + $this->table_prefix . 'styles' => array( + 'COLUMNS' => array( + 'style_id' => array('USINT', NULL, 'auto_increment'), + 'style_name' => array('VCHAR_UNI:255', ''), + 'style_copyright' => array('VCHAR_UNI', ''), + 'style_active' => array('BOOL', 1), + 'template_id' => array('USINT', 0), + 'theme_id' => array('USINT', 0), + 'imageset_id' => array('USINT', 0), + ), + 'PRIMARY_KEY' => 'style_id', + 'KEYS' => array( + 'style_name' => array('UNIQUE', 'style_name'), + 'template_id' => array('INDEX', 'template_id'), + 'theme_id' => array('INDEX', 'theme_id'), + 'imageset_id' => array('INDEX', 'imageset_id'), + ), + ), + + $this->table_prefix . 'styles_template' => array( + 'COLUMNS' => array( + 'template_id' => array('USINT', NULL, 'auto_increment'), + 'template_name' => array('VCHAR_UNI:255', ''), + 'template_copyright' => array('VCHAR_UNI', ''), + 'template_path' => array('VCHAR:100', ''), + 'bbcode_bitfield' => array('VCHAR:255', 'kNg='), + 'template_storedb' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'template_id', + 'KEYS' => array( + 'tmplte_nm' => array('UNIQUE', 'template_name'), + ), + ), + + $this->table_prefix . 'styles_template_data' => array( + 'COLUMNS' => array( + 'template_id' => array('USINT', 0), + 'template_filename' => array('VCHAR:100', ''), + 'template_included' => array('TEXT', ''), + 'template_mtime' => array('TIMESTAMP', 0), + 'template_data' => array('MTEXT_UNI', ''), + ), + 'KEYS' => array( + 'tid' => array('INDEX', 'template_id'), + 'tfn' => array('INDEX', 'template_filename'), + ), + ), + + $this->table_prefix . 'styles_theme' => array( + 'COLUMNS' => array( + 'theme_id' => array('USINT', NULL, 'auto_increment'), + 'theme_name' => array('VCHAR_UNI:255', ''), + 'theme_copyright' => array('VCHAR_UNI', ''), + 'theme_path' => array('VCHAR:100', ''), + 'theme_storedb' => array('BOOL', 0), + 'theme_mtime' => array('TIMESTAMP', 0), + 'theme_data' => array('MTEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'theme_id', + 'KEYS' => array( + 'theme_name' => array('UNIQUE', 'theme_name'), + ), + ), + + $this->table_prefix . 'styles_imageset' => array( + 'COLUMNS' => array( + 'imageset_id' => array('USINT', NULL, 'auto_increment'), + 'imageset_name' => array('VCHAR_UNI:255', ''), + 'imageset_copyright' => array('VCHAR_UNI', ''), + 'imageset_path' => array('VCHAR:100', ''), + ), + 'PRIMARY_KEY' => 'imageset_id', + 'KEYS' => array( + 'imgset_nm' => array('UNIQUE', 'imageset_name'), + ), + ), + + $this->table_prefix . 'styles_imageset_data' => array( + 'COLUMNS' => array( + 'image_id' => array('USINT', NULL, 'auto_increment'), + 'image_name' => array('VCHAR:200', ''), + 'image_filename' => array('VCHAR:200', ''), + 'image_lang' => array('VCHAR:30', ''), + 'image_height' => array('USINT', 0), + 'image_width' => array('USINT', 0), + 'imageset_id' => array('USINT', 0), + ), + 'PRIMARY_KEY' => 'image_id', + 'KEYS' => array( + 'i_d' => array('INDEX', 'imageset_id'), + ), + ), + + $this->table_prefix . 'topics' => array( + 'COLUMNS' => array( + 'topic_id' => array('UINT', NULL, 'auto_increment'), + 'forum_id' => array('UINT', 0), + 'icon_id' => array('UINT', 0), + 'topic_attachment' => array('BOOL', 0), + 'topic_approved' => array('BOOL', 1), + 'topic_reported' => array('BOOL', 0), + 'topic_title' => array('XSTEXT_UNI', '', 'true_sort'), + 'topic_poster' => array('UINT', 0), + 'topic_time' => array('TIMESTAMP', 0), + 'topic_time_limit' => array('TIMESTAMP', 0), + 'topic_views' => array('UINT', 0), + 'topic_replies' => array('UINT', 0), + 'topic_replies_real' => array('UINT', 0), + 'topic_status' => array('TINT:3', 0), + 'topic_type' => array('TINT:3', 0), + 'topic_first_post_id' => array('UINT', 0), + 'topic_first_poster_name' => array('VCHAR_UNI', ''), + 'topic_first_poster_colour' => array('VCHAR:6', ''), + 'topic_last_post_id' => array('UINT', 0), + 'topic_last_poster_id' => array('UINT', 0), + 'topic_last_poster_name' => array('VCHAR_UNI', ''), + 'topic_last_poster_colour' => array('VCHAR:6', ''), + 'topic_last_post_subject' => array('XSTEXT_UNI', ''), + 'topic_last_post_time' => array('TIMESTAMP', 0), + 'topic_last_view_time' => array('TIMESTAMP', 0), + 'topic_moved_id' => array('UINT', 0), + 'topic_bumped' => array('BOOL', 0), + 'topic_bumper' => array('UINT', 0), + 'poll_title' => array('STEXT_UNI', ''), + 'poll_start' => array('TIMESTAMP', 0), + 'poll_length' => array('TIMESTAMP', 0), + 'poll_max_options' => array('TINT:4', 1), + 'poll_last_vote' => array('TIMESTAMP', 0), + 'poll_vote_change' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => 'topic_id', + 'KEYS' => array( + 'forum_id' => array('INDEX', 'forum_id'), + 'forum_id_type' => array('INDEX', array('forum_id', 'topic_type')), + 'last_post_time' => array('INDEX', 'topic_last_post_time'), + 'topic_approved' => array('INDEX', 'topic_approved'), + 'forum_appr_last' => array('INDEX', array('forum_id', 'topic_approved', 'topic_last_post_id')), + 'fid_time_moved' => array('INDEX', array('forum_id', 'topic_last_post_time', 'topic_moved_id')), + ), + ), + + $this->table_prefix . 'topics_track' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + 'topic_id' => array('UINT', 0), + 'forum_id' => array('UINT', 0), + 'mark_time' => array('TIMESTAMP', 0), + ), + 'PRIMARY_KEY' => array('user_id', 'topic_id'), + 'KEYS' => array( + 'forum_id' => array('INDEX', 'forum_id'), + ), + ), + + $this->table_prefix . 'topics_posted' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + 'topic_id' => array('UINT', 0), + 'topic_posted' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => array('user_id', 'topic_id'), + ), + + $this->table_prefix . 'topics_watch' => array( + 'COLUMNS' => array( + 'topic_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'notify_status' => array('BOOL', 0), + ), + 'KEYS' => array( + 'topic_id' => array('INDEX', 'topic_id'), + 'user_id' => array('INDEX', 'user_id'), + 'notify_stat' => array('INDEX', 'notify_status'), + ), + ), + + $this->table_prefix . 'user_group' => array( + 'COLUMNS' => array( + 'group_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'group_leader' => array('BOOL', 0), + 'user_pending' => array('BOOL', 1), + ), + 'KEYS' => array( + 'group_id' => array('INDEX', 'group_id'), + 'user_id' => array('INDEX', 'user_id'), + 'group_leader' => array('INDEX', 'group_leader'), + ), + ), + + $this->table_prefix . 'users' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', NULL, 'auto_increment'), + 'user_type' => array('TINT:2', 0), + 'group_id' => array('UINT', 3), + 'user_permissions' => array('MTEXT', ''), + 'user_perm_from' => array('UINT', 0), + 'user_ip' => array('VCHAR:40', ''), + 'user_regdate' => array('TIMESTAMP', 0), + 'username' => array('VCHAR_CI', ''), + 'username_clean' => array('VCHAR_CI', ''), + 'user_password' => array('VCHAR_UNI:40', ''), + 'user_passchg' => array('TIMESTAMP', 0), + 'user_pass_convert' => array('BOOL', 0), + 'user_email' => array('VCHAR_UNI:100', ''), + 'user_email_hash' => array('BINT', 0), + 'user_birthday' => array('VCHAR:10', ''), + 'user_lastvisit' => array('TIMESTAMP', 0), + 'user_lastmark' => array('TIMESTAMP', 0), + 'user_lastpost_time' => array('TIMESTAMP', 0), + 'user_lastpage' => array('VCHAR_UNI:200', ''), + 'user_last_confirm_key' => array('VCHAR:10', ''), + 'user_last_search' => array('TIMESTAMP', 0), + 'user_warnings' => array('TINT:4', 0), + 'user_last_warning' => array('TIMESTAMP', 0), + 'user_login_attempts' => array('TINT:4', 0), + 'user_inactive_reason' => array('TINT:2', 0), + 'user_inactive_time' => array('TIMESTAMP', 0), + 'user_posts' => array('UINT', 0), + 'user_lang' => array('VCHAR:30', ''), + 'user_timezone' => array('DECIMAL', 0), + 'user_dst' => array('BOOL', 0), + 'user_dateformat' => array('VCHAR_UNI:30', 'd M Y H:i'), + 'user_style' => array('USINT', 0), + 'user_rank' => array('UINT', 0), + 'user_colour' => array('VCHAR:6', ''), + 'user_new_privmsg' => array('INT:4', 0), + 'user_unread_privmsg' => array('INT:4', 0), + 'user_last_privmsg' => array('TIMESTAMP', 0), + 'user_message_rules' => array('BOOL', 0), + 'user_full_folder' => array('INT:11', -3), + 'user_emailtime' => array('TIMESTAMP', 0), + 'user_topic_show_days' => array('USINT', 0), + 'user_topic_sortby_type' => array('VCHAR:1', 't'), + 'user_topic_sortby_dir' => array('VCHAR:1', 'd'), + 'user_post_show_days' => array('USINT', 0), + 'user_post_sortby_type' => array('VCHAR:1', 't'), + 'user_post_sortby_dir' => array('VCHAR:1', 'a'), + 'user_notify' => array('BOOL', 0), + 'user_notify_pm' => array('BOOL', 1), + 'user_notify_type' => array('TINT:4', 0), + 'user_allow_pm' => array('BOOL', 1), + 'user_allow_viewonline' => array('BOOL', 1), + 'user_allow_viewemail' => array('BOOL', 1), + 'user_allow_massemail' => array('BOOL', 1), + 'user_options' => array('UINT:11', 895), + 'user_avatar' => array('VCHAR', ''), + 'user_avatar_type' => array('TINT:2', 0), + 'user_avatar_width' => array('USINT', 0), + 'user_avatar_height' => array('USINT', 0), + 'user_sig' => array('MTEXT_UNI', ''), + 'user_sig_bbcode_uid' => array('VCHAR:8', ''), + 'user_sig_bbcode_bitfield' => array('VCHAR:255', ''), + 'user_from' => array('VCHAR_UNI:100', ''), + 'user_icq' => array('VCHAR:15', ''), + 'user_aim' => array('VCHAR_UNI', ''), + 'user_yim' => array('VCHAR_UNI', ''), + 'user_msnm' => array('VCHAR_UNI', ''), + 'user_jabber' => array('VCHAR_UNI', ''), + 'user_website' => array('VCHAR_UNI:200', ''), + 'user_occ' => array('TEXT_UNI', ''), + 'user_interests' => array('TEXT_UNI', ''), + 'user_actkey' => array('VCHAR:32', ''), + 'user_newpasswd' => array('VCHAR_UNI:40', ''), + 'user_form_salt' => array('VCHAR_UNI:32', ''), + + ), + 'PRIMARY_KEY' => 'user_id', + 'KEYS' => array( + 'user_birthday' => array('INDEX', 'user_birthday'), + 'user_email_hash' => array('INDEX', 'user_email_hash'), + 'user_type' => array('INDEX', 'user_type'), + 'username_clean' => array('UNIQUE', 'username_clean'), + ), + ), + + $this->table_prefix . 'warnings' => array( + 'COLUMNS' => array( + 'warning_id' => array('UINT', NULL, 'auto_increment'), + 'user_id' => array('UINT', 0), + 'post_id' => array('UINT', 0), + 'log_id' => array('UINT', 0), + 'warning_time' => array('TIMESTAMP', 0), + ), + 'PRIMARY_KEY' => 'warning_id', + ), + + $this->table_prefix . 'words' => array( + 'COLUMNS' => array( + 'word_id' => array('UINT', NULL, 'auto_increment'), + 'word' => array('VCHAR_UNI', ''), + 'replacement' => array('VCHAR_UNI', ''), + ), + 'PRIMARY_KEY' => 'word_id', + ), + + $this->table_prefix . 'zebra' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + 'zebra_id' => array('UINT', 0), + 'friend' => array('BOOL', 0), + 'foe' => array('BOOL', 0), + ), + 'PRIMARY_KEY' => array('user_id', 'zebra_id'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'attachments', + $this->table_prefix . 'acl_groups', + $this->table_prefix . 'acl_options', + $this->table_prefix . 'acl_roles', + $this->table_prefix . 'acl_roles_data', + $this->table_prefix . 'acl_users', + $this->table_prefix . 'banlist', + $this->table_prefix . 'bbcodes', + $this->table_prefix . 'bookmarks', + $this->table_prefix . 'bots', + $this->table_prefix . 'config', + $this->table_prefix . 'confirm', + $this->table_prefix . 'disallow', + $this->table_prefix . 'drafts', + $this->table_prefix . 'extensions', + $this->table_prefix . 'extension_groups', + $this->table_prefix . 'forums', + $this->table_prefix . 'forums_access', + $this->table_prefix . 'forums_track', + $this->table_prefix . 'forums_watch', + $this->table_prefix . 'groups', + $this->table_prefix . 'icons', + $this->table_prefix . 'lang', + $this->table_prefix . 'log', + $this->table_prefix . 'moderator_cache', + $this->table_prefix . 'modules', + $this->table_prefix . 'poll_options', + $this->table_prefix . 'poll_votes', + $this->table_prefix . 'posts', + $this->table_prefix . 'privmsgs', + $this->table_prefix . 'privmsgs_folder', + $this->table_prefix . 'privmsgs_rules', + $this->table_prefix . 'privmsgs_to', + $this->table_prefix . 'profile_fields', + $this->table_prefix . 'profile_fields_data', + $this->table_prefix . 'profile_fields_lang', + $this->table_prefix . 'profile_lang', + $this->table_prefix . 'ranks', + $this->table_prefix . 'reports', + $this->table_prefix . 'reports_reasons', + $this->table_prefix . 'search_results', + $this->table_prefix . 'search_wordlist', + $this->table_prefix . 'search_wordmatch', + $this->table_prefix . 'sessions', + $this->table_prefix . 'sessions_keys', + $this->table_prefix . 'sitelist', + $this->table_prefix . 'smilies', + $this->table_prefix . 'styles', + $this->table_prefix . 'styles_template', + $this->table_prefix . 'styles_template_data', + $this->table_prefix . 'styles_theme', + $this->table_prefix . 'styles_imageset', + $this->table_prefix . 'styles_imageset_data', + $this->table_prefix . 'topics', + $this->table_prefix . 'topics_track', + $this->table_prefix . 'topics_posted', + $this->table_prefix . 'topics_watch', + $this->table_prefix . 'user_group', + $this->table_prefix . 'users', + $this->table_prefix . 'warnings', + $this->table_prefix . 'words', + $this->table_prefix . 'zebra', + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_1.php new file mode 100644 index 0000000000..f5c7e56a81 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_1.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_1_rc1'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_10.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10.php new file mode 100644 index 0000000000..0d3a1ca80b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_10 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.10', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_10_rc3'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.10')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc1.php new file mode 100644 index 0000000000..293c46cb06 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_10_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.10-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_9'); + } + + public function update_data() + { + return array( + array('config.add', array('email_max_chunk_size', 50)), + + array('config.update', array('version', '3.0.10-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc2.php new file mode 100644 index 0000000000..f2889120e6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc2.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_10_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.10-RC2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_10_rc1'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.10-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc3.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc3.php new file mode 100644 index 0000000000..9d6697ab7f --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_10_rc3.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_10_rc3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.10-RC3', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_10_rc2'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.10-RC3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_11.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_11.php new file mode 100644 index 0000000000..e77b54a1b5 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_11.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_11 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.11', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11_rc2'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.11')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_11_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_11_rc1.php new file mode 100644 index 0000000000..ed2dabf51c --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_11_rc1.php @@ -0,0 +1,101 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_11_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.11-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_10'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'cleanup_deactivated_styles'))), + array('custom', array(array(&$this, 'delete_orphan_private_messages'))), + + array('config.update', array('version', '3.0.11-RC1')), + ); + } + + public function cleanup_deactivated_styles() + { + // Updates users having current style a deactivated one + $sql = 'SELECT style_id + FROM ' . STYLES_TABLE . ' + WHERE style_active = 0'; + $result = $this->sql_query($sql); + + $deactivated_style_ids = array(); + while ($style_id = $this->db->sql_fetchfield('style_id', false, $result)) + { + $deactivated_style_ids[] = (int) $style_id; + } + $this->db->sql_freeresult($result); + + if (!empty($deactivated_style_ids)) + { + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_style = ' . (int) $this->config['default_style'] .' + WHERE ' . $this->db->sql_in_set('user_style', $deactivated_style_ids); + $this->sql_query($sql); + } + } + + public function delete_orphan_private_messages() + { + // Delete orphan private messages + $batch_size = 500; + + $sql_array = array( + 'SELECT' => 'p.msg_id', + 'FROM' => array( + PRIVMSGS_TABLE => 'p', + ), + 'LEFT_JOIN' => array( + array( + 'FROM' => array(PRIVMSGS_TO_TABLE => 't'), + 'ON' => 'p.msg_id = t.msg_id', + ), + ), + 'WHERE' => 't.user_id IS NULL', + ); + $sql = $this->db->sql_build_query('SELECT', $sql_array); + + $result = $this->db->sql_query_limit($sql, $batch_size); + + $delete_pms = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $delete_pms[] = (int) $row['msg_id']; + } + $this->db->sql_freeresult($result); + + if (!empty($delete_pms)) + { + $sql = 'DELETE FROM ' . PRIVMSGS_TABLE . ' + WHERE ' . $this->db->sql_in_set('msg_id', $delete_pms); + $this->sql_query($sql); + + // Return false to have the Migrator call this function again + return false; + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_11_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_11_rc2.php new file mode 100644 index 0000000000..45d88708bd --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_11_rc2.php @@ -0,0 +1,56 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_11_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.11-RC2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11_rc1'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_novalue' => array('BOOL', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_novalue', + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.11-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_12.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12.php new file mode 100644 index 0000000000..c489c0c0e8 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_12 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.12', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_12_rc3'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.12', '<'), + array('config.update', array('version', '3.0.12')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc1.php new file mode 100644 index 0000000000..f9f6d9f7f7 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc1.php @@ -0,0 +1,72 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +/** @todo DROP LOGIN_ATTEMPT_TABLE.attempt_id in 3.0.12-RC1 **/ + +class release_3_0_12_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.12-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'update_module_auth'))), + array('custom', array(array(&$this, 'disable_bots_from_receiving_pms'))), + + array('config.update', array('version', '3.0.12-RC1')), + ); + } + + public function disable_bots_from_receiving_pms() + { + // Disable receiving pms for bots + $sql = 'SELECT user_id + FROM ' . BOTS_TABLE; + $result = $this->db->sql_query($sql); + + $bot_user_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $bot_user_ids[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + if (!empty($bot_user_ids)) + { + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_allow_pm = 0 + WHERE ' . $this->db->sql_in_set('user_id', $bot_user_ids); + $this->sql_query($sql); + } + } + + public function update_module_auth() + { + $sql = 'UPDATE ' . MODULES_TABLE . ' + SET module_auth = \'acl_u_sig\' + WHERE module_class = \'ucp\' + AND module_basename = \'profile\' + AND module_mode = \'signature\''; + $this->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc2.php new file mode 100644 index 0000000000..8fac273073 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc2.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_12_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.12-RC2', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_12_rc1'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.12-RC2', '<'), + array('config.update', array('version', '3.0.12-RC2')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc3.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc3.php new file mode 100644 index 0000000000..fb1b8014a4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_12_rc3.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_12_rc3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.12-RC3', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_12_rc2'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.12-RC3', '<'), + array('config.update', array('version', '3.0.12-RC3')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_13.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_13.php new file mode 100644 index 0000000000..310fcc70fc --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_13.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_13 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.13', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_13_rc1'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.13', '<'), + array('config.update', array('version', '3.0.13')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_13_pl1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_13_pl1.php new file mode 100644 index 0000000000..b12a96a7fb --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_13_pl1.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_13_pl1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.13-PL1', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_13'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.13-PL1', '<'), + array('config.update', array('version', '3.0.13-PL1')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_13_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_13_rc1.php new file mode 100644 index 0000000000..9ea68fa862 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_13_rc1.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_13_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.13-RC1', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_12'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.13-RC1', '<'), + array('config.update', array('version', '3.0.13-RC1')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_14.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_14.php new file mode 100644 index 0000000000..51475f5a05 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_14.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_14 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.14', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_14_rc1'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.14', '<'), + array('config.update', array('version', '3.0.14')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_14_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_14_rc1.php new file mode 100644 index 0000000000..421ef06dd3 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_14_rc1.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_14_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.14-RC1', '>=') && phpbb_version_compare($this->config['version'], '3.1.0-dev', '<'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_13'); + } + + public function update_data() + { + return array( + array('if', array( + phpbb_version_compare($this->config['version'], '3.0.14-RC1', '<'), + array('config.update', array('version', '3.0.14-RC1')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_1_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_1_rc1.php new file mode 100644 index 0000000000..d1ae0b9cbc --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_1_rc1.php @@ -0,0 +1,119 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_1_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.1-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_0'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'forums' => array( + 'display_subforum_list' => array('BOOL', 1), + ), + $this->table_prefix . 'sessions' => array( + 'session_forum_id' => array('UINT', 0), + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'groups' => array( + 'group_legend', + ), + ), + 'add_index' => array( + $this->table_prefix . 'sessions' => array( + 'session_forum_id' => array('session_forum_id'), + ), + $this->table_prefix . 'groups' => array( + 'group_legend_name' => array('group_legend', 'group_name'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'forums' => array( + 'display_subforum_list', + ), + $this->table_prefix . 'sessions' => array( + 'session_forum_id', + ), + ), + 'add_index' => array( + $this->table_prefix . 'groups' => array( + 'group_legend' => array('group_legend'), + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'sessions' => array( + 'session_forum_id', + ), + $this->table_prefix . 'groups' => array( + 'group_legend_name', + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'fix_unset_last_view_time'))), + array('custom', array(array(&$this, 'reset_smiley_size'))), + + array('config.update', array('version', '3.0.1-RC1')), + ); + } + + public function fix_unset_last_view_time() + { + $sql = 'UPDATE ' . $this->table_prefix . "topics + SET topic_last_view_time = topic_last_post_time + WHERE topic_last_view_time = 0"; + $this->sql_query($sql); + } + + public function reset_smiley_size() + { + // Update smiley sizes + $smileys = array('icon_e_surprised.gif', 'icon_eek.gif', 'icon_cool.gif', 'icon_lol.gif', 'icon_mad.gif', 'icon_razz.gif', 'icon_redface.gif', 'icon_cry.gif', 'icon_evil.gif', 'icon_twisted.gif', 'icon_rolleyes.gif', 'icon_exclaim.gif', 'icon_question.gif', 'icon_idea.gif', 'icon_arrow.gif', 'icon_neutral.gif', 'icon_mrgreen.gif', 'icon_e_ugeek.gif'); + + foreach ($smileys as $smiley) + { + if (file_exists($this->phpbb_root_path . 'images/smilies/' . $smiley)) + { + list($width, $height) = getimagesize($this->phpbb_root_path . 'images/smilies/' . $smiley); + + $sql = 'UPDATE ' . SMILIES_TABLE . ' + SET smiley_width = ' . $width . ', smiley_height = ' . $height . " + WHERE smiley_url = '" . $this->db->sql_escape($smiley) . "'"; + + $this->sql_query($sql); + } + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_2.php new file mode 100644 index 0000000000..c08f01dbeb --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_2.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_2_rc2'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_2_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_2_rc1.php new file mode 100644 index 0000000000..2e7f141a9b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_2_rc1.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_2_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.2-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_1'); + } + + public function update_data() + { + return array( + array('config.add', array('referer_validation', '1')), + array('config.add', array('check_attachment_content', '1')), + array('config.add', array('mime_triggers', 'body|head|html|img|plaintext|a href|pre|script|table|title')), + + array('config.update', array('version', '3.0.2-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_2_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_2_rc2.php new file mode 100644 index 0000000000..bde5febc59 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_2_rc2.php @@ -0,0 +1,86 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_2_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.2-RC2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_2_rc1'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'drafts' => array( + 'draft_subject' => array('STEXT_UNI', ''), + ), + $this->table_prefix . 'forums' => array( + 'forum_last_post_subject' => array('STEXT_UNI', ''), + ), + $this->table_prefix . 'posts' => array( + 'post_subject' => array('STEXT_UNI', '', 'true_sort'), + ), + $this->table_prefix . 'privmsgs' => array( + 'message_subject' => array('STEXT_UNI', ''), + ), + $this->table_prefix . 'topics' => array( + 'topic_title' => array('STEXT_UNI', '', 'true_sort'), + 'topic_last_post_subject' => array('STEXT_UNI', ''), + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'sessions' => array( + 'session_forum_id', + ), + ), + 'add_index' => array( + $this->table_prefix . 'sessions' => array( + 'session_fid' => array('session_forum_id'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_index' => array( + $this->table_prefix . 'sessions' => array( + 'session_forum_id' => array( + 'session_forum_id', + ), + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'sessions' => array( + 'session_fid', + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.2-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_3.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_3.php new file mode 100644 index 0000000000..c277da224c --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_3.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.3', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_3_rc1'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_3_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_3_rc1.php new file mode 100644 index 0000000000..530eaf47e6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_3_rc1.php @@ -0,0 +1,89 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_3_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.3-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_2'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'styles_template' => array( + 'template_inherits_id' => array('UINT:4', 0), + 'template_inherit_path' => array('VCHAR', ''), + ), + $this->table_prefix . 'groups' => array( + 'group_max_recipients' => array('UINT', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'styles_template' => array( + 'template_inherits_id', + 'template_inherit_path', + ), + $this->table_prefix . 'groups' => array( + 'group_max_recipients', + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.add', array('enable_queue_trigger', '0')), + array('config.add', array('queue_trigger_posts', '3')), + array('config.add', array('pm_max_recipients', '0')), + array('custom', array(array(&$this, 'set_group_default_max_recipients'))), + array('config.add', array('dbms_version', $this->db->sql_server_info(true))), + array('permission.add', array('u_masspm_group', true, 'u_masspm')), + array('custom', array(array(&$this, 'correct_acp_email_permissions'))), + + array('config.update', array('version', '3.0.3-RC1')), + ); + } + + public function correct_acp_email_permissions() + { + $sql = 'UPDATE ' . $this->table_prefix . 'modules + SET module_auth = \'acl_a_email && cfg_email_enable\' + WHERE module_class = \'acp\' + AND module_basename = \'email\''; + $this->sql_query($sql); + } + + public function set_group_default_max_recipients() + { + // Set maximum number of recipients for the registered users, bots, guests group + $sql = 'UPDATE ' . GROUPS_TABLE . ' SET group_max_recipients = 5 + WHERE ' . $this->db->sql_in_set('group_name', array('GUESTS', 'REGISTERED', 'REGISTERED_COPPA', 'BOTS')); + $this->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_4.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_4.php new file mode 100644 index 0000000000..9b08da0125 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_4.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_4 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.4', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_4_rc1'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'rename_log_delete_topic'))), + + array('config.update', array('version', '3.0.4')), + ); + } + + public function rename_log_delete_topic() + { + if ($this->db->get_sql_layer() == 'oracle') + { + // log_operation is CLOB - but we can change this later + $sql = 'UPDATE ' . $this->table_prefix . "log + SET log_operation = 'LOG_DELETE_TOPIC' + WHERE log_operation LIKE 'LOG_TOPIC_DELETED'"; + $this->sql_query($sql); + } + else + { + $sql = 'UPDATE ' . $this->table_prefix . "log + SET log_operation = 'LOG_DELETE_TOPIC' + WHERE log_operation = 'LOG_TOPIC_DELETED'"; + $this->sql_query($sql); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_4_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_4_rc1.php new file mode 100644 index 0000000000..10343438b3 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_4_rc1.php @@ -0,0 +1,129 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_4_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.4-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_3'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_profile' => array('BOOL', 0), + ), + ), + 'change_columns' => array( + $this->table_prefix . 'styles' => array( + 'style_id' => array('UINT', NULL, 'auto_increment'), + 'template_id' => array('UINT', 0), + 'theme_id' => array('UINT', 0), + 'imageset_id' => array('UINT', 0), + ), + $this->table_prefix . 'styles_imageset' => array( + 'imageset_id' => array('UINT', NULL, 'auto_increment'), + ), + $this->table_prefix . 'styles_imageset_data' => array( + 'image_id' => array('UINT', NULL, 'auto_increment'), + 'imageset_id' => array('UINT', 0), + ), + $this->table_prefix . 'styles_theme' => array( + 'theme_id' => array('UINT', NULL, 'auto_increment'), + ), + $this->table_prefix . 'styles_template' => array( + 'template_id' => array('UINT', NULL, 'auto_increment'), + ), + $this->table_prefix . 'styles_template_data' => array( + 'template_id' => array('UINT', 0), + ), + $this->table_prefix . 'forums' => array( + 'forum_style' => array('UINT', 0), + ), + $this->table_prefix . 'users' => array( + 'user_style' => array('UINT', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_profile', + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'update_custom_profile_fields'))), + + array('config.update', array('version', '3.0.4-RC1')), + ); + } + + public function update_custom_profile_fields() + { + // Update the Custom Profile Fields based on previous settings to the new \format + $sql = 'SELECT field_id, field_required, field_show_on_reg, field_hide + FROM ' . PROFILE_FIELDS_TABLE; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $sql_ary = array( + 'field_required' => 0, + 'field_show_on_reg' => 0, + 'field_hide' => 0, + 'field_show_profile'=> 0, + ); + + if ($row['field_required']) + { + $sql_ary['field_required'] = $sql_ary['field_show_on_reg'] = $sql_ary['field_show_profile'] = 1; + } + else if ($row['field_show_on_reg']) + { + $sql_ary['field_show_on_reg'] = $sql_ary['field_show_profile'] = 1; + } + else if ($row['field_hide']) + { + // Only administrators and moderators can see this CPF, if the view is enabled, they can see it, otherwise just admins in the acp_users module + $sql_ary['field_hide'] = 1; + } + else + { + // equivelant to "none", which is the "Display in user control panel" option + $sql_ary['field_show_profile'] = 1; + } + + $this->sql_query('UPDATE ' . $this->table_prefix . 'profile_fields SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' WHERE field_id = ' . $row['field_id'], $errored, $error_ary); + } + + $this->db->sql_freeresult($result); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_5.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_5.php new file mode 100644 index 0000000000..09c2bfea50 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_5.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_5 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.5', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_5_rc1part2'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.5')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_5_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_5_rc1.php new file mode 100644 index 0000000000..003ccf8f18 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_5_rc1.php @@ -0,0 +1,133 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +use phpbb\db\migration\container_aware_migration; + +class release_3_0_5_rc1 extends container_aware_migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.5-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_4'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'forums' => array( + 'forum_style' => array('UINT', 0), + ), + ), + ); + } + + public function update_data() + { + $search_indexing_state = $this->config['search_indexing_state']; + + return array( + array('config.add', array('captcha_gd_wave', 0)), + array('config.add', array('captcha_gd_3d_noise', 1)), + array('config.add', array('captcha_gd_fonts', 1)), + array('config.add', array('confirm_refresh', 1)), + array('config.add', array('max_num_search_keywords', 10)), + array('config.remove', array('search_indexing_state')), + array('config.add', array('search_indexing_state', $search_indexing_state, true)), + array('custom', array(array(&$this, 'hash_old_passwords'))), + array('custom', array(array(&$this, 'update_ichiro_bot'))), + ); + } + + public function hash_old_passwords() + { + $passwords_manager = $this->container->get('passwords.manager'); + $sql = 'SELECT user_id, user_password + FROM ' . $this->table_prefix . 'users + WHERE user_pass_convert = 1'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + if (strlen($row['user_password']) == 32) + { + $sql_ary = array( + 'user_password' => '$CP$' . $passwords_manager->hash($row['user_password'], 'passwords.driver.salted_md5'), + ); + + $this->sql_query('UPDATE ' . $this->table_prefix . 'users SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' WHERE user_id = ' . $row['user_id']); + } + } + $this->db->sql_freeresult($result); + } + + public function update_ichiro_bot() + { + // Adjust bot entry + $sql = 'UPDATE ' . $this->table_prefix . "bots + SET bot_agent = 'ichiro/' + WHERE bot_agent = 'ichiro/2'"; + $this->sql_query($sql); + } + + public function remove_duplicate_auth_options() + { + // Before we are able to add a unique key to auth_option, we need to remove duplicate entries + $sql = 'SELECT auth_option + FROM ' . $this->table_prefix . 'acl_options + GROUP BY auth_option + HAVING COUNT(*) >= 2'; + $result = $this->db->sql_query($sql); + + $auth_options = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $auth_options[] = $row['auth_option']; + } + $this->db->sql_freeresult($result); + + // Remove specific auth options + if (!empty($auth_options)) + { + foreach ($auth_options as $option) + { + // Select auth_option_ids... the largest id will be preserved + $sql = 'SELECT auth_option_id + FROM ' . ACL_OPTIONS_TABLE . " + WHERE auth_option = '" . $this->db->sql_escape($option) . "' + ORDER BY auth_option_id DESC"; + // sql_query_limit not possible here, due to bug in postgresql layer + $result = $this->db->sql_query($sql); + + // Skip first row, this is our original auth option we want to preserve + $row = $this->db->sql_fetchrow($result); + + while ($row = $this->db->sql_fetchrow($result)) + { + // Ok, remove this auth option... + $this->sql_query('DELETE FROM ' . ACL_OPTIONS_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id']); + $this->sql_query('DELETE FROM ' . ACL_ROLES_DATA_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id']); + $this->sql_query('DELETE FROM ' . ACL_GROUPS_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id']); + $this->sql_query('DELETE FROM ' . ACL_USERS_TABLE . ' WHERE auth_option_id = ' . $row['auth_option_id']); + } + $this->db->sql_freeresult($result); + } + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_5_rc1part2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_5_rc1part2.php new file mode 100644 index 0000000000..a9041ef354 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_5_rc1part2.php @@ -0,0 +1,48 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_5_rc1part2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.5-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_5_rc1'); + } + + public function update_schema() + { + return array( + 'drop_keys' => array( + $this->table_prefix . 'acl_options' => array('auth_option'), + ), + 'add_unique_index' => array( + $this->table_prefix . 'acl_options' => array( + 'auth_option' => array('auth_option'), + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.5-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_6.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6.php new file mode 100644 index 0000000000..74c338a9c5 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_6 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.6', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_6_rc4'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.6')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc1.php new file mode 100644 index 0000000000..faef68121d --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc1.php @@ -0,0 +1,330 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_6_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.6-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_5'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'confirm' => array( + 'attempts' => array('UINT', 0), + ), + $this->table_prefix . 'users' => array( + 'user_new' => array('BOOL', 1), + 'user_reminded' => array('TINT:4', 0), + 'user_reminded_time' => array('TIMESTAMP', 0), + ), + $this->table_prefix . 'groups' => array( + 'group_skip_auth' => array('BOOL', 0, 'after' => 'group_founder_manage'), + ), + $this->table_prefix . 'privmsgs' => array( + 'message_reported' => array('BOOL', 0), + ), + $this->table_prefix . 'reports' => array( + 'pm_id' => array('UINT', 0), + ), + $this->table_prefix . 'profile_fields' => array( + 'field_show_on_vt' => array('BOOL', 0), + ), + $this->table_prefix . 'forums' => array( + 'forum_options' => array('UINT:20', 0), + ), + ), + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_options' => array('UINT:11', 230271), + ), + ), + 'add_index' => array( + $this->table_prefix . 'reports' => array( + 'post_id' => array('post_id'), + 'pm_id' => array('pm_id'), + ), + $this->table_prefix . 'posts' => array( + 'post_username' => array('post_username:255'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'confirm' => array( + 'attempts', + ), + $this->table_prefix . 'users' => array( + 'user_new', + 'user_reminded', + 'user_reminded_time', + ), + $this->table_prefix . 'groups' => array( + 'group_skip_auth', + ), + $this->table_prefix . 'privmsgs' => array( + 'message_reported', + ), + $this->table_prefix . 'reports' => array( + 'pm_id', + ), + $this->table_prefix . 'profile_fields' => array( + 'field_show_on_vt', + ), + $this->table_prefix . 'forums' => array( + 'forum_options', + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'reports' => array( + 'post_id', + 'pm_id', + ), + $this->table_prefix . 'posts' => array( + 'post_username', + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.add', array('captcha_plugin', 'phpbb_captcha_nogd')), + array('if', array( + ($this->config['captcha_gd']), + array('config.update', array('captcha_plugin', 'phpbb_captcha_gd')), + )), + + array('config.add', array('feed_enable', 0)), + array('config.add', array('feed_limit', 10)), + array('config.add', array('feed_overall_forums', 1)), + array('config.add', array('feed_overall_forums_limit', 15)), + array('config.add', array('feed_overall_topics', 0)), + array('config.add', array('feed_overall_topics_limit', 15)), + array('config.add', array('feed_forum', 1)), + array('config.add', array('feed_topic', 1)), + array('config.add', array('feed_item_statistics', 1)), + + array('config.add', array('smilies_per_page', 50)), + array('config.add', array('allow_pm_report', 1)), + array('config.add', array('min_post_chars', 1)), + array('config.add', array('allow_quick_reply', 1)), + array('config.add', array('new_member_post_limit', 0)), + array('config.add', array('new_member_group_default', 0)), + array('config.add', array('delete_time', $this->config['edit_time'])), + + array('config.add', array('allow_avatar', 0)), + array('if', array( + ($this->config['allow_avatar_upload'] || $this->config['allow_avatar_local'] || $this->config['allow_avatar_remote']), + array('config.update', array('allow_avatar', 1)), + )), + array('config.add', array('allow_avatar_remote_upload', 0)), + array('if', array( + ($this->config['allow_avatar_remote'] && $this->config['allow_avatar_upload']), + array('config.update', array('allow_avatar_remote_upload', 1)), + )), + + array('module.add', array( + 'acp', + 'ACP_BOARD_CONFIGURATION', + array( + 'module_basename' => 'acp_board', + 'modes' => array('feed'), + ), + )), + array('module.add', array( + 'acp', + 'ACP_CAT_USERS', + array( + 'module_basename' => 'acp_users', + 'modes' => array('warnings'), + ), + )), + array('module.add', array( + 'acp', + 'ACP_SERVER_CONFIGURATION', + array( + 'module_basename' => 'acp_send_statistics', + 'modes' => array('send_statistics'), + ), + )), + array('module.add', array( + 'acp', + 'ACP_FORUM_BASED_PERMISSIONS', + array( + 'module_basename' => 'acp_permissions', + 'modes' => array('setting_forum_copy'), + ), + )), + array('module.add', array( + 'mcp', + 'MCP_REPORTS', + array( + 'module_basename' => 'mcp_pm_reports', + 'modes' => array('pm_reports','pm_reports_closed','pm_report_details'), + ), + )), + array('custom', array(array(&$this, 'add_newly_registered_group'))), + array('custom', array(array(&$this, 'set_user_options_default'))), + + array('config.update', array('version', '3.0.6-RC1')), + ); + } + + public function set_user_options_default() + { + // 229376 is the added value to enable all three signature options + $sql = 'UPDATE ' . USERS_TABLE . ' SET user_options = user_options + 229376'; + $this->sql_query($sql); + } + + public function add_newly_registered_group() + { + // Add newly_registered group... but check if it already exists (we always supported running the updater on any schema) + $sql = 'SELECT group_id + FROM ' . GROUPS_TABLE . " + WHERE group_name = 'NEWLY_REGISTERED'"; + $result = $this->db->sql_query($sql); + $group_id = (int) $this->db->sql_fetchfield('group_id'); + $this->db->sql_freeresult($result); + + if (!$group_id) + { + $sql = 'INSERT INTO ' . GROUPS_TABLE . " (group_name, group_type, group_founder_manage, group_colour, group_legend, group_avatar, group_desc, group_desc_uid, group_max_recipients) VALUES ('NEWLY_REGISTERED', 3, 0, '', 0, '', '', '', 5)"; + $this->sql_query($sql); + + $group_id = $this->db->sql_nextid(); + } + + // Insert new user role... at the end of the chain + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = 'ROLE_USER_NEW_MEMBER' + AND role_type = 'u_'"; + $result = $this->db->sql_query($sql); + $u_role = (int) $this->db->sql_fetchfield('role_id'); + $this->db->sql_freeresult($result); + + if (!$u_role) + { + $sql = 'SELECT MAX(role_order) as max_order_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_type = 'u_'"; + $result = $this->db->sql_query($sql); + $next_order_id = (int) $this->db->sql_fetchfield('max_order_id'); + $this->db->sql_freeresult($result); + + $next_order_id++; + + $sql = 'INSERT INTO ' . ACL_ROLES_TABLE . " (role_name, role_description, role_type, role_order) VALUES ('ROLE_USER_NEW_MEMBER', 'ROLE_DESCRIPTION_USER_NEW_MEMBER', 'u_', $next_order_id)"; + $this->sql_query($sql); + $u_role = $this->db->sql_nextid(); + + // Now add the correct data to the roles... + // The standard role says that new users are not able to send a PM, Mass PM, are not able to PM groups + $sql = 'INSERT INTO ' . ACL_ROLES_DATA_TABLE . " (role_id, auth_option_id, auth_setting) SELECT $u_role, auth_option_id, 0 FROM " . ACL_OPTIONS_TABLE . " WHERE auth_option LIKE 'u_%' AND auth_option IN ('u_sendpm', 'u_masspm', 'u_masspm_group')"; + $this->sql_query($sql); + + // Add user role to group + $sql = 'INSERT INTO ' . ACL_GROUPS_TABLE . " (group_id, forum_id, auth_option_id, auth_role_id, auth_setting) VALUES ($group_id, 0, 0, $u_role, 0)"; + $this->sql_query($sql); + } + + // Insert new forum role + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = 'ROLE_FORUM_NEW_MEMBER' + AND role_type = 'f_'"; + $result = $this->db->sql_query($sql); + $f_role = (int) $this->db->sql_fetchfield('role_id'); + $this->db->sql_freeresult($result); + + if (!$f_role) + { + $sql = 'SELECT MAX(role_order) as max_order_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_type = 'f_'"; + $result = $this->db->sql_query($sql); + $next_order_id = (int) $this->db->sql_fetchfield('max_order_id'); + $this->db->sql_freeresult($result); + + $next_order_id++; + + $sql = 'INSERT INTO ' . ACL_ROLES_TABLE . " (role_name, role_description, role_type, role_order) VALUES ('ROLE_FORUM_NEW_MEMBER', 'ROLE_DESCRIPTION_FORUM_NEW_MEMBER', 'f_', $next_order_id)"; + $this->sql_query($sql); + $f_role = $this->db->sql_nextid(); + + $sql = 'INSERT INTO ' . ACL_ROLES_DATA_TABLE . " (role_id, auth_option_id, auth_setting) SELECT $f_role, auth_option_id, 0 FROM " . ACL_OPTIONS_TABLE . " WHERE auth_option LIKE 'f_%' AND auth_option IN ('f_noapprove')"; + $this->sql_query($sql); + } + + // Set every members user_new column to 0 (old users) only if there is no one yet (this makes sure we do not execute this more than once) + $sql = 'SELECT 1 + FROM ' . USERS_TABLE . ' + WHERE user_new = 0'; + $result = $this->db->sql_query_limit($sql, 1); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$row) + { + $sql = 'UPDATE ' . USERS_TABLE . ' SET user_new = 0'; + $this->sql_query($sql); + } + + // To mimick the old "feature" we will assign the forum role to every forum, regardless of the setting (this makes sure there are no "this does not work!!!! YUO!!!" posts... + // Check if the role is already assigned... + $sql = 'SELECT forum_id + FROM ' . ACL_GROUPS_TABLE . ' + WHERE group_id = ' . $group_id . ' + AND auth_role_id = ' . $f_role; + $result = $this->db->sql_query($sql); + $is_options = (int) $this->db->sql_fetchfield('forum_id'); + $this->db->sql_freeresult($result); + + // Not assigned at all... :/ + if (!$is_options) + { + // Get postable forums + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE . ' + WHERE forum_type != ' . FORUM_LINK; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $this->sql_query('INSERT INTO ' . ACL_GROUPS_TABLE . ' (group_id, forum_id, auth_option_id, auth_role_id, auth_setting) VALUES (' . $group_id . ', ' . (int) $row['forum_id'] . ', 0, ' . $f_role . ', 0)'); + } + $this->db->sql_freeresult($result); + } + + // Clear permissions... + include_once($this->phpbb_root_path . 'includes/acp/auth.' . $this->php_ext); + $auth_admin = new \auth_admin(); + $auth_admin->acl_clear_prefetch(); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc2.php new file mode 100644 index 0000000000..c52b71d8fa --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc2.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_6_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.6-RC2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_6_rc1'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.6-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc3.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc3.php new file mode 100644 index 0000000000..2db3341b0a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc3.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_6_rc3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.6-RC3', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_6_rc2'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'update_cp_fields'))), + + array('config.update', array('version', '3.0.6-RC3')), + ); + } + + public function update_cp_fields() + { + // Update the Custom Profile Fields based on previous settings to the new \format + $sql = 'UPDATE ' . PROFILE_FIELDS_TABLE . ' + SET field_show_on_vt = 1 + WHERE field_hide = 0 + AND (field_required = 1 OR field_show_on_reg = 1 OR field_show_profile = 1)'; + $this->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc4.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc4.php new file mode 100644 index 0000000000..5734db25e6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_6_rc4.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_6_rc4 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.6-RC4', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_6_rc3'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.6-RC4')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_7.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7.php new file mode 100644 index 0000000000..d1d602819d --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_7 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.7', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_7_rc2'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.7')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_pl1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_pl1.php new file mode 100644 index 0000000000..784e810f14 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_pl1.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_7_pl1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.7-pl1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_7'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.7-pl1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_rc1.php new file mode 100644 index 0000000000..1843c3f262 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_rc1.php @@ -0,0 +1,82 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_7_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.7-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_6'); + } + + public function update_schema() + { + return array( + 'drop_keys' => array( + $this->table_prefix . 'log' => array( + 'log_time', + ), + ), + 'add_index' => array( + $this->table_prefix . 'topics_track' => array( + 'topic_id' => array('topic_id'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_index' => array( + $this->table_prefix . 'log' => array( + 'log_time' => array('log_time'), + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'topics_track' => array( + 'topic_id', + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.add', array('feed_overall', 1)), + array('config.add', array('feed_http_auth', 0)), + array('config.add', array('feed_limit_post', $this->config['feed_limit'])), + array('config.add', array('feed_limit_topic', $this->config['feed_overall_topics_limit'])), + array('config.add', array('feed_topics_new', $this->config['feed_overall_topics'])), + array('config.add', array('feed_topics_active', $this->config['feed_overall_topics'])), + array('custom', array(array(&$this, 'delete_text_templates'))), + + array('config.update', array('version', '3.0.7-RC1')), + ); + } + + public function delete_text_templates() + { + // Delete all text-templates from the template_data + $sql = 'DELETE FROM ' . STYLES_TEMPLATE_DATA_TABLE . ' + WHERE template_filename ' . $this->db->sql_like_expression($this->db->get_any_char() . '.txt'); + $this->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_rc2.php new file mode 100644 index 0000000000..e497a38765 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_7_rc2.php @@ -0,0 +1,79 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_7_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.7-RC2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_7_rc1'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'update_email_hash'))), + + array('config.update', array('version', '3.0.7-RC2')), + ); + } + + public function update_email_hash($start = 0) + { + $limit = 1000; + + $sql = 'SELECT user_id, user_email, user_email_hash + FROM ' . USERS_TABLE . ' + WHERE user_type <> ' . USER_IGNORE . " + AND user_email <> ''"; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + $i = 0; + while ($row = $this->db->sql_fetchrow($result)) + { + $i++; + + // Snapshot of the phpbb_email_hash() function + // We cannot call it directly because the auto updater updates the DB first. :/ + $user_email_hash = sprintf('%u', crc32(strtolower($row['user_email']))) . strlen($row['user_email']); + + if ($user_email_hash != $row['user_email_hash']) + { + $sql_ary = array( + 'user_email_hash' => $user_email_hash, + ); + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' + WHERE user_id = ' . (int) $row['user_id']; + $this->sql_query($sql); + } + } + $this->db->sql_freeresult($result); + + if ($i < $limit) + { + // Completed + return; + } + + // Return the next start, will be sent to $start when this function is called again + return $start + $limit; + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_8.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_8.php new file mode 100644 index 0000000000..04b5bd4a13 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_8.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_8 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.8', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_8_rc1'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.8')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_8_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_8_rc1.php new file mode 100644 index 0000000000..22fd51543b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_8_rc1.php @@ -0,0 +1,162 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_8_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.8-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_7_pl1'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'update_file_extension_group_names'))), + array('custom', array(array(&$this, 'update_module_auth'))), + array('custom', array(array(&$this, 'delete_orphan_shadow_topics'))), + array('module.add', array( + 'acp', + 'ACP_MESSAGES', + array( + 'module_basename' => 'acp_board', + 'modes' => array('post'), + ), + )), + array('config.add', array('load_unreads_search', 1)), + array('config.update_if_equals', array(600, 'queue_interval', 60)), + array('config.update_if_equals', array(50, 'email_package_size', 20)), + + array('config.update', array('version', '3.0.8-RC1')), + ); + } + + public function update_file_extension_group_names() + { + // Update file extension group names to use language strings. + $sql = 'SELECT lang_dir + FROM ' . LANG_TABLE; + $result = $this->db->sql_query($sql); + + $extension_groups_updated = array(); + while ($lang_dir = $this->db->sql_fetchfield('lang_dir')) + { + $lang_dir = basename($lang_dir); + + // The language strings we need are either in language/.../acp/attachments.php + // in the update package if we're updating to 3.0.8-RC1 or later, + // or they are in language/.../install.php when we're updating from 3.0.7-PL1 or earlier. + // On an already updated board, they can also already be in language/.../acp/attachments.php + // in the board root. + $lang_files = array( + "{$this->phpbb_root_path}install/update/new/language/$lang_dir/acp/attachments.{$this->php_ext}", + "{$this->phpbb_root_path}language/$lang_dir/install.{$this->php_ext}", + "{$this->phpbb_root_path}language/$lang_dir/acp/attachments.{$this->php_ext}", + ); + + foreach ($lang_files as $lang_file) + { + if (!file_exists($lang_file)) + { + continue; + } + + $lang = array(); + include($lang_file); + + foreach($lang as $lang_key => $lang_val) + { + if (isset($extension_groups_updated[$lang_key]) || strpos($lang_key, 'EXT_GROUP_') !== 0) + { + continue; + } + + $sql_ary = array( + 'group_name' => substr($lang_key, 10), // Strip off 'EXT_GROUP_' + ); + + $sql = 'UPDATE ' . EXTENSION_GROUPS_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . " + WHERE group_name = '" . $this->db->sql_escape($lang_val) . "'"; + $this->sql_query($sql); + + $extension_groups_updated[$lang_key] = true; + } + } + } + $this->db->sql_freeresult($result); + } + + public function update_module_auth() + { + $sql = 'UPDATE ' . MODULES_TABLE . ' + SET module_auth = \'cfg_allow_avatar && (cfg_allow_avatar_local || cfg_allow_avatar_remote || cfg_allow_avatar_upload || cfg_allow_avatar_remote_upload)\' + WHERE module_class = \'ucp\' + AND module_basename = \'profile\' + AND module_mode = \'avatar\''; + $this->sql_query($sql); + } + + public function delete_orphan_shadow_topics() + { + // Delete shadow topics pointing to not existing topics + $batch_size = 500; + + // Set of affected forums we have to resync + $sync_forum_ids = array(); + + $sql_array = array( + 'SELECT' => 't1.topic_id, t1.forum_id', + 'FROM' => array( + TOPICS_TABLE => 't1', + ), + 'LEFT_JOIN' => array( + array( + 'FROM' => array(TOPICS_TABLE => 't2'), + 'ON' => 't1.topic_moved_id = t2.topic_id', + ), + ), + 'WHERE' => 't1.topic_moved_id <> 0 + AND t2.topic_id IS NULL', + ); + $sql = $this->db->sql_build_query('SELECT', $sql_array); + $result = $this->db->sql_query_limit($sql, $batch_size); + + $topic_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $topic_ids[] = (int) $row['topic_id']; + + $sync_forum_ids[(int) $row['forum_id']] = (int) $row['forum_id']; + } + $this->db->sql_freeresult($result); + + if (!empty($topic_ids)) + { + $sql = 'DELETE FROM ' . TOPICS_TABLE . ' + WHERE ' . $this->db->sql_in_set('topic_id', $topic_ids); + $this->db->sql_query($sql); + + // Sync the forums we have deleted shadow topics from. + sync('forum', 'forum_id', $sync_forum_ids, true, true); + + return false; + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_9.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9.php new file mode 100644 index 0000000000..e69134c538 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_9 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.9', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_9_rc4'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.9')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc1.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc1.php new file mode 100644 index 0000000000..06e46d522f --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc1.php @@ -0,0 +1,130 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_9_rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.9-RC1', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_8'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'login_attempts' => array( + 'COLUMNS' => array( + // this column was removed from the database updater + // after 3.0.9-RC3 was released. It might still exist + // in 3.0.9-RCX installations and has to be dropped as + // soon as the db_tools class is capable of properly + // removing a primary key. + // 'attempt_id' => array('UINT', NULL, 'auto_increment'), + 'attempt_ip' => array('VCHAR:40', ''), + 'attempt_browser' => array('VCHAR:150', ''), + 'attempt_forwarded_for' => array('VCHAR:255', ''), + 'attempt_time' => array('TIMESTAMP', 0), + 'user_id' => array('UINT', 0), + 'username' => array('VCHAR_UNI:255', 0), + 'username_clean' => array('VCHAR_CI', 0), + ), + //'PRIMARY_KEY' => 'attempt_id', + 'KEYS' => array( + 'att_ip' => array('INDEX', array('attempt_ip', 'attempt_time')), + 'att_for' => array('INDEX', array('attempt_forwarded_for', 'attempt_time')), + 'att_time' => array('INDEX', array('attempt_time')), + 'user_id' => array('INDEX', 'user_id'), + ), + ), + ), + 'change_columns' => array( + $this->table_prefix . 'bbcodes' => array( + 'bbcode_id' => array('USINT', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'login_attempts', + ), + ); + } + + public function update_data() + { + return array( + array('config.add', array('ip_login_limit_max', 50)), + array('config.add', array('ip_login_limit_time', 21600)), + array('config.add', array('ip_login_limit_use_forwarded', 0)), + array('custom', array(array(&$this, 'update_file_extension_group_names'))), + array('custom', array(array(&$this, 'fix_firebird_qa_captcha'))), + + array('config.update', array('version', '3.0.9-RC1')), + ); + } + + public function update_file_extension_group_names() + { + // Update file extension group names to use language strings, again. + $sql = 'SELECT group_id, group_name + FROM ' . EXTENSION_GROUPS_TABLE . ' + WHERE group_name ' . $this->db->sql_like_expression('EXT_GROUP_' . $this->db->get_any_char()); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $sql_ary = array( + 'group_name' => substr($row['group_name'], 10), // Strip off 'EXT_GROUP_' + ); + + $sql = 'UPDATE ' . EXTENSION_GROUPS_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' + WHERE group_id = ' . $row['group_id']; + $this->sql_query($sql); + } + $this->db->sql_freeresult($result); + } + + public function fix_firebird_qa_captcha() + { + // Recover from potentially broken Q&A CAPTCHA table on firebird + // Q&A CAPTCHA was uninstallable, so it's safe to remove these + // without data loss + if ($this->db_tools->sql_layer == 'firebird') + { + $tables = array( + $this->table_prefix . 'captcha_questions', + $this->table_prefix . 'captcha_answers', + $this->table_prefix . 'qa_confirm', + ); + foreach ($tables as $table) + { + if ($this->db_tools->sql_table_exists($table)) + { + $this->db_tools->sql_table_drop($table); + } + } + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc2.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc2.php new file mode 100644 index 0000000000..46fd51e7fe --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc2.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_9_rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.9-RC2', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_9_rc1'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.9-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc3.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc3.php new file mode 100644 index 0000000000..1696060735 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc3.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_9_rc3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.9-RC3', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_9_rc2'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.9-RC3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc4.php b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc4.php new file mode 100644 index 0000000000..fdc92b52f9 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v30x/release_3_0_9_rc4.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v30x; + +class release_3_0_9_rc4 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.0.9-RC4', '>='); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_9_rc3'); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.0.9-RC4')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/.htaccess b/phpBB/phpbb/db/migration/data/v310/.htaccess new file mode 100644 index 0000000000..44242b5418 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/.htaccess @@ -0,0 +1,33 @@ +# With Apache 2.4 the "Order, Deny" syntax has been deprecated and moved from +# module mod_authz_host to a new module called mod_access_compat (which may be +# disabled) and a new "Require" syntax has been introduced to mod_authz_host. +# We could just conditionally provide both versions, but unfortunately Apache +# does not explicitly tell us its version if the module mod_version is not +# available. In this case, we check for the availability of module +# mod_authz_core (which should be on 2.4 or higher only) as a best guess. +<IfModule mod_version.c> + <IfVersion < 2.4> + <Files "*"> + Order Allow,Deny + Deny from All + </Files> + </IfVersion> + <IfVersion >= 2.4> + <Files "*"> + Require all denied + </Files> + </IfVersion> +</IfModule> +<IfModule !mod_version.c> + <IfModule !mod_authz_core.c> + <Files "*"> + Order Allow,Deny + Deny from All + </Files> + </IfModule> + <IfModule mod_authz_core.c> + <Files "*"> + Require all denied + </Files> + </IfModule> +</IfModule> diff --git a/phpBB/phpbb/db/migration/data/v310/acp_prune_users_module.php b/phpBB/phpbb/db/migration/data/v310/acp_prune_users_module.php new file mode 100644 index 0000000000..0ca4f2f19c --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/acp_prune_users_module.php @@ -0,0 +1,81 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class acp_prune_users_module extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'acp' + AND module_langname = 'ACP_CAT_USERS'"; + $result = $this->db->sql_query($sql); + $acp_cat_users_id = (int) $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + $sql = 'SELECT parent_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'acp' + AND module_basename = 'acp_prune' + AND module_mode = 'users'"; + $result = $this->db->sql_query($sql); + $acp_prune_users_parent = (int) $this->db->sql_fetchfield('parent_id'); + $this->db->sql_freeresult($result); + + // Skip migration if "Users" category has been deleted + // or the module has already been moved to that category + return !$acp_cat_users_id || $acp_cat_users_id === $acp_prune_users_parent; + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\beta1'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'move_prune_users_module'))), + ); + } + + public function move_prune_users_module() + { + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'acp' + AND module_basename = 'acp_prune' + AND module_mode = 'users'"; + $result = $this->db->sql_query($sql); + $acp_prune_users_id = (int) $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'acp' + AND module_langname = 'ACP_CAT_USERS'"; + $result = $this->db->sql_query($sql); + $acp_cat_users_id = (int) $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + if (!class_exists('\acp_modules')) + { + include($this->phpbb_root_path . 'includes/acp/acp_modules.' . $this->php_ext); + } + $module_manager = new \acp_modules(); + $module_manager->module_class = 'acp'; + $module_manager->move_module($acp_prune_users_id, $acp_cat_users_id); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/acp_style_components_module.php b/phpBB/phpbb/db/migration/data/v310/acp_style_components_module.php new file mode 100644 index 0000000000..4bd29f87d7 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/acp_style_components_module.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class acp_style_components_module extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'acp' + AND module_langname = 'ACP_STYLE_COMPONENTS'"; + $result = $this->db->sql_query($sql); + $module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + return $module_id == false; + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_data() + { + return array( + array('module.remove', array( + 'acp', + false, + 'ACP_STYLE_COMPONENTS', + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/allow_cdn.php b/phpBB/phpbb/db/migration/data/v310/allow_cdn.php new file mode 100644 index 0000000000..286d20e20b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/allow_cdn.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class allow_cdn extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['allow_cdn']); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\jquery_update', + ); + } + + public function update_data() + { + return array( + array('config.add', array('allow_cdn', (int) $this->config['load_jquery_cdn'])), + array('config.remove', array('load_jquery_cdn')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/alpha1.php b/phpBB/phpbb/db/migration/data/v310/alpha1.php new file mode 100644 index 0000000000..4a48d2830a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/alpha1.php @@ -0,0 +1,53 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class alpha1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-a1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v30x\local_url_bbcode', + '\phpbb\db\migration\data\v30x\release_3_0_12', + '\phpbb\db\migration\data\v310\acp_style_components_module', + '\phpbb\db\migration\data\v310\allow_cdn', + '\phpbb\db\migration\data\v310\auth_provider_oauth', + '\phpbb\db\migration\data\v310\avatars', + '\phpbb\db\migration\data\v310\boardindex', + '\phpbb\db\migration\data\v310\config_db_text', + '\phpbb\db\migration\data\v310\forgot_password', + '\phpbb\db\migration\data\v310\mod_rewrite', + '\phpbb\db\migration\data\v310\mysql_fulltext_drop', + '\phpbb\db\migration\data\v310\namespaces', + '\phpbb\db\migration\data\v310\notifications_cron', + '\phpbb\db\migration\data\v310\notification_options_reconvert', + '\phpbb\db\migration\data\v310\plupload', + '\phpbb\db\migration\data\v310\signature_module_auth', + '\phpbb\db\migration\data\v310\softdelete_mcp_modules', + '\phpbb\db\migration\data\v310\teampage', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-a1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/alpha2.php b/phpBB/phpbb/db/migration/data/v310/alpha2.php new file mode 100644 index 0000000000..bfbcc4f6f5 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/alpha2.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class alpha2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-a2', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\alpha1', + '\phpbb\db\migration\data\v310\notifications_cron_p2', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-a2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/alpha3.php b/phpBB/phpbb/db/migration/data/v310/alpha3.php new file mode 100644 index 0000000000..bb0f904fd4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/alpha3.php @@ -0,0 +1,39 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class alpha3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-a3', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\alpha2', + '\phpbb\db\migration\data\v310\avatar_types', + '\phpbb\db\migration\data\v310\passwords', + '\phpbb\db\migration\data\v310\profilefield_types', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-a3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/auth_provider_oauth.php b/phpBB/phpbb/db/migration/data/v310/auth_provider_oauth.php new file mode 100644 index 0000000000..2d51bd53e4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/auth_provider_oauth.php @@ -0,0 +1,77 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class auth_provider_oauth extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_table_exists($this->table_prefix . 'auth_provider_oauth'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'oauth_tokens' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), // phpbb_users.user_id + 'session_id' => array('CHAR:32', ''), // phpbb_sessions.session_id used only when user_id not set + 'provider' => array('VCHAR', ''), // Name of the OAuth provider + 'oauth_token' => array('MTEXT', ''), // Serialized token + ), + 'KEYS' => array( + 'user_id' => array('INDEX', 'user_id'), + 'provider' => array('INDEX', 'provider'), + ), + ), + $this->table_prefix . 'oauth_accounts' => array( + 'COLUMNS' => array( + 'user_id' => array('UINT', 0), + 'provider' => array('VCHAR', ''), + 'oauth_provider_id' => array('TEXT_UNI', ''), + ), + 'PRIMARY_KEY' => array( + 'user_id', + 'provider', + ), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'oauth_tokens', + $this->table_prefix . 'oauth_accounts', + ), + ); + } + + public function update_data() + { + return array( + array('module.add', array( + 'ucp', + 'UCP_PROFILE', + array( + 'module_basename' => 'ucp_auth_link', + 'modes' => array('auth_link'), + ), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/auth_provider_oauth2.php b/phpBB/phpbb/db/migration/data/v310/auth_provider_oauth2.php new file mode 100644 index 0000000000..e9e726ae20 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/auth_provider_oauth2.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class auth_provider_oauth2 extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\auth_provider_oauth', + ); + } + + public function update_data() + { + return array( + array('custom', array( + array($this, 'update_auth_link_module_auth'), + )), + ); + } + + public function update_auth_link_module_auth() + { + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_auth = 'authmethod_oauth' + WHERE module_class = 'ucp' + AND module_basename = 'ucp_auth_link' + AND module_mode = 'auth_link' + AND module_auth = ''"; + $this->db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/avatar_types.php b/phpBB/phpbb/db/migration/data/v310/avatar_types.php new file mode 100644 index 0000000000..117e93239d --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/avatar_types.php @@ -0,0 +1,64 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class avatar_types extends \phpbb\db\migration\migration +{ + /** + * @var avatar type map + */ + protected $avatar_type_map = array( + AVATAR_UPLOAD => 'avatar.driver.upload', + AVATAR_REMOTE => 'avatar.driver.remote', + AVATAR_GALLERY => 'avatar.driver.local', + ); + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + '\phpbb\db\migration\data\v310\avatars', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_user_avatar_type'))), + array('custom', array(array($this, 'update_group_avatar_type'))), + ); + } + + public function update_user_avatar_type() + { + foreach ($this->avatar_type_map as $old => $new) + { + $sql = 'UPDATE ' . $this->table_prefix . "users + SET user_avatar_type = '$new' + WHERE user_avatar_type = '$old'"; + $this->db->sql_query($sql); + } + } + + public function update_group_avatar_type() + { + foreach ($this->avatar_type_map as $old => $new) + { + $sql = 'UPDATE ' . $this->table_prefix . "groups + SET group_avatar_type = '$new' + WHERE group_avatar_type = '$old'"; + $this->db->sql_query($sql); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/avatars.php b/phpBB/phpbb/db/migration/data/v310/avatars.php new file mode 100644 index 0000000000..9b03a8fa94 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/avatars.php @@ -0,0 +1,95 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class avatars extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + // Get current avatar type of guest user + $sql = 'SELECT user_avatar_type + FROM ' . $this->table_prefix . 'users + WHERE user_id = ' . ANONYMOUS; + $result = $this->db->sql_query($sql); + $backup_type = $this->db->sql_fetchfield('user_avatar_type'); + $this->db->sql_freeresult($result); + + // Try to set avatar type to string + $sql = 'UPDATE ' . $this->table_prefix . "users + SET user_avatar_type = 'avatar.driver.upload' + WHERE user_id = " . ANONYMOUS; + $this->db->sql_return_on_error(true); + $effectively_installed = $this->db->sql_query($sql); + $this->db->sql_return_on_error(); + + // Restore avatar type of guest user to previous state + $sql = 'UPDATE ' . $this->table_prefix . "users + SET user_avatar_type = '{$backup_type}' + WHERE user_id = " . ANONYMOUS; + $this->db->sql_query($sql); + + return $effectively_installed !== false; + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_avatar_type' => array('VCHAR:255', ''), + ), + $this->table_prefix . 'groups' => array( + 'group_avatar_type' => array('VCHAR:255', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_avatar_type' => array('TINT:2', ''), + ), + $this->table_prefix . 'groups' => array( + 'group_avatar_type' => array('TINT:2', ''), + ), + ), + ); + } + + public function update_data() + { + return array( + array('config.add', array('allow_avatar_gravatar', 0)), + array('custom', array(array($this, 'update_module_auth'))), + ); + } + + public function update_module_auth() + { + $sql = 'UPDATE ' . $this->table_prefix . "modules + SET module_auth = 'cfg_allow_avatar' + WHERE module_class = 'ucp' + AND module_basename = 'ucp_profile' + AND module_mode = 'avatar'"; + $this->db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/beta1.php b/phpBB/phpbb/db/migration/data/v310/beta1.php new file mode 100644 index 0000000000..9feba5235d --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/beta1.php @@ -0,0 +1,42 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class beta1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-b1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\alpha3', + '\phpbb\db\migration\data\v310\passwords_p2', + '\phpbb\db\migration\data\v310\postgres_fulltext_drop', + '\phpbb\db\migration\data\v310\profilefield_change_load_settings', + '\phpbb\db\migration\data\v310\profilefield_location', + '\phpbb\db\migration\data\v310\soft_delete_mod_convert2', + '\phpbb\db\migration\data\v310\ucp_popuppm_module', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-b1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/beta2.php b/phpBB/phpbb/db/migration/data/v310/beta2.php new file mode 100644 index 0000000000..d5e31ce4cb --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/beta2.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class beta2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-b2', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\beta1', + '\phpbb\db\migration\data\v310\acp_prune_users_module', + '\phpbb\db\migration\data\v310\profilefield_location_cleanup', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-b2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/beta3.php b/phpBB/phpbb/db/migration/data/v310/beta3.php new file mode 100644 index 0000000000..78c61e8e90 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/beta3.php @@ -0,0 +1,41 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class beta3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-b3', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\beta2', + '\phpbb\db\migration\data\v310\auth_provider_oauth2', + '\phpbb\db\migration\data\v310\board_contact_name', + '\phpbb\db\migration\data\v310\jquery_update2', + '\phpbb\db\migration\data\v310\live_searches_config', + '\phpbb\db\migration\data\v310\prune_shadow_topics', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-b3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/beta4.php b/phpBB/phpbb/db/migration/data/v310/beta4.php new file mode 100644 index 0000000000..e634785c38 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/beta4.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class beta4 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-b4', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\beta3', + '\phpbb\db\migration\data\v310\extensions_version_check_force_unstable', + '\phpbb\db\migration\data\v310\reset_missing_captcha_plugin', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-b4')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/board_contact_name.php b/phpBB/phpbb/db/migration/data/v310/board_contact_name.php new file mode 100644 index 0000000000..6f5188720b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/board_contact_name.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class board_contact_name extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['board_contact_name']); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\beta2'); + } + + public function update_data() + { + return array( + array('config.add', array('board_contact_name', '')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/boardindex.php b/phpBB/phpbb/db/migration/data/v310/boardindex.php new file mode 100644 index 0000000000..77a8558f21 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/boardindex.php @@ -0,0 +1,29 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class boardindex extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['board_index_text']); + } + + public function update_data() + { + return array( + array('config.add', array('board_index_text', '')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/bot_update.php b/phpBB/phpbb/db/migration/data/v310/bot_update.php new file mode 100644 index 0000000000..39b16c68f8 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/bot_update.php @@ -0,0 +1,150 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class bot_update extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\rc6'); + } + + public function update_data() + { + return array( + array('custom', array(array(&$this, 'update_bing_bot'))), + array('custom', array(array(&$this, 'update_bots'))), + ); + } + + public function update_bing_bot() + { + $bot_name = 'Bing [Bot]'; + $bot_name_clean = utf8_clean_string($bot_name); + + $sql = 'SELECT user_id + FROM ' . USERS_TABLE . " + WHERE username_clean = '" . $this->db->sql_escape($bot_name_clean) . "'"; + $result = $this->db->sql_query($sql); + $bing_already_added = (bool) $this->db->sql_fetchfield('user_id'); + $this->db->sql_freeresult($result); + + if (!$bing_already_added) + { + $bot_agent = 'bingbot/'; + $bot_ip = ''; + $sql = 'SELECT group_id, group_colour + FROM ' . GROUPS_TABLE . " + WHERE group_name = 'BOTS'"; + $result = $this->db->sql_query($sql); + $group_row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$group_row) + { + // default fallback, should never get here + $group_row['group_id'] = 6; + $group_row['group_colour'] = '9E8DA7'; + } + + if (!function_exists('user_add')) + { + include($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + + $user_row = array( + 'user_type' => USER_IGNORE, + 'group_id' => $group_row['group_id'], + 'username' => $bot_name, + 'user_regdate' => time(), + 'user_password' => '', + 'user_colour' => $group_row['group_colour'], + 'user_email' => '', + 'user_lang' => $this->config['default_lang'], + 'user_style' => $this->config['default_style'], + 'user_timezone' => 0, + 'user_dateformat' => $this->config['default_dateformat'], + 'user_allow_massemail' => 0, + ); + + $user_id = user_add($user_row); + + $sql = 'INSERT INTO ' . BOTS_TABLE . ' ' . $this->db->sql_build_array('INSERT', array( + 'bot_active' => 1, + 'bot_name' => (string) $bot_name, + 'user_id' => (int) $user_id, + 'bot_agent' => (string) $bot_agent, + 'bot_ip' => (string) $bot_ip, + )); + + $this->sql_query($sql); + } + } + + public function update_bots() + { + // Update bots + if (!function_exists('user_delete')) + { + include($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + + $bots_updates = array( + // Bot Deletions + 'NG-Search [Bot]' => false, + 'Nutch/CVS [Bot]' => false, + 'OmniExplorer [Bot]' => false, + 'Seekport [Bot]' => false, + 'Synoo [Bot]' => false, + 'WiseNut [Bot]' => false, + + // Bot Updates + // Bot name to bot user agent map + 'Baidu [Spider]' => 'Baiduspider', + 'Exabot [Bot]' => 'Exabot', + 'Voyager [Bot]' => 'voyager/', + 'W3C [Validator]' => 'W3C_Validator', + ); + + foreach ($bots_updates as $bot_name => $bot_agent) + { + $sql = 'SELECT user_id + FROM ' . USERS_TABLE . ' + WHERE user_type = ' . USER_IGNORE . " + AND username_clean = '" . $this->db->sql_escape(utf8_clean_string($bot_name)) . "'"; + $result = $this->db->sql_query($sql); + $bot_user_id = (int) $this->db->sql_fetchfield('user_id'); + $this->db->sql_freeresult($result); + + if ($bot_user_id) + { + if ($bot_agent === false) + { + $sql = 'DELETE FROM ' . BOTS_TABLE . " + WHERE user_id = $bot_user_id"; + $this->sql_query($sql); + + user_delete('retain', $bot_user_id); + } + else + { + $sql = 'UPDATE ' . BOTS_TABLE . " + SET bot_agent = '" . $this->db->sql_escape($bot_agent) . "' + WHERE user_id = $bot_user_id"; + $this->sql_query($sql); + } + } + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/captcha_plugins.php b/phpBB/phpbb/db/migration/data/v310/captcha_plugins.php new file mode 100644 index 0000000000..328c08f1ec --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/captcha_plugins.php @@ -0,0 +1,48 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class captcha_plugins extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc2', + ); + } + + public function update_data() + { + $captcha_plugin = $this->config['captcha_plugin']; + if (strpos($captcha_plugin, 'phpbb_captcha_') === 0) + { + $captcha_plugin = substr($captcha_plugin, strlen('phpbb_captcha_')); + } + else if (strpos($captcha_plugin, 'phpbb_') === 0) + { + $captcha_plugin = substr($captcha_plugin, strlen('phpbb_')); + } + + return array( + array('if', array( + (is_file($this->phpbb_root_path . 'phpbb/captcha/plugins/' . $captcha_plugin . '.' . $this->php_ext)), + array('config.update', array('captcha_plugin', 'core.captcha.plugins.' . $captcha_plugin)), + )), + array('if', array( + (!is_file($this->phpbb_root_path . 'phpbb/captcha/plugins/' . $captcha_plugin . '.' . $this->php_ext)), + array('config.update', array('captcha_plugin', 'core.captcha.plugins.nogd')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/config_db_text.php b/phpBB/phpbb/db/migration/data/v310/config_db_text.php new file mode 100644 index 0000000000..438883c438 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/config_db_text.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class config_db_text extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_table_exists($this->table_prefix . 'config_text'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'config_text' => array( + 'COLUMNS' => array( + 'config_name' => array('VCHAR', ''), + 'config_value' => array('MTEXT', ''), + ), + 'PRIMARY_KEY' => 'config_name', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'config_text', + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/contact_admin_acp_module.php b/phpBB/phpbb/db/migration/data/v310/contact_admin_acp_module.php new file mode 100644 index 0000000000..20bd547ac3 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/contact_admin_acp_module.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class contact_admin_acp_module extends \phpbb\db\migration\migration +{ + public function update_data() + { + return array( + array('module.add', array( + 'acp', + 'ACP_BOARD_CONFIGURATION', + array( + 'module_basename' => 'acp_contact', + 'modes' => array('contact'), + ), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/contact_admin_form.php b/phpBB/phpbb/db/migration/data/v310/contact_admin_form.php new file mode 100644 index 0000000000..5736369f1a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/contact_admin_form.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class contact_admin_form extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['contact_admin_form_enable']); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\config_db_text'); + } + + public function update_data() + { + return array( + array('config.add', array('contact_admin_form_enable', 1)), + array('custom', array(array($this, 'contact_admin_info'))), + ); + } + + public function contact_admin_info() + { + $text_config = new \phpbb\config\db_text($this->db, $this->table_prefix . 'config_text'); + $text_config->set_array(array( + 'contact_admin_info' => '', + 'contact_admin_info_uid' => '', + 'contact_admin_info_bitfield' => '', + 'contact_admin_info_flags' => OPTION_FLAG_BBCODE + OPTION_FLAG_SMILIES + OPTION_FLAG_LINKS, + )); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/dev.php b/phpBB/phpbb/db/migration/data/v310/dev.php new file mode 100644 index 0000000000..f037191c2a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/dev.php @@ -0,0 +1,415 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class dev extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return version_compare($this->config['version'], '3.1.0-dev', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\extensions', + '\phpbb\db\migration\data\v310\style_update_p2', + '\phpbb\db\migration\data\v310\timezone_p2', + '\phpbb\db\migration\data\v310\reported_posts_display', + '\phpbb\db\migration\data\v310\migrations_table', + ); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'groups' => array( + 'group_teampage' => array('UINT', 0, 'after' => 'group_legend'), + ), + $this->table_prefix . 'profile_fields' => array( + 'field_show_on_pm' => array('BOOL', 0), + ), + $this->table_prefix . 'styles' => array( + 'style_path' => array('VCHAR:100', ''), + 'bbcode_bitfield' => array('VCHAR:255', 'kNg='), + 'style_parent_id' => array('UINT:4', 0), + 'style_parent_tree' => array('TEXT', ''), + ), + $this->table_prefix . 'reports' => array( + 'reported_post_text' => array('MTEXT_UNI', ''), + 'reported_post_uid' => array('VCHAR:8', ''), + 'reported_post_bitfield' => array('VCHAR:255', ''), + ), + ), + 'change_columns' => array( + $this->table_prefix . 'groups' => array( + 'group_legend' => array('UINT', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'groups' => array( + 'group_teampage', + ), + $this->table_prefix . 'profile_fields' => array( + 'field_show_on_pm', + ), + $this->table_prefix . 'styles' => array( + 'style_path', + 'bbcode_bitfield', + 'style_parent_id', + 'style_parent_tree', + ), + $this->table_prefix . 'reports' => array( + 'reported_post_text', + 'reported_post_uid', + 'reported_post_bitfield', + ), + ), + ); + } + + public function update_data() + { + return array( + array('if', array( + (strpos('phpbb_search_', $this->config['search_type']) !== 0), + array('config.update', array('search_type', 'phpbb_search_' . $this->config['search_type'])), + )), + + array('config.add', array('fulltext_postgres_ts_name', 'simple')), + array('config.add', array('fulltext_postgres_min_word_len', 4)), + array('config.add', array('fulltext_postgres_max_word_len', 254)), + array('config.add', array('fulltext_sphinx_stopwords', 0)), + array('config.add', array('fulltext_sphinx_indexer_mem_limit', 512)), + + array('config.add', array('load_jquery_cdn', 0)), + array('config.add', array('load_jquery_url', '//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js')), + + array('config.add', array('use_system_cron', 0)), + + array('config.add', array('legend_sort_groupname', 0)), + array('config.add', array('teampage_forums', 1)), + array('config.add', array('teampage_memberships', 1)), + + array('config.add', array('load_cpf_pm', 0)), + + array('config.add', array('display_last_subject', 1)), + + array('config.add', array('assets_version', 1)), + + array('config.add', array('site_home_url', '')), + array('config.add', array('site_home_text', '')), + + array('permission.add', array('u_chgprofileinfo', true, 'u_sig')), + + array('module.add', array( + 'acp', + 'ACP_GROUPS', + array( + 'module_basename' => 'acp_groups', + 'modes' => array('position'), + ), + )), + array('module.add', array( + 'acp', + 'ACP_ATTACHMENTS', + array( + 'module_basename' => 'acp_attachments', + 'modes' => array('manage'), + ), + )), + array('module.add', array( + 'acp', + 'ACP_STYLE_MANAGEMENT', + array( + 'module_basename' => 'acp_styles', + 'modes' => array('install', 'cache'), + ), + )), + array('module.add', array( + 'ucp', + 'UCP_PROFILE', + array( + 'module_basename' => 'ucp_profile', + 'modes' => array('autologin_keys'), + ), + )), + // Module will be renamed later + array('module.add', array( + 'acp', + 'ACP_CAT_STYLES', + 'ACP_LANGUAGE' + )), + + array('module.remove', array( + 'acp', + false, + 'ACP_TEMPLATES', + )), + array('module.remove', array( + 'acp', + false, + 'ACP_THEMES', + )), + array('module.remove', array( + 'acp', + false, + 'ACP_IMAGESETS', + )), + + array('custom', array(array($this, 'rename_module_basenames'))), + array('custom', array(array($this, 'rename_styles_module'))), + array('custom', array(array($this, 'add_group_teampage'))), + array('custom', array(array($this, 'update_group_legend'))), + array('custom', array(array($this, 'localise_global_announcements'))), + array('custom', array(array($this, 'update_ucp_pm_basename'))), + array('custom', array(array($this, 'update_ucp_profile_auth'))), + array('custom', array(array($this, 'move_customise_modules'))), + + array('config.update', array('version', '3.1.0-dev')), + ); + } + + public function move_customise_modules() + { + // Move language management to new location in the Customise tab + // First get language module id + $sql = 'SELECT module_id FROM ' . MODULES_TABLE . " + WHERE module_basename = 'acp_language'"; + $result = $this->db->sql_query($sql); + $language_module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + // Next get language management module id of the one just created + $sql = 'SELECT module_id FROM ' . MODULES_TABLE . " + WHERE module_langname = 'ACP_LANGUAGE'"; + $result = $this->db->sql_query($sql); + $language_management_module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + if (!class_exists('acp_modules')) + { + include($this->phpbb_root_path . 'includes/acp/acp_modules.' . $this->php_ext); + } + // acp_modules calls adm_back_link, which is undefined at this point + if (!function_exists('adm_back_link')) + { + include($this->phpbb_root_path . 'includes/functions_acp.' . $this->php_ext); + } + $module_manager = new \acp_modules(); + $module_manager->module_class = 'acp'; + $module_manager->move_module($language_module_id, $language_management_module_id); + } + + public function update_ucp_pm_basename() + { + $sql = 'SELECT module_id, module_basename + FROM ' . MODULES_TABLE . " + WHERE module_basename <> 'ucp_pm' AND + module_langname='UCP_PM'"; + $result = $this->db->sql_query_limit($sql, 1); + + if ($row = $this->db->sql_fetchrow($result)) + { + // This update is still not applied. Applying it + + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_basename = 'ucp_pm' + WHERE module_id = " . (int) $row['module_id']; + + $this->sql_query($sql); + } + $this->db->sql_freeresult($result); + } + + public function update_ucp_profile_auth() + { + // Update the auth setting for the module + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_auth = 'acl_u_chgprofileinfo' + WHERE module_class = 'ucp' + AND module_basename = 'ucp_profile' + AND module_mode = 'profile_info'"; + $this->sql_query($sql); + } + + public function rename_styles_module() + { + // Rename styles module to Customise + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_langname = 'ACP_CAT_CUSTOMISE' + WHERE module_langname = 'ACP_CAT_STYLES'"; + $this->sql_query($sql); + } + + public function rename_module_basenames() + { + // rename all module basenames to full classname + $sql = 'SELECT module_id, module_basename, module_class + FROM ' . MODULES_TABLE; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $module_id = (int) $row['module_id']; + unset($row['module_id']); + + if (!empty($row['module_basename']) && !empty($row['module_class'])) + { + // all the class names start with class name or with phpbb_ for auto loading + if (strpos($row['module_basename'], $row['module_class'] . '_') !== 0 && + strpos($row['module_basename'], 'phpbb_') !== 0) + { + $row['module_basename'] = $row['module_class'] . '_' . $row['module_basename']; + + $sql_update = $this->db->sql_build_array('UPDATE', $row); + + $sql = 'UPDATE ' . MODULES_TABLE . ' + SET ' . $sql_update . ' + WHERE module_id = ' . $module_id; + $this->sql_query($sql); + } + } + } + + $this->db->sql_freeresult($result); + } + + public function add_group_teampage() + { + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_teampage = 1 + WHERE group_type = ' . GROUP_SPECIAL . " + AND group_name = 'ADMINISTRATORS'"; + $this->sql_query($sql); + + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_teampage = 2 + WHERE group_type = ' . GROUP_SPECIAL . " + AND group_name = 'GLOBAL_MODERATORS'"; + $this->sql_query($sql); + } + + public function update_group_legend() + { + $sql = 'SELECT group_id + FROM ' . GROUPS_TABLE . ' + WHERE group_legend = 1 + ORDER BY group_name ASC'; + $result = $this->db->sql_query($sql); + + $next_legend = 1; + while ($row = $this->db->sql_fetchrow($result)) + { + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_legend = ' . $next_legend . ' + WHERE group_id = ' . (int) $row['group_id']; + $this->sql_query($sql); + + $next_legend++; + } + $this->db->sql_freeresult($result); + } + + public function localise_global_announcements() + { + // Localise Global Announcements + $sql = 'SELECT topic_id, topic_approved, (topic_replies + 1) AS topic_posts, topic_last_post_id, topic_last_post_subject, topic_last_post_time, topic_last_poster_id, topic_last_poster_name, topic_last_poster_colour + FROM ' . TOPICS_TABLE . ' + WHERE forum_id = 0 + AND topic_type = ' . POST_GLOBAL; + $result = $this->db->sql_query($sql); + + $global_announcements = $update_lastpost_data = array(); + $update_lastpost_data['forum_last_post_time'] = 0; + $update_forum_data = array( + 'forum_posts' => 0, + 'forum_topics' => 0, + 'forum_topics_real' => 0, + ); + + while ($row = $this->db->sql_fetchrow($result)) + { + $global_announcements[] = (int) $row['topic_id']; + + $update_forum_data['forum_posts'] += (int) $row['topic_posts']; + $update_forum_data['forum_topics_real']++; + if ($row['topic_approved']) + { + $update_forum_data['forum_topics']++; + } + + if ($update_lastpost_data['forum_last_post_time'] < $row['topic_last_post_time']) + { + $update_lastpost_data = array( + 'forum_last_post_id' => (int) $row['topic_last_post_id'], + 'forum_last_post_subject' => $row['topic_last_post_subject'], + 'forum_last_post_time' => (int) $row['topic_last_post_time'], + 'forum_last_poster_id' => (int) $row['topic_last_poster_id'], + 'forum_last_poster_name' => $row['topic_last_poster_name'], + 'forum_last_poster_colour' => $row['topic_last_poster_colour'], + ); + } + } + $this->db->sql_freeresult($result); + + if (!empty($global_announcements)) + { + // Update the post/topic-count for the forum and the last-post if needed + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE . ' + WHERE forum_type = ' . FORUM_POST; + $result = $this->db->sql_query_limit($sql, 1); + $ga_forum_id = $this->db->sql_fetchfield('forum_id'); + $this->db->sql_freeresult($result); + + $sql = 'SELECT forum_last_post_time + FROM ' . FORUMS_TABLE . ' + WHERE forum_id = ' . $ga_forum_id; + $result = $this->db->sql_query($sql); + $lastpost = (int) $this->db->sql_fetchfield('forum_last_post_time'); + $this->db->sql_freeresult($result); + + $sql_update = 'forum_posts = forum_posts + ' . $update_forum_data['forum_posts'] . ', '; + $sql_update .= 'forum_topics_real = forum_topics_real + ' . $update_forum_data['forum_topics_real'] . ', '; + $sql_update .= 'forum_topics = forum_topics + ' . $update_forum_data['forum_topics']; + if ($lastpost < $update_lastpost_data['forum_last_post_time']) + { + $sql_update .= ', ' . $this->db->sql_build_array('UPDATE', $update_lastpost_data); + } + + $sql = 'UPDATE ' . FORUMS_TABLE . ' + SET ' . $sql_update . ' + WHERE forum_id = ' . $ga_forum_id; + $this->sql_query($sql); + + // Update some forum_ids + $table_ary = array(TOPICS_TABLE, POSTS_TABLE, LOG_TABLE, DRAFTS_TABLE, TOPICS_TRACK_TABLE); + foreach ($table_ary as $table) + { + $sql = "UPDATE $table + SET forum_id = $ga_forum_id + WHERE " . $this->db->sql_in_set('topic_id', $global_announcements); + $this->sql_query($sql); + } + unset($table_ary); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/extensions.php b/phpBB/phpbb/db/migration/data/v310/extensions.php new file mode 100644 index 0000000000..3171435482 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/extensions.php @@ -0,0 +1,75 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class extensions extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_table_exists($this->table_prefix . 'ext'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'ext' => array( + 'COLUMNS' => array( + 'ext_name' => array('VCHAR', ''), + 'ext_active' => array('BOOL', 0), + 'ext_state' => array('TEXT', ''), + ), + 'KEYS' => array( + 'ext_name' => array('UNIQUE', 'ext_name'), + ), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'ext', + ), + ); + } + + public function update_data() + { + return array( + // Module will be renamed later + array('module.add', array( + 'acp', + 'ACP_CAT_STYLES', + 'ACP_EXTENSION_MANAGEMENT' + )), + array('module.add', array( + 'acp', + 'ACP_EXTENSION_MANAGEMENT', + array( + 'module_basename' => 'acp_extensions', + 'modes' => array('main'), + ), + )), + array('permission.add', array('a_extensions', true, 'a_styles')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/extensions_version_check_force_unstable.php b/phpBB/phpbb/db/migration/data/v310/extensions_version_check_force_unstable.php new file mode 100644 index 0000000000..1d6276f484 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/extensions_version_check_force_unstable.php @@ -0,0 +1,29 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class extensions_version_check_force_unstable extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_data() + { + return array( + array('config.add', array('extension_force_unstable', false)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/forgot_password.php b/phpBB/phpbb/db/migration/data/v310/forgot_password.php new file mode 100644 index 0000000000..362457cf23 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/forgot_password.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class forgot_password extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['allow_password_reset']); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_data() + { + return array( + array('config.add', array('allow_password_reset', 1)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/gold.php b/phpBB/phpbb/db/migration/data/v310/gold.php new file mode 100644 index 0000000000..188851f87d --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/gold.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class gold extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc6', + '\phpbb\db\migration\data\v310\bot_update', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/jquery_update.php b/phpBB/phpbb/db/migration/data/v310/jquery_update.php new file mode 100644 index 0000000000..8011331e80 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/jquery_update.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class jquery_update extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->config['load_jquery_url'] !== '//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'; + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + ); + } + + public function update_data() + { + return array( + array('config.update', array('load_jquery_url', '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js')), + ); + } + +} diff --git a/phpBB/phpbb/db/migration/data/v310/jquery_update2.php b/phpBB/phpbb/db/migration/data/v310/jquery_update2.php new file mode 100644 index 0000000000..4061be5940 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/jquery_update2.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class jquery_update2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->config['load_jquery_url'] !== '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'; + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\jquery_update', + ); + } + + public function update_data() + { + return array( + array('config.update', array('load_jquery_url', '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js')), + ); + } + +} diff --git a/phpBB/phpbb/db/migration/data/v310/live_searches_config.php b/phpBB/phpbb/db/migration/data/v310/live_searches_config.php new file mode 100644 index 0000000000..3d87e04ac2 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/live_searches_config.php @@ -0,0 +1,29 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class live_searches_config extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['allow_live_searches']); + } + + public function update_data() + { + return array( + array('config.add', array('allow_live_searches', '1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/migrations_table.php b/phpBB/phpbb/db/migration/data/v310/migrations_table.php new file mode 100644 index 0000000000..48508b05c2 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/migrations_table.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class migrations_table extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_table_exists($this->table_prefix . 'migrations'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'migrations' => array( + 'COLUMNS' => array( + 'migration_name' => array('VCHAR', ''), + 'migration_depends_on' => array('TEXT', ''), + 'migration_schema_done' => array('BOOL', 0), + 'migration_data_done' => array('BOOL', 0), + 'migration_data_state' => array('TEXT', ''), + 'migration_start_time' => array('TIMESTAMP', 0), + 'migration_end_time' => array('TIMESTAMP', 0), + ), + 'PRIMARY_KEY' => 'migration_name', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'migrations', + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/mod_rewrite.php b/phpBB/phpbb/db/migration/data/v310/mod_rewrite.php new file mode 100644 index 0000000000..85e479db59 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/mod_rewrite.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class mod_rewrite extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + ); + } + + public function update_data() + { + return array( + array('config.add', array('enable_mod_rewrite', '0')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/mysql_fulltext_drop.php b/phpBB/phpbb/db/migration/data/v310/mysql_fulltext_drop.php new file mode 100644 index 0000000000..e04a705c91 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/mysql_fulltext_drop.php @@ -0,0 +1,80 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class mysql_fulltext_drop extends \phpbb\db\migration\migration +{ + protected $indexes; + + public function effectively_installed() + { + // This migration is irrelevant for all non-MySQL DBMSes. + if (strpos($this->db->get_sql_layer(), 'mysql') === false) + { + return true; + } + + $this->find_indexes_to_drop(); + return empty($this->indexes); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + ); + } + + public function update_schema() + { + if (empty($this->indexes)) + { + return array(); + } + + /* + * Drop FULLTEXT indexes related to MySQL fulltext search. + * Doing so is equivalent to dropping the search index from the ACP. + * Possibly time-consuming recreation of the search index (i.e. + * FULLTEXT indexes) is left as a task to the admin to not + * unnecessarily stall the upgrade process. The new search index will + * then require about 40% less table space (also see PHPBB3-11621). + */ + return array( + 'drop_keys' => array( + $this->table_prefix . 'posts' => $this->indexes, + ), + ); + } + + public function find_indexes_to_drop() + { + if ($this->indexes !== null) + { + return $this->indexes; + } + + $this->indexes = array(); + $potential_keys = array('post_subject', 'post_text', 'post_content'); + foreach ($potential_keys as $key) + { + if ($this->db_tools->sql_index_exists($this->table_prefix . 'posts', $key)) + { + $this->indexes[] = $key; + } + } + + return $this->indexes; + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/namespaces.php b/phpBB/phpbb/db/migration/data/v310/namespaces.php new file mode 100644 index 0000000000..2a4935395e --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/namespaces.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class namespaces extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + ); + } + + public function update_data() + { + return array( + array('if', array( + (preg_match('#^phpbb_search_#', $this->config['search_type'])), + array('config.update', array('search_type', str_replace('phpbb_search_', '\\phpbb\\search\\', $this->config['search_type']))), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/notification_options_reconvert.php b/phpBB/phpbb/db/migration/data/v310/notification_options_reconvert.php new file mode 100644 index 0000000000..d43d432dd9 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/notification_options_reconvert.php @@ -0,0 +1,142 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class notification_options_reconvert extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\notifications_schema_fix'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'purge_notifications'))), + array('custom', array(array($this, 'convert_notifications'))), + ); + } + + public function purge_notifications() + { + $sql = 'DELETE FROM ' . $this->table_prefix . 'user_notifications'; + $this->sql_query($sql); + } + + public function convert_notifications($start) + { + $insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, $this->table_prefix . 'user_notifications'); + + return $this->perform_conversion($insert_buffer, $start); + } + + /** + * Perform the conversion (separate for testability) + * + * @param \phpbb\db\sql_insert_buffer $insert_buffer + * @param int $start Start of staggering step + * @return mixed int start of the next step, null if the end was reached + */ + public function perform_conversion(\phpbb\db\sql_insert_buffer $insert_buffer, $start) + { + $limit = 250; + $converted_users = 0; + $start = $start ?: 0; + + $sql = 'SELECT user_id, user_notify_type, user_notify_pm + FROM ' . $this->table_prefix . 'users + ORDER BY user_id'; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $converted_users++; + $notification_methods = array(); + + // In-board notification + $notification_methods[] = ''; + + if ($row['user_notify_type'] == NOTIFY_EMAIL || $row['user_notify_type'] == NOTIFY_BOTH) + { + $notification_methods[] = 'email'; + } + + if ($row['user_notify_type'] == NOTIFY_IM || $row['user_notify_type'] == NOTIFY_BOTH) + { + $notification_methods[] = 'jabber'; + } + + // Notifications for posts + foreach (array('post', 'topic') as $item_type) + { + $this->add_method_rows( + $insert_buffer, + $item_type, + 0, + $row['user_id'], + $notification_methods + ); + } + + if ($row['user_notify_pm']) + { + // Notifications for private messages + // User either gets all methods or no method + $this->add_method_rows( + $insert_buffer, + 'pm', + 0, + $row['user_id'], + $notification_methods + ); + } + } + $this->db->sql_freeresult($result); + + $insert_buffer->flush(); + + if ($converted_users < $limit) + { + // No more users left, we are done... + return; + } + + return $start + $limit; + } + + /** + * Insert method rows to DB + * + * @param \phpbb\db\sql_insert_buffer $insert_buffer + * @param string $item_type + * @param int $item_id + * @param int $user_id + * @param string $methods + */ + protected function add_method_rows(\phpbb\db\sql_insert_buffer $insert_buffer, $item_type, $item_id, $user_id, array $methods) + { + $row_base = array( + 'item_type' => $item_type, + 'item_id' => (int) $item_id, + 'user_id' => (int) $user_id, + 'notify' => 1 + ); + + foreach ($methods as $method) + { + $row_base['method'] = $method; + $insert_buffer->insert($row_base); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/notifications.php b/phpBB/phpbb/db/migration/data/v310/notifications.php new file mode 100644 index 0000000000..f4d012b5ac --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/notifications.php @@ -0,0 +1,102 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class notifications extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_table_exists($this->table_prefix . 'notifications'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'notification_types' => array( + 'COLUMNS' => array( + 'notification_type' => array('VCHAR:255', ''), + 'notification_type_enabled' => array('BOOL', 1), + ), + 'PRIMARY_KEY' => array('notification_type', 'notification_type_enabled'), + ), + $this->table_prefix . 'notifications' => array( + 'COLUMNS' => array( + 'notification_id' => array('UINT', null, 'auto_increment'), + 'item_type' => array('VCHAR:255', ''), + 'item_id' => array('UINT', 0), + 'item_parent_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'notification_read' => array('BOOL', 0), + 'notification_time' => array('TIMESTAMP', 1), + 'notification_data' => array('TEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'notification_id', + 'KEYS' => array( + 'item_ident' => array('INDEX', array('item_type', 'item_id')), + 'user' => array('INDEX', array('user_id', 'notification_read')), + ), + ), + $this->table_prefix . 'user_notifications' => array( + 'COLUMNS' => array( + 'item_type' => array('VCHAR:255', ''), + 'item_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'method' => array('VCHAR:255', ''), + 'notify' => array('BOOL', 1), + ), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'notification_types', + $this->table_prefix . 'notifications', + $this->table_prefix . 'user_notifications', + ), + ); + } + + public function update_data() + { + return array( + array('module.add', array( + 'ucp', + 'UCP_MAIN', + array( + 'module_basename' => 'ucp_notifications', + 'modes' => array('notification_list'), + ), + )), + array('module.add', array( + 'ucp', + 'UCP_PREFS', + array( + 'module_basename' => 'ucp_notifications', + 'modes' => array('notification_options'), + ), + )), + array('config.add', array('load_notifications', 1)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/notifications_cron.php b/phpBB/phpbb/db/migration/data/v310/notifications_cron.php new file mode 100644 index 0000000000..ba600f7bf5 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/notifications_cron.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class notifications_cron extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\notifications'); + } + + public function update_data() + { + return array( + array('config.add', array('read_notification_expire_days', 30)), + array('config.add', array('read_notification_last_gc', 0)), // last run + array('config.add', array('read_notification_gc', (60 * 60 * 24))), // seconds between run; 1 day + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/notifications_cron_p2.php b/phpBB/phpbb/db/migration/data/v310/notifications_cron_p2.php new file mode 100644 index 0000000000..263584b343 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/notifications_cron_p2.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class notifications_cron_p2 extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\notifications_cron'); + } + + public function update_data() + { + return array( + // Make read_notification_last_gc dynamic. + array('config.remove', array('read_notification_last_gc')), + array('config.add', array('read_notification_last_gc', 0, 1)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/notifications_schema_fix.php b/phpBB/phpbb/db/migration/data/v310/notifications_schema_fix.php new file mode 100644 index 0000000000..21a39a7c91 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/notifications_schema_fix.php @@ -0,0 +1,98 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class notifications_schema_fix extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\notifications'); + } + + public function update_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'notification_types', + $this->table_prefix . 'notifications', + ), + 'add_tables' => array( + $this->table_prefix . 'notification_types' => array( + 'COLUMNS' => array( + 'notification_type_id' => array('USINT', null, 'auto_increment'), + 'notification_type_name' => array('VCHAR:255', ''), + 'notification_type_enabled' => array('BOOL', 1), + ), + 'PRIMARY_KEY' => array('notification_type_id'), + 'KEYS' => array( + 'type' => array('UNIQUE', array('notification_type_name')), + ), + ), + $this->table_prefix . 'notifications' => array( + 'COLUMNS' => array( + 'notification_id' => array('UINT:10', null, 'auto_increment'), + 'notification_type_id' => array('USINT', 0), + 'item_id' => array('UINT', 0), + 'item_parent_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'notification_read' => array('BOOL', 0), + 'notification_time' => array('TIMESTAMP', 1), + 'notification_data' => array('TEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'notification_id', + 'KEYS' => array( + 'item_ident' => array('INDEX', array('notification_type_id', 'item_id')), + 'user' => array('INDEX', array('user_id', 'notification_read')), + ), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'notification_types', + $this->table_prefix . 'notifications', + ), + 'add_tables' => array( + $this->table_prefix . 'notification_types' => array( + 'COLUMNS' => array( + 'notification_type' => array('VCHAR:255', ''), + 'notification_type_enabled' => array('BOOL', 1), + ), + 'PRIMARY_KEY' => array('notification_type', 'notification_type_enabled'), + ), + $this->table_prefix . 'notifications' => array( + 'COLUMNS' => array( + 'notification_id' => array('UINT', null, 'auto_increment'), + 'item_type' => array('VCHAR:255', ''), + 'item_id' => array('UINT', 0), + 'item_parent_id' => array('UINT', 0), + 'user_id' => array('UINT', 0), + 'notification_read' => array('BOOL', 0), + 'notification_time' => array('TIMESTAMP', 1), + 'notification_data' => array('TEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'notification_id', + 'KEYS' => array( + 'item_ident' => array('INDEX', array('item_type', 'item_id')), + 'user' => array('INDEX', array('user_id', 'notification_read')), + ), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/notifications_use_full_name.php b/phpBB/phpbb/db/migration/data/v310/notifications_use_full_name.php new file mode 100644 index 0000000000..112c1e85e8 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/notifications_use_full_name.php @@ -0,0 +1,184 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class notifications_use_full_name extends \phpbb\db\migration\migration +{ + protected $notification_types = array( + 'admin_activate_user', + 'approve_post', + 'approve_topic', + 'bookmark', + 'disapprove_post', + 'disapprove_topic', + 'group_request', + 'group_request_approved', + 'pm', + 'post', + 'post_in_queue', + 'quote', + 'report_pm', + 'report_pm_closed', + 'report_post', + 'report_post_closed', + 'topic', + 'topic_in_queue'); + + protected $notification_methods = array( + 'email', + 'jabber', + ); + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\rc3'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_notifications_name'))), + array('custom', array(array($this, 'update_notifications_method_name'))), + ); + } + + public function revert_data() + { + return array( + array('custom', array(array($this, 'revert_notifications_name'))), + array('custom', array(array($this, 'revert_notifications_method_name'))), + ); + } + + public function update_notifications_method_name() + { + foreach ($this->notification_methods as $notification_method) + { + $sql = 'UPDATE ' . USER_NOTIFICATIONS_TABLE . " + SET method = 'notification.method.{$notification_method}' + WHERE method = '{$notification_method}'"; + $this->db->sql_query($sql); + } + } + + public function revert_notifications_method_name() + { + foreach ($this->notification_methods as $notification_method) + { + $sql = 'UPDATE ' . USER_NOTIFICATIONS_TABLE . " + SET method = '{$notification_method}' + WHERE method = 'notification.method.{$notification_method}'"; + $this->db->sql_query($sql); + } + } + + public function update_notifications_name() + { + $sql = 'UPDATE ' . NOTIFICATION_TYPES_TABLE . ' + SET notification_type_enabled = 0 + WHERE ' . $this->db->sql_in_set('notification_type_name', $this->notification_types, true); + $this->db->sql_query($sql); + + foreach ($this->notification_types as $notification_type) + { + $sql = 'SELECT notification_type_id + FROM ' . NOTIFICATION_TYPES_TABLE . " + WHERE notification_type_name = 'notification.type.{$notification_type}'"; + $result = $this->db->sql_query($sql); + $new_type_id = (int) $this->db->sql_fetchfield('notification_type_id'); + $this->db->sql_freeresult($result); + + if ($new_type_id) + { + // New type name already exists, + // so we delete the old type and update the type id of existing entries. + $sql = 'SELECT notification_type_id + FROM ' . NOTIFICATION_TYPES_TABLE . " + WHERE notification_type_name = '{$notification_type}'"; + $result = $this->db->sql_query($sql); + $old_type_id = (int) $this->db->sql_fetchfield('notification_type_id'); + $this->db->sql_freeresult($result); + + $sql = 'UPDATE ' . NOTIFICATIONS_TABLE . ' + SET notification_type_id = ' . (int) $new_type_id . ' + WHERE notification_type_id = ' . (int) $old_type_id; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . NOTIFICATION_TYPES_TABLE . " + WHERE notification_type_name = '{$notification_type}'"; + $this->db->sql_query($sql); + } + else + { + // Otherwise we just update the name + $sql = 'UPDATE ' . NOTIFICATION_TYPES_TABLE . " + SET notification_type_name = 'notification.type.{$notification_type}' + WHERE notification_type_name = '{$notification_type}'"; + $this->db->sql_query($sql); + } + + $sql = 'UPDATE ' . USER_NOTIFICATIONS_TABLE . " + SET item_type = 'notification.type.{$notification_type}' + WHERE item_type = '{$notification_type}'"; + $this->db->sql_query($sql); + } + } + + public function revert_notifications_name() + { + foreach ($this->notification_types as $notification_type) + { + $sql = 'SELECT notification_type_id + FROM ' . NOTIFICATION_TYPES_TABLE . " + WHERE notification_type_name = '{$notification_type}'"; + $result = $this->db->sql_query($sql); + $new_type_id = (int) $this->db->sql_fetchfield('notification_type_id'); + $this->db->sql_freeresult($result); + + if ($new_type_id) + { + // New type name already exists, + // so we delete the old type and update the type id of existing entries. + $sql = 'SELECT notification_type_id + FROM ' . NOTIFICATION_TYPES_TABLE . " + WHERE notification_type_name = 'notification.type.{$notification_type}'"; + $result = $this->db->sql_query($sql); + $old_type_id = (int) $this->db->sql_fetchfield('notification_type_id'); + $this->db->sql_freeresult($result); + + $sql = 'UPDATE ' . NOTIFICATIONS_TABLE . ' + SET notification_type_id = ' . (int) $new_type_id . ' + WHERE notification_type_id = ' . (int) $old_type_id; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . NOTIFICATION_TYPES_TABLE . " + WHERE notification_type_name = 'notification.type.{$notification_type}'"; + $this->db->sql_query($sql); + } + else + { + // Otherwise we just update the name + $sql = 'UPDATE ' . NOTIFICATION_TYPES_TABLE . " + SET notification_type_name = '{$notification_type}' + WHERE notification_type_name = 'notification.type.{$notification_type}'"; + $this->db->sql_query($sql); + } + + $sql = 'UPDATE ' . USER_NOTIFICATIONS_TABLE . " + SET item_type = '{$notification_type}' + WHERE item_type = 'notification.type.{$notification_type}'"; + $this->db->sql_query($sql); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/passwords.php b/phpBB/phpbb/db/migration/data/v310/passwords.php new file mode 100644 index 0000000000..adee44147f --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/passwords.php @@ -0,0 +1,50 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class passwords extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_password' => array('VCHAR:255', ''), + ), + $this->table_prefix . 'forums' => array( + 'forum_password' => array('VCHAR:255', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_password' => array('VCHAR:40', ''), + ), + $this->table_prefix . 'forums' => array( + 'forum_password' => array('VCHAR:40', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/passwords_convert_p1.php b/phpBB/phpbb/db/migration/data/v310/passwords_convert_p1.php new file mode 100644 index 0000000000..295f2d2a14 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/passwords_convert_p1.php @@ -0,0 +1,81 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class passwords_convert_p1 extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\passwords_p2'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_passwords'))), + ); + } + + public function update_passwords($start) + { + // Nothing to do if user_pass_convert column doesn't exist + if (!$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_pass_convert')) + { + return; + } + + $start = (int) $start; + $limit = 1000; + $converted_users = 0; + + $sql = 'SELECT user_password, user_id + FROM ' . $this->table_prefix . 'users + WHERE user_pass_convert = 1 + ORDER BY user_id'; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + $update_users = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $converted_users++; + + $user_id = (int) $row['user_id']; + // Only prefix passwords without proper prefix + if (!isset($update_users[$user_id]) && !preg_match('#^\$([a-zA-Z0-9\\\]*?)\$#', $row['user_password'])) + { + // Use $CP$ prefix for passwords that need to + // be converted and set pass convert to false. + $update_users[$user_id] = '$CP$' . $row['user_password']; + } + } + $this->db->sql_freeresult($result); + + foreach ($update_users as $user_id => $user_password) + { + $sql = 'UPDATE ' . $this->table_prefix . "users + SET user_password = '" . $this->db->sql_escape($user_password) . "' + WHERE user_id = $user_id"; + $this->sql_query($sql); + } + + if ($converted_users < $limit) + { + // There are no more users to be converted + return; + } + + // There are still more users to query, return the next start value + return $start + $limit; + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/passwords_convert_p2.php b/phpBB/phpbb/db/migration/data/v310/passwords_convert_p2.php new file mode 100644 index 0000000000..26a99184a6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/passwords_convert_p2.php @@ -0,0 +1,49 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class passwords_convert_p2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_pass_convert'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\passwords_convert_p1'); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_pass_convert', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_pass_convert' => array('BOOL', 0, 'after' => 'user_passchg'), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/passwords_p2.php b/phpBB/phpbb/db/migration/data/v310/passwords_p2.php new file mode 100644 index 0000000000..afc7ba2813 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/passwords_p2.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class passwords_p2 extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\passwords'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_newpasswd' => array('VCHAR:255', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_newpasswd' => array('VCHAR:40', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/plupload.php b/phpBB/phpbb/db/migration/data/v310/plupload.php new file mode 100644 index 0000000000..69367f86a9 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/plupload.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class plupload extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return isset($this->config['plupload_last_gc']) && + isset($this->config['plupload_salt']); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_data() + { + return array( + array('config.add', array('plupload_last_gc', 0)), + array('config.add', array('plupload_salt', unique_id())), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/postgres_fulltext_drop.php b/phpBB/phpbb/db/migration/data/v310/postgres_fulltext_drop.php new file mode 100644 index 0000000000..3457c19478 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/postgres_fulltext_drop.php @@ -0,0 +1,80 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class postgres_fulltext_drop extends \phpbb\db\migration\migration +{ + protected $indexes; + + public function effectively_installed() + { + // This migration is irrelevant for all non-PostgreSQL DBMSes. + if (strpos($this->db->get_sql_layer(), 'postgres') === false) + { + return true; + } + + $this->find_indexes_to_drop(); + return empty($this->indexes); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + ); + } + + public function update_schema() + { + if (empty($this->indexes)) + { + return array(); + } + + /* + * Drop FULLTEXT indexes related to PostgreSQL fulltext search. + * Doing so is equivalent to dropping the search index from the ACP. + * Possibly time-consuming recreation of the search index (i.e. + * FULLTEXT indexes) is left as a task to the admin to not + * unnecessarily stall the upgrade process. The new search index will + * then require about 40% less table space (also see PHPBB3-11040). + */ + return array( + 'drop_keys' => array( + $this->table_prefix . 'posts' => $this->indexes, + ), + ); + } + + public function find_indexes_to_drop() + { + if ($this->indexes !== null) + { + return $this->indexes; + } + + $this->indexes = array(); + $potential_keys = array('post_subject', 'post_text', 'post_content'); + foreach ($potential_keys as $key) + { + if ($this->db_tools->sql_index_exists($this->table_prefix . 'posts', $key)) + { + $this->indexes[] = $key; + } + } + + return $this->indexes; + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_aol.php b/phpBB/phpbb/db/migration/data/v310/profilefield_aol.php new file mode 100644 index 0000000000..65d4fe1078 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_aol.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_aol extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_yahoo_cleanup', + ); + } + + protected $profilefield_name = 'phpbb_aol'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_aol', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_aol', + 'field_length' => '40', + 'field_minlen' => '5', + 'field_maxlen' => '255', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '.*', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_on_ml' => 0, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => '', + 'field_contact_url' => '', + ); + + protected $user_column_name = 'user_aim'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_aol_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_aol_cleanup.php new file mode 100644 index 0000000000..f884d83d26 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_aol_cleanup.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_aol_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_aim'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_aol', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_aim', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_aim' => array('VCHAR_UNI', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_change_load_settings.php b/phpBB/phpbb/db/migration/data/v310/profilefield_change_load_settings.php new file mode 100644 index 0000000000..7cc4fd8daa --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_change_load_settings.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_change_load_settings extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_aol_cleanup', + ); + } + + public function update_data() + { + return array( + array('config.update', array('load_cpf_memberlist', '1')), + array('config.update', array('load_cpf_pm', '1')), + array('config.update', array('load_cpf_viewprofile', '1')), + array('config.update', array('load_cpf_viewtopic', '1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_cleanup.php new file mode 100644 index 0000000000..c44167dbfe --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_cleanup.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_occ') && + !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_interests'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_interests', + '\phpbb\db\migration\data\v310\profilefield_occupation', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_occ', + 'user_interests', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_occ' => array('MTEXT', ''), + 'user_interests' => array('MTEXT', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_contact_field.php b/phpBB/phpbb/db/migration/data/v310/profilefield_contact_field.php new file mode 100644 index 0000000000..02cd420c0f --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_contact_field.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_contact_field extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_column_exists($this->table_prefix . 'profile_fields', 'field_is_contact'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_on_memberlist', + ); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_is_contact' => array('BOOL', 0), + 'field_contact_desc' => array('VCHAR', ''), + 'field_contact_url' => array('VCHAR', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_is_contact', + 'field_contact_desc', + 'field_contact_url', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_facebook.php b/phpBB/phpbb/db/migration/data/v310/profilefield_facebook.php new file mode 100644 index 0000000000..7324b893cc --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_facebook.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_facebook extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_contact_field', + '\phpbb\db\migration\data\v310\profilefield_show_novalue', + '\phpbb\db\migration\data\v310\profilefield_types', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'create_custom_field'))), + ); + } + + protected $profilefield_name = 'phpbb_facebook'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_facebook', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_facebook', + 'field_length' => '20', + 'field_minlen' => '5', + 'field_maxlen' => '50', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '[\w.]+', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'VIEW_FACEBOOK_PROFILE', + 'field_contact_url' => 'http://facebook.com/%s/', + ); +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_field_validation_length.php b/phpBB/phpbb/db/migration/data/v310/profilefield_field_validation_length.php new file mode 100644 index 0000000000..c7d8b2dc91 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_field_validation_length.php @@ -0,0 +1,90 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_field_validation_length extends \phpbb\db\migration\migration +{ + protected $validation_options_old = array( + 'ALPHA_SPACERS' => '[\w_\+\. \-\[\]]+', + ); + + protected $validation_options_new = array( + 'ALPHA_SPACERS' => '[\w\x20_+\-\[\]]+', + ); + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc3', + ); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_validation' => array('VCHAR_UNI:64', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_validation' => array('VCHAR_UNI:20', ''), + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_profile_fields_validation'))), + ); + } + + public function revert_data() + { + return array( + array('custom', array(array($this, 'revert_profile_fields_validation'))), + ); + } + + public function update_profile_fields_validation() + { + foreach ($this->validation_options_new as $validation_type => $regex) + { + $sql = 'UPDATE ' . $this->table_prefix . "profile_fields + SET field_validation = '" . $this->db->sql_escape($this->validation_options_new[$validation_type]) . "' + WHERE field_validation = '" . $this->db->sql_escape($this->validation_options_old[$validation_type]) . "'"; + $this->sql_query($sql); + } + } + + public function revert_profile_fields_validation() + { + foreach ($this->validation_options_new as $validation_type => $regex) + { + $sql = 'UPDATE ' . $this->table_prefix . "profile_fields + SET field_validation = '" . $this->db->sql_escape($this->validation_options_old[$validation_type]) . "' + WHERE field_validation = '" . $this->db->sql_escape($this->validation_options_new[$validation_type]) . "'"; + $this->sql_query($sql); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_googleplus.php b/phpBB/phpbb/db/migration/data/v310/profilefield_googleplus.php new file mode 100644 index 0000000000..3b0963fc19 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_googleplus.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_googleplus extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_contact_field', + '\phpbb\db\migration\data\v310\profilefield_show_novalue', + '\phpbb\db\migration\data\v310\profilefield_types', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'create_custom_field'))), + ); + } + + protected $profilefield_name = 'phpbb_googleplus'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_googleplus', + 'field_type' => 'profilefields.type.googleplus', + 'field_ident' => 'phpbb_googleplus', + 'field_length' => '20', + 'field_minlen' => '3', + 'field_maxlen' => '255', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '[\w]+', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'VIEW_GOOGLEPLUS_PROFILE', + 'field_contact_url' => 'http://plus.google.com/%s', + ); +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_icq.php b/phpBB/phpbb/db/migration/data/v310/profilefield_icq.php new file mode 100644 index 0000000000..e61653f3db --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_icq.php @@ -0,0 +1,54 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_icq extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_contact_field', + ); + } + + protected $profilefield_name = 'phpbb_icq'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_icq', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_icq', + 'field_length' => '20', + 'field_minlen' => '3', + 'field_maxlen' => '15', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '[0-9]+', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'SEND_ICQ_MESSAGE', + 'field_contact_url' => 'https://www.icq.com/people/%s/', + ); + + protected $user_column_name = 'user_icq'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_icq_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_icq_cleanup.php new file mode 100644 index 0000000000..516c690093 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_icq_cleanup.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_icq_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_icq'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_icq', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_icq', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_icq' => array('VCHAR:20', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_interests.php b/phpBB/phpbb/db/migration/data/v310/profilefield_interests.php new file mode 100644 index 0000000000..33a5ba15ae --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_interests.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_interests extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_types', + '\phpbb\db\migration\data\v310\profilefield_show_novalue', + ); + } + + protected $profilefield_name = 'phpbb_interests'; + + protected $profilefield_database_type = array('MTEXT', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_interests', + 'field_type' => 'profilefields.type.text', + 'field_ident' => 'phpbb_interests', + 'field_length' => '3|30', + 'field_minlen' => '2', + 'field_maxlen' => '500', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '.*', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 0, + 'field_show_on_vt' => 0, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + ); + + protected $user_column_name = 'user_interests'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_location.php b/phpBB/phpbb/db/migration/data/v310/profilefield_location.php new file mode 100644 index 0000000000..2d27c09e68 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_location.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_location extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_types', + '\phpbb\db\migration\data\v310\profilefield_on_memberlist', + ); + } + + protected $profilefield_name = 'phpbb_location'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_location', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_location', + 'field_length' => '20', + 'field_minlen' => '2', + 'field_maxlen' => '100', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '.*', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + ); + + protected $user_column_name = 'user_from'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_location_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_location_cleanup.php new file mode 100644 index 0000000000..b824e3406a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_location_cleanup.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_location_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_from'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_location', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_from', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_from' => array('VCHAR_UNI:100', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_occupation.php b/phpBB/phpbb/db/migration/data/v310/profilefield_occupation.php new file mode 100644 index 0000000000..75df2bcdee --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_occupation.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_occupation extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_interests', + ); + } + + protected $profilefield_name = 'phpbb_occupation'; + + protected $profilefield_database_type = array('MTEXT', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_occupation', + 'field_type' => 'profilefields.type.text', + 'field_ident' => 'phpbb_occupation', + 'field_length' => '3|30', + 'field_minlen' => '2', + 'field_maxlen' => '500', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '.*', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 0, + 'field_show_on_vt' => 0, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + ); + + protected $user_column_name = 'user_occ'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_on_memberlist.php b/phpBB/phpbb/db/migration/data/v310/profilefield_on_memberlist.php new file mode 100644 index 0000000000..7ce5de0f00 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_on_memberlist.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_on_memberlist extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_column_exists($this->table_prefix . 'profile_fields', 'field_show_on_ml'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_cleanup', + ); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_on_ml' => array('BOOL', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_on_ml', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_show_novalue.php b/phpBB/phpbb/db/migration/data/v310/profilefield_show_novalue.php new file mode 100644 index 0000000000..5fc88b6809 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_show_novalue.php @@ -0,0 +1,49 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_show_novalue extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_column_exists($this->table_prefix . 'profile_fields', 'field_show_novalue'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\profilefield_types'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_novalue' => array('BOOL', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_show_novalue', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_skype.php b/phpBB/phpbb/db/migration/data/v310/profilefield_skype.php new file mode 100644 index 0000000000..0dbe9041bb --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_skype.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_skype extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_contact_field', + '\phpbb\db\migration\data\v310\profilefield_show_novalue', + '\phpbb\db\migration\data\v310\profilefield_types', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'create_custom_field'))), + ); + } + + protected $profilefield_name = 'phpbb_skype'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_skype', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_skype', + 'field_length' => '20', + 'field_minlen' => '6', + 'field_maxlen' => '32', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '[a-zA-Z][\w\.,\-_]+', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'VIEW_SKYPE_PROFILE', + 'field_contact_url' => 'skype:%s?userinfo', + ); +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_twitter.php b/phpBB/phpbb/db/migration/data/v310/profilefield_twitter.php new file mode 100644 index 0000000000..850e096439 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_twitter.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_twitter extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_contact_field', + '\phpbb\db\migration\data\v310\profilefield_show_novalue', + '\phpbb\db\migration\data\v310\profilefield_types', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'create_custom_field'))), + ); + } + + protected $profilefield_name = 'phpbb_twitter'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_twitter', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_twitter', + 'field_length' => '20', + 'field_minlen' => '1', + 'field_maxlen' => '15', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '[\w_]+', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'VIEW_TWITTER_PROFILE', + 'field_contact_url' => 'http://twitter.com/%s', + ); +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_types.php b/phpBB/phpbb/db/migration/data/v310/profilefield_types.php new file mode 100644 index 0000000000..5045eb8807 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_types.php @@ -0,0 +1,110 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_types extends \phpbb\db\migration\migration +{ + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\alpha2', + ); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'profile_fields' => array( + 'field_type' => array('VCHAR:100', ''), + ), + $this->table_prefix . 'profile_fields_lang' => array( + 'field_type' => array('VCHAR:100', ''), + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_profile_fields_type'))), + array('custom', array(array($this, 'update_profile_fields_lang_type'))), + ); + } + + public function update_profile_fields_type() + { + // Update profile field types + $sql = 'SELECT field_type + FROM ' . $this->table_prefix . 'profile_fields + GROUP BY field_type'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $sql = 'UPDATE ' . $this->table_prefix . "profile_fields + SET field_type = '" . $this->db->sql_escape($this->convert_phpbb30_field_type($row['field_type'])) . "' + WHERE field_type = '" . $this->db->sql_escape($row['field_type']) . "'"; + $this->sql_query($sql); + } + $this->db->sql_freeresult($result); + } + + public function update_profile_fields_lang_type() + { + // Update profile field language types + $sql = 'SELECT field_type + FROM ' . $this->table_prefix . 'profile_fields_lang + GROUP BY field_type'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $sql = 'UPDATE ' . $this->table_prefix . "profile_fields_lang + SET field_type = '" . $this->db->sql_escape($this->convert_phpbb30_field_type($row['field_type'])) . "' + WHERE field_type = '" . $this->db->sql_escape($row['field_type']) . "'"; + $this->sql_query($sql); + } + $this->db->sql_freeresult($result); + } + + /** + * Determine the new field type for a given phpBB 3.0 field type + * + * @param $field_type string Field type in 3.0 + * @return string Field new type which is used since 3.1 + */ + public function convert_phpbb30_field_type($field_type) + { + switch ($field_type) + { + case FIELD_INT: + return 'profilefields.type.int'; + case FIELD_STRING: + return 'profilefields.type.string'; + case FIELD_TEXT: + return 'profilefields.type.text'; + case FIELD_BOOL: + return 'profilefields.type.bool'; + case FIELD_DROPDOWN: + return 'profilefields.type.dropdown'; + case FIELD_DATE: + return 'profilefields.type.date'; + default: + return $field_type; + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_website.php b/phpBB/phpbb/db/migration/data/v310/profilefield_website.php new file mode 100644 index 0000000000..e1e10f09f4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_website.php @@ -0,0 +1,56 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_website extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_on_memberlist', + '\phpbb\db\migration\data\v310\profilefield_icq_cleanup', + ); + } + + protected $profilefield_name = 'phpbb_website'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_website', + 'field_type' => 'profilefields.type.url', + 'field_ident' => 'phpbb_website', + 'field_length' => '40', + 'field_minlen' => '12', + 'field_maxlen' => '255', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_on_ml' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'VISIT_WEBSITE', + 'field_contact_url' => '%s', + ); + + protected $user_column_name = 'user_website'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_website_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_website_cleanup.php new file mode 100644 index 0000000000..94442f0497 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_website_cleanup.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_website_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_website'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_website', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_website', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_website' => array('VCHAR_UNI:200', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_wlm.php b/phpBB/phpbb/db/migration/data/v310/profilefield_wlm.php new file mode 100644 index 0000000000..2cd333fcbd --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_wlm.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_wlm extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_website_cleanup', + ); + } + + protected $profilefield_name = 'phpbb_wlm'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_wlm', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_wlm', + 'field_length' => '40', + 'field_minlen' => '5', + 'field_maxlen' => '255', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '.*', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_on_ml' => 0, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => '', + 'field_contact_url' => '', + ); + + protected $user_column_name = 'user_msnm'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_wlm_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_wlm_cleanup.php new file mode 100644 index 0000000000..7ef9e44020 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_wlm_cleanup.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_wlm_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_msnm'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_wlm', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_msnm', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_msnm' => array('VCHAR_UNI', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_yahoo.php b/phpBB/phpbb/db/migration/data/v310/profilefield_yahoo.php new file mode 100644 index 0000000000..e269f88420 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_yahoo.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_yahoo extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_wlm_cleanup', + ); + } + + protected $profilefield_name = 'phpbb_yahoo'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_yahoo', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_yahoo', + 'field_length' => '40', + 'field_minlen' => '5', + 'field_maxlen' => '255', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '.*', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_on_ml' => 0, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'SEND_YIM_MESSAGE', + 'field_contact_url' => 'http://edit.yahoo.com/config/send_webmesg?.target=%s&.src=pg', + ); + + protected $user_column_name = 'user_yim'; +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_yahoo_cleanup.php b/phpBB/phpbb/db/migration/data/v310/profilefield_yahoo_cleanup.php new file mode 100644 index 0000000000..bd724ff7db --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_yahoo_cleanup.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_yahoo_cleanup extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_yim'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_yahoo', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_yim', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_yim' => array('VCHAR_UNI', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/profilefield_youtube.php b/phpBB/phpbb/db/migration/data/v310/profilefield_youtube.php new file mode 100644 index 0000000000..40a569d2a2 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/profilefield_youtube.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class profilefield_youtube extends \phpbb\db\migration\profilefield_base_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\profilefield_contact_field', + '\phpbb\db\migration\data\v310\profilefield_show_novalue', + '\phpbb\db\migration\data\v310\profilefield_types', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'create_custom_field'))), + ); + } + + protected $profilefield_name = 'phpbb_youtube'; + + protected $profilefield_database_type = array('VCHAR', ''); + + protected $profilefield_data = array( + 'field_name' => 'phpbb_youtube', + 'field_type' => 'profilefields.type.string', + 'field_ident' => 'phpbb_youtube', + 'field_length' => '20', + 'field_minlen' => '3', + 'field_maxlen' => '60', + 'field_novalue' => '', + 'field_default_value' => '', + 'field_validation' => '[a-zA-Z][\w\.,\-_]+', + 'field_required' => 0, + 'field_show_novalue' => 0, + 'field_show_on_reg' => 0, + 'field_show_on_pm' => 1, + 'field_show_on_vt' => 1, + 'field_show_profile' => 1, + 'field_hide' => 0, + 'field_no_view' => 0, + 'field_active' => 1, + 'field_is_contact' => 1, + 'field_contact_desc' => 'VIEW_YOUTUBE_CHANNEL', + 'field_contact_url' => 'http://youtube.com/user/%s', + ); +} diff --git a/phpBB/phpbb/db/migration/data/v310/prune_shadow_topics.php b/phpBB/phpbb/db/migration/data/v310/prune_shadow_topics.php new file mode 100644 index 0000000000..f6d27d385e --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/prune_shadow_topics.php @@ -0,0 +1,50 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class prune_shadow_topics extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'forums' => array( + 'enable_shadow_prune' => array('BOOL', 0), + 'prune_shadow_days' => array('UINT', 7), + 'prune_shadow_freq' => array('UINT', 1), + 'prune_shadow_next' => array('INT:11', 0), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'forums' => array( + 'enable_shadow_prune', + 'prune_shadow_days', + 'prune_shadow_freq', + 'prune_shadow_next', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rc1.php b/phpBB/phpbb/db/migration/data/v310/rc1.php new file mode 100644 index 0000000000..751208c6ca --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rc1.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\beta4', + '\phpbb\db\migration\data\v310\contact_admin_acp_module', + '\phpbb\db\migration\data\v310\contact_admin_form', + '\phpbb\db\migration\data\v310\passwords_convert_p2', + '\phpbb\db\migration\data\v310\profilefield_facebook', + '\phpbb\db\migration\data\v310\profilefield_googleplus', + '\phpbb\db\migration\data\v310\profilefield_skype', + '\phpbb\db\migration\data\v310\profilefield_twitter', + '\phpbb\db\migration\data\v310\profilefield_youtube', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rc2.php b/phpBB/phpbb/db/migration/data/v310/rc2.php new file mode 100644 index 0000000000..5cd0393a13 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rc2.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-RC2', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rc3.php b/phpBB/phpbb/db/migration/data/v310/rc3.php new file mode 100644 index 0000000000..9fb483ef6a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rc3.php @@ -0,0 +1,40 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rc3 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-RC3', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc2', + '\phpbb\db\migration\data\v310\captcha_plugins', + '\phpbb\db\migration\data\v310\rename_too_long_indexes', + '\phpbb\db\migration\data\v310\search_type', + '\phpbb\db\migration\data\v310\topic_sort_username', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-RC3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rc4.php b/phpBB/phpbb/db/migration/data/v310/rc4.php new file mode 100644 index 0000000000..0d756c762c --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rc4.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rc4 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-RC4', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc3', + '\phpbb\db\migration\data\v310\notifications_use_full_name', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-RC4')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rc5.php b/phpBB/phpbb/db/migration/data/v310/rc5.php new file mode 100644 index 0000000000..d92537d877 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rc5.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rc5 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-RC5', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc4', + '\phpbb\db\migration\data\v310\profilefield_field_validation_length', + '\phpbb\db\migration\data\v310\remove_acp_styles_cache', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-RC5')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rc6.php b/phpBB/phpbb/db/migration/data/v310/rc6.php new file mode 100644 index 0000000000..1df502a1e4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rc6.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rc6 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.0-RC6', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\rc5', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.0-RC6')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/remove_acp_styles_cache.php b/phpBB/phpbb/db/migration/data/v310/remove_acp_styles_cache.php new file mode 100644 index 0000000000..7b84539814 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/remove_acp_styles_cache.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class remove_acp_styles_cache extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'acp' + AND module_langname = 'ACP_STYLES_CACHE'"; + $result = $this->db->sql_query($sql); + $module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + return !$module_id; + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\rc4'); + } + + public function update_data() + { + return array( + array('module.remove', array( + 'acp', + 'ACP_STYLE_MANAGEMENT', + array( + 'module_basename' => 'acp_styles', + 'module_langname' => 'ACP_STYLES_CACHE', + 'module_mode' => 'cache', + 'module_auth' => 'acl_a_styles', + ), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/rename_too_long_indexes.php b/phpBB/phpbb/db/migration/data/v310/rename_too_long_indexes.php new file mode 100644 index 0000000000..8d2a15d8ea --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/rename_too_long_indexes.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class rename_too_long_indexes extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_0'); + } + + public function update_schema() + { + return array( + 'drop_keys' => array( + $this->table_prefix . 'search_wordmatch' => array( + 'unq_mtch', + ), + ), + 'add_unique_index' => array( + $this->table_prefix . 'search_wordmatch' => array( + 'un_mtch' => array('word_id', 'post_id', 'title_match'), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/reported_posts_display.php b/phpBB/phpbb/db/migration/data/v310/reported_posts_display.php new file mode 100644 index 0000000000..575a65d9dd --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/reported_posts_display.php @@ -0,0 +1,53 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class reported_posts_display extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_column_exists($this->table_prefix . 'reports', 'reported_post_enable_bbcode'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'reports' => array( + 'reported_post_enable_bbcode' => array('BOOL', 1), + 'reported_post_enable_smilies' => array('BOOL', 1), + 'reported_post_enable_magic_url' => array('BOOL', 1), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'reports' => array( + 'reported_post_enable_bbcode', + 'reported_post_enable_smilies', + 'reported_post_enable_magic_url', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/reset_missing_captcha_plugin.php b/phpBB/phpbb/db/migration/data/v310/reset_missing_captcha_plugin.php new file mode 100644 index 0000000000..8211457dc6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/reset_missing_captcha_plugin.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +/** +* Class captcha_plugin +* +* Reset the captcha setting to the default plugin if the defined 'captcha_plugin' is missing. +*/ +class reset_missing_captcha_plugin extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_data() + { + return array( + array('if', array( + (is_dir($this->phpbb_root_path . 'includes/captcha/plugins/') && + !is_file($this->phpbb_root_path . "includes/captcha/plugins/{$this->config['captcha_plugin']}_plugin." . $this->php_ext)), + array('config.update', array('captcha_plugin', 'phpbb_captcha_nogd')), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/search_type.php b/phpBB/phpbb/db/migration/data/v310/search_type.php new file mode 100644 index 0000000000..f89456ae19 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/search_type.php @@ -0,0 +1,34 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class search_type extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + ); + } + + public function update_data() + { + return array( + array('if', array( + (is_file($this->phpbb_root_path . 'phpbb/search/' . $this->config['search_type'] . $this->php_ext)), + array('config.update', array('search_type', '\\phpbb\\search\\' . $this->config['search_type'])), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/signature_module_auth.php b/phpBB/phpbb/db/migration/data/v310/signature_module_auth.php new file mode 100644 index 0000000000..e50f5e53a0 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/signature_module_auth.php @@ -0,0 +1,57 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class signature_module_auth extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + $sql = 'SELECT module_auth + FROM ' . MODULES_TABLE . " + WHERE module_class = 'ucp' + AND module_basename = 'ucp_profile' + AND module_mode = 'signature'"; + $result = $this->db->sql_query($sql); + $module_auth = $this->db->sql_fetchfield('module_auth'); + $this->db->sql_freeresult($result); + + return $module_auth === 'acl_u_sig' || $module_auth === false; + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_data() + { + return array( + array('custom', array( + array($this, 'update_signature_module_auth'), + ), + ), + ); + } + + public function update_signature_module_auth() + { + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_auth = 'acl_u_sig' + WHERE module_class = 'ucp' + AND module_basename = 'ucp_profile' + AND module_mode = 'signature' + AND module_auth = ''"; + $this->db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/soft_delete_mod_convert.php b/phpBB/phpbb/db/migration/data/v310/soft_delete_mod_convert.php new file mode 100644 index 0000000000..85b90da5fa --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/soft_delete_mod_convert.php @@ -0,0 +1,127 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +use phpbb\db\migration\container_aware_migration; + +/** + * Migration to convert the Soft Delete MOD for 3.0 + * + * https://www.phpbb.com/customise/db/mod/soft_delete/ + */ +class soft_delete_mod_convert extends container_aware_migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\alpha3', + ); + } + + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'posts', 'post_deleted'); + } + + public function update_data() + { + return array( + array('permission.remove', array('m_harddelete', true)), + array('permission.remove', array('m_harddelete', false)), + + array('custom', array(array($this, 'convert_posts'))), + array('custom', array(array($this, 'convert_topics'))), + ); + } + + public function convert_posts($start) + { + $content_visibility = $this->get_content_visibility(); + + $limit = 250; + $i = 0; + + $sql = 'SELECT p.*, t.topic_first_post_id, t.topic_last_post_id + FROM ' . $this->table_prefix . 'posts p, ' . $this->table_prefix . 'topics t + WHERE p.post_deleted > 0 + AND t.topic_id = p.topic_id'; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $content_visibility->set_post_visibility( + ITEM_DELETED, + $row['post_id'], + $row['topic_id'], + $row['forum_id'], + $row['post_deleted'], + $row['post_deleted_time'], + '', + ($row['post_id'] == $row['topic_first_post_id']) ? true : false, + ($row['post_id'] == $row['topic_last_post_id']) ? true : false + ); + + $i++; + } + + $this->db->sql_freeresult($result); + + if ($i == $limit) + { + return $start + $i; + } + } + + public function convert_topics($start) + { + $content_visibility = $this->get_content_visibility(); + + $limit = 100; + $i = 0; + + $sql = 'SELECT * + FROM ' . $this->table_prefix . 'topics + WHERE topic_deleted > 0'; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $content_visibility->set_topic_visibility( + ITEM_DELETED, + $row['topic_id'], + $row['forum_id'], + $row['topic_deleted'], + $row['topic_deleted_time'], + '' + ); + + $i++; + } + + $this->db->sql_freeresult($result); + + if ($i == $limit) + { + return $start + $i; + } + } + + /** + * @return \phpbb\content_visibility + */ + protected function get_content_visibility() + { + return $this->container->get('content.visibility'); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/soft_delete_mod_convert2.php b/phpBB/phpbb/db/migration/data/v310/soft_delete_mod_convert2.php new file mode 100644 index 0000000000..246a267a8c --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/soft_delete_mod_convert2.php @@ -0,0 +1,66 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +/** + * Migration to convert the Soft Delete MOD for 3.0 + * + * https://www.phpbb.com/customise/db/mod/soft_delete/ + */ +class soft_delete_mod_convert2 extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\soft_delete_mod_convert', + ); + } + + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'posts', 'post_deleted'); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'forums' => array('forum_deleted_topic_count', 'forum_deleted_reply_count'), + $this->table_prefix . 'posts' => array('post_deleted', 'post_deleted_time'), + $this->table_prefix . 'topics' => array('topic_deleted', 'topic_deleted_time', 'topic_deleted_reply_count'), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'forums' => array( + 'forum_deleted_topic_count' => array('UINT', 0), + 'forum_deleted_reply_count' => array('UINT', 0), + ), + $this->table_prefix . 'posts' => array( + 'post_deleted' => array('UINT', 0), + 'post_deleted_time' => array('TIMESTAMP', 0), + ), + $this->table_prefix . 'topics' => array( + 'topic_deleted' => array('UINT', 0), + 'topic_deleted_time' => array('TIMESTAMP', 0), + 'topic_deleted_reply_count' => array('UINT', 0), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/softdelete_mcp_modules.php b/phpBB/phpbb/db/migration/data/v310/softdelete_mcp_modules.php new file mode 100644 index 0000000000..5e68db5889 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/softdelete_mcp_modules.php @@ -0,0 +1,61 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class softdelete_mcp_modules extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'mcp' + AND module_basename = 'mcp_queue' + AND module_mode = 'deleted_topics'"; + $result = $this->db->sql_query($sql); + $module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + return $module_id !== false; + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + '\phpbb\db\migration\data\v310\softdelete_p2', + ); + } + + public function update_data() + { + return array( + array('module.add', array( + 'mcp', + 'MCP_QUEUE', + array( + 'module_basename' => 'mcp_queue', + 'modes' => array('deleted_topics'), + ), + )), + array('module.add', array( + 'mcp', + 'MCP_QUEUE', + array( + 'module_basename' => 'mcp_queue', + 'modes' => array('deleted_posts'), + ), + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/softdelete_p1.php b/phpBB/phpbb/db/migration/data/v310/softdelete_p1.php new file mode 100644 index 0000000000..b1e7486e24 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/softdelete_p1.php @@ -0,0 +1,211 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class softdelete_p1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_column_exists($this->table_prefix . 'posts', 'post_visibility'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'forums' => array( + 'forum_posts_approved' => array('UINT', 0), + 'forum_posts_unapproved' => array('UINT', 0), + 'forum_posts_softdeleted' => array('UINT', 0), + 'forum_topics_approved' => array('UINT', 0), + 'forum_topics_unapproved' => array('UINT', 0), + 'forum_topics_softdeleted' => array('UINT', 0), + ), + $this->table_prefix . 'posts' => array( + 'post_visibility' => array('TINT:3', 0), + 'post_delete_time' => array('TIMESTAMP', 0), + 'post_delete_reason' => array('STEXT_UNI', ''), + 'post_delete_user' => array('UINT', 0), + ), + $this->table_prefix . 'topics' => array( + 'topic_visibility' => array('TINT:3', 0), + 'topic_delete_time' => array('TIMESTAMP', 0), + 'topic_delete_reason' => array('STEXT_UNI', ''), + 'topic_delete_user' => array('UINT', 0), + 'topic_posts_approved' => array('UINT', 0), + 'topic_posts_unapproved' => array('UINT', 0), + 'topic_posts_softdeleted' => array('UINT', 0), + ), + ), + 'add_index' => array( + $this->table_prefix . 'posts' => array( + 'post_visibility' => array('post_visibility'), + ), + $this->table_prefix . 'topics' => array( + 'topic_visibility' => array('topic_visibility'), + 'forum_vis_last' => array('forum_id', 'topic_visibility', 'topic_last_post_id'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'forums' => array( + 'forum_posts_approved', + 'forum_posts_unapproved', + 'forum_posts_softdeleted', + 'forum_topics_approved', + 'forum_topics_unapproved', + 'forum_topics_softdeleted', + ), + $this->table_prefix . 'posts' => array( + 'post_visibility', + 'post_delete_time', + 'post_delete_reason', + 'post_delete_user', + ), + $this->table_prefix . 'topics' => array( + 'topic_visibility', + 'topic_delete_time', + 'topic_delete_reason', + 'topic_delete_user', + 'topic_posts_approved', + 'topic_posts_unapproved', + 'topic_posts_softdeleted', + ), + ), + 'drop_keys' => array( + $this->table_prefix . 'posts' => array('post_visibility'), + $this->table_prefix . 'topics' => array('topic_visibility', 'forum_vis_last'), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_post_visibility'))), + array('custom', array(array($this, 'update_topic_visibility'))), + array('custom', array(array($this, 'update_topics_post_counts'))), + array('custom', array(array($this, 'update_forums_topic_and_post_counts'))), + + array('permission.add', array('f_softdelete', false)), + array('permission.add', array('m_softdelete', false)), + ); + } + + public function update_post_visibility() + { + $sql = 'UPDATE ' . $this->table_prefix . 'posts + SET post_visibility = post_approved'; + $this->sql_query($sql); + } + + public function update_topic_visibility() + { + $sql = 'UPDATE ' . $this->table_prefix . 'topics + SET topic_visibility = topic_approved'; + $this->sql_query($sql); + } + + public function update_topics_post_counts() + { + /* + * Using sql_case here to avoid "BIGINT UNSIGNED value is out of range" errors. + * As we update all topics in 2 queries, one broken topic would stop the conversion + * for all topics and the surpressed error will cause the admin to not even notice it. + */ + $sql = 'UPDATE ' . $this->table_prefix . 'topics + SET topic_posts_approved = topic_replies + 1, + topic_posts_unapproved = ' . $this->db->sql_case('topic_replies_real > topic_replies', 'topic_replies_real - topic_replies', '0') . ' + WHERE topic_visibility = ' . ITEM_APPROVED; + $this->sql_query($sql); + + $sql = 'UPDATE ' . $this->table_prefix . 'topics + SET topic_posts_approved = 0, + topic_posts_unapproved = (' . $this->db->sql_case('topic_replies_real > topic_replies', 'topic_replies_real - topic_replies', '0') . ') + 1 + WHERE topic_visibility = ' . ITEM_UNAPPROVED; + $this->sql_query($sql); + } + + public function update_forums_topic_and_post_counts($start) + { + $start = (int) $start; + $limit = 10; + $converted_forums = 0; + + if (!$start) + { + // Preserve the forum_posts value for link forums as it represents redirects. + $sql = 'UPDATE ' . $this->table_prefix . 'forums + SET forum_posts_approved = forum_posts + WHERE forum_type = ' . FORUM_LINK; + $this->db->sql_query($sql); + } + + $sql = 'SELECT forum_id, topic_visibility, COUNT(topic_id) AS sum_topics, SUM(topic_posts_approved) AS sum_posts_approved, SUM(topic_posts_unapproved) AS sum_posts_unapproved + FROM ' . $this->table_prefix . 'topics + GROUP BY forum_id, topic_visibility + ORDER BY forum_id, topic_visibility'; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + $update_forums = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $converted_forums++; + + $forum_id = (int) $row['forum_id']; + if (!isset($update_forums[$forum_id])) + { + $update_forums[$forum_id] = array( + 'forum_posts_approved' => 0, + 'forum_posts_unapproved' => 0, + 'forum_topics_approved' => 0, + 'forum_topics_unapproved' => 0, + ); + } + + $update_forums[$forum_id]['forum_posts_approved'] += (int) $row['sum_posts_approved']; + $update_forums[$forum_id]['forum_posts_unapproved'] += (int) $row['sum_posts_unapproved']; + + $update_forums[$forum_id][(($row['topic_visibility'] == ITEM_APPROVED) ? 'forum_topics_approved' : 'forum_topics_unapproved')] += (int) $row['sum_topics']; + } + $this->db->sql_freeresult($result); + + foreach ($update_forums as $forum_id => $forum_data) + { + $sql = 'UPDATE ' . FORUMS_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $forum_data) . ' + WHERE forum_id = ' . $forum_id; + $this->sql_query($sql); + } + + if ($converted_forums < $limit) + { + // There are no more topics, we are done + return; + } + + // There are still more topics to query, return the next start value + return $start + $limit; + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/softdelete_p2.php b/phpBB/phpbb/db/migration/data/v310/softdelete_p2.php new file mode 100644 index 0000000000..849a996c1b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/softdelete_p2.php @@ -0,0 +1,78 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class softdelete_p2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'posts', 'post_approved'); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\dev', + '\phpbb\db\migration\data\v310\softdelete_p1', + ); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'forums' => array('forum_posts', 'forum_topics', 'forum_topics_real'), + $this->table_prefix . 'posts' => array('post_approved'), + $this->table_prefix . 'topics' => array('topic_approved', 'topic_replies', 'topic_replies_real'), + ), + 'drop_keys' => array( + $this->table_prefix . 'posts' => array('post_approved'), + $this->table_prefix . 'topics' => array( + 'forum_appr_last', + 'topic_approved', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'forums' => array( + 'forum_posts' => array('UINT', 0), + 'forum_topics' => array('UINT', 0), + 'forum_topics_real' => array('UINT', 0), + ), + $this->table_prefix . 'posts' => array( + 'post_approved' => array('BOOL', 1), + ), + $this->table_prefix . 'topics' => array( + 'topic_approved' => array('BOOL', 1), + 'topic_replies' => array('UINT', 0), + 'topic_replies_real' => array('UINT', 0), + ), + ), + 'add_index' => array( + $this->table_prefix . 'posts' => array( + 'post_approved' => array('post_approved'), + ), + $this->table_prefix . 'topics' => array( + 'forum_appr_last' => array('forum_id', 'topic_approved', 'topic_last_post_id'), + 'topic_approved' => array('topic_approved'), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/style_update_p1.php b/phpBB/phpbb/db/migration/data/v310/style_update_p1.php new file mode 100644 index 0000000000..2c7b7edf2e --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/style_update_p1.php @@ -0,0 +1,191 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class style_update_p1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_table_exists($this->table_prefix . 'styles_imageset'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'styles' => array( + 'style_path' => array('VCHAR:100', ''), + 'bbcode_bitfield' => array('VCHAR:255', 'kNg='), + 'style_parent_id' => array('UINT', 0), + 'style_parent_tree' => array('TEXT', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'styles' => array( + 'style_path', + 'bbcode_bitfield', + 'style_parent_id', + 'style_parent_tree', + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'styles_update'))), + ); + } + + public function styles_update() + { + // Get list of valid 3.1 styles + $available_styles = array('prosilver'); + + $iterator = new \DirectoryIterator($this->phpbb_root_path . 'styles'); + $skip_dirs = array('.', '..', 'prosilver'); + foreach ($iterator as $fileinfo) + { + if ($fileinfo->isDir() && !in_array($fileinfo->getFilename(), $skip_dirs) && file_exists($fileinfo->getPathname() . '/style.cfg')) + { + $style_cfg = parse_cfg_file($fileinfo->getPathname() . '/style.cfg'); + if (isset($style_cfg['phpbb_version']) && version_compare($style_cfg['phpbb_version'], '3.1.0-dev', '>=')) + { + // 3.1 style + $available_styles[] = $fileinfo->getFilename(); + } + } + } + + // Get all installed styles + if ($this->db_tools->sql_table_exists($this->table_prefix . 'styles_imageset')) + { + $sql = 'SELECT s.style_id, t.template_path, t.template_id, t.bbcode_bitfield, t.template_inherits_id, t.template_inherit_path, c.theme_path, c.theme_id, i.imageset_path + FROM ' . STYLES_TABLE . ' s, ' . $this->table_prefix . 'styles_template t, ' . $this->table_prefix . 'styles_theme c, ' . $this->table_prefix . "styles_imageset i + WHERE t.template_id = s.template_id + AND c.theme_id = s.theme_id + AND i.imageset_id = s.imageset_id"; + } + else + { + $sql = 'SELECT s.style_id, t.template_path, t.template_id, t.bbcode_bitfield, t.template_inherits_id, t.template_inherit_path, c.theme_path, c.theme_id + FROM ' . STYLES_TABLE . ' s, ' . $this->table_prefix . 'styles_template t, ' . $this->table_prefix . "styles_theme c + WHERE t.template_id = s.template_id + AND c.theme_id = s.theme_id"; + } + $result = $this->db->sql_query($sql); + + $styles = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $styles[] = $row; + } + $this->db->sql_freeresult($result); + + // Decide which styles to keep, all others will be deleted + $valid_styles = array(); + foreach ($styles as $style_row) + { + if ( + // Delete styles with parent style (not supported yet) + $style_row['template_inherits_id'] == 0 && + // Check if components match + $style_row['template_path'] == $style_row['theme_path'] && (!isset($style_row['imageset_path']) || $style_row['template_path'] == $style_row['imageset_path']) && + // Check if components are valid + in_array($style_row['template_path'], $available_styles) + ) + { + // Valid style. Keep it + $sql_ary = array( + 'style_path' => $style_row['template_path'], + 'bbcode_bitfield' => $style_row['bbcode_bitfield'], + 'style_parent_id' => 0, + 'style_parent_tree' => '', + ); + $this->sql_query('UPDATE ' . STYLES_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . ' + WHERE style_id = ' . $style_row['style_id']); + $valid_styles[] = (int) $style_row['style_id']; + } + } + + // Remove old entries from styles table + if (!sizeof($valid_styles)) + { + // No valid styles: remove everything and add prosilver + $this->sql_query('DELETE FROM ' . STYLES_TABLE); + + $sql_ary = array( + 'style_name' => 'prosilver', + 'style_copyright' => '© phpBB Limited', + 'style_active' => 1, + 'style_path' => 'prosilver', + 'bbcode_bitfield' => 'lNg=', + 'style_parent_id' => 0, + 'style_parent_tree' => '', + + // Will be removed in the next step + 'imageset_id' => 0, + 'template_id' => 0, + 'theme_id' => 0, + ); + + $sql = 'INSERT INTO ' . STYLES_TABLE . ' ' . $this->db->sql_build_array('INSERT', $sql_ary); + $this->sql_query($sql); + + $sql = 'SELECT style_id + FROM ' . STYLES_TABLE . " + WHERE style_name = 'prosilver'"; + $result = $this->sql_query($sql); + $default_style = $this->db->sql_fetchfield('style_id'); + $this->db->sql_freeresult($result); + + $this->config->set('default_style', $default_style); + + $sql = 'UPDATE ' . USERS_TABLE . ' SET user_style = 0'; + $this->sql_query($sql); + } + else + { + // There are valid styles in styles table. Remove styles that are outdated + $this->sql_query('DELETE FROM ' . STYLES_TABLE . ' + WHERE ' . $this->db->sql_in_set('style_id', $valid_styles, true)); + + // Change default style + if (!in_array($this->config['default_style'], $valid_styles)) + { + $this->sql_query('UPDATE ' . CONFIG_TABLE . " + SET config_value = '" . $valid_styles[0] . "' + WHERE config_name = 'default_style'"); + } + + // Reset styles for users + $this->sql_query('UPDATE ' . USERS_TABLE . ' + SET user_style = 0 + WHERE ' . $this->db->sql_in_set('user_style', $valid_styles, true)); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/style_update_p2.php b/phpBB/phpbb/db/migration/data/v310/style_update_p2.php new file mode 100644 index 0000000000..52c8ffb2e2 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/style_update_p2.php @@ -0,0 +1,151 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class style_update_p2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_table_exists($this->table_prefix . 'styles_imageset'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\style_update_p1'); + } + + public function update_schema() + { + return array( + 'drop_keys' => array( + $this->table_prefix . 'styles' => array( + 'imageset_id', + 'template_id', + 'theme_id', + ), + ), + + 'drop_columns' => array( + $this->table_prefix . 'styles' => array( + 'imageset_id', + 'template_id', + 'theme_id', + ), + ), + + 'drop_tables' => array( + $this->table_prefix . 'styles_imageset', + $this->table_prefix . 'styles_imageset_data', + $this->table_prefix . 'styles_template', + $this->table_prefix . 'styles_template_data', + $this->table_prefix . 'styles_theme', + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'styles' => array( + 'imageset_id' => array('UINT', 0), + 'template_id' => array('UINT', 0), + 'theme_id' => array('UINT', 0), + ), + ), + + 'add_index' => array( + $this->table_prefix . 'styles' => array( + 'imageset_id' => array('imageset_id'), + 'template_id' => array('template_id'), + 'theme_id' => array('theme_id'), + ), + ), + + 'add_tables' => array( + $this->table_prefix . 'styles_imageset' => array( + 'COLUMNS' => array( + 'imageset_id' => array('UINT', null, 'auto_increment'), + 'imageset_name' => array('VCHAR_UNI:255', ''), + 'imageset_copyright' => array('VCHAR_UNI', ''), + 'imageset_path' => array('VCHAR:100', ''), + ), + 'PRIMARY_KEY' => 'imageset_id', + 'KEYS' => array( + 'imgset_nm' => array('UNIQUE', 'imageset_name'), + ), + ), + $this->table_prefix . 'styles_imageset_data' => array( + 'COLUMNS' => array( + 'image_id' => array('UINT', null, 'auto_increment'), + 'image_name' => array('VCHAR:200', ''), + 'image_filename' => array('VCHAR:200', ''), + 'image_lang' => array('VCHAR:30', ''), + 'image_height' => array('USINT', 0), + 'image_width' => array('USINT', 0), + 'imageset_id' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'image_id', + 'KEYS' => array( + 'i_d' => array('INDEX', 'imageset_id'), + ), + ), + $this->table_prefix . 'styles_template' => array( + 'COLUMNS' => array( + 'template_id' => array('UINT', null, 'auto_increment'), + 'template_name' => array('VCHAR_UNI:255', ''), + 'template_copyright' => array('VCHAR_UNI', ''), + 'template_path' => array('VCHAR:100', ''), + 'bbcode_bitfield' => array('VCHAR:255', 'kNg='), + 'template_storedb' => array('BOOL', 0), + 'template_inherits_id' => array('UINT:4', 0), + 'template_inherit_path' => array('VCHAR', ''), + ), + 'PRIMARY_KEY' => 'template_id', + 'KEYS' => array( + 'tmplte_nm' => array('UNIQUE', 'template_name'), + ), + ), + $this->table_prefix . 'styles_template_data' => array( + 'COLUMNS' => array( + 'template_id' => array('UINT', 0), + 'template_filename' => array('VCHAR:100', ''), + 'template_included' => array('TEXT', ''), + 'template_mtime' => array('TIMESTAMP', 0), + 'template_data' => array('MTEXT_UNI', ''), + ), + 'KEYS' => array( + 'tid' => array('INDEX', 'template_id'), + 'tfn' => array('INDEX', 'template_filename'), + ), + ), + $this->table_prefix . 'styles_theme' => array( + 'COLUMNS' => array( + 'theme_id' => array('UINT', null, 'auto_increment'), + 'theme_name' => array('VCHAR_UNI:255', ''), + 'theme_copyright' => array('VCHAR_UNI', ''), + 'theme_path' => array('VCHAR:100', ''), + 'theme_storedb' => array('BOOL', 0), + 'theme_mtime' => array('TIMESTAMP', 0), + 'theme_data' => array('MTEXT_UNI', ''), + ), + 'PRIMARY_KEY' => 'theme_id', + 'KEYS' => array( + 'theme_name' => array('UNIQUE', 'theme_name'), + ), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/teampage.php b/phpBB/phpbb/db/migration/data/v310/teampage.php new file mode 100644 index 0000000000..f8edbc3492 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/teampage.php @@ -0,0 +1,110 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class teampage extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return $this->db_tools->sql_table_exists($this->table_prefix . 'teampage'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_schema() + { + return array( + 'add_tables' => array( + $this->table_prefix . 'teampage' => array( + 'COLUMNS' => array( + 'teampage_id' => array('UINT', null, 'auto_increment'), + 'group_id' => array('UINT', 0), + 'teampage_name' => array('VCHAR_UNI:255', ''), + 'teampage_position' => array('UINT', 0), + 'teampage_parent' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'teampage_id', + ), + ), + 'drop_columns' => array( + $this->table_prefix . 'groups' => array( + 'group_teampage', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_tables' => array( + $this->table_prefix . 'teampage', + ), + 'add_columns' => array( + $this->table_prefix . 'groups' => array( + 'group_teampage' => array('UINT', 0, 'after' => 'group_legend'), + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'add_groups_teampage'))), + ); + } + + public function add_groups_teampage() + { + $sql = 'SELECT teampage_id + FROM ' . TEAMPAGE_TABLE; + $result = $this->db->sql_query_limit($sql, 1); + $added_groups_teampage = (bool) $this->db->sql_fetchfield('teampage_id'); + $this->db->sql_freeresult($result); + + if (!$added_groups_teampage) + { + $sql = 'SELECT * + FROM ' . GROUPS_TABLE . ' + WHERE group_type = ' . GROUP_SPECIAL . " + AND (group_name = 'ADMINISTRATORS' + OR group_name = 'GLOBAL_MODERATORS') + ORDER BY group_name ASC"; + $result = $this->db->sql_query($sql); + + $teampage_entries = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $teampage_entries[] = array( + 'group_id' => (int) $row['group_id'], + 'teampage_name' => '', + 'teampage_position' => sizeof($teampage_entries) + 1, + 'teampage_parent' => 0, + ); + } + $this->db->sql_freeresult($result); + + if (sizeof($teampage_entries)) + { + $this->db->sql_multi_insert(TEAMPAGE_TABLE, $teampage_entries); + } + unset($teampage_entries); + } + + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/timezone.php b/phpBB/phpbb/db/migration/data/v310/timezone.php new file mode 100644 index 0000000000..1f6b47ad50 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/timezone.php @@ -0,0 +1,194 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class timezone extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_dst'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v30x\release_3_0_11'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_timezone' => array('VCHAR:100', ''), + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_timezones'))), + ); + } + + public function update_timezones($start) + { + $start = (int) $start; + $limit = 500; + $converted = 0; + + $update_blocks = array(); + + $sql = 'SELECT user_id, user_timezone, user_dst + FROM ' . $this->table_prefix . 'users + ORDER BY user_id ASC'; + $result = $this->db->sql_query_limit($sql, $limit, $start); + while ($row = $this->db->sql_fetchrow($result)) + { + $converted++; + + // In case this is somehow run twice on a row. + // Otherwise it would just end up as UTC on the second run + if (is_numeric($row['user_timezone'])) + { + $update_blocks[$row['user_timezone'] . ':' . $row['user_dst']][] = (int) $row['user_id']; + } + } + $this->db->sql_freeresult($result); + + // Update blocks of users who share the same timezone/dst + foreach ($update_blocks as $timezone => $user_ids) + { + $timezone = explode(':', $timezone); + $converted_timezone = $this->convert_phpbb30_timezone($timezone[0], $timezone[1]); + + $sql = 'UPDATE ' . $this->table_prefix . "users + SET user_timezone = '" . $this->db->sql_escape($converted_timezone) . "' + WHERE " . $this->db->sql_in_set('user_id', $user_ids); + $this->sql_query($sql); + } + + if ($converted == $limit) + { + // There are still more to convert + return $start + $limit; + } + + // Update board default timezone + $sql = 'UPDATE ' . $this->table_prefix . "config + SET config_value = '" . $this->convert_phpbb30_timezone($this->config['board_timezone'], $this->config['board_dst']) . "' + WHERE config_name = 'board_timezone'"; + $this->sql_query($sql); + } + + /** + * Determine the new timezone for a given phpBB 3.0 timezone and + * "Daylight Saving Time" option + * + * @param $timezone float Users timezone in 3.0 + * @param $dst int Users daylight saving time + * @return string Users new php Timezone which is used since 3.1 + */ + public function convert_phpbb30_timezone($timezone, $dst) + { + $offset = $timezone + $dst; + + switch ($timezone) + { + case '-12': + return 'Etc/GMT+' . abs($offset); //'[UTC - 12] Baker Island Time' + case '-11': + return 'Etc/GMT+' . abs($offset); //'[UTC - 11] Niue Time, Samoa Standard Time' + case '-10': + return 'Etc/GMT+' . abs($offset); //'[UTC - 10] Hawaii-Aleutian Standard Time, Cook Island Time' + case '-9.5': + return 'Pacific/Marquesas'; //'[UTC - 9:30] Marquesas Islands Time' + case '-9': + return 'Etc/GMT+' . abs($offset); //'[UTC - 9] Alaska Standard Time, Gambier Island Time' + case '-8': + return 'Etc/GMT+' . abs($offset); //'[UTC - 8] Pacific Standard Time' + case '-7': + return 'Etc/GMT+' . abs($offset); //'[UTC - 7] Mountain Standard Time' + case '-6': + return 'Etc/GMT+' . abs($offset); //'[UTC - 6] Central Standard Time' + case '-5': + return 'Etc/GMT+' . abs($offset); //'[UTC - 5] Eastern Standard Time' + case '-4.5': + return 'America/Caracas'; //'[UTC - 4:30] Venezuelan Standard Time' + case '-4': + return 'Etc/GMT+' . abs($offset); //'[UTC - 4] Atlantic Standard Time' + case '-3.5': + return 'America/St_Johns'; //'[UTC - 3:30] Newfoundland Standard Time' + case '-3': + return 'Etc/GMT+' . abs($offset); //'[UTC - 3] Amazon Standard Time, Central Greenland Time' + case '-2': + return 'Etc/GMT+' . abs($offset); //'[UTC - 2] Fernando de Noronha Time, South Georgia & the South Sandwich Islands Time' + case '-1': + return 'Etc/GMT+' . abs($offset); //'[UTC - 1] Azores Standard Time, Cape Verde Time, Eastern Greenland Time' + case '0': + return (!$dst) ? 'UTC' : 'Etc/GMT-1'; //'[UTC] Western European Time, Greenwich Mean Time' + case '1': + return 'Etc/GMT-' . $offset; //'[UTC + 1] Central European Time, West African Time' + case '2': + return 'Etc/GMT-' . $offset; //'[UTC + 2] Eastern European Time, Central African Time' + case '3': + return 'Etc/GMT-' . $offset; //'[UTC + 3] Moscow Standard Time, Eastern African Time' + case '3.5': + return 'Asia/Tehran'; //'[UTC + 3:30] Iran Standard Time' + case '4': + return 'Etc/GMT-' . $offset; //'[UTC + 4] Gulf Standard Time, Samara Standard Time' + case '4.5': + return 'Asia/Kabul'; //'[UTC + 4:30] Afghanistan Time' + case '5': + return 'Etc/GMT-' . $offset; //'[UTC + 5] Pakistan Standard Time, Yekaterinburg Standard Time' + case '5.5': + return 'Asia/Kolkata'; //'[UTC + 5:30] Indian Standard Time, Sri Lanka Time' + case '5.75': + return 'Asia/Kathmandu'; //'[UTC + 5:45] Nepal Time' + case '6': + return 'Etc/GMT-' . $offset; //'[UTC + 6] Bangladesh Time, Bhutan Time, Novosibirsk Standard Time' + case '6.5': + return 'Indian/Cocos'; //'[UTC + 6:30] Cocos Islands Time, Myanmar Time' + case '7': + return 'Etc/GMT-' . $offset; //'[UTC + 7] Indochina Time, Krasnoyarsk Standard Time' + case '8': + return 'Etc/GMT-' . $offset; //'[UTC + 8] Chinese Standard Time, Australian Western Standard Time, Irkutsk Standard Time' + case '8.75': + return 'Australia/Eucla'; //'[UTC + 8:45] Southeastern Western Australia Standard Time' + case '9': + return 'Etc/GMT-' . $offset; //'[UTC + 9] Japan Standard Time, Korea Standard Time, Chita Standard Time' + case '9.5': + return 'Australia/ACT'; //'[UTC + 9:30] Australian Central Standard Time' + case '10': + return 'Etc/GMT-' . $offset; //'[UTC + 10] Australian Eastern Standard Time, Vladivostok Standard Time' + case '10.5': + return 'Australia/Lord_Howe'; //'[UTC + 10:30] Lord Howe Standard Time' + case '11': + return 'Etc/GMT-' . $offset; //'[UTC + 11] Solomon Island Time, Magadan Standard Time' + case '11.5': + return 'Pacific/Norfolk'; //'[UTC + 11:30] Norfolk Island Time' + case '12': + return 'Etc/GMT-12'; //'[UTC + 12] New Zealand Time, Fiji Time, Kamchatka Standard Time' + case '12.75': + return 'Pacific/Chatham'; //'[UTC + 12:45] Chatham Islands Time' + case '13': + return 'Pacific/Tongatapu'; //'[UTC + 13] Tonga Time, Phoenix Islands Time' + case '14': + return 'Pacific/Kiritimati'; //'[UTC + 14] Line Island Time' + default: + return 'UTC'; + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/timezone_p2.php b/phpBB/phpbb/db/migration/data/v310/timezone_p2.php new file mode 100644 index 0000000000..3ac7ab3c51 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/timezone_p2.php @@ -0,0 +1,49 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class timezone_p2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return !$this->db_tools->sql_column_exists($this->table_prefix . 'users', 'user_dst'); + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\timezone'); + } + + public function update_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'users' => array( + 'user_dst', + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'users' => array( + 'user_dst' => array('BOOL', 0), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/topic_sort_username.php b/phpBB/phpbb/db/migration/data/v310/topic_sort_username.php new file mode 100644 index 0000000000..527da20590 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/topic_sort_username.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class topic_sort_username extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'topics' => array( + 'topic_first_poster_name' => array('VCHAR_UNI:255', '', 'true_sort'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'topics' => array( + 'topic_first_poster_name' => array('VCHAR_UNI:255', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v310/ucp_popuppm_module.php b/phpBB/phpbb/db/migration/data/v310/ucp_popuppm_module.php new file mode 100644 index 0000000000..8600f6ee27 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v310/ucp_popuppm_module.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v310; + +class ucp_popuppm_module extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + $sql = 'SELECT module_id + FROM ' . MODULES_TABLE . " + WHERE module_class = 'ucp' + AND module_langname = 'UCP_PM_POPUP_TITLE'"; + $result = $this->db->sql_query($sql); + $module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + return $module_id == false; + } + + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\dev'); + } + + public function update_data() + { + return array( + array('module.remove', array( + 'ucp', + 'UCP_PM', + 'UCP_PM_POPUP_TITLE', + )), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/.htaccess b/phpBB/phpbb/db/migration/data/v31x/.htaccess new file mode 100644 index 0000000000..44242b5418 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/.htaccess @@ -0,0 +1,33 @@ +# With Apache 2.4 the "Order, Deny" syntax has been deprecated and moved from +# module mod_authz_host to a new module called mod_access_compat (which may be +# disabled) and a new "Require" syntax has been introduced to mod_authz_host. +# We could just conditionally provide both versions, but unfortunately Apache +# does not explicitly tell us its version if the module mod_version is not +# available. In this case, we check for the availability of module +# mod_authz_core (which should be on 2.4 or higher only) as a best guess. +<IfModule mod_version.c> + <IfVersion < 2.4> + <Files "*"> + Order Allow,Deny + Deny from All + </Files> + </IfVersion> + <IfVersion >= 2.4> + <Files "*"> + Require all denied + </Files> + </IfVersion> +</IfModule> +<IfModule !mod_version.c> + <IfModule !mod_authz_core.c> + <Files "*"> + Order Allow,Deny + Deny from All + </Files> + </IfModule> + <IfModule mod_authz_core.c> + <Files "*"> + Require all denied + </Files> + </IfModule> +</IfModule> diff --git a/phpBB/phpbb/db/migration/data/v31x/add_jabber_ssl_context_config_options.php b/phpBB/phpbb/db/migration/data/v31x/add_jabber_ssl_context_config_options.php new file mode 100644 index 0000000000..9f416fe069 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/add_jabber_ssl_context_config_options.php @@ -0,0 +1,32 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class add_jabber_ssl_context_config_options extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v3110'); + } + + public function update_data() + { + return array( + // See http://php.net/manual/en/context.ssl.php + array('config.add', array('jab_verify_peer', 1)), + array('config.add', array('jab_verify_peer_name', 1)), + array('config.add', array('jab_allow_self_signed', 0)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/add_latest_topics_index.php b/phpBB/phpbb/db/migration/data/v31x/add_latest_topics_index.php new file mode 100644 index 0000000000..fa2899e348 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/add_latest_topics_index.php @@ -0,0 +1,51 @@ +<?php +/** + * + * This file is part of the phpBB Forum Software package. + * + * @copyright (c) phpBB Limited <https://www.phpbb.com> + * @license GNU General Public License, version 2 (GPL-2.0) + * + * For full copyright and license information, please see + * the docs/CREDITS.txt file. + * + */ + +namespace phpbb\db\migration\data\v31x; + +class add_latest_topics_index extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v3110', + ); + } + + public function update_schema() + { + return array( + 'add_index' => array( + $this->table_prefix . 'topics' => array( + 'latest_topics' => array( + 'forum_id', + 'topic_last_post_time', + 'topic_last_post_id', + 'topic_moved_id', + ), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_keys' => array( + $this->table_prefix . 'topics' => array( + 'latest_topics', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/add_log_time_index.php b/phpBB/phpbb/db/migration/data/v31x/add_log_time_index.php new file mode 100644 index 0000000000..f53eedcd49 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/add_log_time_index.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class add_log_time_index extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v319', + ); + } + + public function update_schema() + { + return array( + 'add_index' => array( + $this->table_prefix . 'log' => array( + 'log_time' => array('log_time'), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_keys' => array( + $this->table_prefix . 'log' => array( + 'log_time', + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/add_smtp_ssl_context_config_options.php b/phpBB/phpbb/db/migration/data/v31x/add_smtp_ssl_context_config_options.php new file mode 100644 index 0000000000..92051dc3ca --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/add_smtp_ssl_context_config_options.php @@ -0,0 +1,32 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class add_smtp_ssl_context_config_options extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v3110'); + } + + public function update_data() + { + return array( + // See http://php.net/manual/en/context.ssl.php + array('config.add', array('smtp_verify_peer', 1)), + array('config.add', array('smtp_verify_peer_name', 1)), + array('config.add', array('smtp_allow_self_signed', 0)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/increase_size_of_dateformat.php b/phpBB/phpbb/db/migration/data/v31x/increase_size_of_dateformat.php new file mode 100644 index 0000000000..bdf83f3d62 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/increase_size_of_dateformat.php @@ -0,0 +1,35 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class increase_size_of_dateformat extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v317', + ); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'users' => array( + 'user_dateformat' => array('VCHAR_UNI:64', 'd M Y H:i'), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/increase_size_of_emotion.php b/phpBB/phpbb/db/migration/data/v31x/increase_size_of_emotion.php new file mode 100644 index 0000000000..7e486aca7c --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/increase_size_of_emotion.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class increase_size_of_emotion extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v3110', + ); + } + + public function update_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'smilies' => array( + 'emotion' => array('VCHAR_UNI', ''), + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'change_columns' => array( + $this->table_prefix . 'smilies' => array( + 'emotion' => array('VCHAR_UNI:50', ''), + ), + ), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/m_pm_report.php b/phpBB/phpbb/db/migration/data/v31x/m_pm_report.php new file mode 100644 index 0000000000..9b5710c639 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/m_pm_report.php @@ -0,0 +1,64 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class m_pm_report extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v316rc1'); + } + + public function update_data() + { + return array( + array('permission.add', array('m_pm_report', true, 'm_report')), + array('custom', array( + array($this, 'update_module_auth'), + ), + ), + ); + } + + public function revert_data() + { + return array( + array('permission.remove', array('m_pm_report')), + array('custom', array( + array($this, 'revert_module_auth'), + ), + ), + ); + } + + public function update_module_auth() + { + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_auth = 'acl_m_pm_report' + WHERE module_class = 'mcp' + AND module_basename = 'mcp_pm_reports' + AND module_auth = 'aclf_m_report'"; + $this->db->sql_query($sql); + } + + public function revert_module_auth() + { + $sql = 'UPDATE ' . MODULES_TABLE . " + SET module_auth = 'aclf_m_report' + WHERE module_class = 'mcp' + AND module_basename = 'mcp_pm_reports' + AND module_auth = 'acl_m_pm_report'"; + $this->db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/m_softdelete_global.php b/phpBB/phpbb/db/migration/data/v31x/m_softdelete_global.php new file mode 100644 index 0000000000..dd7e20e762 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/m_softdelete_global.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class m_softdelete_global extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v311'); + } + + public function update_data() + { + return array( + // Make m_softdelete global. The add method will take care of updating + // it if it already exists. + array('permission.add', array('m_softdelete', true)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/plupload_last_gc_dynamic.php b/phpBB/phpbb/db/migration/data/v31x/plupload_last_gc_dynamic.php new file mode 100644 index 0000000000..0783d707c5 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/plupload_last_gc_dynamic.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class plupload_last_gc_dynamic extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v312'); + } + + public function update_data() + { + return array( + // Make plupload_last_gc dynamic. + array('config.remove', array('plupload_last_gc')), + array('config.add', array('plupload_last_gc', 0, 1)), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/profilefield_remove_underscore_from_alpha.php b/phpBB/phpbb/db/migration/data/v31x/profilefield_remove_underscore_from_alpha.php new file mode 100644 index 0000000000..60491f8de8 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/profilefield_remove_underscore_from_alpha.php @@ -0,0 +1,47 @@ +<?php + +/** + * + * This file is part of the phpBB Forum Software package. + * + * @copyright (c) phpBB Limited <https://www.phpbb.com> + * @license GNU General Public License, version 2 (GPL-2.0) + * + * For full copyright and license information, please see + * the docs/CREDITS.txt file. + * + */ + +namespace phpbb\db\migration\data\v31x; + +class profilefield_remove_underscore_from_alpha extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v311'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'remove_underscore_from_alpha_validations'))), + ); + } + + public function remove_underscore_from_alpha_validations() + { + $this->update_validation_rule('[\w]+', '[a-zA-Z0-9]+'); + $this->update_validation_rule('[\w_]+', '[\w]+'); + $this->update_validation_rule('[\w.]+', '[a-zA-Z0-9.]+'); + $this->update_validation_rule('[\w\x20_+\-\[\]]+', '[\w\x20+\-\[\]]+'); + $this->update_validation_rule('[a-zA-Z][\w\.,\-_]+', '[a-zA-Z][\w\.,\-]+'); + } + + public function update_validation_rule($old_validation, $new_validation) + { + $sql = 'UPDATE ' . PROFILE_FIELDS_TABLE . " + SET field_validation = '" . $this->db->sql_escape($new_validation) . "' + WHERE field_validation = '" . $this->db->sql_escape($old_validation) . "'"; + $this->db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/profilefield_yahoo_update_url.php b/phpBB/phpbb/db/migration/data/v31x/profilefield_yahoo_update_url.php new file mode 100644 index 0000000000..4df9083bdf --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/profilefield_yahoo_update_url.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class profilefield_yahoo_update_url extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v312'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_contact_url'))), + ); + } + + public function update_contact_url() + { + $sql = 'UPDATE ' . $this->table_prefix . "profile_fields + SET field_contact_url = 'ymsgr:sendim?%s' + WHERE field_name = 'phpbb_yahoo' + AND field_contact_url = 'http://edit.yahoo.com/config/send_webmesg?.target=%s&.src=pg'"; + $this->sql_query($sql); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/remove_duplicate_migrations.php b/phpBB/phpbb/db/migration/data/v31x/remove_duplicate_migrations.php new file mode 100644 index 0000000000..417d569a09 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/remove_duplicate_migrations.php @@ -0,0 +1,77 @@ +<?php + +/** + * + * This file is part of the phpBB Forum Software package. + * + * @copyright (c) phpBB Limited <https://www.phpbb.com> + * @license GNU General Public License, version 2 (GPL-2.0) + * + * For full copyright and license information, please see + * the docs/CREDITS.txt file. + * + */ + +namespace phpbb\db\migration\data\v31x; + +class remove_duplicate_migrations extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v31x\v3110'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'deduplicate_entries'))), + ); + } + + public function deduplicate_entries() + { + $migration_state = array(); + $duplicate_migrations = array(); + + $sql = "SELECT * + FROM " . $this->table_prefix . 'migrations'; + $result = $this->db->sql_query($sql); + + if (!$this->db->get_sql_error_triggered()) + { + while ($migration = $this->db->sql_fetchrow($result)) + { + $migration_state[$migration['migration_name']] = $migration; + + $migration_state[$migration['migration_name']]['migration_depends_on'] = unserialize($migration['migration_depends_on']); + } + } + + $this->db->sql_freeresult($result); + + foreach ($migration_state as $name => $migration) + { + $prepended_name = ($name[0] == '\\' ? '' : '\\') . $name; + $prefixless_name = $name[0] == '\\' ? substr($name, 1) : $name; + + if ($prepended_name != $name && isset($migration_state[$prepended_name]) && $migration_state[$prepended_name]['migration_depends_on'] == $migration_state[$name]['migration_depends_on']) + { + $duplicate_migrations[] = $name; + unset($migration_state[$prepended_name]); + } + else if ($prefixless_name != $name && isset($migration_state[$prefixless_name]) && $migration_state[$prefixless_name]['migration_depends_on'] == $migration_state[$name]['migration_depends_on']) + { + $duplicate_migrations[] = $prefixless_name; + unset($migration_state[$prefixless_name]); + } + } + + if (count($duplicate_migrations)) + { + $sql = 'DELETE + FROM ' . $this->table_prefix . 'migrations + WHERE ' . $this->db->sql_in_set('migration_name', $duplicate_migrations); + $this->db->sql_query($sql); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/style_update.php b/phpBB/phpbb/db/migration/data/v31x/style_update.php new file mode 100644 index 0000000000..bb030bbe6d --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/style_update.php @@ -0,0 +1,136 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class style_update extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array('\phpbb\db\migration\data\v310\gold'); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_installed_styles'))), + ); + } + + public function update_installed_styles() + { + // Get all currently available styles + $styles = $this->find_style_dirs(); + $style_paths = $style_ids = array(); + + $sql = 'SELECT style_path, style_id + FROM ' . $this->table_prefix . 'styles'; + $result = $this->db->sql_query($sql); + while ($styles_row = $this->db->sql_fetchrow()) + { + if (in_array($styles_row['style_path'], $styles)) + { + $style_paths[] = $styles_row['style_path']; + $style_ids[] = $styles_row['style_id']; + } + } + $this->db->sql_freeresult($result); + + // Install prosilver if no style is available and prosilver can be installed + if (empty($style_paths) && in_array('prosilver', $styles)) + { + // Try to parse config file + $cfg = parse_cfg_file($this->phpbb_root_path . 'styles/prosilver/style.cfg'); + + // Stop running this if prosilver cfg file can't be read + if (empty($cfg)) + { + throw new \RuntimeException('No styles available and could not fall back to prosilver.'); + } + + $style = array( + 'style_name' => 'prosilver', + 'style_copyright' => '© phpBB Limited', + 'style_active' => 1, + 'style_path' => 'prosilver', + 'bbcode_bitfield' => 'kNg=', + 'style_parent_id' => 0, + 'style_parent_tree' => '', + ); + + // Add to database + $this->db->sql_transaction('begin'); + + $sql = 'INSERT INTO ' . $this->table_prefix . 'styles + ' . $this->db->sql_build_array('INSERT', $style); + $this->db->sql_query($sql); + + $style_id = $this->db->sql_nextid(); + $style_ids[] = $style_id; + + $this->db->sql_transaction('commit'); + + // Set prosilver to default style + $this->config->set('default_style', $style_id); + } + else if (empty($styles) && empty($available_styles)) + { + throw new \RuntimeException('No valid styles available'); + } + + // Make sure default style is available + if (!in_array($this->config['default_style'], $style_ids)) + { + $this->config->set('default_style', array_pop($style_ids)); + } + + // Reset users to default style if their user_style is nonexistent + $sql = 'UPDATE ' . $this->table_prefix . "users + SET user_style = {$this->config['default_style']} + WHERE " . $this->db->sql_in_set('user_style', $style_ids, true, true); + $this->db->sql_query($sql); + } + + /** + * Find all directories that have styles + * Copied from acp_styles + * + * @return array Directory names + */ + protected function find_style_dirs() + { + $styles = array(); + $styles_path = $this->phpbb_root_path . 'styles/'; + + $dp = @opendir($styles_path); + if ($dp) + { + while (($file = readdir($dp)) !== false) + { + $dir = $styles_path . $file; + if ($file[0] == '.' || !is_dir($dir)) + { + continue; + } + + if (file_exists("{$dir}/style.cfg")) + { + $styles[] = $file; + } + } + closedir($dp); + } + + return $styles; + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/update_custom_bbcodes_with_idn.php b/phpBB/phpbb/db/migration/data/v31x/update_custom_bbcodes_with_idn.php new file mode 100644 index 0000000000..854ed1f568 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/update_custom_bbcodes_with_idn.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class update_custom_bbcodes_with_idn extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v312', + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'update_bbcodes_table'))), + ); + } + + public function update_bbcodes_table() + { + if (!class_exists('acp_bbcodes')) + { + include($this->phpbb_root_path . 'includes/acp/acp_bbcodes.' . $this->php_ext); + } + + $bbcodes = new \acp_bbcodes(); + + $sql = 'SELECT bbcode_id, bbcode_match, bbcode_tpl + FROM ' . BBCODES_TABLE; + $result = $this->sql_query($sql); + + $sql_ary = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $data = array(); + if (preg_match('/(URL|LOCAL_URL|RELATIVE_URL)/', $row['bbcode_match'])) + { + $data = $bbcodes->build_regexp($row['bbcode_match'], $row['bbcode_tpl']); + $sql_ary[$row['bbcode_id']] = array( + 'first_pass_match' => $data['first_pass_match'], + 'first_pass_replace' => $data['first_pass_replace'], + 'second_pass_match' => $data['second_pass_match'], + 'second_pass_replace' => $data['second_pass_replace'] + ); + } + } + $this->db->sql_freeresult($result); + + foreach ($sql_ary as $bbcode_id => $bbcode_data) + { + $sql = 'UPDATE ' . BBCODES_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $bbcode_data) . ' + WHERE bbcode_id = ' . (int) $bbcode_id; + $this->sql_query($sql); + } + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/update_hashes.php b/phpBB/phpbb/db/migration/data/v31x/update_hashes.php new file mode 100644 index 0000000000..aa83c3ffbf --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/update_hashes.php @@ -0,0 +1,33 @@ +<?php +/** + * + * This file is part of the phpBB Forum Software package. + * + * @copyright (c) phpBB Limited <https://www.phpbb.com> + * @license GNU General Public License, version 2 (GPL-2.0) + * + * For full copyright and license information, please see + * the docs/CREDITS.txt file. + * + */ + +namespace phpbb\db\migration\data\v31x; + +class update_hashes extends \phpbb\db\migration\migration +{ + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v3110', + ); + } + + public function update_data() + { + return array( + array('config.add', array('enable_update_hashes', '1')), + array('config.add', array('update_hashes_lock', '')), + array('config.add', array('update_hashes_last_cron', '0')) + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v311.php b/phpBB/phpbb/db/migration/data/v31x/v311.php new file mode 100644 index 0000000000..b9d6ed3053 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v311.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v311 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v310\gold', + '\phpbb\db\migration\data\v31x\style_update', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v3110.php b/phpBB/phpbb/db/migration/data/v31x/v3110.php new file mode 100644 index 0000000000..b89b4cc6e6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v3110.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v3110 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.10', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v3110rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.10')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v3110rc1.php b/phpBB/phpbb/db/migration/data/v31x/v3110rc1.php new file mode 100644 index 0000000000..da69f2384e --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v3110rc1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v3110rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.10-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v319', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.10-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v3111.php b/phpBB/phpbb/db/migration/data/v31x/v3111.php new file mode 100644 index 0000000000..f01bbc2bff --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v3111.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v3111 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.11', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v3111rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.11')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v3111rc1.php b/phpBB/phpbb/db/migration/data/v31x/v3111rc1.php new file mode 100644 index 0000000000..259656283f --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v3111rc1.php @@ -0,0 +1,43 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v3111rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.11-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v3110', + '\phpbb\db\migration\data\v31x\add_log_time_index', + '\phpbb\db\migration\data\v31x\increase_size_of_emotion', + '\phpbb\db\migration\data\v31x\add_jabber_ssl_context_config_options', + '\phpbb\db\migration\data\v31x\add_smtp_ssl_context_config_options', + '\phpbb\db\migration\data\v31x\update_hashes', + '\phpbb\db\migration\data\v31x\remove_duplicate_migrations', + '\phpbb\db\migration\data\v31x\add_latest_topics_index', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.11-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v312.php b/phpBB/phpbb/db/migration/data/v31x/v312.php new file mode 100644 index 0000000000..114c2b959b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v312.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v312 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.2', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v312rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v312rc1.php b/phpBB/phpbb/db/migration/data/v31x/v312rc1.php new file mode 100644 index 0000000000..e2408d432b --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v312rc1.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v312rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.2-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v311', + '\phpbb\db\migration\data\v31x\m_softdelete_global', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.2-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v313.php b/phpBB/phpbb/db/migration/data/v31x/v313.php new file mode 100644 index 0000000000..b86788da16 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v313.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v313 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.3', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v313rc2', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.3')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v313rc1.php b/phpBB/phpbb/db/migration/data/v31x/v313rc1.php new file mode 100644 index 0000000000..b1dcc03364 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v313rc1.php @@ -0,0 +1,40 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v313rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.3-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v30x\release_3_0_13_rc1', + '\phpbb\db\migration\data\v31x\plupload_last_gc_dynamic', + '\phpbb\db\migration\data\v31x\profilefield_remove_underscore_from_alpha', + '\phpbb\db\migration\data\v31x\profilefield_yahoo_update_url', + '\phpbb\db\migration\data\v31x\update_custom_bbcodes_with_idn', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.3-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v313rc2.php b/phpBB/phpbb/db/migration/data/v31x/v313rc2.php new file mode 100644 index 0000000000..b701dca5ed --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v313rc2.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v313rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.3-RC2', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v30x\release_3_0_13_pl1', + '\phpbb\db\migration\data\v31x\v313rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.3-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v314.php b/phpBB/phpbb/db/migration/data/v31x/v314.php new file mode 100644 index 0000000000..82dbbf29c9 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v314.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v314 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.4', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v30x\release_3_0_14', + '\phpbb\db\migration\data\v31x\v314rc2', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.4')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v314rc1.php b/phpBB/phpbb/db/migration/data/v31x/v314rc1.php new file mode 100644 index 0000000000..e7baf0c2ce --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v314rc1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v314rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.4-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v313', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.4-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v314rc2.php b/phpBB/phpbb/db/migration/data/v31x/v314rc2.php new file mode 100644 index 0000000000..3fc5bf2ad5 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v314rc2.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v314rc2 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.4-RC2', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v30x\release_3_0_14_rc1', + '\phpbb\db\migration\data\v31x\v314rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.4-RC2')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v315.php b/phpBB/phpbb/db/migration/data/v31x/v315.php new file mode 100644 index 0000000000..d5eacf8dd3 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v315.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v315 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.5', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v315rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.5')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v315rc1.php b/phpBB/phpbb/db/migration/data/v31x/v315rc1.php new file mode 100644 index 0000000000..a58b6a0f2a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v315rc1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v315rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.5-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v314', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.5-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v316.php b/phpBB/phpbb/db/migration/data/v31x/v316.php new file mode 100644 index 0000000000..b3e0060ced --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v316.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v316 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.6', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v316rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.6')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v316rc1.php b/phpBB/phpbb/db/migration/data/v31x/v316rc1.php new file mode 100644 index 0000000000..6badfb68d4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v316rc1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v316rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.6-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v315', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.6-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v317.php b/phpBB/phpbb/db/migration/data/v31x/v317.php new file mode 100644 index 0000000000..d95be06ba6 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v317.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v317 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.7', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v317rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.7')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v317pl1.php b/phpBB/phpbb/db/migration/data/v31x/v317pl1.php new file mode 100644 index 0000000000..1cb39b03f0 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v317pl1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v317pl1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.7-pl1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v317', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.7-pl1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v317rc1.php b/phpBB/phpbb/db/migration/data/v31x/v317rc1.php new file mode 100644 index 0000000000..77759daa66 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v317rc1.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v317rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.7-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\m_pm_report', + '\phpbb\db\migration\data\v31x\v316', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.7-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v318.php b/phpBB/phpbb/db/migration/data/v31x/v318.php new file mode 100644 index 0000000000..7663529d3a --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v318.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v318 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.8', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v318rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.8')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v318rc1.php b/phpBB/phpbb/db/migration/data/v31x/v318rc1.php new file mode 100644 index 0000000000..2cab5c96d4 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v318rc1.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v318rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.8-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\increase_size_of_dateformat', + '\phpbb\db\migration\data\v31x\v317pl1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.8-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v319.php b/phpBB/phpbb/db/migration/data/v31x/v319.php new file mode 100644 index 0000000000..f773814028 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v319.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v319 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.9', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v319rc1', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.9')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/data/v31x/v319rc1.php b/phpBB/phpbb/db/migration/data/v31x/v319rc1.php new file mode 100644 index 0000000000..9805b45572 --- /dev/null +++ b/phpBB/phpbb/db/migration/data/v31x/v319rc1.php @@ -0,0 +1,36 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\data\v31x; + +class v319rc1 extends \phpbb\db\migration\migration +{ + public function effectively_installed() + { + return phpbb_version_compare($this->config['version'], '3.1.9-RC1', '>='); + } + + static public function depends_on() + { + return array( + '\phpbb\db\migration\data\v31x\v318', + ); + } + + public function update_data() + { + return array( + array('config.update', array('version', '3.1.9-RC1')), + ); + } +} diff --git a/phpBB/phpbb/db/migration/exception.php b/phpBB/phpbb/db/migration/exception.php new file mode 100644 index 0000000000..7990e85f2d --- /dev/null +++ b/phpBB/phpbb/db/migration/exception.php @@ -0,0 +1,75 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration; + +/** +* The migrator is responsible for applying new migrations in the correct order. +*/ +class exception extends \Exception +{ + /** + * Extra parameters sent to exception to aid in debugging + * @var array + */ + protected $parameters; + + /** + * Throw an exception. + * + * First argument is the error message. + * Additional arguments will be output with the error message. + */ + public function __construct() + { + $parameters = func_get_args(); + $message = array_shift($parameters); + parent::__construct($message); + + $this->parameters = $parameters; + } + + /** + * Output the error as a string + * + * @return string + */ + public function __toString() + { + return $this->message . ': ' . var_export($this->parameters, true); + } + + /** + * Get the parameters + * + * @return array + */ + public function getParameters() + { + return $this->parameters; + } + + /** + * Get localised message (with $user->lang()) + * + * @param \phpbb\user $user + * @return string + */ + public function getLocalisedMessage(\phpbb\user $user) + { + $parameters = $this->getParameters(); + array_unshift($parameters, $this->getMessage()); + + return call_user_func_array(array($user, 'lang'), $parameters); + } +} diff --git a/phpBB/phpbb/db/migration/helper.php b/phpBB/phpbb/db/migration/helper.php new file mode 100644 index 0000000000..bce2efff51 --- /dev/null +++ b/phpBB/phpbb/db/migration/helper.php @@ -0,0 +1,116 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration; + +/** +* The migrator is responsible for applying new migrations in the correct order. +*/ +class helper +{ + /** + * Get the schema steps from an array of schema changes + * + * This splits up $schema_changes into individual changes so that the + * changes can be chunked + * + * @param array $schema_changes from migration + * @return array + */ + public function get_schema_steps($schema_changes) + { + $steps = array(); + + // Nested level of data (only supports 1/2 currently) + $nested_level = array( + 'drop_tables' => 1, + 'add_tables' => 1, + 'change_columns' => 2, + 'add_columns' => 2, + 'drop_keys' => 2, + 'drop_columns' => 2, + 'add_primary_keys' => 2, // perform_schema_changes only uses one level, but second is in the function + 'add_unique_index' => 2, + 'add_index' => 2, + ); + + foreach ($nested_level as $change_type => $data_depth) + { + if (!empty($schema_changes[$change_type])) + { + foreach ($schema_changes[$change_type] as $key => $value) + { + if ($data_depth === 1) + { + $steps[] = array( + 'dbtools.perform_schema_changes', array(array( + $change_type => array( + (!is_int($key)) ? $key : 0 => $value, + ), + )), + ); + } + else if ($data_depth === 2) + { + foreach ($value as $key2 => $value2) + { + $steps[] = array( + 'dbtools.perform_schema_changes', array(array( + $change_type => array( + $key => array( + $key2 => $value2, + ), + ), + )), + ); + } + } + } + } + } + + return $steps; + } + + /** + * Reverse the update steps from an array of data changes + * + * 'If' statements and custom methods will be skipped, for all + * other calls the reverse method of the tool class will be called + * + * @param array $steps Update changes from migration + * + * @return array + */ + public function reverse_update_data($steps) + { + $reversed_array = array(); + + foreach ($steps as $step) + { + $parts = explode('.', $step[0]); + $parameters = $step[1]; + + $class = $parts[0]; + $method = isset($parts[1]) ? $parts[1] : false; + + if ($class !== 'if' && $class !== 'custom') + { + array_unshift($parameters, $method); + $reversed_array[] = array($class . '.reverse', $parameters); + } + } + + return array_reverse($reversed_array); + } +} diff --git a/phpBB/phpbb/db/migration/migration.php b/phpBB/phpbb/db/migration/migration.php new file mode 100644 index 0000000000..5f120333e1 --- /dev/null +++ b/phpBB/phpbb/db/migration/migration.php @@ -0,0 +1,186 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration; + +/** +* Abstract base class for database migrations +* +* Each migration consists of a set of schema and data changes to be implemented +* in a subclass. This class provides various utility methods to simplify editing +* a phpBB. +*/ +abstract class migration +{ + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\db\tools */ + protected $db_tools; + + /** @var string */ + protected $table_prefix; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** @var array Errors, if any occurred */ + protected $errors; + + /** @var array List of queries executed through $this->sql_query() */ + protected $queries = array(); + + /** + * Constructor + * + * @param \phpbb\config\config $config + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\db\tools $db_tools + * @param string $phpbb_root_path + * @param string $php_ext + * @param string $table_prefix + */ + public function __construct(\phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\db\tools $db_tools, $phpbb_root_path, $php_ext, $table_prefix) + { + $this->config = $config; + $this->db = $db; + $this->db_tools = $db_tools; + $this->table_prefix = $table_prefix; + + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + + $this->errors = array(); + } + + /** + * Defines other migrations to be applied first + * + * @return array An array of migration class names + */ + static public function depends_on() + { + return array(); + } + + /** + * Allows you to check if the migration is effectively installed (entirely optional) + * + * This is checked when a migration is installed. If true is returned, the migration will be set as + * installed without performing the database changes. + * This function is intended to help moving to migrations from a previous database updater, where some + * migrations may have been installed already even though they are not yet listed in the migrations table. + * + * @return bool True if this migration is installed, False if this migration is not installed (checked on install) + */ + public function effectively_installed() + { + return false; + } + + /** + * Updates the database schema by providing a set of change instructions + * + * @return array Array of schema changes (compatible with db_tools->perform_schema_changes()) + */ + public function update_schema() + { + return array(); + } + + /** + * Reverts the database schema by providing a set of change instructions + * + * @return array Array of schema changes (compatible with db_tools->perform_schema_changes()) + */ + public function revert_schema() + { + return array(); + } + + /** + * Updates data by returning a list of instructions to be executed + * + * @return array Array of data update instructions + */ + public function update_data() + { + return array(); + } + + /** + * Reverts data by returning a list of instructions to be executed + * + * @return array Array of data instructions that will be performed on revert + * NOTE: calls to tools (such as config.add) are automatically reverted when + * possible, so you should not attempt to revert those, this is mostly for + * otherwise unrevertable calls (custom functions for example) + */ + public function revert_data() + { + return array(); + } + + /** + * Wrapper for running queries to generate user feedback on updates + * + * @param string $sql SQL query to run on the database + * @return mixed Query result from db->sql_query() + */ + protected function sql_query($sql) + { + $this->queries[] = $sql; + + $this->db->sql_return_on_error(true); + + if ($sql === 'begin') + { + $result = $this->db->sql_transaction('begin'); + } + else if ($sql === 'commit') + { + $result = $this->db->sql_transaction('commit'); + } + else + { + $result = $this->db->sql_query($sql); + if ($this->db->get_sql_error_triggered()) + { + $this->errors[] = array( + 'sql' => $this->db->get_sql_error_sql(), + 'code' => $this->db->get_sql_error_returned(), + ); + } + } + + $this->db->sql_return_on_error(false); + + return $result; + } + + /** + * Get the list of queries run + * + * @return array + */ + public function get_queries() + { + return $this->queries; + } +} diff --git a/phpBB/phpbb/db/migration/profilefield_base_migration.php b/phpBB/phpbb/db/migration/profilefield_base_migration.php new file mode 100644 index 0000000000..b20ca874be --- /dev/null +++ b/phpBB/phpbb/db/migration/profilefield_base_migration.php @@ -0,0 +1,247 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration; + +abstract class profilefield_base_migration extends container_aware_migration +{ + protected $profilefield_name; + + protected $profilefield_database_type; + + protected $profilefield_data; + + /** + * Language data should be in array -> each language_data in separate key + * array( + * array( + * 'option_id' => value, + * 'field_type' => value, + * 'lang_value' => value, + * ), + * array( + * 'option_id' => value, + * 'field_type' => value, + * 'lang_value' => value, + * ), + * ) + */ + protected $profilefield_language_data; + + protected $user_column_name; + + public function effectively_installed() + { + return $this->db_tools->sql_column_exists($this->table_prefix . 'profile_fields_data', 'pf_' . $this->profilefield_name); + } + + public function update_schema() + { + return array( + 'add_columns' => array( + $this->table_prefix . 'profile_fields_data' => array( + 'pf_' . $this->profilefield_name => $this->profilefield_database_type, + ), + ), + ); + } + + public function revert_schema() + { + return array( + 'drop_columns' => array( + $this->table_prefix . 'profile_fields_data' => array( + 'pf_' . $this->profilefield_name, + ), + ), + ); + } + + public function update_data() + { + return array( + array('custom', array(array($this, 'create_custom_field'))), + array('custom', array(array($this, 'convert_user_field_to_custom_field'))), + ); + } + + public function revert_data() + { + return array( + array('custom', array(array($this, 'delete_custom_profile_field_data'))), + ); + } + + public function create_custom_field() + { + $sql = 'SELECT MAX(field_order) as max_field_order + FROM ' . PROFILE_FIELDS_TABLE; + $result = $this->db->sql_query($sql); + $max_field_order = (int) $this->db->sql_fetchfield('max_field_order'); + $this->db->sql_freeresult($result); + + $sql_ary = array_merge($this->profilefield_data, array( + 'field_order' => $max_field_order + 1, + )); + + $sql = 'INSERT INTO ' . PROFILE_FIELDS_TABLE . ' ' . $this->db->sql_build_array('INSERT', $sql_ary); + $this->db->sql_query($sql); + $field_id = (int) $this->db->sql_nextid(); + + $insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, PROFILE_LANG_TABLE); + + $sql = 'SELECT lang_id + FROM ' . LANG_TABLE; + $result = $this->db->sql_query($sql); + $lang_name = (strpos($this->profilefield_name, 'phpbb_') === 0) ? strtoupper(substr($this->profilefield_name, 6)) : strtoupper($this->profilefield_name); + while ($lang_id = (int) $this->db->sql_fetchfield('lang_id')) + { + $insert_buffer->insert(array( + 'field_id' => (int) $field_id, + 'lang_id' => (int) $lang_id, + 'lang_name' => $lang_name, + 'lang_explain' => '', + 'lang_default_value' => '', + )); + } + $this->db->sql_freeresult($result); + + $insert_buffer->flush(); + } + + /** + * Create Custom profile fields languguage entries + */ + public function create_language_entries() + { + $field_id = $this->get_custom_profile_field_id(); + + $insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, PROFILE_FIELDS_LANG_TABLE); + + $sql = 'SELECT lang_id + FROM ' . LANG_TABLE; + $result = $this->db->sql_query($sql); + while ($lang_id = (int) $this->db->sql_fetchfield('lang_id')) + { + foreach ($this->profilefield_language_data as $language_data) + { + $insert_buffer->insert(array_merge(array( + 'field_id' => (int) $field_id, + 'lang_id' => (int) $lang_id, + ), $language_data)); + } + } + $this->db->sql_freeresult($result); + + $insert_buffer->flush(); + } + + /** + * Clean database when reverting the migration + */ + public function delete_custom_profile_field_data() + { + $field_id = $this->get_custom_profile_field_id(); + + $sql = 'DELETE FROM ' . PROFILE_FIELDS_TABLE . ' + WHERE field_id = ' . (int) $field_id; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . PROFILE_LANG_TABLE . ' + WHERE field_id = ' . (int) $field_id; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . PROFILE_FIELDS_LANG_TABLE . ' + WHERE field_id = ' . (int) $field_id; + $this->db->sql_query($sql); + } + + /** + * Get custom profile field id + * @return int custom profile filed id + */ + public function get_custom_profile_field_id() + { + $sql = 'SELECT field_id + FROM ' . PROFILE_FIELDS_TABLE . " + WHERE field_name = '" . $this->profilefield_name . "'"; + $result = $this->db->sql_query($sql); + $field_id = (int) $this->db->sql_fetchfield('field_id'); + $this->db->sql_freeresult($result); + + return $field_id; + } + + /** + * @param int $start Start of staggering step + * @return mixed int start of the next step, null if the end was reached + */ + public function convert_user_field_to_custom_field($start) + { + $insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, $this->table_prefix . 'profile_fields_data'); + $limit = 250; + $converted_users = 0; + $start = $start ?: 0; + + $sql = 'SELECT user_id, ' . $this->user_column_name . ' + FROM ' . $this->table_prefix . 'users + WHERE ' . $this->user_column_name . " <> '' + ORDER BY user_id"; + $result = $this->db->sql_query_limit($sql, $limit, $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $converted_users++; + + $cp_data = array( + 'pf_' . $this->profilefield_name => $row[$this->user_column_name], + ); + + $sql = 'UPDATE ' . $this->table_prefix . 'profile_fields_data + SET ' . $this->db->sql_build_array('UPDATE', $cp_data) . ' + WHERE user_id = ' . (int) $row['user_id']; + $this->db->sql_query($sql); + + if (!$this->db->sql_affectedrows()) + { + $cp_data['user_id'] = (int) $row['user_id']; + $cp_data = array_merge($this->get_insert_sql_array(), $cp_data); + $insert_buffer->insert($cp_data); + } + } + $this->db->sql_freeresult($result); + + $insert_buffer->flush(); + + if ($converted_users < $limit) + { + // No more users left, we are done... + return; + } + + return $start + $limit; + } + + protected function get_insert_sql_array() + { + static $profile_row; + + if ($profile_row === null) + { + $manager = $this->container->get('profilefields.manager'); + $profile_row = $manager->build_insert_sql_array(array()); + } + + return $profile_row; + } +} diff --git a/phpBB/phpbb/db/migration/schema_generator.php b/phpBB/phpbb/db/migration/schema_generator.php new file mode 100644 index 0000000000..91d8307d91 --- /dev/null +++ b/phpBB/phpbb/db/migration/schema_generator.php @@ -0,0 +1,235 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration; + +/** +* The schema generator generates the schema based on the existing migrations +*/ +class schema_generator +{ + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\db\tools */ + protected $db_tools; + + /** @var array */ + protected $class_names; + + /** @var string */ + protected $table_prefix; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** @var array */ + protected $tables; + + /** @var array */ + protected $dependencies = array(); + + /** + * Constructor + */ + public function __construct(array $class_names, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\db\tools $db_tools, $phpbb_root_path, $php_ext, $table_prefix) + { + $this->config = $config; + $this->db = $db; + $this->db_tools = $db_tools; + $this->class_names = $class_names; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->table_prefix = $table_prefix; + } + + /** + * Loads all migrations and their application state from the database. + * + * @return array + */ + public function get_schema() + { + if (!empty($this->tables)) + { + return $this->tables; + } + + $migrations = $this->class_names; + + $tree = array(); + $check_dependencies = true; + while (!empty($migrations)) + { + foreach ($migrations as $migration_class) + { + $open_dependencies = array_diff($migration_class::depends_on(), $tree); + + if (empty($open_dependencies)) + { + $migration = new $migration_class($this->config, $this->db, $this->db_tools, $this->phpbb_root_path, $this->php_ext, $this->table_prefix); + $tree[] = $migration_class; + $migration_key = array_search($migration_class, $migrations); + + foreach ($migration->update_schema() as $change_type => $data) + { + if ($change_type === 'add_tables') + { + foreach ($data as $table => $table_data) + { + $this->tables[$table] = $table_data; + } + } + else if ($change_type === 'drop_tables') + { + foreach ($data as $table) + { + unset($this->tables[$table]); + } + } + else if ($change_type === 'add_columns') + { + foreach ($data as $table => $add_columns) + { + foreach ($add_columns as $column => $column_data) + { + if (isset($column_data['after'])) + { + $columns = $this->tables[$table]['COLUMNS']; + $offset = array_search($column_data['after'], array_keys($columns)); + unset($column_data['after']); + + if ($offset === false) + { + $this->tables[$table]['COLUMNS'][$column] = array_values($column_data); + } + else + { + $this->tables[$table]['COLUMNS'] = array_merge(array_slice($columns, 0, $offset + 1, true), array($column => array_values($column_data)), array_slice($columns, $offset)); + } + } + else + { + $this->tables[$table]['COLUMNS'][$column] = $column_data; + } + } + } + } + else if ($change_type === 'change_columns') + { + foreach ($data as $table => $change_columns) + { + foreach ($change_columns as $column => $column_data) + { + $this->tables[$table]['COLUMNS'][$column] = $column_data; + } + } + } + else if ($change_type === 'drop_columns') + { + foreach ($data as $table => $drop_columns) + { + if (is_array($drop_columns)) + { + foreach ($drop_columns as $column) + { + unset($this->tables[$table]['COLUMNS'][$column]); + } + } + else + { + unset($this->tables[$table]['COLUMNS'][$drop_columns]); + } + } + } + else if ($change_type === 'add_unique_index') + { + foreach ($data as $table => $add_index) + { + foreach ($add_index as $key => $index_data) + { + $this->tables[$table]['KEYS'][$key] = array('UNIQUE', $index_data); + } + } + } + else if ($change_type === 'add_index') + { + foreach ($data as $table => $add_index) + { + foreach ($add_index as $key => $index_data) + { + $this->tables[$table]['KEYS'][$key] = array('INDEX', $index_data); + } + } + } + else if ($change_type === 'drop_keys') + { + foreach ($data as $table => $drop_keys) + { + foreach ($drop_keys as $key) + { + unset($this->tables[$table]['KEYS'][$key]); + } + } + } + else + { + var_dump($change_type); + } + } + unset($migrations[$migration_key]); + } + else if ($check_dependencies) + { + $this->dependencies = array_merge($this->dependencies, $open_dependencies); + } + } + + // Only run this check after the first run + if ($check_dependencies) + { + $this->check_dependencies(); + $check_dependencies = false; + } + } + + ksort($this->tables); + return $this->tables; + } + + /** + * Check if one of the migrations files' dependencies can't be resolved + * by the supplied list of migrations + * + * @throws \UnexpectedValueException If a dependency can't be resolved + */ + protected function check_dependencies() + { + // Strip duplicate values from array + $this->dependencies = array_unique($this->dependencies); + + foreach ($this->dependencies as $dependency) + { + if (!in_array($dependency, $this->class_names)) + { + throw new \UnexpectedValueException("Unable to resolve the dependency '$dependency'"); + } + } + } +} diff --git a/phpBB/phpbb/db/migration/tool/config.php b/phpBB/phpbb/db/migration/tool/config.php new file mode 100644 index 0000000000..33aa8ff026 --- /dev/null +++ b/phpBB/phpbb/db/migration/tool/config.php @@ -0,0 +1,165 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\tool; + +/** +* Migration config tool +*/ +class config implements \phpbb\db\migration\tool\tool_interface +{ + /** @var \phpbb\config\config */ + protected $config; + + /** + * Constructor + * + * @param \phpbb\config\config $config + */ + public function __construct(\phpbb\config\config $config) + { + $this->config = $config; + } + + /** + * {@inheritdoc} + */ + public function get_name() + { + return 'config'; + } + + /** + * Add a config setting. + * + * @param string $config_name The name of the config setting + * you would like to add + * @param mixed $config_value The value of the config setting + * @param bool $is_dynamic True if it is dynamic (changes very often) + * and should not be stored in the cache, false if not. + * @return null + */ + public function add($config_name, $config_value, $is_dynamic = false) + { + if (isset($this->config[$config_name])) + { + return; + } + + $this->config->set($config_name, $config_value, !$is_dynamic); + } + + /** + * Update an existing config setting. + * + * @param string $config_name The name of the config setting you would + * like to update + * @param mixed $config_value The value of the config setting + * @return null + * @throws \phpbb\db\migration\exception + */ + public function update($config_name, $config_value) + { + if (!isset($this->config[$config_name])) + { + throw new \phpbb\db\migration\exception('CONFIG_NOT_EXIST', $config_name); + } + + $this->config->set($config_name, $config_value); + } + + /** + * Update a config setting if the first argument equal to the + * current config value + * + * @param string $compare If equal to the current config value, will be + * updated to the new config value, otherwise not + * @param string $config_name The name of the config setting you would + * like to update + * @param mixed $config_value The value of the config setting + * @return null + * @throws \phpbb\db\migration\exception + */ + public function update_if_equals($compare, $config_name, $config_value) + { + if (!isset($this->config[$config_name])) + { + throw new \phpbb\db\migration\exception('CONFIG_NOT_EXIST', $config_name); + } + + $this->config->set_atomic($config_name, $compare, $config_value); + } + + /** + * Remove an existing config setting. + * + * @param string $config_name The name of the config setting you would + * like to remove + * @return null + */ + public function remove($config_name) + { + if (!isset($this->config[$config_name])) + { + return; + } + + $this->config->delete($config_name); + } + + /** + * {@inheritdoc} + */ + public function reverse() + { + $arguments = func_get_args(); + $original_call = array_shift($arguments); + + $call = false; + switch ($original_call) + { + case 'add': + $call = 'remove'; + break; + + case 'remove': + $call = 'add'; + if (sizeof($arguments) == 1) + { + $arguments[] = ''; + } + break; + + case 'update_if_equals': + $call = 'update_if_equals'; + + // Set to the original value if the current value is what we compared to originally + $arguments = array( + $arguments[2], + $arguments[1], + $arguments[0], + ); + break; + + case 'reverse': + // Reversing a reverse is just the call itself + $call = array_shift($arguments); + break; + } + + if ($call) + { + return call_user_func_array(array(&$this, $call), $arguments); + } + } +} diff --git a/phpBB/phpbb/db/migration/tool/config_text.php b/phpBB/phpbb/db/migration/tool/config_text.php new file mode 100644 index 0000000000..54b45f6f6d --- /dev/null +++ b/phpBB/phpbb/db/migration/tool/config_text.php @@ -0,0 +1,130 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\tool; + +/** +* Migration config_text tool +*/ +class config_text implements \phpbb\db\migration\tool\tool_interface +{ + /** @var \phpbb\config\db_text */ + protected $config_text; + + /** + * Constructor + * + * @param \phpbb\config\db_text $config_text + */ + public function __construct(\phpbb\config\db_text $config_text) + { + $this->config_text = $config_text; + } + + /** + * {@inheritdoc} + */ + public function get_name() + { + return 'config_text'; + } + + /** + * Add a config_text setting. + * + * @param string $config_name The name of the config_text setting + * you would like to add + * @param mixed $config_value The value of the config_text setting + * @return null + */ + public function add($config_name, $config_value) + { + if (!is_null($this->config_text->get($config_name))) + { + return; + } + + $this->config_text->set($config_name, $config_value); + } + + /** + * Update an existing config_text setting. + * + * @param string $config_name The name of the config_text setting you would + * like to update + * @param mixed $config_value The value of the config_text setting + * @return null + * @throws \phpbb\db\migration\exception + */ + public function update($config_name, $config_value) + { + if (is_null($this->config_text->get($config_name))) + { + throw new \phpbb\db\migration\exception('CONFIG_NOT_EXIST', $config_name); + } + + $this->config_text->set($config_name, $config_value); + } + + /** + * Remove an existing config_text setting. + * + * @param string $config_name The name of the config_text setting you would + * like to remove + * @return null + */ + public function remove($config_name) + { + if (is_null($this->config_text->get($config_name))) + { + return; + } + + $this->config_text->delete($config_name); + } + + /** + * {@inheritdoc} + */ + public function reverse() + { + $arguments = func_get_args(); + $original_call = array_shift($arguments); + + $call = false; + switch ($original_call) + { + case 'add': + $call = 'remove'; + break; + + case 'remove': + $call = 'add'; + if (sizeof($arguments) == 1) + { + $arguments[] = ''; + } + break; + + case 'reverse': + // Reversing a reverse is just the call itself + $call = array_shift($arguments); + break; + } + + if ($call) + { + return call_user_func_array(array(&$this, $call), $arguments); + } + } +} diff --git a/phpBB/phpbb/db/migration/tool/module.php b/phpBB/phpbb/db/migration/tool/module.php new file mode 100644 index 0000000000..7ea7d1dac1 --- /dev/null +++ b/phpBB/phpbb/db/migration/tool/module.php @@ -0,0 +1,563 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\tool; + +/** +* Migration module management tool +*/ +class module implements \phpbb\db\migration\tool\tool_interface +{ + /** @var \phpbb\cache\service */ + protected $cache; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\user */ + protected $user; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** @var string */ + protected $modules_table; + + /** @var array */ + protected $module_categories = array(); + + /** + * Constructor + * + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\cache\service $cache + * @param \phpbb\user $user + * @param string $phpbb_root_path + * @param string $php_ext + * @param string $modules_table + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\cache\service $cache, \phpbb\user $user, $phpbb_root_path, $php_ext, $modules_table) + { + $this->db = $db; + $this->cache = $cache; + $this->user = $user; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->modules_table = $modules_table; + } + + /** + * {@inheritdoc} + */ + public function get_name() + { + return 'module'; + } + + /** + * Module Exists + * + * Check if a module exists + * + * @param string $class The module class(acp|mcp|ucp) + * @param int|string|bool $parent The parent module_id|module_langname (0 for no parent). + * Use false to ignore the parent check and check class wide. + * @param int|string $module The module_id|module_langname you would like to + * check for to see if it exists + * @return bool true/false if module exists + */ + public function exists($class, $parent, $module) + { + // the main root directory should return true + if (!$module) + { + return true; + } + + $parent_sql = ''; + if ($parent !== false) + { + $parent = $this->get_parent_module_id($parent, $module, false); + if ($parent === false) + { + return false; + } + + $parent_sql = 'AND parent_id = ' . (int) $parent; + } + + $sql = 'SELECT module_id + FROM ' . $this->modules_table . " + WHERE module_class = '" . $this->db->sql_escape($class) . "' + $parent_sql + AND " . ((is_numeric($module)) ? 'module_id = ' . (int) $module : "module_langname = '" . $this->db->sql_escape($module) . "'"); + $result = $this->db->sql_query($sql); + $module_id = $this->db->sql_fetchfield('module_id'); + $this->db->sql_freeresult($result); + + if ($module_id) + { + return true; + } + + return false; + } + + /** + * Module Add + * + * Add a new module + * + * @param string $class The module class(acp|mcp|ucp) + * @param int|string $parent The parent module_id|module_langname (0 for no parent) + * @param array $data an array of the data on the new \module. + * This can be setup in two different ways. + * 1. The "manual" way. For inserting a category or one at a time. + * It will be merged with the base array shown a bit below, + * but at the least requires 'module_langname' to be sent, and, + * if you want to create a module (instead of just a category) you must + * send module_basename and module_mode. + * array( + * 'module_enabled' => 1, + * 'module_display' => 1, + * 'module_basename' => '', + * 'module_class' => $class, + * 'parent_id' => (int) $parent, + * 'module_langname' => '', + * 'module_mode' => '', + * 'module_auth' => '', + * ) + * 2. The "automatic" way. For inserting multiple at a time based on the + * specs in the info file for the module(s). For this to work the + * modules must be correctly setup in the info file. + * An example follows (this would insert the settings, log, and flag + * modes from the includes/acp/info/acp_asacp.php file): + * array( + * 'module_basename' => 'asacp', + * 'modes' => array('settings', 'log', 'flag'), + * ) + * Optionally you may not send 'modes' and it will insert all of the + * modules in that info file. + * path, specify that here + * @return null + * @throws \phpbb\db\migration\exception + */ + public function add($class, $parent = 0, $data = array()) + { + // allow sending the name as a string in $data to create a category + if (!is_array($data)) + { + $data = array('module_langname' => $data); + } + + $parent = $data['parent_id'] = $this->get_parent_module_id($parent, $data); + + if (!isset($data['module_langname'])) + { + // The "automatic" way + $basename = (isset($data['module_basename'])) ? $data['module_basename'] : ''; + $module = $this->get_module_info($class, $basename); + + $result = ''; + foreach ($module['modes'] as $mode => $module_info) + { + if (!isset($data['modes']) || in_array($mode, $data['modes'])) + { + $new_module = array( + 'module_basename' => $basename, + 'module_langname' => $module_info['title'], + 'module_mode' => $mode, + 'module_auth' => $module_info['auth'], + 'module_display' => (isset($module_info['display'])) ? $module_info['display'] : true, + 'before' => (isset($module_info['before'])) ? $module_info['before'] : false, + 'after' => (isset($module_info['after'])) ? $module_info['after'] : false, + ); + + // Run the "manual" way with the data we've collected. + $this->add($class, $parent, $new_module); + } + } + + return; + } + + // The "manual" way + if (!$this->exists($class, false, $parent)) + { + throw new \phpbb\db\migration\exception('MODULE_NOT_EXIST', $parent); + } + + if ($this->exists($class, $parent, $data['module_langname'])) + { + throw new \phpbb\db\migration\exception('MODULE_EXISTS', $data['module_langname']); + } + + if (!class_exists('acp_modules')) + { + include($this->phpbb_root_path . 'includes/acp/acp_modules.' . $this->php_ext); + $this->user->add_lang('acp/modules'); + } + $acp_modules = new \acp_modules(); + + $module_data = array( + 'module_enabled' => (isset($data['module_enabled'])) ? $data['module_enabled'] : 1, + 'module_display' => (isset($data['module_display'])) ? $data['module_display'] : 1, + 'module_basename' => (isset($data['module_basename'])) ? $data['module_basename'] : '', + 'module_class' => $class, + 'parent_id' => (int) $parent, + 'module_langname' => (isset($data['module_langname'])) ? $data['module_langname'] : '', + 'module_mode' => (isset($data['module_mode'])) ? $data['module_mode'] : '', + 'module_auth' => (isset($data['module_auth'])) ? $data['module_auth'] : '', + ); + $result = $acp_modules->update_module_data($module_data, true); + + // update_module_data can either return a string or an empty array... + if (is_string($result)) + { + // Error + throw new \phpbb\db\migration\exception('MODULE_ERROR', $result); + } + else + { + // Success + $module_log_name = ((isset($this->user->lang[$data['module_langname']])) ? $this->user->lang[$data['module_langname']] : $data['module_langname']); + add_log('admin', 'LOG_MODULE_ADD', $module_log_name); + + // Move the module if requested above/below an existing one + if (isset($data['before']) && $data['before']) + { + $sql = 'SELECT left_id + FROM ' . $this->modules_table . " + WHERE module_class = '" . $this->db->sql_escape($class) . "' + AND parent_id = " . (int) $parent . " + AND module_langname = '" . $this->db->sql_escape($data['before']) . "'"; + $this->db->sql_query($sql); + $to_left = (int) $this->db->sql_fetchfield('left_id'); + + $sql = 'UPDATE ' . $this->modules_table . " + SET left_id = left_id + 2, right_id = right_id + 2 + WHERE module_class = '" . $this->db->sql_escape($class) . "' + AND left_id >= $to_left + AND left_id < {$module_data['left_id']}"; + $this->db->sql_query($sql); + + $sql = 'UPDATE ' . $this->modules_table . " + SET left_id = $to_left, right_id = " . ($to_left + 1) . " + WHERE module_class = '" . $this->db->sql_escape($class) . "' + AND module_id = {$module_data['module_id']}"; + $this->db->sql_query($sql); + } + else if (isset($data['after']) && $data['after']) + { + $sql = 'SELECT right_id + FROM ' . $this->modules_table . " + WHERE module_class = '" . $this->db->sql_escape($class) . "' + AND parent_id = " . (int) $parent . " + AND module_langname = '" . $this->db->sql_escape($data['after']) . "'"; + $this->db->sql_query($sql); + $to_right = (int) $this->db->sql_fetchfield('right_id'); + + $sql = 'UPDATE ' . $this->modules_table . " + SET left_id = left_id + 2, right_id = right_id + 2 + WHERE module_class = '" . $this->db->sql_escape($class) . "' + AND left_id >= $to_right + AND left_id < {$module_data['left_id']}"; + $this->db->sql_query($sql); + + $sql = 'UPDATE ' . $this->modules_table . ' + SET left_id = ' . ($to_right + 1) . ', right_id = ' . ($to_right + 2) . " + WHERE module_class = '" . $this->db->sql_escape($class) . "' + AND module_id = {$module_data['module_id']}"; + $this->db->sql_query($sql); + } + } + + // Clear the Modules Cache + $this->cache->destroy("_modules_$class"); + } + + /** + * Module Remove + * + * Remove a module + * + * @param string $class The module class(acp|mcp|ucp) + * @param int|string|bool $parent The parent module_id|module_langname(0 for no parent). + * Use false to ignore the parent check and check class wide. + * @param int|string $module The module id|module_langname + * specify that here + * @return null + * @throws \phpbb\db\migration\exception + */ + public function remove($class, $parent = 0, $module = '') + { + // Imitation of module_add's "automatic" and "manual" method so the uninstaller works from the same set of instructions for umil_auto + if (is_array($module)) + { + if (isset($module['module_langname'])) + { + // Manual Method + return $this->remove($class, $parent, $module['module_langname']); + } + + // Failed. + if (!isset($module['module_basename'])) + { + throw new \phpbb\db\migration\exception('MODULE_NOT_EXIST'); + } + + // Automatic method + $basename = $module['module_basename']; + $module_info = $this->get_module_info($class, $basename); + + foreach ($module_info['modes'] as $mode => $info) + { + if (!isset($module['modes']) || in_array($mode, $module['modes'])) + { + $this->remove($class, $parent, $info['title']); + } + } + } + else + { + if (!$this->exists($class, $parent, $module)) + { + return; + } + + $parent_sql = ''; + if ($parent !== false) + { + $parent = $this->get_parent_module_id($parent, $module); + $parent_sql = 'AND parent_id = ' . (int) $parent; + } + + $module_ids = array(); + if (!is_numeric($module)) + { + $sql = 'SELECT module_id + FROM ' . $this->modules_table . " + WHERE module_langname = '" . $this->db->sql_escape($module) . "' + AND module_class = '" . $this->db->sql_escape($class) . "' + $parent_sql"; + $result = $this->db->sql_query($sql); + while ($module_id = $this->db->sql_fetchfield('module_id')) + { + $module_ids[] = (int) $module_id; + } + $this->db->sql_freeresult($result); + } + else + { + $module_ids[] = (int) $module; + } + + if (!class_exists('acp_modules')) + { + include($this->phpbb_root_path . 'includes/acp/acp_modules.' . $this->php_ext); + $this->user->add_lang('acp/modules'); + } + $acp_modules = new \acp_modules(); + $acp_modules->module_class = $class; + + foreach ($module_ids as $module_id) + { + $result = $acp_modules->delete_module($module_id); + if (!empty($result)) + { + return; + } + } + + $this->cache->destroy("_modules_$class"); + } + } + + /** + * {@inheritdoc} + */ + public function reverse() + { + $arguments = func_get_args(); + $original_call = array_shift($arguments); + + $call = false; + switch ($original_call) + { + case 'add': + $call = 'remove'; + break; + + case 'remove': + $call = 'add'; + break; + + case 'reverse': + // Reversing a reverse is just the call itself + $call = array_shift($arguments); + break; + } + + if ($call) + { + return call_user_func_array(array(&$this, $call), $arguments); + } + } + + /** + * Wrapper for \acp_modules::get_module_infos() + * + * @param string $class Module Class + * @param string $basename Module Basename + * @return array Module Information + * @throws \phpbb\db\migration\exception + */ + protected function get_module_info($class, $basename) + { + if (!class_exists('acp_modules')) + { + include($this->phpbb_root_path . 'includes/acp/acp_modules.' . $this->php_ext); + $this->user->add_lang('acp/modules'); + } + $acp_modules = new \acp_modules(); + $module = $acp_modules->get_module_infos($basename, $class, true); + + if (empty($module)) + { + throw new \phpbb\db\migration\exception('MODULE_INFO_FILE_NOT_EXIST', $class, $basename); + } + + return array_pop($module); + } + + /** + * Get the list of installed module categories + * key - module_id + * value - module_langname + * + * @return null + */ + protected function get_categories_list() + { + // Select the top level categories + // and 2nd level [sub]categories + $sql = 'SELECT m2.module_id, m2.module_langname + FROM ' . $this->modules_table . ' m1, ' . $this->modules_table . " m2 + WHERE m1.parent_id = 0 + AND (m1.module_id = m2.module_id OR m2.parent_id = m1.module_id) + ORDER BY m1.module_id, m2.module_id ASC"; + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $this->module_categories[(int) $row['module_id']] = $row['module_langname']; + } + $this->db->sql_freeresult($result); + } + + /** + * Get parent module id + * + * @param string|int $parent_id The parent module_id|module_langname + * @param int|string|array $data The module_id, module_langname for existance checking or module data array for adding + * @param bool $throw_exception The flag indicating if exception should be thrown on error + * @return mixed The int parent module_id or false + * @throws \phpbb\db\migration\exception + */ + public function get_parent_module_id($parent_id, $data = '', $throw_exception = true) + { + // Initialize exception object placeholder + $exception = false; + + // Allow '' to be sent as 0 + $parent_id = $parent_id ?: 0; + + // If automatic adding is in action, convert array back to string to simplify things + if (is_array($data) && sizeof($data) == 1) + { + $data = $data['module_langname']; + } + + if (!is_numeric($parent_id)) + { + // Refresh the $module_categories array + $this->get_categories_list(); + + // Search for the parent module_langname + $ids = array_keys($this->module_categories, $parent_id); + + switch (sizeof($ids)) + { + // No parent with the given module_langname exist + case 0: + $exception = new \phpbb\db\migration\exception('MODULE_NOT_EXIST', $parent_id); + break; + + // Return the module id + case 1: + $parent_id = (int) $ids[0]; + break; + + // Several modules with the given module_langname were found + // Try to determine the parent_id by the neighbour module parent + default: + if (is_array($data) && (isset($data['before']) || isset($data['after']))) + { + $neighbour_module_langname = isset($data['before']) ? $data['before'] : $data['after']; + $sql = 'SELECT parent_id + FROM ' . $this->modules_table . " + WHERE module_langname = '" . $this->db->sql_escape($neighbour_module_langname) . "' + AND " . $this->db->sql_in_set('parent_id', $ids); + $result = $this->db->sql_query($sql); + $parent_id = (int) $this->db->sql_fetchfield('parent_id'); + if (!$parent_id) + { + $exception = new \phpbb\db\migration\exception('PARENT_MODULE_FIND_ERROR', $data['parent_id']); + } + } + else if (!empty($data) && !is_array($data)) + { + // The module_langname is set, checking for the module existance + // As more than 1 parents were found already, there's no way for null parent_id here + $sql = 'SELECT m2.module_id as module_parent_id + FROM ' . $this->modules_table . ' m1, ' . $this->modules_table . " m2 + WHERE " . ((is_numeric($data)) ? 'm1.module_id = ' . (int) $data : "m1.module_langname = '" . $this->db->sql_escape($data)) . "' + AND m2.module_id = m1.parent_id + AND " . $this->db->sql_in_set('m2.module_id', $ids); + $result = $this->db->sql_query($sql); + $parent_id = (int) $this->db->sql_fetchfield('module_parent_id'); + } + else + { + //Unable to get the parent module id, throwing an exception + $exception = new \phpbb\db\migration\exception('MODULE_EXIST_MULTIPLE', $parent_id); + } + break; + } + } + + if ($exception !== false) + { + if ($throw_exception) + { + throw $exception; + } + return false; + } + + return $parent_id; + } +} diff --git a/phpBB/phpbb/db/migration/tool/permission.php b/phpBB/phpbb/db/migration/tool/permission.php new file mode 100644 index 0000000000..9688420025 --- /dev/null +++ b/phpBB/phpbb/db/migration/tool/permission.php @@ -0,0 +1,652 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\tool; + +/** +* Migration permission management tool +*/ +class permission implements \phpbb\db\migration\tool\tool_interface +{ + /** @var \phpbb\auth\auth */ + protected $auth; + + /** @var \phpbb\cache\service */ + protected $cache; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** + * Constructor + * + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\cache\service $cache + * @param \phpbb\auth\auth $auth + * @param string $phpbb_root_path + * @param string $php_ext + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\cache\service $cache, \phpbb\auth\auth $auth, $phpbb_root_path, $php_ext) + { + $this->db = $db; + $this->cache = $cache; + $this->auth = $auth; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * {@inheritdoc} + */ + public function get_name() + { + return 'permission'; + } + + /** + * Permission Exists + * + * Check if a permission (auth) setting exists + * + * @param string $auth_option The name of the permission (auth) option + * @param bool $global True for checking a global permission setting, + * False for a local permission setting + * @return bool true if it exists, false if not + */ + public function exists($auth_option, $global = true) + { + if ($global) + { + $type_sql = ' AND is_global = 1'; + } + else + { + $type_sql = ' AND is_local = 1'; + } + + $sql = 'SELECT auth_option_id + FROM ' . ACL_OPTIONS_TABLE . " + WHERE auth_option = '" . $this->db->sql_escape($auth_option) . "'" + . $type_sql; + $result = $this->db->sql_query($sql); + + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + return true; + } + + return false; + } + + /** + * Permission Add + * + * Add a permission (auth) option + * + * @param string $auth_option The name of the permission (auth) option + * @param bool $global True for checking a global permission setting, + * False for a local permission setting + * @param int|false $copy_from If set, contains the id of the permission from which to copy the new one. + * @return null + */ + public function add($auth_option, $global = true, $copy_from = false) + { + if ($this->exists($auth_option, $global)) + { + return; + } + + // We've added permissions, so set to true to notify the user. + $this->permissions_added = true; + + if (!class_exists('auth_admin')) + { + include($this->phpbb_root_path . 'includes/acp/auth.' . $this->php_ext); + } + $auth_admin = new \auth_admin(); + + // We have to add a check to see if the !$global (if global, local, and if local, global) permission already exists. If it does, acl_add_option currently has a bug which would break the ACL system, so we are having a work-around here. + if ($this->exists($auth_option, !$global)) + { + $sql_ary = array( + 'is_global' => 1, + 'is_local' => 1, + ); + $sql = 'UPDATE ' . ACL_OPTIONS_TABLE . ' + SET ' . $this->db->sql_build_array('UPDATE', $sql_ary) . " + WHERE auth_option = '" . $this->db->sql_escape($auth_option) . "'"; + $this->db->sql_query($sql); + } + else + { + if ($global) + { + $auth_admin->acl_add_option(array('global' => array($auth_option))); + } + else + { + $auth_admin->acl_add_option(array('local' => array($auth_option))); + } + } + + // The permission has been added, now we can copy it if needed + if ($copy_from && isset($auth_admin->acl_options['id'][$copy_from])) + { + $old_id = $auth_admin->acl_options['id'][$copy_from]; + $new_id = $auth_admin->acl_options['id'][$auth_option]; + + $tables = array(ACL_GROUPS_TABLE, ACL_ROLES_DATA_TABLE, ACL_USERS_TABLE); + + foreach ($tables as $table) + { + $sql = 'SELECT * + FROM ' . $table . ' + WHERE auth_option_id = ' . $old_id; + $result = $this->db->sql_query($sql); + + $sql_ary = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $row['auth_option_id'] = $new_id; + $sql_ary[] = $row; + } + $this->db->sql_freeresult($result); + + if (!empty($sql_ary)) + { + $this->db->sql_multi_insert($table, $sql_ary); + } + } + + $auth_admin->acl_clear_prefetch(); + } + } + + /** + * Permission Remove + * + * Remove a permission (auth) option + * + * @param string $auth_option The name of the permission (auth) option + * @param bool $global True for checking a global permission setting, + * False for a local permission setting + * @return null + */ + public function remove($auth_option, $global = true) + { + if (!$this->exists($auth_option, $global)) + { + return; + } + + if ($global) + { + $type_sql = ' AND is_global = 1'; + } + else + { + $type_sql = ' AND is_local = 1'; + } + $sql = 'SELECT auth_option_id, is_global, is_local + FROM ' . ACL_OPTIONS_TABLE . " + WHERE auth_option = '" . $this->db->sql_escape($auth_option) . "'" . + $type_sql; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $id = (int) $row['auth_option_id']; + + // If it is a local and global permission, do not remove the row! :P + if ($row['is_global'] && $row['is_local']) + { + $sql = 'UPDATE ' . ACL_OPTIONS_TABLE . ' + SET ' . (($global) ? 'is_global = 0' : 'is_local = 0') . ' + WHERE auth_option_id = ' . $id; + $this->db->sql_query($sql); + } + else + { + // Delete time + $tables = array(ACL_GROUPS_TABLE, ACL_ROLES_DATA_TABLE, ACL_USERS_TABLE, ACL_OPTIONS_TABLE); + foreach ($tables as $table) + { + $this->db->sql_query('DELETE FROM ' . $table . ' + WHERE auth_option_id = ' . $id); + } + } + + // Purge the auth cache + $this->cache->destroy('_acl_options'); + $this->auth->acl_clear_prefetch(); + } + + /** + * Add a new permission role + * + * @param string $role_name The new role name + * @param string $role_type The type (u_, m_, a_) + * @param string $role_description Description of the new role + * + * @return null + */ + public function role_add($role_name, $role_type, $role_description = '') + { + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = '" . $this->db->sql_escape($role_name) . "'"; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('role_id'); + + if ($role_id) + { + return; + } + + $sql = 'SELECT MAX(role_order) AS max_role_order + FROM ' . ACL_ROLES_TABLE . " + WHERE role_type = '" . $this->db->sql_escape($role_type) . "'"; + $this->db->sql_query($sql); + $role_order = (int) $this->db->sql_fetchfield('max_role_order'); + $role_order = (!$role_order) ? 1 : $role_order + 1; + + $sql_ary = array( + 'role_name' => $role_name, + 'role_description' => $role_description, + 'role_type' => $role_type, + 'role_order' => $role_order, + ); + + $sql = 'INSERT INTO ' . ACL_ROLES_TABLE . ' ' . $this->db->sql_build_array('INSERT', $sql_ary); + $this->db->sql_query($sql); + } + + /** + * Update the name on a permission role + * + * @param string $old_role_name The old role name + * @param string $new_role_name The new role name + * @return null + * @throws \phpbb\db\migration\exception + */ + public function role_update($old_role_name, $new_role_name) + { + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = '" . $this->db->sql_escape($old_role_name) . "'"; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('role_id'); + + if (!$role_id) + { + throw new \phpbb\db\migration\exception('ROLE_NOT_EXIST', $old_role_name); + } + + $sql = 'UPDATE ' . ACL_ROLES_TABLE . " + SET role_name = '" . $this->db->sql_escape($new_role_name) . "' + WHERE role_name = '" . $this->db->sql_escape($old_role_name) . "'"; + $this->db->sql_query($sql); + } + + /** + * Remove a permission role + * + * @param string $role_name The role name to remove + * @return null + */ + public function role_remove($role_name) + { + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = '" . $this->db->sql_escape($role_name) . "'"; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('role_id'); + + if (!$role_id) + { + return; + } + + $sql = 'DELETE FROM ' . ACL_ROLES_DATA_TABLE . ' + WHERE role_id = ' . $role_id; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . ACL_ROLES_TABLE . ' + WHERE role_id = ' . $role_id; + $this->db->sql_query($sql); + + $this->auth->acl_clear_prefetch(); + } + + /** + * Permission Set + * + * Allows you to set permissions for a certain group/role + * + * @param string $name The name of the role/group + * @param string|array $auth_option The auth_option or array of + * auth_options you would like to set + * @param string $type The type (role|group) + * @param bool $has_permission True if you want to give them permission, + * false if you want to deny them permission + * @return null + * @throws \phpbb\db\migration\exception + */ + public function permission_set($name, $auth_option, $type = 'role', $has_permission = true) + { + if (!is_array($auth_option)) + { + $auth_option = array($auth_option); + } + + $new_auth = array(); + $sql = 'SELECT auth_option_id + FROM ' . ACL_OPTIONS_TABLE . ' + WHERE ' . $this->db->sql_in_set('auth_option', $auth_option); + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $new_auth[] = (int) $row['auth_option_id']; + } + $this->db->sql_freeresult($result); + + if (empty($new_auth)) + { + return; + } + + $current_auth = array(); + + $type = (string) $type; // Prevent PHP bug. + + switch ($type) + { + case 'role': + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('role_id'); + + if (!$role_id) + { + throw new \phpbb\db\migration\exception('ROLE_NOT_EXIST', $name); + } + + $sql = 'SELECT auth_option_id, auth_setting + FROM ' . ACL_ROLES_DATA_TABLE . ' + WHERE role_id = ' . $role_id; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $current_auth[$row['auth_option_id']] = $row['auth_setting']; + } + $this->db->sql_freeresult($result); + break; + + case 'group': + $sql = 'SELECT group_id + FROM ' . GROUPS_TABLE . " + WHERE group_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + $group_id = (int) $this->db->sql_fetchfield('group_id'); + + if (!$group_id) + { + throw new \phpbb\db\migration\exception('GROUP_NOT_EXIST', $name); + } + + // If the group has a role set for them we will add the requested permissions to that role. + $sql = 'SELECT auth_role_id + FROM ' . ACL_GROUPS_TABLE . ' + WHERE group_id = ' . $group_id . ' + AND auth_role_id <> 0 + AND forum_id = 0'; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('auth_role_id'); + if ($role_id) + { + $sql = 'SELECT role_name, role_type + FROM ' . ACL_ROLES_TABLE . ' + WHERE role_id = ' . $role_id; + $this->db->sql_query($sql); + $role_data = $this->db->sql_fetchrow(); + $role_name = $role_data['role_name']; + $role_type = $role_data['role_type']; + + // Filter new auth options to match the role type: a_ | f_ | m_ | u_ + // Set new auth options to the role only if options matching the role type were found + $auth_option = array_filter($auth_option, + function ($option) use ($role_type) + { + return strpos($option, $role_type) === 0; + } + ); + + if (sizeof($auth_option)) + { + return $this->permission_set($role_name, $auth_option, 'role', $has_permission); + } + } + + $sql = 'SELECT auth_option_id, auth_setting + FROM ' . ACL_GROUPS_TABLE . ' + WHERE group_id = ' . $group_id; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $current_auth[$row['auth_option_id']] = $row['auth_setting']; + } + $this->db->sql_freeresult($result); + break; + } + + $sql_ary = array(); + switch ($type) + { + case 'role': + foreach ($new_auth as $auth_option_id) + { + if (!isset($current_auth[$auth_option_id])) + { + $sql_ary[] = array( + 'role_id' => $role_id, + 'auth_option_id' => $auth_option_id, + 'auth_setting' => $has_permission, + ); + } + } + + $this->db->sql_multi_insert(ACL_ROLES_DATA_TABLE, $sql_ary); + break; + + case 'group': + foreach ($new_auth as $auth_option_id) + { + if (!isset($current_auth[$auth_option_id])) + { + $sql_ary[] = array( + 'group_id' => $group_id, + 'auth_option_id' => $auth_option_id, + 'auth_setting' => $has_permission, + ); + } + } + + $this->db->sql_multi_insert(ACL_GROUPS_TABLE, $sql_ary); + break; + } + + $this->auth->acl_clear_prefetch(); + } + + /** + * Permission Unset + * + * Allows you to unset (remove) permissions for a certain group/role + * + * @param string $name The name of the role/group + * @param string|array $auth_option The auth_option or array of + * auth_options you would like to set + * @param string $type The type (role|group) + * @return null + * @throws \phpbb\db\migration\exception + */ + public function permission_unset($name, $auth_option, $type = 'role') + { + if (!is_array($auth_option)) + { + $auth_option = array($auth_option); + } + + $to_remove = array(); + $sql = 'SELECT auth_option_id + FROM ' . ACL_OPTIONS_TABLE . ' + WHERE ' . $this->db->sql_in_set('auth_option', $auth_option); + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $to_remove[] = (int) $row['auth_option_id']; + } + $this->db->sql_freeresult($result); + + if (empty($to_remove)) + { + return; + } + + $type = (string) $type; // Prevent PHP bug. + + switch ($type) + { + case 'role': + $sql = 'SELECT role_id + FROM ' . ACL_ROLES_TABLE . " + WHERE role_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('role_id'); + + if (!$role_id) + { + throw new \phpbb\db\migration\exception('ROLE_NOT_EXIST', $name); + } + + $sql = 'DELETE FROM ' . ACL_ROLES_DATA_TABLE . ' + WHERE ' . $this->db->sql_in_set('auth_option_id', $to_remove) . ' + AND role_id = ' . (int) $role_id; + $this->db->sql_query($sql); + break; + + case 'group': + $sql = 'SELECT group_id + FROM ' . GROUPS_TABLE . " + WHERE group_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + $group_id = (int) $this->db->sql_fetchfield('group_id'); + + if (!$group_id) + { + throw new \phpbb\db\migration\exception('GROUP_NOT_EXIST', $name); + } + + // If the group has a role set for them we will remove the requested permissions from that role. + $sql = 'SELECT auth_role_id + FROM ' . ACL_GROUPS_TABLE . ' + WHERE group_id = ' . $group_id . ' + AND auth_role_id <> 0'; + $this->db->sql_query($sql); + $role_id = (int) $this->db->sql_fetchfield('auth_role_id'); + if ($role_id) + { + $sql = 'SELECT role_name + FROM ' . ACL_ROLES_TABLE . ' + WHERE role_id = ' . $role_id; + $this->db->sql_query($sql); + $role_name = $this->db->sql_fetchfield('role_name'); + + return $this->permission_unset($role_name, $auth_option, 'role'); + } + + $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . ' + WHERE ' . $this->db->sql_in_set('auth_option_id', $to_remove); + $this->db->sql_query($sql); + break; + } + + $this->auth->acl_clear_prefetch(); + } + + /** + * {@inheritdoc} + */ + public function reverse() + { + $arguments = func_get_args(); + $original_call = array_shift($arguments); + + $call = false; + switch ($original_call) + { + case 'add': + $call = 'remove'; + break; + + case 'remove': + $call = 'add'; + break; + + case 'permission_set': + $call = 'permission_unset'; + break; + + case 'permission_unset': + $call = 'permission_set'; + break; + + case 'role_add': + $call = 'role_remove'; + break; + + case 'role_remove': + $call = 'role_add'; + break; + + case 'role_update': + // Set to the original value if the current value is what we compared to originally + $arguments = array( + $arguments[1], + $arguments[0], + ); + break; + + case 'reverse': + // Reversing a reverse is just the call itself + $call = array_shift($arguments); + break; + } + + if ($call) + { + return call_user_func_array(array(&$this, $call), $arguments); + } + } +} diff --git a/phpBB/phpbb/db/migration/tool/tool_interface.php b/phpBB/phpbb/db/migration/tool/tool_interface.php new file mode 100644 index 0000000000..07cd2435e4 --- /dev/null +++ b/phpBB/phpbb/db/migration/tool/tool_interface.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db\migration\tool; + +/** +* Migration tool interface +*/ +interface tool_interface +{ + /** + * Retrieve a short name used for commands in migrations. + * + * @return string short name + */ + public function get_name(); + + /** + * Reverse an original install action + * + * First argument is the original call to the class (e.g. add, remove) + * After the first argument, send the original arguments to the function in the original call + * + * @return null + */ + public function reverse(); +} diff --git a/phpBB/phpbb/db/migrator.php b/phpBB/phpbb/db/migrator.php new file mode 100644 index 0000000000..45a333ac94 --- /dev/null +++ b/phpBB/phpbb/db/migrator.php @@ -0,0 +1,924 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +use Symfony\Component\DependencyInjection\ContainerAwareInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* The migrator is responsible for applying new migrations in the correct order. +*/ +class migrator +{ + /** + * @var ContainerInterface + */ + protected $container; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\db\tools */ + protected $db_tools; + + /** @var \phpbb\db\migration\helper */ + protected $helper; + + /** @var string */ + protected $table_prefix; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** @var string */ + protected $migrations_table; + + /** + * State of all migrations + * + * (SELECT * FROM migrations table) + * + * @var array + */ + protected $migration_state = array(); + + /** + * Array of all migrations available to be run + * + * @var array + */ + protected $migrations = array(); + + /** + * Array of migrations that have been determined to be fulfillable + * + * @var array + */ + protected $fulfillable_migrations = array(); + + /** + * 'name,' 'class,' and 'state' of the last migration run + * + * 'effectively_installed' set and set to true if the migration was effectively_installed + * + * @var array + */ + protected $last_run_migration = false; + + /** + * The output handler. A null handler is configured by default. + * + * @var migrator_output_handler_interface + */ + protected $output_handler; + + /** + * Constructor of the database migrator + */ + public function __construct(ContainerInterface $container, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\db\tools $db_tools, $migrations_table, $phpbb_root_path, $php_ext, $table_prefix, $tools, \phpbb\db\migration\helper $helper) + { + $this->container = $container; + $this->config = $config; + $this->db = $db; + $this->db_tools = $db_tools; + $this->helper = $helper; + + $this->migrations_table = $migrations_table; + + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + + $this->table_prefix = $table_prefix; + + $this->output_handler = new null_migrator_output_handler(); + + foreach ($tools as $tool) + { + $this->tools[$tool->get_name()] = $tool; + } + + $this->tools['dbtools'] = $this->db_tools; + + $this->load_migration_state(); + } + + /** + * Set the output handler. + * + * @param migrator_output_handler $handler The output handler + */ + public function set_output_handler(migrator_output_handler_interface $handler) + { + $this->output_handler = $handler; + } + + /** + * Loads all migrations and their application state from the database. + * + * @return null + */ + public function load_migration_state() + { + $this->migration_state = array(); + + // prevent errors in case the table does not exist yet + $this->db->sql_return_on_error(true); + + $sql = "SELECT * + FROM " . $this->migrations_table; + $result = $this->db->sql_query($sql); + + if (!$this->db->get_sql_error_triggered()) + { + while ($migration = $this->db->sql_fetchrow($result)) + { + $this->migration_state[$migration['migration_name']] = $migration; + + $this->migration_state[$migration['migration_name']]['migration_depends_on'] = unserialize($migration['migration_depends_on']); + $this->migration_state[$migration['migration_name']]['migration_data_state'] = !empty($migration['migration_data_state']) ? unserialize($migration['migration_data_state']) : ''; + } + } + + $this->db->sql_freeresult($result); + + $this->db->sql_return_on_error(false); + } + + /** + * Get an array with information about the last migration run. + * + * The array contains 'name', 'class' and 'state'. 'effectively_installed' is set + * and set to true if the last migration was effectively_installed. + * + * @return array + */ + public function get_last_run_migration() + { + return $this->last_run_migration; + } + + /** + * Sets the list of available migration class names to the given array. + * + * @param array $class_names An array of migration class names + * @return null + */ + public function set_migrations($class_names) + { + $this->migrations = $class_names; + } + + /** + * Runs a single update step from the next migration to be applied. + * + * The update step can either be a schema or a (partial) data update. To + * check if update() needs to be called again use the finished() method. + * + * @return null + */ + public function update() + { + $this->container->get('dispatcher')->disable(); + $this->update_do(); + $this->container->get('dispatcher')->enable(); + } + + /** + * Get a valid migration name from the migration state array in case the + * supplied name is not in the migration state list. + * + * @param string $name Migration name + * @return string Migration name + */ + protected function get_valid_name($name) + { + // Try falling back to a valid migration name with or without leading backslash + if (!isset($this->migration_state[$name])) + { + $prepended_name = ($name[0] == '\\' ? '' : '\\') . $name; + $prefixless_name = $name[0] == '\\' ? substr($name, 1) : $name; + + if (isset($this->migration_state[$prepended_name])) + { + $name = $prepended_name; + } + else if (isset($this->migration_state[$prefixless_name])) + { + $name = $prefixless_name; + } + } + + return $name; + } + + /** + * Effectively runs a single update step from the next migration to be applied. + * + * @return null + */ + protected function update_do() + { + foreach ($this->migrations as $name) + { + $name = $this->get_valid_name($name); + + if (!isset($this->migration_state[$name]) || + !$this->migration_state[$name]['migration_schema_done'] || + !$this->migration_state[$name]['migration_data_done']) + { + if (!$this->try_apply($name)) + { + continue; + } + else + { + return; + } + } + else + { + $this->output_handler->write(array('MIGRATION_EFFECTIVELY_INSTALLED', $name), migrator_output_handler_interface::VERBOSITY_DEBUG); + } + } + } + + /** + * Attempts to apply a step of the given migration or one of its dependencies + * + * @param string $name The class name of the migration + * @return bool Whether any update step was successfully run + * @throws \phpbb\db\migration\exception + */ + protected function try_apply($name) + { + if (!class_exists($name)) + { + $this->output_handler->write(array('MIGRATION_NOT_VALID', $name), migrator_output_handler_interface::VERBOSITY_DEBUG); + return false; + } + + $migration = $this->get_migration($name); + + $state = (isset($this->migration_state[$name])) ? + $this->migration_state[$name] : + array( + 'migration_depends_on' => $migration->depends_on(), + 'migration_schema_done' => false, + 'migration_data_done' => false, + 'migration_data_state' => '', + 'migration_start_time' => 0, + 'migration_end_time' => 0, + ); + + if (!empty($state['migration_depends_on'])) + { + $this->output_handler->write(array('MIGRATION_APPLY_DEPENDENCIES', $name), migrator_output_handler_interface::VERBOSITY_DEBUG); + } + + foreach ($state['migration_depends_on'] as $depend) + { + $depend = $this->get_valid_name($depend); + + // Test all possible namings before throwing exception + if ($this->unfulfillable($depend) !== false) + { + throw new \phpbb\db\migration\exception('MIGRATION_NOT_FULFILLABLE', $name, $depend); + } + + if (!isset($this->migration_state[$depend]) || + !$this->migration_state[$depend]['migration_schema_done'] || + !$this->migration_state[$depend]['migration_data_done']) + { + return $this->try_apply($depend); + } + } + + $this->last_run_migration = array( + 'name' => $name, + 'class' => $migration, + 'state' => $state, + 'task' => '', + ); + + if (!isset($this->migration_state[$name])) + { + if ($state['migration_start_time'] == 0 && $migration->effectively_installed()) + { + $state = array( + 'migration_depends_on' => $migration->depends_on(), + 'migration_schema_done' => true, + 'migration_data_done' => true, + 'migration_data_state' => '', + 'migration_start_time' => 0, + 'migration_end_time' => 0, + ); + + $this->last_run_migration['effectively_installed'] = true; + + $this->output_handler->write(array('MIGRATION_EFFECTIVELY_INSTALLED', $name), migrator_output_handler_interface::VERBOSITY_VERBOSE); + } + else + { + $state['migration_start_time'] = time(); + } + } + + $this->set_migration_state($name, $state); + + if (!$state['migration_schema_done']) + { + $verbosity = empty($state['migration_data_state']) ? + migrator_output_handler_interface::VERBOSITY_VERBOSE : migrator_output_handler_interface::VERBOSITY_DEBUG; + $this->output_handler->write(array('MIGRATION_SCHEMA_RUNNING', $name), $verbosity); + + $this->last_run_migration['task'] = 'process_schema_step'; + + $total_time = (is_array($state['migration_data_state']) && isset($state['migration_data_state']['_total_time'])) ? + $state['migration_data_state']['_total_time'] : 0.0; + $elapsed_time = microtime(true); + + $steps = $this->helper->get_schema_steps($migration->update_schema()); + $result = $this->process_data_step($steps, $state['migration_data_state']); + + $elapsed_time = microtime(true) - $elapsed_time; + $total_time += $elapsed_time; + + if (is_array($result)) + { + $result['_total_time'] = $total_time; + } + + $state['migration_data_state'] = ($result === true) ? '' : $result; + $state['migration_schema_done'] = ($result === true); + + if ($state['migration_schema_done']) + { + $this->output_handler->write(array('MIGRATION_SCHEMA_DONE', $name, $total_time), migrator_output_handler_interface::VERBOSITY_NORMAL); + } + else + { + $this->output_handler->write(array('MIGRATION_SCHEMA_IN_PROGRESS', $name, $elapsed_time), migrator_output_handler_interface::VERBOSITY_VERY_VERBOSE); + } + } + else if (!$state['migration_data_done']) + { + try + { + $verbosity = empty($state['migration_data_state']) ? + migrator_output_handler_interface::VERBOSITY_VERBOSE : migrator_output_handler_interface::VERBOSITY_DEBUG; + $this->output_handler->write(array('MIGRATION_DATA_RUNNING', $name), $verbosity); + + $this->last_run_migration['task'] = 'process_data_step'; + + $total_time = (is_array($state['migration_data_state']) && isset($state['migration_data_state']['_total_time'])) ? + $state['migration_data_state']['_total_time'] : 0.0; + $elapsed_time = microtime(true); + + $result = $this->process_data_step($migration->update_data(), $state['migration_data_state']); + + $elapsed_time = microtime(true) - $elapsed_time; + $total_time += $elapsed_time; + + if (is_array($result)) + { + $result['_total_time'] = $total_time; + } + + $state['migration_data_state'] = ($result === true) ? '' : $result; + $state['migration_data_done'] = ($result === true); + $state['migration_end_time'] = ($result === true) ? time() : 0; + + if ($state['migration_data_done']) + { + $this->output_handler->write(array('MIGRATION_DATA_DONE', $name, $total_time), migrator_output_handler_interface::VERBOSITY_NORMAL); + } + else + { + $this->output_handler->write(array('MIGRATION_DATA_IN_PROGRESS', $name, $elapsed_time), migrator_output_handler_interface::VERBOSITY_VERY_VERBOSE); + } + } + catch (\phpbb\db\migration\exception $e) + { + // Reset data state and revert the schema changes + $state['migration_data_state'] = ''; + $this->set_migration_state($name, $state); + + $this->revert_do($name); + + throw $e; + } + } + + $this->set_migration_state($name, $state); + + return true; + } + + /** + * Runs a single revert step from the last migration installed + * + * YOU MUST ADD/SET ALL MIGRATIONS THAT COULD BE DEPENDENT ON THE MIGRATION TO REVERT TO BEFORE CALLING THIS METHOD! + * The revert step can either be a schema or a (partial) data revert. To + * check if revert() needs to be called again use the migration_state() method. + * + * @param string $migration String migration name to revert (including any that depend on this migration) + */ + public function revert($migration) + { + $this->container->get('dispatcher')->disable(); + $this->revert_do($migration); + $this->container->get('dispatcher')->enable(); + } + + /** + * Effectively runs a single revert step from the last migration installed + * + * @param string $migration String migration name to revert (including any that depend on this migration) + * @return null + */ + protected function revert_do($migration) + { + if (!isset($this->migration_state[$migration])) + { + // Not installed + return; + } + + foreach ($this->migration_state as $name => $state) + { + if (!empty($state['migration_depends_on']) && in_array($migration, $state['migration_depends_on'])) + { + $this->revert_do($name); + } + } + + $this->try_revert($migration); + } + + /** + * Attempts to revert a step of the given migration or one of its dependencies + * + * @param string $name The class name of the migration + * @return bool Whether any update step was successfully run + */ + protected function try_revert($name) + { + if (!class_exists($name)) + { + return false; + } + + $migration = $this->get_migration($name); + + $state = $this->migration_state[$name]; + + $this->last_run_migration = array( + 'name' => $name, + 'class' => $migration, + 'task' => '', + ); + + if ($state['migration_data_done']) + { + $steps = array_merge($this->helper->reverse_update_data($migration->update_data()), $migration->revert_data()); + $result = $this->process_data_step($steps, $state['migration_data_state']); + + $state['migration_data_state'] = ($result === true) ? '' : $result; + $state['migration_data_done'] = ($result === true) ? false : true; + + $this->set_migration_state($name, $state); + } + else if ($state['migration_schema_done']) + { + $steps = $this->helper->get_schema_steps($migration->revert_schema()); + $result = $this->process_data_step($steps, $state['migration_data_state']); + + $state['migration_data_state'] = ($result === true) ? '' : $result; + $state['migration_schema_done'] = ($result === true) ? false : true; + + if (!$state['migration_schema_done']) + { + $sql = 'DELETE FROM ' . $this->migrations_table . " + WHERE migration_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + + $this->last_run_migration = false; + unset($this->migration_state[$name]); + } + else + { + $this->set_migration_state($name, $state); + } + } + + return true; + } + + /** + * Process the data step of the migration + * + * @param array $steps The steps to run + * @param bool|string $state Current state of the migration + * @param bool $revert true to revert a data step + * @return bool|string migration state. True if completed, serialized array if not finished + * @throws \phpbb\db\migration\exception + */ + protected function process_data_step($steps, $state, $revert = false) + { + if (sizeof($steps) === 0) + { + return true; + } + + $state = is_array($state) ? $state : false; + + // reverse order of steps if reverting + if ($revert === true) + { + $steps = array_reverse($steps); + } + + $step = $last_result = 0; + if ($state) + { + $step = $state['step']; + + // We send the result from last time to the callable function + $last_result = $state['result']; + } + + try + { + // Result will be null or true if everything completed correctly + // Stop after each update step, to let the updater control the script runtime + $result = $this->run_step($steps[$step], $last_result, $revert); + if (($result !== null && $result !== true) || $step + 1 < sizeof($steps)) + { + return array( + 'result' => $result, + // Move on if the last call finished + 'step' => ($result !== null && $result !== true) ? $step : $step + 1, + ); + } + } + catch (\phpbb\db\migration\exception $e) + { + // We should try rolling back here + foreach ($steps as $reverse_step_identifier => $reverse_step) + { + // If we've reached the current step we can break because we reversed everything that was run + if ($reverse_step_identifier == $step) + { + break; + } + + // Reverse the step that was run + $result = $this->run_step($reverse_step, false, !$revert); + } + + throw $e; + } + + return true; + } + + /** + * Run a single step + * + * An exception should be thrown if an error occurs + * + * @param mixed $step Data step from migration + * @param mixed $last_result Result to pass to the callable (only for 'custom' method) + * @param bool $reverse False to install, True to attempt uninstallation by reversing the call + * @return null + */ + protected function run_step($step, $last_result = 0, $reverse = false) + { + $callable_and_parameters = $this->get_callable_from_step($step, $last_result, $reverse); + + if ($callable_and_parameters === false) + { + return; + } + + $callable = $callable_and_parameters[0]; + $parameters = $callable_and_parameters[1]; + + return call_user_func_array($callable, $parameters); + } + + /** + * Get a callable statement from a data step + * + * @param array $step Data step from migration + * @param mixed $last_result Result to pass to the callable (only for 'custom' method) + * @param bool $reverse False to install, True to attempt uninstallation by reversing the call + * @return array Array with parameters for call_user_func_array(), 0 is the callable, 1 is parameters + * @throws \phpbb\db\migration\exception + */ + protected function get_callable_from_step(array $step, $last_result = 0, $reverse = false) + { + $type = $step[0]; + $parameters = $step[1]; + + $parts = explode('.', $type); + + $class = $parts[0]; + $method = false; + + if (isset($parts[1])) + { + $method = $parts[1]; + } + + switch ($class) + { + case 'if': + if (!isset($parameters[0])) + { + throw new \phpbb\db\migration\exception('MIGRATION_INVALID_DATA_MISSING_CONDITION', $step); + } + + if (!isset($parameters[1])) + { + throw new \phpbb\db\migration\exception('MIGRATION_INVALID_DATA_MISSING_STEP', $step); + } + + if ($reverse) + { + // We might get unexpected results when trying + // to revert this, so just avoid it + return false; + } + + $condition = $parameters[0]; + + if (!$condition) + { + return false; + } + + $step = $parameters[1]; + + return $this->get_callable_from_step($step); + break; + + case 'custom': + if (!is_callable($parameters[0])) + { + throw new \phpbb\db\migration\exception('MIGRATION_INVALID_DATA_CUSTOM_NOT_CALLABLE', $step); + } + + if ($reverse) + { + return false; + } + else + { + return array( + $parameters[0], + array($last_result), + ); + } + break; + + default: + if (!$method) + { + throw new \phpbb\db\migration\exception('MIGRATION_INVALID_DATA_UNKNOWN_TYPE', $step); + } + + if (!isset($this->tools[$class])) + { + throw new \phpbb\db\migration\exception('MIGRATION_INVALID_DATA_UNDEFINED_TOOL', $step); + } + + if (!method_exists(get_class($this->tools[$class]), $method)) + { + throw new \phpbb\db\migration\exception('MIGRATION_INVALID_DATA_UNDEFINED_METHOD', $step); + } + + // Attempt to reverse operations + if ($reverse) + { + array_unshift($parameters, $method); + + return array( + array($this->tools[$class], 'reverse'), + $parameters, + ); + } + + return array( + array($this->tools[$class], $method), + $parameters, + ); + break; + } + } + + /** + * Insert/Update migration row into the database + * + * @param string $name Name of the migration + * @param array $state + * @return null + */ + protected function set_migration_state($name, $state) + { + $migration_row = $state; + $migration_row['migration_depends_on'] = serialize($state['migration_depends_on']); + $migration_row['migration_data_state'] = !empty($state['migration_data_state']) ? serialize($state['migration_data_state']) : ''; + + if (isset($this->migration_state[$name])) + { + $sql = 'UPDATE ' . $this->migrations_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $migration_row) . " + WHERE migration_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + } + else + { + $migration_row['migration_name'] = $name; + $sql = 'INSERT INTO ' . $this->migrations_table . ' + ' . $this->db->sql_build_array('INSERT', $migration_row); + $this->db->sql_query($sql); + } + + $this->migration_state[$name] = $state; + + $this->last_run_migration['state'] = $state; + } + + /** + * Checks if a migration's dependencies can even theoretically be satisfied. + * + * @param string $name The class name of the migration + * @return bool|string False if fulfillable, string of missing migration name if unfulfillable + */ + public function unfulfillable($name) + { + $name = $this->get_valid_name($name); + + if (isset($this->migration_state[$name]) || isset($this->fulfillable_migrations[$name])) + { + return false; + } + + if (!class_exists($name)) + { + return $name; + } + + $migration = $this->get_migration($name); + $depends = $migration->depends_on(); + + foreach ($depends as $depend) + { + $depend = $this->get_valid_name($depend); + $unfulfillable = $this->unfulfillable($depend); + if ($unfulfillable !== false) + { + return $unfulfillable; + } + } + $this->fulfillable_migrations[$name] = true; + + return false; + } + + /** + * Checks whether all available, fulfillable migrations have been applied. + * + * @return bool Whether the migrations have been applied + */ + public function finished() + { + foreach ($this->migrations as $name) + { + if (!isset($this->migration_state[$name])) + { + // skip unfulfillable migrations, but fulfillables mean we + // are not finished yet + if ($this->unfulfillable($name) !== false) + { + continue; + } + + return false; + } + + $migration = $this->migration_state[$name]; + + if (!$migration['migration_schema_done'] || !$migration['migration_data_done']) + { + return false; + } + } + + return true; + } + + /** + * Gets a migration state (whether it is installed and to what extent) + * + * @param string $migration String migration name to check if it is installed + * @return bool|array False if the migration has not at all been installed, array + */ + public function migration_state($migration) + { + if (!isset($this->migration_state[$migration])) + { + return false; + } + + return $this->migration_state[$migration]; + } + + /** + * Helper to get a migration + * + * @param string $name Name of the migration + * @return \phpbb\db\migration\migration + */ + protected function get_migration($name) + { + $migration = new $name($this->config, $this->db, $this->db_tools, $this->phpbb_root_path, $this->php_ext, $this->table_prefix); + + if ($migration instanceof ContainerAwareInterface) + { + $migration->setContainer($this->container); + } + + return $migration; + } + + /** + * This function adds all migrations sent to it to the migrations table + * + * THIS SHOULD NOT GENERALLY BE USED! THIS IS FOR THE PHPBB INSTALLER. + * THIS WILL THROW ERRORS IF MIGRATIONS ALREADY EXIST IN THE TABLE, DO NOT CALL MORE THAN ONCE! + * + * @param array $migrations Array of migrations (names) to add to the migrations table + * @return null + */ + public function populate_migrations($migrations) + { + foreach ($migrations as $name) + { + if ($this->migration_state($name) === false) + { + $state = array( + 'migration_depends_on' => $name::depends_on(), + 'migration_schema_done' => true, + 'migration_data_done' => true, + 'migration_data_state' => '', + 'migration_start_time' => time(), + 'migration_end_time' => time(), + ); + $this->set_migration_state($name, $state); + } + } + } + + /** + * Creates the migrations table if it does not exist. + * @return null + */ + public function create_migrations_table() + { + // Make sure migrations have been installed. + if (!$this->db_tools->sql_table_exists($this->table_prefix . 'migrations')) + { + $this->db_tools->sql_create_table($this->table_prefix . 'migrations', array( + 'COLUMNS' => array( + 'migration_name' => array('VCHAR', ''), + 'migration_depends_on' => array('TEXT', ''), + 'migration_schema_done' => array('BOOL', 0), + 'migration_data_done' => array('BOOL', 0), + 'migration_data_state' => array('TEXT', ''), + 'migration_start_time' => array('TIMESTAMP', 0), + 'migration_end_time' => array('TIMESTAMP', 0), + ), + 'PRIMARY_KEY' => 'migration_name', + )); + } + } +} diff --git a/phpBB/phpbb/db/migrator_output_handler_interface.php b/phpBB/phpbb/db/migrator_output_handler_interface.php new file mode 100644 index 0000000000..9947b51dcc --- /dev/null +++ b/phpBB/phpbb/db/migrator_output_handler_interface.php @@ -0,0 +1,31 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +interface migrator_output_handler_interface +{ + const VERBOSITY_QUIET = 16; + const VERBOSITY_NORMAL = 32; + const VERBOSITY_VERBOSE = 64; + const VERBOSITY_VERY_VERBOSE = 128; + const VERBOSITY_DEBUG = 256; + + /** + * Write output using the configured closure. + * + * @param string|array $message The message to write or an array containing the language key and all of its parameters. + * @param int $verbosity The verbosity of the message. + */ + public function write($message, $verbosity); +} diff --git a/phpBB/phpbb/db/null_migrator_output_handler.php b/phpBB/phpbb/db/null_migrator_output_handler.php new file mode 100644 index 0000000000..0e8cfbb049 --- /dev/null +++ b/phpBB/phpbb/db/null_migrator_output_handler.php @@ -0,0 +1,24 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +class null_migrator_output_handler implements migrator_output_handler_interface +{ + /** + * {@inheritdoc} + */ + public function write($message, $verbosity) + { + } +} diff --git a/phpBB/phpbb/db/sql_insert_buffer.php b/phpBB/phpbb/db/sql_insert_buffer.php new file mode 100644 index 0000000000..18e4814a77 --- /dev/null +++ b/phpBB/phpbb/db/sql_insert_buffer.php @@ -0,0 +1,146 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +/** +* Collects rows for insert into a database until the buffer size is reached. +* Then flushes the buffer to the database and starts over again. +* +* Benefits over collecting a (possibly huge) insert array and then using +* $db->sql_multi_insert() include: +* +* - Going over max packet size of the database connection is usually prevented +* because the data is submitted in batches. +* +* - Reaching database connection timeout is usually prevented because +* submission of batches talks to the database every now and then. +* +* - Usage of less PHP memory because data no longer needed is discarded on +* buffer flush. +* +* Attention: +* Please note that users of this class have to call flush() to flush the +* remaining rows to the database after their batch insert operation is +* finished. +* +* Usage: +* <code> +* $buffer = new \phpbb\db\sql_insert_buffer($db, 'test_table', 1234); +* +* while (do_stuff()) +* { +* $buffer->insert(array( +* 'column1' => 'value1', +* 'column2' => 'value2', +* )); +* } +* +* $buffer->flush(); +* </code> +*/ +class sql_insert_buffer +{ + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var string */ + protected $table_name; + + /** @var int */ + protected $max_buffered_rows; + + /** @var array */ + protected $buffer = array(); + + /** + * @param \phpbb\db\driver\driver_interface $db + * @param string $table_name + * @param int $max_buffered_rows + */ + public function __construct(\phpbb\db\driver\driver_interface $db, $table_name, $max_buffered_rows = 500) + { + $this->db = $db; + $this->table_name = $table_name; + $this->max_buffered_rows = $max_buffered_rows; + } + + /** + * Inserts a single row into the buffer if multi insert is supported by the + * database (otherwise an insert query is sent immediately). Then flushes + * the buffer if the number of rows in the buffer is now greater than or + * equal to $max_buffered_rows. + * + * @param array $row + * + * @return bool True when some data was flushed to the database. + * False otherwise. + */ + public function insert(array $row) + { + $this->buffer[] = $row; + + // Flush buffer if it is full or when DB does not support multi inserts. + // In the later case, the buffer will always only contain one row. + if (!$this->db->get_multi_insert() || sizeof($this->buffer) >= $this->max_buffered_rows) + { + return $this->flush(); + } + + return false; + } + + /** + * Inserts a row set, i.e. an array of rows, by calling insert(). + * + * Please note that it is in most cases better to use insert() instead of + * first building a huge rowset. Or at least sizeof($rows) should be kept + * small. + * + * @param array $rows + * + * @return bool True when some data was flushed to the database. + * False otherwise. + */ + public function insert_all(array $rows) + { + // Using bitwise |= because PHP does not have logical ||= + $result = 0; + + foreach ($rows as $row) + { + $result |= (int) $this->insert($row); + } + + return (bool) $result; + } + + /** + * Flushes the buffer content to the DB and clears the buffer. + * + * @return bool True when some data was flushed to the database. + * False otherwise. + */ + public function flush() + { + if (!empty($this->buffer)) + { + $this->db->sql_multi_insert($this->table_name, $this->buffer); + $this->buffer = array(); + + return true; + } + + return false; + } +} diff --git a/phpBB/phpbb/db/tools.php b/phpBB/phpbb/db/tools.php new file mode 100644 index 0000000000..832a0c510c --- /dev/null +++ b/phpBB/phpbb/db/tools.php @@ -0,0 +1,2840 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\db; + +/** +* Database Tools for handling cross-db actions such as altering columns, etc. +* Currently not supported is returning SQL for creating tables. +*/ +class tools +{ + /** + * Current sql layer + */ + var $sql_layer = ''; + + /** + * @var object DB object + */ + var $db = null; + + /** + * The Column types for every database we support + * @var array + */ + var $dbms_type_map = array(); + + /** + * Is the used MS SQL Server a SQL Server 2000? + * @var bool + */ + protected $is_sql_server_2000; + + /** + * Get the column types for every database we support + * + * @return array + */ + public static function get_dbms_type_map() + { + return array( + 'mysql_41' => array( + 'INT:' => 'int(%d)', + 'BINT' => 'bigint(20)', + 'UINT' => 'mediumint(8) UNSIGNED', + 'UINT:' => 'int(%d) UNSIGNED', + 'TINT:' => 'tinyint(%d)', + 'USINT' => 'smallint(4) UNSIGNED', + 'BOOL' => 'tinyint(1) UNSIGNED', + 'VCHAR' => 'varchar(255)', + 'VCHAR:' => 'varchar(%d)', + 'CHAR:' => 'char(%d)', + 'XSTEXT' => 'text', + 'XSTEXT_UNI'=> 'varchar(100)', + 'STEXT' => 'text', + 'STEXT_UNI' => 'varchar(255)', + 'TEXT' => 'text', + 'TEXT_UNI' => 'text', + 'MTEXT' => 'mediumtext', + 'MTEXT_UNI' => 'mediumtext', + 'TIMESTAMP' => 'int(11) UNSIGNED', + 'DECIMAL' => 'decimal(5,2)', + 'DECIMAL:' => 'decimal(%d,2)', + 'PDECIMAL' => 'decimal(6,3)', + 'PDECIMAL:' => 'decimal(%d,3)', + 'VCHAR_UNI' => 'varchar(255)', + 'VCHAR_UNI:'=> 'varchar(%d)', + 'VCHAR_CI' => 'varchar(255)', + 'VARBINARY' => 'varbinary(255)', + ), + + 'mysql_40' => array( + 'INT:' => 'int(%d)', + 'BINT' => 'bigint(20)', + 'UINT' => 'mediumint(8) UNSIGNED', + 'UINT:' => 'int(%d) UNSIGNED', + 'TINT:' => 'tinyint(%d)', + 'USINT' => 'smallint(4) UNSIGNED', + 'BOOL' => 'tinyint(1) UNSIGNED', + 'VCHAR' => 'varbinary(255)', + 'VCHAR:' => 'varbinary(%d)', + 'CHAR:' => 'binary(%d)', + 'XSTEXT' => 'blob', + 'XSTEXT_UNI'=> 'blob', + 'STEXT' => 'blob', + 'STEXT_UNI' => 'blob', + 'TEXT' => 'blob', + 'TEXT_UNI' => 'blob', + 'MTEXT' => 'mediumblob', + 'MTEXT_UNI' => 'mediumblob', + 'TIMESTAMP' => 'int(11) UNSIGNED', + 'DECIMAL' => 'decimal(5,2)', + 'DECIMAL:' => 'decimal(%d,2)', + 'PDECIMAL' => 'decimal(6,3)', + 'PDECIMAL:' => 'decimal(%d,3)', + 'VCHAR_UNI' => 'blob', + 'VCHAR_UNI:'=> array('varbinary(%d)', 'limit' => array('mult', 3, 255, 'blob')), + 'VCHAR_CI' => 'blob', + 'VARBINARY' => 'varbinary(255)', + ), + + 'mssql' => array( + 'INT:' => '[int]', + 'BINT' => '[float]', + 'UINT' => '[int]', + 'UINT:' => '[int]', + 'TINT:' => '[int]', + 'USINT' => '[int]', + 'BOOL' => '[int]', + 'VCHAR' => '[varchar] (255)', + 'VCHAR:' => '[varchar] (%d)', + 'CHAR:' => '[char] (%d)', + 'XSTEXT' => '[varchar] (1000)', + 'STEXT' => '[varchar] (3000)', + 'TEXT' => '[varchar] (8000)', + 'MTEXT' => '[text]', + 'XSTEXT_UNI'=> '[varchar] (100)', + 'STEXT_UNI' => '[varchar] (255)', + 'TEXT_UNI' => '[varchar] (4000)', + 'MTEXT_UNI' => '[text]', + 'TIMESTAMP' => '[int]', + 'DECIMAL' => '[float]', + 'DECIMAL:' => '[float]', + 'PDECIMAL' => '[float]', + 'PDECIMAL:' => '[float]', + 'VCHAR_UNI' => '[varchar] (255)', + 'VCHAR_UNI:'=> '[varchar] (%d)', + 'VCHAR_CI' => '[varchar] (255)', + 'VARBINARY' => '[varchar] (255)', + ), + + 'mssqlnative' => array( + 'INT:' => '[int]', + 'BINT' => '[float]', + 'UINT' => '[int]', + 'UINT:' => '[int]', + 'TINT:' => '[int]', + 'USINT' => '[int]', + 'BOOL' => '[int]', + 'VCHAR' => '[varchar] (255)', + 'VCHAR:' => '[varchar] (%d)', + 'CHAR:' => '[char] (%d)', + 'XSTEXT' => '[varchar] (1000)', + 'STEXT' => '[varchar] (3000)', + 'TEXT' => '[varchar] (8000)', + 'MTEXT' => '[text]', + 'XSTEXT_UNI'=> '[varchar] (100)', + 'STEXT_UNI' => '[varchar] (255)', + 'TEXT_UNI' => '[varchar] (4000)', + 'MTEXT_UNI' => '[text]', + 'TIMESTAMP' => '[int]', + 'DECIMAL' => '[float]', + 'DECIMAL:' => '[float]', + 'PDECIMAL' => '[float]', + 'PDECIMAL:' => '[float]', + 'VCHAR_UNI' => '[varchar] (255)', + 'VCHAR_UNI:'=> '[varchar] (%d)', + 'VCHAR_CI' => '[varchar] (255)', + 'VARBINARY' => '[varchar] (255)', + ), + + 'oracle' => array( + 'INT:' => 'number(%d)', + 'BINT' => 'number(20)', + 'UINT' => 'number(8)', + 'UINT:' => 'number(%d)', + 'TINT:' => 'number(%d)', + 'USINT' => 'number(4)', + 'BOOL' => 'number(1)', + 'VCHAR' => 'varchar2(255)', + 'VCHAR:' => 'varchar2(%d)', + 'CHAR:' => 'char(%d)', + 'XSTEXT' => 'varchar2(1000)', + 'STEXT' => 'varchar2(3000)', + 'TEXT' => 'clob', + 'MTEXT' => 'clob', + 'XSTEXT_UNI'=> 'varchar2(300)', + 'STEXT_UNI' => 'varchar2(765)', + 'TEXT_UNI' => 'clob', + 'MTEXT_UNI' => 'clob', + 'TIMESTAMP' => 'number(11)', + 'DECIMAL' => 'number(5, 2)', + 'DECIMAL:' => 'number(%d, 2)', + 'PDECIMAL' => 'number(6, 3)', + 'PDECIMAL:' => 'number(%d, 3)', + 'VCHAR_UNI' => 'varchar2(765)', + 'VCHAR_UNI:'=> array('varchar2(%d)', 'limit' => array('mult', 3, 765, 'clob')), + 'VCHAR_CI' => 'varchar2(255)', + 'VARBINARY' => 'raw(255)', + ), + + 'sqlite' => array( + 'INT:' => 'int(%d)', + 'BINT' => 'bigint(20)', + 'UINT' => 'INTEGER UNSIGNED', //'mediumint(8) UNSIGNED', + 'UINT:' => 'INTEGER UNSIGNED', // 'int(%d) UNSIGNED', + 'TINT:' => 'tinyint(%d)', + 'USINT' => 'INTEGER UNSIGNED', //'mediumint(4) UNSIGNED', + 'BOOL' => 'INTEGER UNSIGNED', //'tinyint(1) UNSIGNED', + 'VCHAR' => 'varchar(255)', + 'VCHAR:' => 'varchar(%d)', + 'CHAR:' => 'char(%d)', + 'XSTEXT' => 'text(65535)', + 'STEXT' => 'text(65535)', + 'TEXT' => 'text(65535)', + 'MTEXT' => 'mediumtext(16777215)', + 'XSTEXT_UNI'=> 'text(65535)', + 'STEXT_UNI' => 'text(65535)', + 'TEXT_UNI' => 'text(65535)', + 'MTEXT_UNI' => 'mediumtext(16777215)', + 'TIMESTAMP' => 'INTEGER UNSIGNED', //'int(11) UNSIGNED', + 'DECIMAL' => 'decimal(5,2)', + 'DECIMAL:' => 'decimal(%d,2)', + 'PDECIMAL' => 'decimal(6,3)', + 'PDECIMAL:' => 'decimal(%d,3)', + 'VCHAR_UNI' => 'varchar(255)', + 'VCHAR_UNI:'=> 'varchar(%d)', + 'VCHAR_CI' => 'varchar(255)', + 'VARBINARY' => 'blob', + ), + + 'sqlite3' => array( + 'INT:' => 'INT(%d)', + 'BINT' => 'BIGINT(20)', + 'UINT' => 'INTEGER UNSIGNED', + 'UINT:' => 'INTEGER UNSIGNED', + 'TINT:' => 'TINYINT(%d)', + 'USINT' => 'INTEGER UNSIGNED', + 'BOOL' => 'INTEGER UNSIGNED', + 'VCHAR' => 'VARCHAR(255)', + 'VCHAR:' => 'VARCHAR(%d)', + 'CHAR:' => 'CHAR(%d)', + 'XSTEXT' => 'TEXT(65535)', + 'STEXT' => 'TEXT(65535)', + 'TEXT' => 'TEXT(65535)', + 'MTEXT' => 'MEDIUMTEXT(16777215)', + 'XSTEXT_UNI'=> 'TEXT(65535)', + 'STEXT_UNI' => 'TEXT(65535)', + 'TEXT_UNI' => 'TEXT(65535)', + 'MTEXT_UNI' => 'MEDIUMTEXT(16777215)', + 'TIMESTAMP' => 'INTEGER UNSIGNED', //'int(11) UNSIGNED', + 'DECIMAL' => 'DECIMAL(5,2)', + 'DECIMAL:' => 'DECIMAL(%d,2)', + 'PDECIMAL' => 'DECIMAL(6,3)', + 'PDECIMAL:' => 'DECIMAL(%d,3)', + 'VCHAR_UNI' => 'VARCHAR(255)', + 'VCHAR_UNI:'=> 'VARCHAR(%d)', + 'VCHAR_CI' => 'VARCHAR(255)', + 'VARBINARY' => 'BLOB', + ), + + 'postgres' => array( + 'INT:' => 'INT4', + 'BINT' => 'INT8', + 'UINT' => 'INT4', // unsigned + 'UINT:' => 'INT4', // unsigned + 'USINT' => 'INT2', // unsigned + 'BOOL' => 'INT2', // unsigned + 'TINT:' => 'INT2', + 'VCHAR' => 'varchar(255)', + 'VCHAR:' => 'varchar(%d)', + 'CHAR:' => 'char(%d)', + 'XSTEXT' => 'varchar(1000)', + 'STEXT' => 'varchar(3000)', + 'TEXT' => 'varchar(8000)', + 'MTEXT' => 'TEXT', + 'XSTEXT_UNI'=> 'varchar(100)', + 'STEXT_UNI' => 'varchar(255)', + 'TEXT_UNI' => 'varchar(4000)', + 'MTEXT_UNI' => 'TEXT', + 'TIMESTAMP' => 'INT4', // unsigned + 'DECIMAL' => 'decimal(5,2)', + 'DECIMAL:' => 'decimal(%d,2)', + 'PDECIMAL' => 'decimal(6,3)', + 'PDECIMAL:' => 'decimal(%d,3)', + 'VCHAR_UNI' => 'varchar(255)', + 'VCHAR_UNI:'=> 'varchar(%d)', + 'VCHAR_CI' => 'varchar_ci', + 'VARBINARY' => 'bytea', + ), + ); + } + + /** + * A list of types being unsigned for better reference in some db's + * @var array + */ + var $unsigned_types = array('UINT', 'UINT:', 'USINT', 'BOOL', 'TIMESTAMP'); + + /** + * A list of supported DBMS. We change this class to support more DBMS, the DBMS itself only need to follow some rules. + * @var array + */ + var $supported_dbms = array('mssql', 'mssqlnative', 'mysql_40', 'mysql_41', 'oracle', 'postgres', 'sqlite', 'sqlite3'); + + /** + * This is set to true if user only wants to return the 'to-be-executed' SQL statement(s) (as an array). + * This mode has no effect on some methods (inserting of data for example). This is expressed within the methods command. + */ + var $return_statements = false; + + /** + * Constructor. Set DB Object and set {@link $return_statements return_statements}. + * + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param bool $return_statements True if only statements should be returned and no SQL being executed + */ + public function __construct(\phpbb\db\driver\driver_interface $db, $return_statements = false) + { + $this->db = $db; + $this->return_statements = $return_statements; + + $this->dbms_type_map = self::get_dbms_type_map(); + + // Determine mapping database type + switch ($this->db->get_sql_layer()) + { + case 'mysql': + $this->sql_layer = 'mysql_40'; + break; + + case 'mysql4': + if (version_compare($this->db->sql_server_info(true), '4.1.3', '>=')) + { + $this->sql_layer = 'mysql_41'; + } + else + { + $this->sql_layer = 'mysql_40'; + } + break; + + case 'mysqli': + $this->sql_layer = 'mysql_41'; + break; + + case 'mssql': + case 'mssql_odbc': + $this->sql_layer = 'mssql'; + break; + + case 'mssqlnative': + $this->sql_layer = 'mssqlnative'; + break; + + default: + $this->sql_layer = $this->db->get_sql_layer(); + break; + } + } + + /** + * Setter for {@link $return_statements return_statements}. + * + * @param bool $return_statements True if SQL should not be executed but returned as strings + * @return null + */ + public function set_return_statements($return_statements) + { + $this->return_statements = $return_statements; + } + + /** + * Gets a list of tables in the database. + * + * @return array Array of table names (all lower case) + */ + function sql_list_tables() + { + switch ($this->db->get_sql_layer()) + { + case 'mysql': + case 'mysql4': + case 'mysqli': + $sql = 'SHOW TABLES'; + break; + + case 'sqlite': + $sql = 'SELECT name + FROM sqlite_master + WHERE type = "table"'; + break; + + case 'sqlite3': + $sql = 'SELECT name + FROM sqlite_master + WHERE type = "table" + AND name <> "sqlite_sequence"'; + break; + + case 'mssql': + case 'mssql_odbc': + case 'mssqlnative': + $sql = "SELECT name + FROM sysobjects + WHERE type='U'"; + break; + + case 'postgres': + $sql = 'SELECT relname + FROM pg_stat_user_tables'; + break; + + case 'oracle': + $sql = 'SELECT table_name + FROM USER_TABLES'; + break; + } + + $result = $this->db->sql_query($sql); + + $tables = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $name = current($row); + $tables[$name] = $name; + } + $this->db->sql_freeresult($result); + + return $tables; + } + + /** + * Check if table exists + * + * + * @param string $table_name The table name to check for + * @return bool true if table exists, else false + */ + function sql_table_exists($table_name) + { + $this->db->sql_return_on_error(true); + $result = $this->db->sql_query_limit('SELECT * FROM ' . $table_name, 1); + $this->db->sql_return_on_error(false); + + if ($result) + { + $this->db->sql_freeresult($result); + return true; + } + + return false; + } + + /** + * Create SQL Table + * + * @param string $table_name The table name to create + * @param array $table_data Array containing table data. + * @return array Statements if $return_statements is true. + */ + function sql_create_table($table_name, $table_data) + { + // holds the DDL for a column + $columns = $statements = array(); + + if ($this->sql_table_exists($table_name)) + { + return $this->_sql_run_sql($statements); + } + + // Begin transaction + $statements[] = 'begin'; + + // Determine if we have created a PRIMARY KEY in the earliest + $primary_key_gen = false; + + // Determine if the table requires a sequence + $create_sequence = false; + + // Begin table sql statement + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + $table_sql = 'CREATE TABLE [' . $table_name . '] (' . "\n"; + break; + + default: + $table_sql = 'CREATE TABLE ' . $table_name . ' (' . "\n"; + break; + } + + if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative') + { + if (!isset($table_data['PRIMARY_KEY'])) + { + $table_data['COLUMNS']['mssqlindex'] = array('UINT', null, 'auto_increment'); + $table_data['PRIMARY_KEY'] = 'mssqlindex'; + } + } + + // Iterate through the columns to create a table + foreach ($table_data['COLUMNS'] as $column_name => $column_data) + { + // here lies an array, filled with information compiled on the column's data + $prepared_column = $this->sql_prepare_column_data($table_name, $column_name, $column_data); + + if (isset($prepared_column['auto_increment']) && $prepared_column['auto_increment'] && strlen($column_name) > 26) // "${column_name}_gen" + { + trigger_error("Index name '${column_name}_gen' on table '$table_name' is too long. The maximum auto increment column length is 26 characters.", E_USER_ERROR); + } + + // here we add the definition of the new column to the list of columns + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + $columns[] = "\t [{$column_name}] " . $prepared_column['column_type_sql_default']; + break; + + default: + $columns[] = "\t {$column_name} " . $prepared_column['column_type_sql']; + break; + } + + // see if we have found a primary key set due to a column definition if we have found it, we can stop looking + if (!$primary_key_gen) + { + $primary_key_gen = isset($prepared_column['primary_key_set']) && $prepared_column['primary_key_set']; + } + + // create sequence DDL based off of the existance of auto incrementing columns + if (!$create_sequence && isset($prepared_column['auto_increment']) && $prepared_column['auto_increment']) + { + $create_sequence = $column_name; + } + } + + // this makes up all the columns in the create table statement + $table_sql .= implode(",\n", $columns); + + // Close the table for two DBMS and add to the statements + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + $table_sql .= "\n);"; + $statements[] = $table_sql; + break; + } + + // we have yet to create a primary key for this table, + // this means that we can add the one we really wanted instead + if (!$primary_key_gen) + { + // Write primary key + if (isset($table_data['PRIMARY_KEY'])) + { + if (!is_array($table_data['PRIMARY_KEY'])) + { + $table_data['PRIMARY_KEY'] = array($table_data['PRIMARY_KEY']); + } + + switch ($this->sql_layer) + { + case 'mysql_40': + case 'mysql_41': + case 'postgres': + case 'sqlite': + case 'sqlite3': + $table_sql .= ",\n\t PRIMARY KEY (" . implode(', ', $table_data['PRIMARY_KEY']) . ')'; + break; + + case 'mssql': + case 'mssqlnative': + // We need the data here + $old_return_statements = $this->return_statements; + $this->return_statements = true; + + $primary_key_stmts = $this->sql_create_primary_key($table_name, $table_data['PRIMARY_KEY']); + foreach ($primary_key_stmts as $pk_stmt) + { + $statements[] = $pk_stmt; + } + + $this->return_statements = $old_return_statements; + break; + + case 'oracle': + $table_sql .= ",\n\t CONSTRAINT pk_{$table_name} PRIMARY KEY (" . implode(', ', $table_data['PRIMARY_KEY']) . ')'; + break; + } + } + } + + // close the table + switch ($this->sql_layer) + { + case 'mysql_41': + // make sure the table is in UTF-8 mode + $table_sql .= "\n) CHARACTER SET `utf8` COLLATE `utf8_bin`;"; + $statements[] = $table_sql; + break; + + case 'mysql_40': + case 'sqlite': + case 'sqlite3': + $table_sql .= "\n);"; + $statements[] = $table_sql; + break; + + case 'postgres': + // do we need to add a sequence for auto incrementing columns? + if ($create_sequence) + { + $statements[] = "CREATE SEQUENCE {$table_name}_seq;"; + } + + $table_sql .= "\n);"; + $statements[] = $table_sql; + break; + + case 'oracle': + $table_sql .= "\n)"; + $statements[] = $table_sql; + + // do we need to add a sequence and a tigger for auto incrementing columns? + if ($create_sequence) + { + // create the actual sequence + $statements[] = "CREATE SEQUENCE {$table_name}_seq"; + + // the trigger is the mechanism by which we increment the counter + $trigger = "CREATE OR REPLACE TRIGGER t_{$table_name}\n"; + $trigger .= "BEFORE INSERT ON {$table_name}\n"; + $trigger .= "FOR EACH ROW WHEN (\n"; + $trigger .= "\tnew.{$create_sequence} IS NULL OR new.{$create_sequence} = 0\n"; + $trigger .= ")\n"; + $trigger .= "BEGIN\n"; + $trigger .= "\tSELECT {$table_name}_seq.nextval\n"; + $trigger .= "\tINTO :new.{$create_sequence}\n"; + $trigger .= "\tFROM dual;\n"; + $trigger .= "END;"; + + $statements[] = $trigger; + } + break; + } + + // Write Keys + if (isset($table_data['KEYS'])) + { + foreach ($table_data['KEYS'] as $key_name => $key_data) + { + if (!is_array($key_data[1])) + { + $key_data[1] = array($key_data[1]); + } + + $old_return_statements = $this->return_statements; + $this->return_statements = true; + + $key_stmts = ($key_data[0] == 'UNIQUE') ? $this->sql_create_unique_index($table_name, $key_name, $key_data[1]) : $this->sql_create_index($table_name, $key_name, $key_data[1]); + + foreach ($key_stmts as $key_stmt) + { + $statements[] = $key_stmt; + } + + $this->return_statements = $old_return_statements; + } + } + + // Commit Transaction + $statements[] = 'commit'; + + return $this->_sql_run_sql($statements); + } + + /** + * Handle passed database update array. + * Expected structure... + * Key being one of the following + * drop_tables: Drop tables + * add_tables: Add tables + * change_columns: Column changes (only type, not name) + * add_columns: Add columns to a table + * drop_keys: Dropping keys + * drop_columns: Removing/Dropping columns + * add_primary_keys: adding primary keys + * add_unique_index: adding an unique index + * add_index: adding an index (can be column:index_size if you need to provide size) + * + * The values are in this format: + * {TABLE NAME} => array( + * {COLUMN NAME} => array({COLUMN TYPE}, {DEFAULT VALUE}, {OPTIONAL VARIABLES}), + * {KEY/INDEX NAME} => array({COLUMN NAMES}), + * ) + * + * For more information have a look at /develop/create_schema_files.php (only available through SVN) + */ + function perform_schema_changes($schema_changes) + { + if (empty($schema_changes)) + { + return; + } + + $statements = array(); + $sqlite = false; + + // For SQLite we need to perform the schema changes in a much more different way + if (($this->db->get_sql_layer() == 'sqlite' || $this->db->get_sql_layer() == 'sqlite3') && $this->return_statements) + { + $sqlite_data = array(); + $sqlite = true; + } + + // Drop tables? + if (!empty($schema_changes['drop_tables'])) + { + foreach ($schema_changes['drop_tables'] as $table) + { + // only drop table if it exists + if ($this->sql_table_exists($table)) + { + $result = $this->sql_table_drop($table); + if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + + // Add tables? + if (!empty($schema_changes['add_tables'])) + { + foreach ($schema_changes['add_tables'] as $table => $table_data) + { + $result = $this->sql_create_table($table, $table_data); + if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + + // Change columns? + if (!empty($schema_changes['change_columns'])) + { + foreach ($schema_changes['change_columns'] as $table => $columns) + { + foreach ($columns as $column_name => $column_data) + { + // If the column exists we change it, else we add it ;) + if ($column_exists = $this->sql_column_exists($table, $column_name)) + { + $result = $this->sql_column_change($table, $column_name, $column_data, true); + } + else + { + $result = $this->sql_column_add($table, $column_name, $column_data, true); + } + + if ($sqlite) + { + if ($column_exists) + { + $sqlite_data[$table]['change_columns'][] = $result; + } + else + { + $sqlite_data[$table]['add_columns'][] = $result; + } + } + else if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + + // Add columns? + if (!empty($schema_changes['add_columns'])) + { + foreach ($schema_changes['add_columns'] as $table => $columns) + { + foreach ($columns as $column_name => $column_data) + { + // Only add the column if it does not exist yet + if ($column_exists = $this->sql_column_exists($table, $column_name)) + { + continue; + // This is commented out here because it can take tremendous time on updates +// $result = $this->sql_column_change($table, $column_name, $column_data, true); + } + else + { + $result = $this->sql_column_add($table, $column_name, $column_data, true); + } + + if ($sqlite) + { + if ($column_exists) + { + continue; +// $sqlite_data[$table]['change_columns'][] = $result; + } + else + { + $sqlite_data[$table]['add_columns'][] = $result; + } + } + else if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + + // Remove keys? + if (!empty($schema_changes['drop_keys'])) + { + foreach ($schema_changes['drop_keys'] as $table => $indexes) + { + foreach ($indexes as $index_name) + { + if (!$this->sql_index_exists($table, $index_name)) + { + continue; + } + + $result = $this->sql_index_drop($table, $index_name); + + if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + + // Drop columns? + if (!empty($schema_changes['drop_columns'])) + { + foreach ($schema_changes['drop_columns'] as $table => $columns) + { + foreach ($columns as $column) + { + // Only remove the column if it exists... + if ($this->sql_column_exists($table, $column)) + { + $result = $this->sql_column_remove($table, $column, true); + + if ($sqlite) + { + $sqlite_data[$table]['drop_columns'][] = $result; + } + else if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + } + + // Add primary keys? + if (!empty($schema_changes['add_primary_keys'])) + { + foreach ($schema_changes['add_primary_keys'] as $table => $columns) + { + $result = $this->sql_create_primary_key($table, $columns, true); + + if ($sqlite) + { + $sqlite_data[$table]['primary_key'] = $result; + } + else if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + + // Add unique indexes? + if (!empty($schema_changes['add_unique_index'])) + { + foreach ($schema_changes['add_unique_index'] as $table => $index_array) + { + foreach ($index_array as $index_name => $column) + { + if ($this->sql_unique_index_exists($table, $index_name)) + { + continue; + } + + $result = $this->sql_create_unique_index($table, $index_name, $column); + + if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + + // Add indexes? + if (!empty($schema_changes['add_index'])) + { + foreach ($schema_changes['add_index'] as $table => $index_array) + { + foreach ($index_array as $index_name => $column) + { + if ($this->sql_index_exists($table, $index_name)) + { + continue; + } + + $result = $this->sql_create_index($table, $index_name, $column); + + if ($this->return_statements) + { + $statements = array_merge($statements, $result); + } + } + } + } + + if ($sqlite) + { + foreach ($sqlite_data as $table_name => $sql_schema_changes) + { + // Create temporary table with original data + $statements[] = 'begin'; + + $sql = "SELECT sql + FROM sqlite_master + WHERE type = 'table' + AND name = '{$table_name}' + ORDER BY type DESC, name;"; + $result = $this->db->sql_query($sql); + + if (!$result) + { + continue; + } + + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + // Create a backup table and populate it, destroy the existing one + $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']); + $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; + $statements[] = 'DROP TABLE ' . $table_name; + + // Get the columns... + preg_match('#\((.*)\)#s', $row['sql'], $matches); + + $plain_table_cols = trim($matches[1]); + $new_table_cols = preg_split('/,(?![\s\w]+\))/m', $plain_table_cols); + $column_list = array(); + + foreach ($new_table_cols as $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if ($entities[0] == 'PRIMARY') + { + continue; + } + $column_list[] = $entities[0]; + } + + // note down the primary key notation because sqlite only supports adding it to the end for the new table + $primary_key = false; + $_new_cols = array(); + + foreach ($new_table_cols as $key => $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if ($entities[0] == 'PRIMARY') + { + $primary_key = $declaration; + continue; + } + $_new_cols[] = $declaration; + } + + $new_table_cols = $_new_cols; + + // First of all... change columns + if (!empty($sql_schema_changes['change_columns'])) + { + foreach ($sql_schema_changes['change_columns'] as $column_sql) + { + foreach ($new_table_cols as $key => $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if (strpos($column_sql, $entities[0] . ' ') === 0) + { + $new_table_cols[$key] = $column_sql; + } + } + } + } + + if (!empty($sql_schema_changes['add_columns'])) + { + foreach ($sql_schema_changes['add_columns'] as $column_sql) + { + $new_table_cols[] = $column_sql; + } + } + + // Now drop them... + if (!empty($sql_schema_changes['drop_columns'])) + { + foreach ($sql_schema_changes['drop_columns'] as $column_name) + { + // Remove from column list... + $new_column_list = array(); + foreach ($column_list as $key => $value) + { + if ($value === $column_name) + { + continue; + } + + $new_column_list[] = $value; + } + + $column_list = $new_column_list; + + // Remove from table... + $_new_cols = array(); + foreach ($new_table_cols as $key => $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if (strpos($column_name . ' ', $entities[0] . ' ') === 0) + { + continue; + } + $_new_cols[] = $declaration; + } + $new_table_cols = $_new_cols; + } + } + + // Primary key... + if (!empty($sql_schema_changes['primary_key'])) + { + $new_table_cols[] = 'PRIMARY KEY (' . implode(', ', $sql_schema_changes['primary_key']) . ')'; + } + // Add a new one or the old primary key + else if ($primary_key !== false) + { + $new_table_cols[] = $primary_key; + } + + $columns = implode(',', $column_list); + + // create a new table and fill it up. destroy the temp one + $statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $new_table_cols) . ');'; + $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; + $statements[] = 'DROP TABLE ' . $table_name . '_temp'; + + $statements[] = 'commit'; + } + } + + if ($this->return_statements) + { + return $statements; + } + } + + /** + * Gets a list of columns of a table. + * + * @param string $table Table name + * + * @return array Array of column names (all lower case) + */ + function sql_list_columns($table) + { + $columns = array(); + + switch ($this->sql_layer) + { + case 'mysql_40': + case 'mysql_41': + $sql = "SHOW COLUMNS FROM $table"; + break; + + // PostgreSQL has a way of doing this in a much simpler way but would + // not allow us to support all versions of PostgreSQL + case 'postgres': + $sql = "SELECT a.attname + FROM pg_class c, pg_attribute a + WHERE c.relname = '{$table}' + AND a.attnum > 0 + AND a.attrelid = c.oid"; + break; + + // same deal with PostgreSQL, we must perform more complex operations than + // we technically could + case 'mssql': + case 'mssqlnative': + $sql = "SELECT c.name + FROM syscolumns c + LEFT JOIN sysobjects o ON c.id = o.id + WHERE o.name = '{$table}'"; + break; + + case 'oracle': + $sql = "SELECT column_name + FROM user_tab_columns + WHERE LOWER(table_name) = '" . strtolower($table) . "'"; + break; + + case 'sqlite': + case 'sqlite3': + $sql = "SELECT sql + FROM sqlite_master + WHERE type = 'table' + AND name = '{$table}'"; + + $result = $this->db->sql_query($sql); + + if (!$result) + { + return false; + } + + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + preg_match('#\((.*)\)#s', $row['sql'], $matches); + + $cols = trim($matches[1]); + $col_array = preg_split('/,(?![\s\w]+\))/m', $cols); + + foreach ($col_array as $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if ($entities[0] == 'PRIMARY') + { + continue; + } + + $column = strtolower($entities[0]); + $columns[$column] = $column; + } + + return $columns; + break; + } + + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $column = strtolower(current($row)); + $columns[$column] = $column; + } + $this->db->sql_freeresult($result); + + return $columns; + } + + /** + * Check whether a specified column exist in a table + * + * @param string $table Table to check + * @param string $column_name Column to check + * + * @return bool True if column exists, false otherwise + */ + function sql_column_exists($table, $column_name) + { + $columns = $this->sql_list_columns($table); + + return isset($columns[$column_name]); + } + + /** + * Check if a specified index exists in table. Does not return PRIMARY KEY and UNIQUE indexes. + * + * @param string $table_name Table to check the index at + * @param string $index_name The index name to check + * + * @return bool True if index exists, else false + */ + function sql_index_exists($table_name, $index_name) + { + if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative') + { + $sql = "EXEC sp_statistics '$table_name'"; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + if ($row['TYPE'] == 3) + { + if (strtolower($row['INDEX_NAME']) == strtolower($index_name)) + { + $this->db->sql_freeresult($result); + return true; + } + } + } + $this->db->sql_freeresult($result); + + return false; + } + + switch ($this->sql_layer) + { + case 'postgres': + $sql = "SELECT ic.relname as index_name + FROM pg_class bc, pg_class ic, pg_index i + WHERE (bc.oid = i.indrelid) + AND (ic.oid = i.indexrelid) + AND (bc.relname = '" . $table_name . "') + AND (i.indisunique != 't') + AND (i.indisprimary != 't')"; + $col = 'index_name'; + break; + + case 'mysql_40': + case 'mysql_41': + $sql = 'SHOW KEYS + FROM ' . $table_name; + $col = 'Key_name'; + break; + + case 'oracle': + $sql = "SELECT index_name + FROM user_indexes + WHERE table_name = '" . strtoupper($table_name) . "' + AND generated = 'N' + AND uniqueness = 'NONUNIQUE'"; + $col = 'index_name'; + break; + + case 'sqlite': + case 'sqlite3': + $sql = "PRAGMA index_list('" . $table_name . "');"; + $col = 'name'; + break; + } + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && !$row['Non_unique']) + { + continue; + } + + // These DBMS prefix index name with the table name + switch ($this->sql_layer) + { + case 'oracle': + case 'postgres': + case 'sqlite': + case 'sqlite3': + $row[$col] = substr($row[$col], strlen($table_name) + 1); + break; + } + + if (strtolower($row[$col]) == strtolower($index_name)) + { + $this->db->sql_freeresult($result); + return true; + } + } + $this->db->sql_freeresult($result); + + return false; + } + + /** + * Check if a specified index exists in table. Does not return PRIMARY KEY indexes. + * + * @param string $table_name Table to check the index at + * @param string $index_name The index name to check + * + * @return bool True if index exists, else false + */ + function sql_unique_index_exists($table_name, $index_name) + { + if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative') + { + $sql = "EXEC sp_statistics '$table_name'"; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + // Usually NON_UNIQUE is the column we want to check, but we allow for both + if ($row['TYPE'] == 3) + { + if (strtolower($row['INDEX_NAME']) == strtolower($index_name)) + { + $this->db->sql_freeresult($result); + return true; + } + } + } + $this->db->sql_freeresult($result); + return false; + } + + switch ($this->sql_layer) + { + case 'postgres': + $sql = "SELECT ic.relname as index_name, i.indisunique + FROM pg_class bc, pg_class ic, pg_index i + WHERE (bc.oid = i.indrelid) + AND (ic.oid = i.indexrelid) + AND (bc.relname = '" . $table_name . "') + AND (i.indisprimary != 't')"; + $col = 'index_name'; + break; + + case 'mysql_40': + case 'mysql_41': + $sql = 'SHOW KEYS + FROM ' . $table_name; + $col = 'Key_name'; + break; + + case 'oracle': + $sql = "SELECT index_name, table_owner + FROM user_indexes + WHERE table_name = '" . strtoupper($table_name) . "' + AND generated = 'N' + AND uniqueness = 'UNIQUE'"; + $col = 'index_name'; + break; + + case 'sqlite': + case 'sqlite3': + $sql = "PRAGMA index_list('" . $table_name . "');"; + $col = 'name'; + break; + } + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && ($row['Non_unique'] || $row[$col] == 'PRIMARY')) + { + continue; + } + + if (($this->sql_layer == 'sqlite' || $this->sql_layer == 'sqlite3') && !$row['unique']) + { + continue; + } + + if ($this->sql_layer == 'postgres' && $row['indisunique'] != 't') + { + continue; + } + + // These DBMS prefix index name with the table name + switch ($this->sql_layer) + { + case 'oracle': + // Two cases here... prefixed with U_[table_owner] and not prefixed with table_name + if (strpos($row[$col], 'U_') === 0) + { + $row[$col] = substr($row[$col], strlen('U_' . $row['table_owner']) + 1); + } + else if (strpos($row[$col], strtoupper($table_name)) === 0) + { + $row[$col] = substr($row[$col], strlen($table_name) + 1); + } + break; + + case 'postgres': + case 'sqlite': + case 'sqlite3': + $row[$col] = substr($row[$col], strlen($table_name) + 1); + break; + } + + if (strtolower($row[$col]) == strtolower($index_name)) + { + $this->db->sql_freeresult($result); + return true; + } + } + $this->db->sql_freeresult($result); + + return false; + } + + /** + * Private method for performing sql statements (either execute them or return them) + * @access private + */ + function _sql_run_sql($statements) + { + if ($this->return_statements) + { + return $statements; + } + + // We could add error handling here... + foreach ($statements as $sql) + { + if ($sql === 'begin') + { + $this->db->sql_transaction('begin'); + } + else if ($sql === 'commit') + { + $this->db->sql_transaction('commit'); + } + else + { + $this->db->sql_query($sql); + } + } + + return true; + } + + /** + * Function to prepare some column information for better usage + * @access private + */ + function sql_prepare_column_data($table_name, $column_name, $column_data) + { + if (strlen($column_name) > 30) + { + trigger_error("Column name '$column_name' on table '$table_name' is too long. The maximum is 30 characters.", E_USER_ERROR); + } + + // Get type + list($column_type, $orig_column_type) = $this->get_column_type($column_data[0]); + + // Adjust default value if db-dependent specified + if (is_array($column_data[1])) + { + $column_data[1] = (isset($column_data[1][$this->sql_layer])) ? $column_data[1][$this->sql_layer] : $column_data[1]['default']; + } + + $sql = ''; + + $return_array = array(); + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + $sql .= " {$column_type} "; + $sql_default = " {$column_type} "; + + // For adding columns we need the default definition + if (!is_null($column_data[1])) + { + // For hexadecimal values do not use single quotes + if (strpos($column_data[1], '0x') === 0) + { + $return_array['default'] = 'DEFAULT (' . $column_data[1] . ') '; + $sql_default .= $return_array['default']; + } + else + { + $return_array['default'] = 'DEFAULT (' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ') '; + $sql_default .= $return_array['default']; + } + } + + if (isset($column_data[2]) && $column_data[2] == 'auto_increment') + { +// $sql .= 'IDENTITY (1, 1) '; + $sql_default .= 'IDENTITY (1, 1) '; + } + + $return_array['textimage'] = $column_type === '[text]'; + + if (!is_null($column_data[1]) || (isset($column_data[2]) && $column_data[2] == 'auto_increment')) + { + $sql .= 'NOT NULL'; + $sql_default .= 'NOT NULL'; + } + else + { + $sql .= 'NULL'; + $sql_default .= 'NULL'; + } + + $return_array['column_type_sql_default'] = $sql_default; + + break; + + case 'mysql_40': + case 'mysql_41': + $sql .= " {$column_type} "; + + // For hexadecimal values do not use single quotes + if (!is_null($column_data[1]) && substr($column_type, -4) !== 'text' && substr($column_type, -4) !== 'blob') + { + $sql .= (strpos($column_data[1], '0x') === 0) ? "DEFAULT {$column_data[1]} " : "DEFAULT '{$column_data[1]}' "; + } + + if (!is_null($column_data[1]) || (isset($column_data[2]) && $column_data[2] == 'auto_increment')) + { + $sql .= 'NOT NULL'; + } + else + { + $sql .= 'NULL'; + } + + if (isset($column_data[2])) + { + if ($column_data[2] == 'auto_increment') + { + $sql .= ' auto_increment'; + } + else if ($this->sql_layer === 'mysql_41' && $column_data[2] == 'true_sort') + { + $sql .= ' COLLATE utf8_unicode_ci'; + } + } + + if (isset($column_data['after'])) + { + $return_array['after'] = $column_data['after']; + } + + break; + + case 'oracle': + $sql .= " {$column_type} "; + $sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}' " : ''; + + // In Oracle empty strings ('') are treated as NULL. + // Therefore in oracle we allow NULL's for all DEFAULT '' entries + // Oracle does not like setting NOT NULL on a column that is already NOT NULL (this happens only on number fields) + if (!preg_match('/number/i', $column_type)) + { + $sql .= ($column_data[1] === '' || $column_data[1] === null) ? '' : 'NOT NULL'; + } + + $return_array['auto_increment'] = false; + if (isset($column_data[2]) && $column_data[2] == 'auto_increment') + { + $return_array['auto_increment'] = true; + } + + break; + + case 'postgres': + $return_array['column_type'] = $column_type; + + $sql .= " {$column_type} "; + + $return_array['auto_increment'] = false; + if (isset($column_data[2]) && $column_data[2] == 'auto_increment') + { + $default_val = "nextval('{$table_name}_seq')"; + $return_array['auto_increment'] = true; + } + else if (!is_null($column_data[1])) + { + $default_val = "'" . $column_data[1] . "'"; + $return_array['null'] = 'NOT NULL'; + $sql .= 'NOT NULL '; + } + else + { + // Integers need to have 0 instead of empty string as default + if (strpos($column_type, 'INT') === 0) + { + $default_val = '0'; + } + else + { + $default_val = "'" . $column_data[1] . "'"; + } + $return_array['null'] = 'NULL'; + $sql .= 'NULL '; + } + + $return_array['default'] = $default_val; + + $sql .= "DEFAULT {$default_val}"; + + // Unsigned? Then add a CHECK contraint + if (in_array($orig_column_type, $this->unsigned_types)) + { + $return_array['constraint'] = "CHECK ({$column_name} >= 0)"; + $sql .= " CHECK ({$column_name} >= 0)"; + } + + break; + + case 'sqlite': + case 'sqlite3': + $return_array['primary_key_set'] = false; + if (isset($column_data[2]) && $column_data[2] == 'auto_increment') + { + $sql .= ' INTEGER PRIMARY KEY'; + $return_array['primary_key_set'] = true; + + if ($this->sql_layer === 'sqlite3') + { + $sql .= ' AUTOINCREMENT'; + } + } + else + { + $sql .= ' ' . $column_type; + } + + if (!is_null($column_data[1])) + { + $sql .= ' NOT NULL '; + $sql .= "DEFAULT '{$column_data[1]}'"; + } + + break; + } + + $return_array['column_type_sql'] = $sql; + + return $return_array; + } + + /** + * Get the column's database type from the type map + * + * @param string $column_map_type + * @return array column type for this database + * and map type without length + */ + function get_column_type($column_map_type) + { + if (strpos($column_map_type, ':') !== false) + { + list($orig_column_type, $column_length) = explode(':', $column_map_type); + if (!is_array($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'])) + { + $column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'], $column_length); + } + else + { + if (isset($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'])) + { + switch ($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'][0]) + { + case 'div': + $column_length /= $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'][1]; + $column_length = ceil($column_length); + $column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'][0], $column_length); + break; + } + } + + if (isset($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'])) + { + switch ($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][0]) + { + case 'mult': + $column_length *= $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][1]; + if ($column_length > $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][2]) + { + $column_type = $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][3]; + } + else + { + $column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'][0], $column_length); + } + break; + } + } + } + $orig_column_type .= ':'; + } + else + { + $orig_column_type = $column_map_type; + $column_type = $this->dbms_type_map[$this->sql_layer][$column_map_type]; + } + + return array($column_type, $orig_column_type); + } + + /** + * Add new column + */ + function sql_column_add($table_name, $column_name, $column_data, $inline = false) + { + $column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data); + $statements = array(); + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + // Does not support AFTER, only through temporary table + $statements[] = 'ALTER TABLE [' . $table_name . '] ADD [' . $column_name . '] ' . $column_data['column_type_sql_default']; + break; + + case 'mysql_40': + case 'mysql_41': + $after = (!empty($column_data['after'])) ? ' AFTER ' . $column_data['after'] : ''; + $statements[] = 'ALTER TABLE `' . $table_name . '` ADD COLUMN `' . $column_name . '` ' . $column_data['column_type_sql'] . $after; + break; + + case 'oracle': + // Does not support AFTER, only through temporary table + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql']; + break; + + case 'postgres': + // Does not support AFTER, only through temporary table + if (version_compare($this->db->sql_server_info(true), '8.0', '>=')) + { + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type_sql']; + } + else + { + // old versions cannot add columns with default and null information + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type'] . ' ' . $column_data['constraint']; + + if (isset($column_data['null'])) + { + if ($column_data['null'] == 'NOT NULL') + { + $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET NOT NULL'; + } + } + + if (isset($column_data['default'])) + { + $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default']; + } + } + + break; + + case 'sqlite': + if ($inline && $this->return_statements) + { + return $column_name . ' ' . $column_data['column_type_sql']; + } + + $recreate_queries = $this->sqlite_get_recreate_table_queries($table_name); + if (empty($recreate_queries)) + { + break; + } + + $statements[] = 'begin'; + + $sql_create_table = array_shift($recreate_queries); + + // Create a backup table and populate it, destroy the existing one + $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $sql_create_table); + $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; + $statements[] = 'DROP TABLE ' . $table_name; + + preg_match('#\((.*)\)#s', $sql_create_table, $matches); + + $new_table_cols = trim($matches[1]); + $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); + $column_list = array(); + + foreach ($old_table_cols as $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if ($entities[0] == 'PRIMARY') + { + continue; + } + $column_list[] = $entities[0]; + } + + $columns = implode(',', $column_list); + + $new_table_cols = $column_name . ' ' . $column_data['column_type_sql'] . ',' . $new_table_cols; + + // create a new table and fill it up. destroy the temp one + $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');'; + $statements = array_merge($statements, $recreate_queries); + + $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; + $statements[] = 'DROP TABLE ' . $table_name . '_temp'; + + $statements[] = 'commit'; + break; + + case 'sqlite3': + if ($inline && $this->return_statements) + { + return $column_name . ' ' . $column_data['column_type_sql']; + } + + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql']; + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Drop column + */ + function sql_column_remove($table_name, $column_name, $inline = false) + { + $statements = array(); + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + // We need the data here + $old_return_statements = $this->return_statements; + $this->return_statements = true; + + $indexes = $this->get_existing_indexes($table_name, $column_name); + $indexes = array_merge($indexes, $this->get_existing_indexes($table_name, $column_name, true)); + + // Drop any indexes + $recreate_indexes = array(); + if (!empty($indexes)) + { + foreach ($indexes as $index_name => $index_data) + { + $result = $this->sql_index_drop($table_name, $index_name); + $statements = array_merge($statements, $result); + if (sizeof($index_data) > 1) + { + // Remove this column from the index and recreate it + $recreate_indexes[$index_name] = array_diff($index_data, array($column_name)); + } + } + } + + // Drop default value constraint + $result = $this->mssql_get_drop_default_constraints_queries($table_name, $column_name); + $statements = array_merge($statements, $result); + + // Remove the column + $statements[] = 'ALTER TABLE [' . $table_name . '] DROP COLUMN [' . $column_name . ']'; + + if (!empty($recreate_indexes)) + { + // Recreate indexes after we removed the column + foreach ($recreate_indexes as $index_name => $index_data) + { + $result = $this->sql_create_index($table_name, $index_name, $index_data); + $statements = array_merge($statements, $result); + } + } + + $this->return_statements = $old_return_statements; + break; + + case 'mysql_40': + case 'mysql_41': + $statements[] = 'ALTER TABLE `' . $table_name . '` DROP COLUMN `' . $column_name . '`'; + break; + + case 'oracle': + $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN ' . $column_name; + break; + + case 'postgres': + $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN "' . $column_name . '"'; + break; + + case 'sqlite': + case 'sqlite3': + + if ($inline && $this->return_statements) + { + return $column_name; + } + + $recreate_queries = $this->sqlite_get_recreate_table_queries($table_name, $column_name); + if (empty($recreate_queries)) + { + break; + } + + $statements[] = 'begin'; + + $sql_create_table = array_shift($recreate_queries); + + // Create a backup table and populate it, destroy the existing one + $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $sql_create_table); + $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; + $statements[] = 'DROP TABLE ' . $table_name; + + preg_match('#\((.*)\)#s', $sql_create_table, $matches); + + $new_table_cols = trim($matches[1]); + $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); + $column_list = array(); + + foreach ($old_table_cols as $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if ($entities[0] == 'PRIMARY' || $entities[0] === $column_name) + { + continue; + } + $column_list[] = $entities[0]; + } + + $columns = implode(',', $column_list); + + $new_table_cols = trim(preg_replace('/' . $column_name . '\b[^,]+(?:,|$)/m', '', $new_table_cols)); + if (substr($new_table_cols, -1) === ',') + { + // Remove the comma from the last entry again + $new_table_cols = substr($new_table_cols, 0, -1); + } + + // create a new table and fill it up. destroy the temp one + $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');'; + $statements = array_merge($statements, $recreate_queries); + + $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; + $statements[] = 'DROP TABLE ' . $table_name . '_temp'; + + $statements[] = 'commit'; + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Drop Index + */ + function sql_index_drop($table_name, $index_name) + { + $statements = array(); + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + $statements[] = 'DROP INDEX ' . $table_name . '.' . $index_name; + break; + + case 'mysql_40': + case 'mysql_41': + $statements[] = 'DROP INDEX ' . $index_name . ' ON ' . $table_name; + break; + + case 'oracle': + case 'postgres': + case 'sqlite': + case 'sqlite3': + $statements[] = 'DROP INDEX ' . $table_name . '_' . $index_name; + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Drop Table + */ + function sql_table_drop($table_name) + { + $statements = array(); + + if (!$this->sql_table_exists($table_name)) + { + return $this->_sql_run_sql($statements); + } + + // the most basic operation, get rid of the table + $statements[] = 'DROP TABLE ' . $table_name; + + switch ($this->sql_layer) + { + case 'oracle': + $sql = 'SELECT A.REFERENCED_NAME + FROM USER_DEPENDENCIES A, USER_TRIGGERS B + WHERE A.REFERENCED_TYPE = \'SEQUENCE\' + AND A.NAME = B.TRIGGER_NAME + AND B.TABLE_NAME = \'' . strtoupper($table_name) . "'"; + $result = $this->db->sql_query($sql); + + // any sequences ref'd to this table's triggers? + while ($row = $this->db->sql_fetchrow($result)) + { + $statements[] = "DROP SEQUENCE {$row['referenced_name']}"; + } + $this->db->sql_freeresult($result); + break; + + case 'postgres': + // PGSQL does not "tightly" bind sequences and tables, we must guess... + $sql = "SELECT relname + FROM pg_class + WHERE relkind = 'S' + AND relname = '{$table_name}_seq'"; + $result = $this->db->sql_query($sql); + + // We don't even care about storing the results. We already know the answer if we get rows back. + if ($this->db->sql_fetchrow($result)) + { + $statements[] = "DROP SEQUENCE {$table_name}_seq;\n"; + } + $this->db->sql_freeresult($result); + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Add primary key + */ + function sql_create_primary_key($table_name, $column, $inline = false) + { + $statements = array(); + + switch ($this->sql_layer) + { + case 'postgres': + case 'mysql_40': + case 'mysql_41': + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD PRIMARY KEY (' . implode(', ', $column) . ')'; + break; + + case 'mssql': + case 'mssqlnative': + $sql = "ALTER TABLE [{$table_name}] WITH NOCHECK ADD "; + $sql .= "CONSTRAINT [PK_{$table_name}] PRIMARY KEY CLUSTERED ("; + $sql .= '[' . implode("],\n\t\t[", $column) . ']'; + $sql .= ')'; + + $statements[] = $sql; + break; + + case 'oracle': + $statements[] = 'ALTER TABLE ' . $table_name . ' add CONSTRAINT pk_' . $table_name . ' PRIMARY KEY (' . implode(', ', $column) . ')'; + break; + + case 'sqlite': + case 'sqlite3': + + if ($inline && $this->return_statements) + { + return $column; + } + + $recreate_queries = $this->sqlite_get_recreate_table_queries($table_name); + if (empty($recreate_queries)) + { + break; + } + + $statements[] = 'begin'; + + $sql_create_table = array_shift($recreate_queries); + + // Create a backup table and populate it, destroy the existing one + $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $sql_create_table); + $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; + $statements[] = 'DROP TABLE ' . $table_name; + + preg_match('#\((.*)\)#s', $sql_create_table, $matches); + + $new_table_cols = trim($matches[1]); + $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); + $column_list = array(); + + foreach ($old_table_cols as $declaration) + { + $entities = preg_split('#\s+#', trim($declaration)); + if ($entities[0] == 'PRIMARY') + { + continue; + } + $column_list[] = $entities[0]; + } + + $columns = implode(',', $column_list); + + // create a new table and fill it up. destroy the temp one + $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ', PRIMARY KEY (' . implode(', ', $column) . '));'; + $statements = array_merge($statements, $recreate_queries); + + $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; + $statements[] = 'DROP TABLE ' . $table_name . '_temp'; + + $statements[] = 'commit'; + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Add unique index + */ + function sql_create_unique_index($table_name, $index_name, $column) + { + $statements = array(); + + $table_prefix = substr(CONFIG_TABLE, 0, -6); // strlen(config) + if (strlen($table_name . '_' . $index_name) - strlen($table_prefix) > 24) + { + $max_length = strlen($table_prefix) + 24; + trigger_error("Index name '{$table_name}_$index_name' on table '$table_name' is too long. The maximum is $max_length characters.", E_USER_ERROR); + } + + switch ($this->sql_layer) + { + case 'postgres': + case 'oracle': + case 'sqlite': + case 'sqlite3': + $statements[] = 'CREATE UNIQUE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')'; + break; + + case 'mysql_40': + case 'mysql_41': + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD UNIQUE INDEX ' . $index_name . '(' . implode(', ', $column) . ')'; + break; + + case 'mssql': + case 'mssqlnative': + $statements[] = 'CREATE UNIQUE INDEX [' . $index_name . '] ON [' . $table_name . ']([' . implode('], [', $column) . '])'; + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Add index + */ + function sql_create_index($table_name, $index_name, $column) + { + $statements = array(); + + $table_prefix = substr(CONFIG_TABLE, 0, -6); // strlen(config) + if (strlen($table_name . $index_name) - strlen($table_prefix) > 24) + { + $max_length = strlen($table_prefix) + 24; + trigger_error("Index name '{$table_name}_$index_name' on table '$table_name' is too long. The maximum is $max_length characters.", E_USER_ERROR); + } + + // remove index length unless MySQL4 + if ('mysql_40' != $this->sql_layer) + { + $column = preg_replace('#:.*$#', '', $column); + } + + switch ($this->sql_layer) + { + case 'postgres': + case 'oracle': + case 'sqlite': + case 'sqlite3': + $statements[] = 'CREATE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')'; + break; + + case 'mysql_40': + // add index size to definition as required by MySQL4 + foreach ($column as $i => $col) + { + if (false !== strpos($col, ':')) + { + list($col, $index_size) = explode(':', $col); + $column[$i] = "$col($index_size)"; + } + } + // no break + case 'mysql_41': + $statements[] = 'ALTER TABLE ' . $table_name . ' ADD INDEX ' . $index_name . ' (' . implode(', ', $column) . ')'; + break; + + case 'mssql': + case 'mssqlnative': + $statements[] = 'CREATE INDEX [' . $index_name . '] ON [' . $table_name . ']([' . implode('], [', $column) . '])'; + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * List all of the indices that belong to a table, + * does not count: + * * UNIQUE indices + * * PRIMARY keys + */ + function sql_list_index($table_name) + { + $index_array = array(); + + if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative') + { + $sql = "EXEC sp_statistics '$table_name'"; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if ($row['TYPE'] == 3) + { + $index_array[] = $row['INDEX_NAME']; + } + } + $this->db->sql_freeresult($result); + } + else + { + switch ($this->sql_layer) + { + case 'postgres': + $sql = "SELECT ic.relname as index_name + FROM pg_class bc, pg_class ic, pg_index i + WHERE (bc.oid = i.indrelid) + AND (ic.oid = i.indexrelid) + AND (bc.relname = '" . $table_name . "') + AND (i.indisunique != 't') + AND (i.indisprimary != 't')"; + $col = 'index_name'; + break; + + case 'mysql_40': + case 'mysql_41': + $sql = 'SHOW KEYS + FROM ' . $table_name; + $col = 'Key_name'; + break; + + case 'oracle': + $sql = "SELECT index_name + FROM user_indexes + WHERE table_name = '" . strtoupper($table_name) . "' + AND generated = 'N' + AND uniqueness = 'NONUNIQUE'"; + $col = 'index_name'; + break; + + case 'sqlite': + case 'sqlite3': + $sql = "PRAGMA index_info('" . $table_name . "');"; + $col = 'name'; + break; + } + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && !$row['Non_unique']) + { + continue; + } + + switch ($this->sql_layer) + { + case 'oracle': + case 'postgres': + case 'sqlite': + case 'sqlite3': + $row[$col] = substr($row[$col], strlen($table_name) + 1); + break; + } + + $index_array[] = $row[$col]; + } + $this->db->sql_freeresult($result); + } + + return array_map('strtolower', $index_array); + } + + /** + * Removes table_name from the index_name if it is at the beginning + * + * @param $table_name + * @param $index_name + * @return string + */ + protected function strip_table_name_from_index_name($table_name, $index_name) + { + return (strpos(strtoupper($index_name), strtoupper($table_name)) === 0) ? substr($index_name, strlen($table_name) + 1) : $index_name; + } + + /** + * Change column type (not name!) + */ + function sql_column_change($table_name, $column_name, $column_data, $inline = false) + { + $original_column_data = $column_data; + $column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data); + $statements = array(); + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + // We need the data here + $old_return_statements = $this->return_statements; + $this->return_statements = true; + + $indexes = $this->get_existing_indexes($table_name, $column_name); + $unique_indexes = $this->get_existing_indexes($table_name, $column_name, true); + + // Drop any indexes + if (!empty($indexes) || !empty($unique_indexes)) + { + $drop_indexes = array_merge(array_keys($indexes), array_keys($unique_indexes)); + foreach ($drop_indexes as $index_name) + { + $result = $this->sql_index_drop($table_name, $index_name); + $statements = array_merge($statements, $result); + } + } + + // Drop default value constraint + $result = $this->mssql_get_drop_default_constraints_queries($table_name, $column_name); + $statements = array_merge($statements, $result); + + // Change the column + $statements[] = 'ALTER TABLE [' . $table_name . '] ALTER COLUMN [' . $column_name . '] ' . $column_data['column_type_sql']; + + if (!empty($column_data['default'])) + { + // Add new default value constraint + $statements[] = 'ALTER TABLE [' . $table_name . '] ADD CONSTRAINT [DF_' . $table_name . '_' . $column_name . '_1] ' . $column_data['default'] . ' FOR [' . $column_name . ']'; + } + + if (!empty($indexes)) + { + // Recreate indexes after we changed the column + foreach ($indexes as $index_name => $index_data) + { + $result = $this->sql_create_index($table_name, $index_name, $index_data); + $statements = array_merge($statements, $result); + } + } + + if (!empty($unique_indexes)) + { + // Recreate unique indexes after we changed the column + foreach ($unique_indexes as $index_name => $index_data) + { + $result = $this->sql_create_unique_index($table_name, $index_name, $index_data); + $statements = array_merge($statements, $result); + } + } + + $this->return_statements = $old_return_statements; + break; + + case 'mysql_40': + case 'mysql_41': + $statements[] = 'ALTER TABLE `' . $table_name . '` CHANGE `' . $column_name . '` `' . $column_name . '` ' . $column_data['column_type_sql']; + break; + + case 'oracle': + // We need the data here + $old_return_statements = $this->return_statements; + $this->return_statements = true; + + // Get list of existing indexes + $indexes = $this->get_existing_indexes($table_name, $column_name); + $unique_indexes = $this->get_existing_indexes($table_name, $column_name, true); + + // Drop any indexes + if (!empty($indexes) || !empty($unique_indexes)) + { + $drop_indexes = array_merge(array_keys($indexes), array_keys($unique_indexes)); + foreach ($drop_indexes as $index_name) + { + $result = $this->sql_index_drop($table_name, $this->strip_table_name_from_index_name($table_name, $index_name)); + $statements = array_merge($statements, $result); + } + } + + $temp_column_name = 'temp_' . substr(md5($column_name), 0, 25); + // Add a temporary table with the new type + $result = $this->sql_column_add($table_name, $temp_column_name, $original_column_data); + $statements = array_merge($statements, $result); + + // Copy the data to the new column + $statements[] = 'UPDATE ' . $table_name . ' SET ' . $temp_column_name . ' = ' . $column_name; + + // Drop the original column + $result = $this->sql_column_remove($table_name, $column_name); + $statements = array_merge($statements, $result); + + // Recreate the original column with the new type + $result = $this->sql_column_add($table_name, $column_name, $original_column_data); + $statements = array_merge($statements, $result); + + if (!empty($indexes)) + { + // Recreate indexes after we changed the column + foreach ($indexes as $index_name => $index_data) + { + $result = $this->sql_create_index($table_name, $this->strip_table_name_from_index_name($table_name, $index_name), $index_data); + $statements = array_merge($statements, $result); + } + } + + if (!empty($unique_indexes)) + { + // Recreate unique indexes after we changed the column + foreach ($unique_indexes as $index_name => $index_data) + { + $result = $this->sql_create_unique_index($table_name, $this->strip_table_name_from_index_name($table_name, $index_name), $index_data); + $statements = array_merge($statements, $result); + } + } + + // Copy the data to the original column + $statements[] = 'UPDATE ' . $table_name . ' SET ' . $column_name . ' = ' . $temp_column_name; + + // Drop the temporary column again + $result = $this->sql_column_remove($table_name, $temp_column_name); + $statements = array_merge($statements, $result); + + $this->return_statements = $old_return_statements; + break; + + case 'postgres': + $sql = 'ALTER TABLE ' . $table_name . ' '; + + $sql_array = array(); + $sql_array[] = 'ALTER COLUMN ' . $column_name . ' TYPE ' . $column_data['column_type']; + + if (isset($column_data['null'])) + { + if ($column_data['null'] == 'NOT NULL') + { + $sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET NOT NULL'; + } + else if ($column_data['null'] == 'NULL') + { + $sql_array[] = 'ALTER COLUMN ' . $column_name . ' DROP NOT NULL'; + } + } + + if (isset($column_data['default'])) + { + $sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default']; + } + + // we don't want to double up on constraints if we change different number data types + if (isset($column_data['constraint'])) + { + $constraint_sql = "SELECT consrc as constraint_data + FROM pg_constraint, pg_class bc + WHERE conrelid = bc.oid + AND bc.relname = '{$table_name}' + AND NOT EXISTS ( + SELECT * + FROM pg_constraint as c, pg_inherits as i + WHERE i.inhrelid = pg_constraint.conrelid + AND c.conname = pg_constraint.conname + AND c.consrc = pg_constraint.consrc + AND c.conrelid = i.inhparent + )"; + + $constraint_exists = false; + + $result = $this->db->sql_query($constraint_sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if (trim($row['constraint_data']) == trim($column_data['constraint'])) + { + $constraint_exists = true; + break; + } + } + $this->db->sql_freeresult($result); + + if (!$constraint_exists) + { + $sql_array[] = 'ADD ' . $column_data['constraint']; + } + } + + $sql .= implode(', ', $sql_array); + + $statements[] = $sql; + break; + + case 'sqlite': + case 'sqlite3': + + if ($inline && $this->return_statements) + { + return $column_name . ' ' . $column_data['column_type_sql']; + } + + $recreate_queries = $this->sqlite_get_recreate_table_queries($table_name); + if (empty($recreate_queries)) + { + break; + } + + $statements[] = 'begin'; + + $sql_create_table = array_shift($recreate_queries); + + // Create a temp table and populate it, destroy the existing one + $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $sql_create_table); + $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; + $statements[] = 'DROP TABLE ' . $table_name; + + preg_match('#\((.*)\)#s', $sql_create_table, $matches); + + $new_table_cols = trim($matches[1]); + $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); + $column_list = array(); + + foreach ($old_table_cols as $key => $declaration) + { + $declaration = trim($declaration); + + // Check for the beginning of the constraint section and stop + if (preg_match('/[^\(]*\s*PRIMARY KEY\s+\(/', $declaration) || + preg_match('/[^\(]*\s*UNIQUE\s+\(/', $declaration) || + preg_match('/[^\(]*\s*FOREIGN KEY\s+\(/', $declaration) || + preg_match('/[^\(]*\s*CHECK\s+\(/', $declaration)) + { + break; + } + + $entities = preg_split('#\s+#', $declaration); + $column_list[] = $entities[0]; + if ($entities[0] == $column_name) + { + $old_table_cols[$key] = $column_name . ' ' . $column_data['column_type_sql']; + } + } + + $columns = implode(',', $column_list); + + // Create a new table and fill it up. destroy the temp one + $statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $old_table_cols) . ');'; + $statements = array_merge($statements, $recreate_queries); + + $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; + $statements[] = 'DROP TABLE ' . $table_name . '_temp'; + + $statements[] = 'commit'; + + break; + } + + return $this->_sql_run_sql($statements); + } + + /** + * Get queries to drop the default constraints of a column + * + * We need to drop the default constraints of a column, + * before being able to change their type or deleting them. + * + * @param string $table_name + * @param string $column_name + * @return array Array with SQL statements + */ + protected function mssql_get_drop_default_constraints_queries($table_name, $column_name) + { + $statements = array(); + if ($this->mssql_is_sql_server_2000()) + { + // http://msdn.microsoft.com/en-us/library/aa175912%28v=sql.80%29.aspx + // Deprecated in SQL Server 2005 + $sql = "SELECT so.name AS def_name + FROM sysobjects so + JOIN sysconstraints sc ON so.id = sc.constid + WHERE object_name(so.parent_obj) = '{$table_name}' + AND so.xtype = 'D' + AND sc.colid = (SELECT colid FROM syscolumns + WHERE id = object_id('{$table_name}') + AND name = '{$column_name}')"; + } + else + { + $sql = "SELECT dobj.name AS def_name + FROM sys.columns col + LEFT OUTER JOIN sys.objects dobj ON (dobj.object_id = col.default_object_id AND dobj.type = 'D') + WHERE col.object_id = object_id('{$table_name}') + AND col.name = '{$column_name}' + AND dobj.name IS NOT NULL"; + } + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $statements[] = 'ALTER TABLE [' . $table_name . '] DROP CONSTRAINT [' . $row['def_name'] . ']'; + } + $this->db->sql_freeresult($result); + + return $statements; + } + + /** + * Get a list with existing indexes for the column + * + * @param string $table_name + * @param string $column_name + * @param bool $unique Should we get unique indexes or normal ones + * @return array Array with Index name => columns + */ + public function get_existing_indexes($table_name, $column_name, $unique = false) + { + switch ($this->sql_layer) + { + case 'mysql_40': + case 'mysql_41': + case 'postgres': + case 'sqlite': + case 'sqlite3': + // Not supported + throw new \Exception('DBMS is not supported'); + break; + } + + $sql = ''; + $existing_indexes = array(); + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + if ($this->mssql_is_sql_server_2000()) + { + // http://msdn.microsoft.com/en-us/library/aa175912%28v=sql.80%29.aspx + // Deprecated in SQL Server 2005 + $sql = "SELECT DISTINCT ix.name AS phpbb_index_name + FROM sysindexes ix + INNER JOIN sysindexkeys ixc + ON ixc.id = ix.id + AND ixc.indid = ix.indid + INNER JOIN syscolumns cols + ON cols.colid = ixc.colid + AND cols.id = ix.id + WHERE ix.id = object_id('{$table_name}') + AND cols.name = '{$column_name}' + AND INDEXPROPERTY(ix.id, ix.name, 'IsUnique') = " . ($unique ? '1' : '0'); + } + else + { + $sql = "SELECT DISTINCT ix.name AS phpbb_index_name + FROM sys.indexes ix + INNER JOIN sys.index_columns ixc + ON ixc.object_id = ix.object_id + AND ixc.index_id = ix.index_id + INNER JOIN sys.columns cols + ON cols.column_id = ixc.column_id + AND cols.object_id = ix.object_id + WHERE ix.object_id = object_id('{$table_name}') + AND cols.name = '{$column_name}' + AND ix.is_unique = " . ($unique ? '1' : '0'); + } + break; + + case 'oracle': + $sql = "SELECT ix.index_name AS phpbb_index_name, ix.uniqueness AS is_unique + FROM all_ind_columns ixc, all_indexes ix + WHERE ix.index_name = ixc.index_name + AND ixc.table_name = '" . strtoupper($table_name) . "' + AND ixc.column_name = '" . strtoupper($column_name) . "'"; + break; + } + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + if (!isset($row['is_unique']) || ($unique && $row['is_unique'] == 'UNIQUE') || (!$unique && $row['is_unique'] == 'NONUNIQUE')) + { + $existing_indexes[$row['phpbb_index_name']] = array(); + } + } + $this->db->sql_freeresult($result); + + if (empty($existing_indexes)) + { + return array(); + } + + switch ($this->sql_layer) + { + case 'mssql': + case 'mssqlnative': + if ($this->mssql_is_sql_server_2000()) + { + $sql = "SELECT DISTINCT ix.name AS phpbb_index_name, cols.name AS phpbb_column_name + FROM sysindexes ix + INNER JOIN sysindexkeys ixc + ON ixc.id = ix.id + AND ixc.indid = ix.indid + INNER JOIN syscolumns cols + ON cols.colid = ixc.colid + AND cols.id = ix.id + WHERE ix.id = object_id('{$table_name}') + AND " . $this->db->sql_in_set('ix.name', array_keys($existing_indexes)); + } + else + { + $sql = "SELECT DISTINCT ix.name AS phpbb_index_name, cols.name AS phpbb_column_name + FROM sys.indexes ix + INNER JOIN sys.index_columns ixc + ON ixc.object_id = ix.object_id + AND ixc.index_id = ix.index_id + INNER JOIN sys.columns cols + ON cols.column_id = ixc.column_id + AND cols.object_id = ix.object_id + WHERE ix.object_id = object_id('{$table_name}') + AND " . $this->db->sql_in_set('ix.name', array_keys($existing_indexes)); + } + break; + + case 'oracle': + $sql = "SELECT index_name AS phpbb_index_name, column_name AS phpbb_column_name + FROM all_ind_columns + WHERE table_name = '" . strtoupper($table_name) . "' + AND " . $this->db->sql_in_set('index_name', array_keys($existing_indexes)); + break; + } + + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $existing_indexes[$row['phpbb_index_name']][] = $row['phpbb_column_name']; + } + $this->db->sql_freeresult($result); + + return $existing_indexes; + } + + /** + * Is the used MS SQL Server a SQL Server 2000? + * + * @return bool + */ + protected function mssql_is_sql_server_2000() + { + if ($this->is_sql_server_2000 === null) + { + $sql = "SELECT CAST(SERVERPROPERTY('productversion') AS VARCHAR(25)) AS mssql_version"; + $result = $this->db->sql_query($sql); + $properties = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + $this->is_sql_server_2000 = $properties['mssql_version'][0] == '8'; + } + + return $this->is_sql_server_2000; + } + + /** + * Returns the Queries which are required to recreate a table including indexes + * + * @param string $table_name + * @param string $remove_column When we drop a column, we remove the column + * from all indexes. If the index has no other + * column, we drop it completly. + * @return array + */ + protected function sqlite_get_recreate_table_queries($table_name, $remove_column = '') + { + $queries = array(); + + $sql = "SELECT sql + FROM sqlite_master + WHERE type = 'table' + AND name = '{$table_name}'"; + $result = $this->db->sql_query($sql); + $sql_create_table = $this->db->sql_fetchfield('sql'); + $this->db->sql_freeresult($result); + + if (!$sql_create_table) + { + return array(); + } + $queries[] = $sql_create_table; + + $sql = "SELECT sql + FROM sqlite_master + WHERE type = 'index' + AND tbl_name = '{$table_name}'"; + $result = $this->db->sql_query($sql); + while ($sql_create_index = $this->db->sql_fetchfield('sql')) + { + if ($remove_column) + { + $match = array(); + preg_match('#(?:[\w ]+)\((.*)\)#', $sql_create_index, $match); + if (!isset($match[1])) + { + continue; + } + + // Find and remove $remove_column from the index + $columns = explode(', ', $match[1]); + $found_column = array_search($remove_column, $columns); + if ($found_column !== false) + { + unset($columns[$found_column]); + + // If the column list is not empty add the index to the list + if (!empty($columns)) + { + $queries[] = str_replace($match[1], implode(', ', $columns), $sql_create_index); + } + } + else + { + $queries[] = $sql_create_index; + } + } + else + { + $queries[] = $sql_create_index; + } + } + $this->db->sql_freeresult($result); + + return $queries; + } +} diff --git a/phpBB/phpbb/di/container_builder.php b/phpBB/phpbb/di/container_builder.php new file mode 100644 index 0000000000..5f3aa685bf --- /dev/null +++ b/phpBB/phpbb/di/container_builder.php @@ -0,0 +1,418 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Dumper\PhpDumper; +use Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass; + +class container_builder +{ + /** @var string phpBB Root Path */ + protected $phpbb_root_path; + + /** @var string php file extension */ + protected $php_ext; + + /** + * The container under construction + * + * @var ContainerBuilder + */ + protected $container; + + /** + * @var \phpbb\db\driver\driver_interface + */ + protected $dbal_connection = null; + + /** + * @var array the installed extensions + */ + protected $installed_exts = null; + + /** + * Indicates whether the php config file should be injected into the container (default to true). + * + * @var bool + */ + protected $inject_config = true; + + /** + * Indicates whether extensions should be used (default to true). + * + * @var bool + */ + protected $use_extensions = true; + + /** + * Defines a custom path to find the configuration of the container (default to $this->phpbb_root_path . 'config') + * + * @var string + */ + protected $config_path = null; + + /** + * Indicates whether the phpBB compile pass should be used (default to true). + * + * @var bool + */ + protected $use_custom_pass = true; + + /** + * Indicates whether the kernel compile pass should be used (default to true). + * + * @var bool + */ + protected $use_kernel_pass = true; + + /** + * Indicates whether the container should be dumped to the filesystem (default to true). + * + * If DEBUG_CONTAINER is set this option is ignored and a new container is build. + * + * @var bool + */ + protected $dump_container = true; + + /** + * Indicates if the container should be compiled automatically (default to true). + * + * @var bool + */ + protected $compile_container = true; + + /** + * Custom parameters to inject into the container. + * + * Default to true: + * array( + * 'core.root_path', $this->phpbb_root_path, + * 'core.php_ext', $this->php_ext, + * ); + * + * @var array + */ + protected $custom_parameters = null; + + /** + * @var \phpbb\config_php_file + */ + protected $config_php_file; + + /** + * Constructor + * + * @param \phpbb\config_php_file $config_php_file + * @param string $phpbb_root_path Path to the phpbb includes directory. + * @param string $php_ext php file extension + */ + function __construct(\phpbb\config_php_file $config_php_file, $phpbb_root_path, $php_ext) + { + $this->config_php_file = $config_php_file; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * Build and return a new Container respecting the current configuration + * + * @return \phpbb_cache_container|ContainerBuilder + */ + public function get_container() + { + $container_filename = $this->get_container_filename(); + if (!defined('DEBUG_CONTAINER') && $this->dump_container && file_exists($container_filename)) + { + require($container_filename); + $this->container = new \phpbb_cache_container(); + } + else + { + if ($this->config_path === null) + { + $this->config_path = $this->phpbb_root_path . 'config'; + } + $container_extensions = array(new \phpbb\di\extension\core($this->config_path)); + + if ($this->use_extensions) + { + $installed_exts = $this->get_installed_extensions(); + $container_extensions[] = new \phpbb\di\extension\ext($installed_exts); + } + + if ($this->inject_config) + { + $container_extensions[] = new \phpbb\di\extension\config($this->config_php_file); + } + + $this->container = $this->create_container($container_extensions); + + if ($this->use_custom_pass) + { + // Symfony Kernel Listeners + $this->container->addCompilerPass(new \phpbb\di\pass\collection_pass()); + $this->container->addCompilerPass(new RegisterListenersPass('dispatcher', 'event.listener_listener', 'event.listener')); + + if ($this->use_kernel_pass) + { + $this->container->addCompilerPass(new RegisterListenersPass('dispatcher')); + } + } + + $this->inject_custom_parameters(); + + if ($this->compile_container) + { + $this->container->compile(); + } + + if ($this->dump_container && !defined('DEBUG_CONTAINER')) + { + $this->dump_container($container_filename); + } + } + + $this->container->set('config.php', $this->config_php_file); + $this->inject_dbal_driver(); + + if ($this->compile_container) + { + $this->inject_dbal(); + } + + return $this->container; + } + + /** + * Set if the extensions should be used. + * + * @param bool $use_extensions + */ + public function set_use_extensions($use_extensions) + { + $this->use_extensions = $use_extensions; + } + + /** + * Set if the phpBB compile pass have to be used. + * + * @param bool $use_custom_pass + */ + public function set_use_custom_pass($use_custom_pass) + { + $this->use_custom_pass = $use_custom_pass; + } + + /** + * Set if the kernel compile pass have to be used. + * + * @param bool $use_kernel_pass + */ + public function set_use_kernel_pass($use_kernel_pass) + { + $this->use_kernel_pass = $use_kernel_pass; + } + + /** + * Set if the php config file should be injecting into the container. + * + * @param bool $inject_config + */ + public function set_inject_config($inject_config) + { + $this->inject_config = $inject_config; + } + + /** + * Set if a dump container should be used. + * + * If DEBUG_CONTAINER is set this option is ignored and a new container is build. + * + * @var bool $dump_container + */ + public function set_dump_container($dump_container) + { + $this->dump_container = $dump_container; + } + + /** + * Set if the container should be compiled automatically (default to true). + * + * @var bool $dump_container + */ + public function set_compile_container($compile_container) + { + $this->compile_container = $compile_container; + } + + /** + * Set a custom path to find the configuration of the container + * + * @param string $config_path + */ + public function set_config_path($config_path) + { + $this->config_path = $config_path; + } + + /** + * Set custom parameters to inject into the container. + * + * @param array $custom_parameters + */ + public function set_custom_parameters($custom_parameters) + { + $this->custom_parameters = $custom_parameters; + } + + /** + * Dump the container to the disk. + * + * @param string $container_filename The name of the file. + */ + protected function dump_container($container_filename) + { + $dumper = new PhpDumper($this->container); + $cached_container_dump = $dumper->dump(array( + 'class' => 'phpbb_cache_container', + 'base_class' => 'Symfony\\Component\\DependencyInjection\\ContainerBuilder', + )); + + file_put_contents($container_filename, $cached_container_dump); + } + + /** + * Inject the connection into the container if one was opened. + */ + protected function inject_dbal() + { + if ($this->dbal_connection !== null) + { + $this->container->get('dbal.conn')->set_driver($this->dbal_connection); + } + } + + /** + * Inject the dbal connection driver into container + */ + protected function inject_dbal_driver() + { + $config_data = $this->config_php_file->get_all(); + if (!empty($config_data)) + { + $this->container->set('dbal.conn.driver', $this->get_dbal_connection()); + } + } + + /** + * Get DB connection. + * + * @return \phpbb\db\driver\driver_interface + */ + protected function get_dbal_connection() + { + if ($this->dbal_connection === null) + { + $dbal_driver_class = $this->config_php_file->convert_30_dbms_to_31($this->config_php_file->get('dbms')); + $this->dbal_connection = new $dbal_driver_class(); + $this->dbal_connection->sql_connect( + $this->config_php_file->get('dbhost'), + $this->config_php_file->get('dbuser'), + $this->config_php_file->get('dbpasswd'), + $this->config_php_file->get('dbname'), + $this->config_php_file->get('dbport'), + false, + defined('PHPBB_DB_NEW_LINK') && PHPBB_DB_NEW_LINK + ); + } + + return $this->dbal_connection; + } + + /** + * Get enabled extensions. + * + * @return array enabled extensions + */ + protected function get_installed_extensions() + { + $db = $this->get_dbal_connection(); + $extension_table = $this->config_php_file->get('table_prefix') . 'ext'; + + $sql = 'SELECT * + FROM ' . $extension_table . ' + WHERE ext_active = 1'; + + $result = $db->sql_query($sql); + $rows = $db->sql_fetchrowset($result); + $db->sql_freeresult($result); + + $exts = array(); + foreach ($rows as $row) + { + $exts[$row['ext_name']] = $this->phpbb_root_path . 'ext/' . $row['ext_name'] . '/'; + } + + return $exts; + } + + /** + * Create the ContainerBuilder object + * + * @param array $extensions Array of Container extension objects + * @return ContainerBuilder object + */ + protected function create_container(array $extensions) + { + $container = new ContainerBuilder(); + + foreach ($extensions as $extension) + { + $container->registerExtension($extension); + $container->loadFromExtension($extension->getAlias()); + } + + return $container; + } + + /** + * Inject the customs parameters into the container + */ + protected function inject_custom_parameters() + { + if ($this->custom_parameters === null) + { + $this->custom_parameters = array( + 'core.root_path' => $this->phpbb_root_path, + 'core.php_ext' => $this->php_ext, + ); + } + + foreach ($this->custom_parameters as $key => $value) + { + $this->container->setParameter($key, $value); + } + } + + /** + * Get the filename under which the dumped container will be stored. + * + * @return string Path for dumped container + */ + protected function get_container_filename() + { + return $this->phpbb_root_path . 'cache/container_' . md5($this->phpbb_root_path) . '.' . $this->php_ext; + } +} diff --git a/phpBB/phpbb/di/extension/config.php b/phpBB/phpbb/di/extension/config.php new file mode 100644 index 0000000000..8c9de48823 --- /dev/null +++ b/phpBB/phpbb/di/extension/config.php @@ -0,0 +1,83 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di\extension; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; + +/** +* Container config extension +*/ +class config extends Extension +{ + /** @var array */ + protected $config_php; + + public function __construct(\phpbb\config_php_file $config_php) + { + $this->config_php = $config_php; + } + + /** + * Loads a specific configuration. + * + * @param array $config An array of configuration values + * @param ContainerBuilder $container A ContainerBuilder instance + * + * @throws \InvalidArgumentException When provided tag is not defined in this extension + */ + public function load(array $config, ContainerBuilder $container) + { + $parameters = array( + 'core.adm_relative_path' => $this->config_php->get('phpbb_adm_relative_path') ? $this->config_php->get('phpbb_adm_relative_path') : 'adm/', + 'core.table_prefix' => $this->config_php->get('table_prefix'), + 'cache.driver.class' => $this->convert_30_acm_type($this->config_php->get('acm_type')), + 'dbal.new_link' => defined('PHPBB_DB_NEW_LINK') && PHPBB_DB_NEW_LINK, + ); + $parameter_bag = $container->getParameterBag(); + + foreach ($parameters as $parameter => $value) + { + $container->setParameter($parameter, $parameter_bag->escapeValue($value)); + } + } + + /** + * Returns the recommended alias to use in XML. + * + * This alias is also the mandatory prefix to use when using YAML. + * + * @return string The alias + */ + public function getAlias() + { + return 'config'; + } + + /** + * Convert 3.0 ACM type to 3.1 cache driver class name + * + * @param string $acm_type ACM type + * @return string cache driver class + */ + protected function convert_30_acm_type($acm_type) + { + if (preg_match('#^[a-z]+$#', $acm_type)) + { + return 'phpbb\\cache\\driver\\' . $acm_type; + } + + return $acm_type; + } +} diff --git a/phpBB/phpbb/di/extension/core.php b/phpBB/phpbb/di/extension/core.php new file mode 100644 index 0000000000..ca4fa5c082 --- /dev/null +++ b/phpBB/phpbb/di/extension/core.php @@ -0,0 +1,67 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di\extension; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; +use Symfony\Component\Config\FileLocator; + +/** +* Container core extension +*/ +class core extends Extension +{ + /** + * Config path + * @var string + */ + protected $config_path; + + /** + * Constructor + * + * @param string $config_path Config path + */ + public function __construct($config_path) + { + $this->config_path = $config_path; + } + + /** + * Loads a specific configuration. + * + * @param array $config An array of configuration values + * @param ContainerBuilder $container A ContainerBuilder instance + * + * @throws \InvalidArgumentException When provided tag is not defined in this extension + */ + public function load(array $config, ContainerBuilder $container) + { + $loader = new YamlFileLoader($container, new FileLocator(phpbb_realpath($this->config_path))); + $loader->load('services.yml'); + } + + /** + * Returns the recommended alias to use in XML. + * + * This alias is also the mandatory prefix to use when using YAML. + * + * @return string The alias + */ + public function getAlias() + { + return 'core'; + } +} diff --git a/phpBB/phpbb/di/extension/ext.php b/phpBB/phpbb/di/extension/ext.php new file mode 100644 index 0000000000..718c992d2e --- /dev/null +++ b/phpBB/phpbb/di/extension/ext.php @@ -0,0 +1,67 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di\extension; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; +use Symfony\Component\Config\FileLocator; + +/** +* Container ext extension +*/ +class ext extends Extension +{ + protected $paths = array(); + + public function __construct($enabled_extensions) + { + foreach ($enabled_extensions as $ext => $path) + { + $this->paths[] = $path; + } + } + + /** + * Loads a specific configuration. + * + * @param array $config An array of configuration values + * @param ContainerBuilder $container A ContainerBuilder instance + * + * @throws \InvalidArgumentException When provided tag is not defined in this extension + */ + public function load(array $config, ContainerBuilder $container) + { + foreach ($this->paths as $path) + { + if (file_exists($path . '/config/services.yml')) + { + $loader = new YamlFileLoader($container, new FileLocator(phpbb_realpath($path . '/config'))); + $loader->load('services.yml'); + } + } + } + + /** + * Returns the recommended alias to use in XML. + * + * This alias is also the mandatory prefix to use when using YAML. + * + * @return string The alias + */ + public function getAlias() + { + return 'ext'; + } +} diff --git a/phpBB/phpbb/di/pass/collection_pass.php b/phpBB/phpbb/di/pass/collection_pass.php new file mode 100644 index 0000000000..a5c054674e --- /dev/null +++ b/phpBB/phpbb/di/pass/collection_pass.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di\pass; + +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; + +/** +* Appends an add method call to the definition of each collection service for +* the services tagged with the appropriate name defined in the collection's +* service_collection tag. +*/ +class collection_pass implements CompilerPassInterface +{ + /** + * Modify the container before it is passed to the rest of the code + * + * @param ContainerBuilder $container ContainerBuilder object + * @return null + */ + public function process(ContainerBuilder $container) + { + foreach ($container->findTaggedServiceIds('service_collection') as $id => $data) + { + $definition = $container->getDefinition($id); + + foreach ($container->findTaggedServiceIds($data[0]['tag']) as $service_id => $service_data) + { + $definition->addMethodCall('add', array($service_id)); + } + } + } +} diff --git a/phpBB/phpbb/di/service_collection.php b/phpBB/phpbb/di/service_collection.php new file mode 100644 index 0000000000..82ca9bf679 --- /dev/null +++ b/phpBB/phpbb/di/service_collection.php @@ -0,0 +1,79 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* Collection of services to be configured at container compile time. +*/ +class service_collection extends \ArrayObject +{ + /** + * @var \Symfony\Component\DependencyInjection\ContainerInterface + */ + protected $container; + + /** + * Constructor + * + * @param ContainerInterface $container Container object + */ + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + /** + * {@inheritdoc} + */ + public function getIterator() + { + return new service_collection_iterator($this); + } + + // Because of a PHP issue we have to redefine offsetExists + // (even with a call to the parent): + // https://bugs.php.net/bug.php?id=66834 + // https://bugs.php.net/bug.php?id=67067 + // But it triggers a sniffer issue that we have to skip + // @codingStandardsIgnoreStart + /** + * {@inheritdoc} + */ + public function offsetExists($index) + { + return parent::offsetExists($index); + } + // @codingStandardsIgnoreEnd + + /** + * {@inheritdoc} + */ + public function offsetGet($index) + { + return $this->container->get($index); + } + + /** + * Add a service to the collection + * + * @param string $name The service name + * @return null + */ + public function add($name) + { + $this->offsetSet($name, null); + } +} diff --git a/phpBB/phpbb/di/service_collection_iterator.php b/phpBB/phpbb/di/service_collection_iterator.php new file mode 100644 index 0000000000..0d031ab52d --- /dev/null +++ b/phpBB/phpbb/di/service_collection_iterator.php @@ -0,0 +1,46 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\di; + +/** +* Iterator which loads the services when they are requested +*/ +class service_collection_iterator extends \ArrayIterator +{ + /** + * @var \phpbb\di\service_collection + */ + protected $collection; + + /** + * Construct an ArrayIterator for service_collection + * + * @param \phpbb\di\service_collection $collection The collection to iterate over + * @param int $flags Flags to control the behaviour of the ArrayObject object. + * @see ArrayObject::setFlags() + */ + public function __construct(service_collection $collection, $flags = 0) + { + parent::__construct($collection, $flags); + $this->collection = $collection; + } + + /** + * {@inheritdoc} + */ + public function current() + { + return $this->collection->offsetGet($this->key()); + } +} diff --git a/phpBB/phpbb/error_collector.php b/phpBB/phpbb/error_collector.php new file mode 100644 index 0000000000..bf8efd1065 --- /dev/null +++ b/phpBB/phpbb/error_collector.php @@ -0,0 +1,73 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +class error_collector +{ + var $errors; + var $error_types; + + /** + * Constructor. + * + * The variable $error_types may be set to a mask of PHP error types that + * the collector should keep, e.g. `E_ALL`. If unset, the current value of + * the error_reporting() function will be used to determine which errors + * the collector will keep. + * + * @see PHPBB3-13306 + * @param int|null $error_types + */ + function __construct($error_types = null) + { + $this->errors = array(); + $this->error_types = $error_types; + } + + function install() + { + set_error_handler(array(&$this, 'error_handler'), ($this->error_types !== null) ? $this->error_types : error_reporting()); + } + + function uninstall() + { + restore_error_handler(); + } + + function error_handler($errno, $msg_text, $errfile, $errline) + { + $this->errors[] = array($errno, $msg_text, $errfile, $errline); + } + + function format_errors() + { + $text = ''; + foreach ($this->errors as $error) + { + if (!empty($text)) + { + $text .= "<br />\n"; + } + + list($errno, $msg_text, $errfile, $errline) = $error; + + // Prevent leakage of local path to phpBB install + $errfile = phpbb_filter_root_path($errfile); + + $text .= "Errno $errno: $msg_text at $errfile line $errline"; + } + + return $text; + } +} diff --git a/phpBB/phpbb/event/data.php b/phpBB/phpbb/event/data.php new file mode 100644 index 0000000000..c7365aee35 --- /dev/null +++ b/phpBB/phpbb/event/data.php @@ -0,0 +1,66 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +use Symfony\Component\EventDispatcher\Event; + +class data extends Event implements \ArrayAccess +{ + private $data; + + public function __construct(array $data = array()) + { + $this->set_data($data); + } + + public function set_data(array $data = array()) + { + $this->data = $data; + } + + public function get_data() + { + return $this->data; + } + + /** + * Returns data filtered to only include specified keys. + * + * This effectively discards any keys added to data by hooks. + */ + public function get_data_filtered($keys) + { + return array_intersect_key($this->data, array_flip($keys)); + } + + public function offsetExists($offset) + { + return isset($this->data[$offset]); + } + + public function offsetGet($offset) + { + return isset($this->data[$offset]) ? $this->data[$offset] : null; + } + + public function offsetSet($offset, $value) + { + $this->data[$offset] = $value; + } + + public function offsetUnset($offset) + { + unset($this->data[$offset]); + } +} diff --git a/phpBB/phpbb/event/dispatcher.php b/phpBB/phpbb/event/dispatcher.php new file mode 100644 index 0000000000..1c4abeb108 --- /dev/null +++ b/phpBB/phpbb/event/dispatcher.php @@ -0,0 +1,78 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; +use Symfony\Component\EventDispatcher\Event; + +/** +* Extension of the Symfony2 EventDispatcher +* +* It provides an additional `trigger_event` method, which +* gives some syntactic sugar for dispatching events. Instead +* of creating the event object, the method will do that for +* you. +* +* Example: +* +* $vars = array('page_title'); +* extract($phpbb_dispatcher->trigger_event('core.index', compact($vars))); +* +*/ +class dispatcher extends ContainerAwareEventDispatcher implements dispatcher_interface +{ + /** + * @var bool + */ + protected $disabled = false; + + /** + * {@inheritdoc} + */ + public function trigger_event($eventName, $data = array()) + { + $event = new \phpbb\event\data($data); + $this->dispatch($eventName, $event); + return $event->get_data_filtered(array_keys($data)); + } + + /** + * {@inheritdoc} + */ + public function dispatch($eventName, Event $event = null) + { + if ($this->disabled) + { + return $event; + } + + return parent::dispatch($eventName, $event); + } + + /** + * {@inheritdoc} + */ + public function disable() + { + $this->disabled = true; + } + + /** + * {@inheritdoc} + */ + public function enable() + { + $this->disabled = false; + } +} diff --git a/phpBB/phpbb/event/dispatcher_interface.php b/phpBB/phpbb/event/dispatcher_interface.php new file mode 100644 index 0000000000..c66aa98260 --- /dev/null +++ b/phpBB/phpbb/event/dispatcher_interface.php @@ -0,0 +1,50 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +/** +* Extension of the Symfony2 EventDispatcher +* +* It provides an additional `trigger_event` method, which +* gives some syntactic sugar for dispatching events. Instead +* of creating the event object, the method will do that for +* you. +* +* Example: +* +* $vars = array('page_title'); +* extract($phpbb_dispatcher->trigger_event('core.index', compact($vars))); +* +*/ +interface dispatcher_interface extends \Symfony\Component\EventDispatcher\EventDispatcherInterface +{ + /** + * Construct and dispatch an event + * + * @param string $eventName The event name + * @param array $data An array containing the variables sending with the event + * @return mixed + */ + public function trigger_event($eventName, $data = array()); + + /** + * Disable the event dispatcher. + */ + public function disable(); + + /** + * Enable the event dispatcher. + */ + public function enable(); +} diff --git a/phpBB/phpbb/event/kernel_exception_subscriber.php b/phpBB/phpbb/event/kernel_exception_subscriber.php new file mode 100644 index 0000000000..1ee771cfe7 --- /dev/null +++ b/phpBB/phpbb/event/kernel_exception_subscriber.php @@ -0,0 +1,123 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; +use Symfony\Component\HttpFoundation\Response; + +class kernel_exception_subscriber implements EventSubscriberInterface +{ + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** @var \phpbb\request\type_cast_helper */ + protected $type_caster; + + /** + * Construct method + * + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\template\template $template, \phpbb\user $user) + { + $this->template = $template; + $this->user = $user; + $this->type_caster = new \phpbb\request\type_cast_helper(); + } + + /** + * This listener is run when the KernelEvents::EXCEPTION event is triggered + * + * @param GetResponseForExceptionEvent $event + * @return null + */ + public function on_kernel_exception(GetResponseForExceptionEvent $event) + { + $exception = $event->getException(); + + $message = $exception->getMessage(); + $this->type_caster->set_var($message, $message, 'string', true, false); + + if ($exception instanceof \phpbb\exception\exception_interface) + { + $message = call_user_func_array(array($this->user, 'lang'), array_merge(array($message), $exception->get_parameters())); + } + + // Show <strong> text in bold + $message = preg_replace('#<(/?strong)>#i', '<$1>', $message); + + if (!$event->getRequest()->isXmlHttpRequest()) + { + page_header($this->user->lang('INFORMATION')); + + $this->template->assign_vars(array( + 'MESSAGE_TITLE' => $this->user->lang('INFORMATION'), + 'MESSAGE_TEXT' => $message, + )); + + $this->template->set_filenames(array( + 'body' => 'message_body.html', + )); + + page_footer(true, false, false); + + $response = new Response($this->template->assign_display('body'), 500); + } + else + { + $data = array(); + + if (!empty($message)) + { + $data['message'] = $message; + } + + if (defined('DEBUG')) + { + $data['trace'] = $exception->getTrace(); + } + + $response = new JsonResponse($data, 500); + } + + if ($exception instanceof HttpExceptionInterface) + { + $response->setStatusCode($exception->getStatusCode()); + $response->headers->add($exception->getHeaders()); + } + + $event->setResponse($response); + } + + public static function getSubscribedEvents() + { + return array( + KernelEvents::EXCEPTION => 'on_kernel_exception', + ); + } +} diff --git a/phpBB/phpbb/event/kernel_request_subscriber.php b/phpBB/phpbb/event/kernel_request_subscriber.php new file mode 100644 index 0000000000..ee9f29a59d --- /dev/null +++ b/phpBB/phpbb/event/kernel_request_subscriber.php @@ -0,0 +1,82 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\EventListener\RouterListener; +use Symfony\Component\Routing\RequestContext; + +class kernel_request_subscriber implements EventSubscriberInterface +{ + /** + * Extension manager object + * @var \phpbb\extension\manager + */ + protected $manager; + + /** + * PHP file extension + * @var string + */ + protected $php_ext; + + /** + * Root path + * @var string + */ + protected $root_path; + + /** + * Construct method + * + * @param \phpbb\extension\manager $manager Extension manager object + * @param string $root_path Root path + * @param string $php_ext PHP file extension + */ + public function __construct(\phpbb\extension\manager $manager, $root_path, $php_ext) + { + $this->root_path = $root_path; + $this->php_ext = $php_ext; + $this->manager = $manager; + } + + /** + * This listener is run when the KernelEvents::REQUEST event is triggered + * + * This is responsible for setting up the routing information + * + * @param GetResponseEvent $event + * @throws \BadMethodCallException + * @return null + */ + public function on_kernel_request(GetResponseEvent $event) + { + $request = $event->getRequest(); + $context = new RequestContext(); + $context->fromRequest($request); + + $matcher = phpbb_get_url_matcher($this->manager, $context, $this->root_path, $this->php_ext); + $router_listener = new RouterListener($matcher, $context); + $router_listener->onKernelRequest($event); + } + + public static function getSubscribedEvents() + { + return array( + KernelEvents::REQUEST => 'on_kernel_request', + ); + } +} diff --git a/phpBB/phpbb/event/kernel_terminate_subscriber.php b/phpBB/phpbb/event/kernel_terminate_subscriber.php new file mode 100644 index 0000000000..3a709f73fd --- /dev/null +++ b/phpBB/phpbb/event/kernel_terminate_subscriber.php @@ -0,0 +1,41 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\HttpKernel\Event\PostResponseEvent; + +class kernel_terminate_subscriber implements EventSubscriberInterface +{ + /** + * This listener is run when the KernelEvents::TERMINATE event is triggered + * This comes after a Response has been sent to the server; this is + * primarily cleanup stuff. + * + * @param PostResponseEvent $event + * @return null + */ + public function on_kernel_terminate(PostResponseEvent $event) + { + exit_handler(); + } + + public static function getSubscribedEvents() + { + return array( + KernelEvents::TERMINATE => array('on_kernel_terminate', ~PHP_INT_MAX), + ); + } +} diff --git a/phpBB/phpbb/event/md_exporter.php b/phpBB/phpbb/event/md_exporter.php new file mode 100644 index 0000000000..02c2a1b9d6 --- /dev/null +++ b/phpBB/phpbb/event/md_exporter.php @@ -0,0 +1,565 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +/** +* Crawls through a markdown file and grabs all events +*/ +class md_exporter +{ + /** @var string Path where we look for files*/ + protected $path; + + /** @var string phpBB Root Path */ + protected $root_path; + + /** @var string The minimum version for the events to return */ + protected $min_version; + + /** @var string The maximum version for the events to return */ + protected $max_version; + + /** @var string */ + protected $filter; + + /** @var string */ + protected $current_event; + + /** @var array */ + protected $events; + + /** + * @param string $phpbb_root_path + * @param mixed $extension String 'vendor/ext' to filter, null for phpBB core + * @param string $min_version + * @param string $max_version + */ + public function __construct($phpbb_root_path, $extension = null, $min_version = null, $max_version = null) + { + $this->root_path = $phpbb_root_path; + $this->path = $this->root_path; + if ($extension) + { + $this->path .= 'ext/' . $extension . '/'; + } + + $this->events = array(); + $this->events_by_file = array(); + $this->filter = $this->current_event = ''; + $this->min_version = $min_version; + $this->max_version = $max_version; + } + + /** + * Get the list of all events + * + * @return array Array with events: name => details + */ + public function get_events() + { + return $this->events; + } + + /** + * @param string $md_file Relative from phpBB root + * @return int Number of events found + * @throws \LogicException + */ + public function crawl_phpbb_directory_adm($md_file) + { + $this->crawl_eventsmd($md_file, 'adm'); + + $file_list = $this->get_recursive_file_list($this->path . 'adm/style/'); + foreach ($file_list as $file) + { + $file_name = 'adm/style/' . $file; + $this->validate_events_from_file($file_name, $this->crawl_file_for_events($file_name)); + } + + return sizeof($this->events); + } + + /** + * @param string $md_file Relative from phpBB root + * @return int Number of events found + * @throws \LogicException + */ + public function crawl_phpbb_directory_styles($md_file) + { + $this->crawl_eventsmd($md_file, 'styles'); + + $styles = array('prosilver', 'subsilver2'); + foreach ($styles as $style) + { + $file_list = $this->get_recursive_file_list( + $this->path . 'styles/' . $style . '/template/' + ); + + foreach ($file_list as $file) + { + $file_name = 'styles/' . $style . '/template/' . $file; + $this->validate_events_from_file($file_name, $this->crawl_file_for_events($file_name)); + } + } + + return sizeof($this->events); + } + + /** + * @param string $md_file Relative from phpBB root + * @param string $filter Should be 'styles' or 'adm' + * @return int Number of events found + * @throws \LogicException + */ + public function crawl_eventsmd($md_file, $filter) + { + if (!file_exists($this->path . $md_file)) + { + throw new \LogicException("The event docs file '{$md_file}' could not be found"); + } + + $file_content = file_get_contents($this->path . $md_file); + $this->filter = $filter; + + $events = explode("\n\n", $file_content); + foreach ($events as $event) + { + // Last row of the file + if (strpos($event, "\n===\n") === false) + { + continue; + } + + list($event_name, $details) = explode("\n===\n", $event, 2); + $this->validate_event_name($event_name); + $this->current_event = $event_name; + + if (isset($this->events[$this->current_event])) + { + throw new \LogicException("The event '{$this->current_event}' is defined multiple times"); + } + + if (($this->filter == 'adm' && strpos($this->current_event, 'acp_') !== 0) + || ($this->filter == 'styles' && strpos($this->current_event, 'acp_') === 0)) + { + continue; + } + + list($file_details, $details) = explode("\n* Since: ", $details, 2); + + $changed_versions = array(); + if (strpos($details, "\n* Changed: ") !== false) + { + list($since, $details) = explode("\n* Changed: ", $details, 2); + while (strpos($details, "\n* Changed: ") !== false) + { + list($changed, $details) = explode("\n* Changed: ", $details, 2); + $changed_versions[] = $changed; + } + list($changed, $description) = explode("\n* Purpose: ", $details, 2); + $changed_versions[] = $changed; + } + else + { + list($since, $description) = explode("\n* Purpose: ", $details, 2); + $changed_versions = array(); + } + + $files = $this->validate_file_list($file_details); + $since = $this->validate_since($since); + $changes = array(); + foreach ($changed_versions as $changed) + { + list($changed_version, $changed_description) = $this->validate_changed($changed); + + if (isset($changes[$changed_version])) + { + throw new \LogicException("Duplicate change information found for event '{$this->current_event}'"); + } + + $changes[$changed_version] = $changed_description; + } + $description = trim($description, "\n") . "\n"; + + if (!$this->version_is_filtered($since)) + { + $is_filtered = false; + foreach ($changes as $version => $null) + { + if ($this->version_is_filtered($version)) + { + $is_filtered = true; + break; + } + } + + if (!$is_filtered) + { + continue; + } + } + + $this->events[$event_name] = array( + 'event' => $this->current_event, + 'files' => $files, + 'since' => $since, + 'changed' => $changes, + 'description' => $description, + ); + } + + return sizeof($this->events); + } + + /** + * The version to check + * + * @param string $version + * @return bool + */ + protected function version_is_filtered($version) + { + return (!$this->min_version || phpbb_version_compare($this->min_version, $version, '<=')) + && (!$this->max_version || phpbb_version_compare($this->max_version, $version, '>=')); + } + + /** + * Format the php events as a wiki table + * + * @param string $action + * @return string Number of events found + */ + public function export_events_for_wiki($action = '') + { + if ($this->filter === 'adm') + { + if ($action === 'diff') + { + $wiki_page = '=== ACP Template Events ===' . "\n"; + } + else + { + $wiki_page = '= ACP Template Events =' . "\n"; + } + $wiki_page .= '{| class="zebra sortable" cellspacing="0" cellpadding="5"' . "\n"; + $wiki_page .= '! Identifier !! Placement !! Added in Release !! Explanation' . "\n"; + } + else + { + if ($action === 'diff') + { + $wiki_page = '=== Template Events ===' . "\n"; + } + else + { + $wiki_page = '= Template Events =' . "\n"; + } + $wiki_page .= '{| class="zebra sortable" cellspacing="0" cellpadding="5"' . "\n"; + $wiki_page .= '! Identifier !! Prosilver Placement (If applicable) !! Subsilver Placement (If applicable) !! Added in Release !! Explanation' . "\n"; + } + + foreach ($this->events as $event_name => $event) + { + $wiki_page .= "|- id=\"{$event_name}\"\n"; + $wiki_page .= "| [[#{$event_name}|{$event_name}]] || "; + + if ($this->filter === 'adm') + { + $wiki_page .= implode(', ', $event['files']['adm']); + } + else + { + $wiki_page .= implode(', ', $event['files']['prosilver']) . ' || ' . implode(', ', $event['files']['subsilver2']); + } + + $wiki_page .= " || {$event['since']} || " . str_replace("\n", ' ', $event['description']) . "\n"; + } + $wiki_page .= '|}' . "\n"; + + return $wiki_page; + } + + /** + * Validates a template event name + * + * @param $event_name + * @return null + * @throws \LogicException + */ + public function validate_event_name($event_name) + { + if (!preg_match('#^([a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)+)$#', $event_name)) + { + throw new \LogicException("Invalid event name '{$event_name}'"); + } + } + + /** + * Validate "Since" Information + * + * @param string $since + * @return string + * @throws \LogicException + */ + public function validate_since($since) + { + if (!$this->validate_version($since)) + { + throw new \LogicException("Invalid since information found for event '{$this->current_event}'"); + } + + return $since; + } + + /** + * Validate "Changed" Information + * + * @param string $changed + * @return string + * @throws \LogicException + */ + public function validate_changed($changed) + { + if (strpos($changed, ' ') !== false) + { + list($version, $description) = explode(' ', $changed, 2); + } + else + { + $version = $changed; + $description = ''; + } + + if (!$this->validate_version($version)) + { + throw new \LogicException("Invalid changed information found for event '{$this->current_event}'"); + } + + return array($version, $description); + } + + /** + * Validate "version" Information + * + * @param string $version + * @return bool True if valid, false otherwise + */ + public function validate_version($version) + { + return preg_match('#^\d+\.\d+\.\d+(?:-(?:a|b|RC|pl)\d+)?$#', $version); + } + + /** + * Validate the files list + * + * @param string $file_details + * @return array + * @throws \LogicException + */ + public function validate_file_list($file_details) + { + $files_list = array( + 'prosilver' => array(), + 'subsilver2' => array(), + 'adm' => array(), + ); + + // Multi file list + if (strpos($file_details, "* Locations:\n + ") === 0) + { + $file_details = substr($file_details, strlen("* Locations:\n + ")); + $files = explode("\n + ", $file_details); + foreach ($files as $file) + { + if (!file_exists($this->path . $file) || substr($file, -5) !== '.html') + { + throw new \LogicException("Invalid file '{$file}' not found for event '{$this->current_event}'", 1); + } + + if (($this->filter !== 'adm') && strpos($file, 'styles/prosilver/template/') === 0) + { + $files_list['prosilver'][] = substr($file, strlen('styles/prosilver/template/')); + } + else if (($this->filter !== 'adm') && strpos($file, 'styles/subsilver2/template/') === 0) + { + $files_list['subsilver2'][] = substr($file, strlen('styles/subsilver2/template/')); + } + else if (($this->filter === 'adm') && strpos($file, 'adm/style/') === 0) + { + $files_list['adm'][] = substr($file, strlen('adm/style/')); + } + else + { + throw new \LogicException("Invalid file '{$file}' not found for event '{$this->current_event}'", 2); + } + + $this->events_by_file[$file][] = $this->current_event; + } + } + else if ($this->filter == 'adm') + { + $file = substr($file_details, strlen('* Location: ')); + if (!file_exists($this->path . $file) || substr($file, -5) !== '.html') + { + throw new \LogicException("Invalid file '{$file}' not found for event '{$this->current_event}'", 1); + } + + $files_list['adm'][] = substr($file, strlen('adm/style/')); + + $this->events_by_file[$file][] = $this->current_event; + } + else + { + throw new \LogicException("Invalid file list found for event '{$this->current_event}'", 2); + } + + return $files_list; + } + + /** + * Get all template events in a template file + * + * @param string $file + * @return array + * @throws \LogicException + */ + public function crawl_file_for_events($file) + { + if (!file_exists($this->path . $file)) + { + throw new \LogicException("File '{$file}' does not exist", 1); + } + + $event_list = array(); + $file_content = file_get_contents($this->path . $file); + + $events = explode('<!-- EVENT ', $file_content); + // Remove the code before the first event + array_shift($events); + foreach ($events as $event) + { + $event = explode(' -->', $event, 2); + $event_list[] = array_shift($event); + } + + return $event_list; + } + + /** + * Validates whether all events from $file are in the md file and vice-versa + * + * @param string $file + * @param array $events + * @return true + * @throws \LogicException + */ + public function validate_events_from_file($file, array $events) + { + if (empty($this->events_by_file[$file]) && empty($events)) + { + return true; + } + else if (empty($this->events_by_file[$file])) + { + $event_list = implode("', '", $events); + throw new \LogicException("File '{$file}' should not contain events, but contains: " + . "'{$event_list}'", 1); + } + else if (empty($events)) + { + $event_list = implode("', '", $this->events_by_file[$file]); + throw new \LogicException("File '{$file}' contains no events, but should contain: " + . "'{$event_list}'", 1); + } + + $missing_events_from_file = array(); + foreach ($this->events_by_file[$file] as $event) + { + if (!in_array($event, $events)) + { + $missing_events_from_file[] = $event; + } + } + + if (!empty($missing_events_from_file)) + { + $event_list = implode("', '", $missing_events_from_file); + throw new \LogicException("File '{$file}' does not contain events: '{$event_list}'", 2); + } + + $missing_events_from_md = array(); + foreach ($events as $event) + { + if (!in_array($event, $this->events_by_file[$file])) + { + $missing_events_from_md[] = $event; + } + } + + if (!empty($missing_events_from_md)) + { + $event_list = implode("', '", $missing_events_from_md); + throw new \LogicException("File '{$file}' contains additional events: '{$event_list}'", 3); + } + + return true; + } + + /** + * Returns a list of files in $dir + * + * Works recursive with any depth + * + * @param string $dir Directory to go through + * @return array List of files (including directories) + */ + public function get_recursive_file_list($dir) + { + try + { + $iterator = new \RecursiveIteratorIterator( + new \phpbb\recursive_dot_prefix_filter_iterator( + new \RecursiveDirectoryIterator( + $dir, + \FilesystemIterator::SKIP_DOTS + ) + ), + \RecursiveIteratorIterator::SELF_FIRST + ); + } + catch (\Exception $e) + { + return array(); + } + + $files = array(); + foreach ($iterator as $file_info) + { + /** @var \RecursiveDirectoryIterator $file_info */ + if ($file_info->isDir()) + { + continue; + } + + $relative_path = $iterator->getInnerIterator()->getSubPathname(); + + if (substr($relative_path, -5) == '.html') + { + $files[] = str_replace(DIRECTORY_SEPARATOR, '/', $relative_path); + } + } + + return $files; + } +} diff --git a/phpBB/phpbb/event/php_exporter.php b/phpBB/phpbb/event/php_exporter.php new file mode 100644 index 0000000000..ae3553c558 --- /dev/null +++ b/phpBB/phpbb/event/php_exporter.php @@ -0,0 +1,718 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +/** +* Class php_exporter +* Crawls through a list of files and grabs all php-events +*/ +class php_exporter +{ + /** @var string Path where we look for files*/ + protected $path; + + /** @var string phpBB Root Path */ + protected $root_path; + + /** @var string The minimum version for the events to return */ + protected $min_version; + + /** @var string The maximum version for the events to return */ + protected $max_version; + + /** @var string */ + protected $current_file; + + /** @var string */ + protected $current_event; + + /** @var int */ + protected $current_event_line; + + /** @var array */ + protected $events; + + /** @var array */ + protected $file_lines; + + /** + * @param string $phpbb_root_path + * @param mixed $extension String 'vendor/ext' to filter, null for phpBB core + * @param string $min_version + * @param string $max_version + */ + public function __construct($phpbb_root_path, $extension = null, $min_version = null, $max_version = null) + { + $this->root_path = $phpbb_root_path; + $this->path = $phpbb_root_path; + $this->events = $this->file_lines = array(); + $this->current_file = $this->current_event = ''; + $this->current_event_line = 0; + $this->min_version = $min_version; + $this->max_version = $max_version; + + $this->path = $this->root_path; + if ($extension) + { + $this->path .= 'ext/' . $extension . '/'; + } + } + + /** + * Get the list of all events + * + * @return array Array with events: name => details + */ + public function get_events() + { + return $this->events; + } + + /** + * Set current event data + * + * @param string $name Name of the current event (used for error messages) + * @param int $line Line where the current event is placed in + * @return null + */ + public function set_current_event($name, $line) + { + $this->current_event = $name; + $this->current_event_line = $line; + } + + /** + * Set the content of this file + * + * @param array $content Array with the lines of the file + * @return null + */ + public function set_content($content) + { + $this->file_lines = $content; + } + + /** + * Crawl the phpBB/ directory for php events + * @return int The number of events found + */ + public function crawl_phpbb_directory_php() + { + $files = $this->get_recursive_file_list(); + $this->events = array(); + foreach ($files as $file) + { + $this->crawl_php_file($file); + } + ksort($this->events); + + return sizeof($this->events); + } + + /** + * Returns a list of files in $dir + * + * @return array List of files (including the path) + */ + public function get_recursive_file_list() + { + try + { + $iterator = new \RecursiveIteratorIterator( + new \phpbb\event\recursive_event_filter_iterator( + new \RecursiveDirectoryIterator( + $this->path, + \FilesystemIterator::SKIP_DOTS + ), + $this->path + ), + \RecursiveIteratorIterator::LEAVES_ONLY + ); + } + catch (\Exception $e) + { + return array(); + } + + $files = array(); + foreach ($iterator as $file_info) + { + /** @var \RecursiveDirectoryIterator $file_info */ + $relative_path = $iterator->getInnerIterator()->getSubPathname(); + $files[] = str_replace(DIRECTORY_SEPARATOR, '/', $relative_path); + } + + return $files; + } + + /** + * Format the php events as a wiki table + * + * @param string $action + * @return string + */ + public function export_events_for_wiki($action = '') + { + if ($action === 'diff') + { + $wiki_page = '=== PHP Events (Hook Locations) ===' . "\n"; + } + else + { + $wiki_page = '= PHP Events (Hook Locations) =' . "\n"; + } + $wiki_page .= '{| class="sortable zebra" cellspacing="0" cellpadding="5"' . "\n"; + $wiki_page .= '! Identifier !! Placement !! Arguments !! Added in Release !! Explanation' . "\n"; + foreach ($this->events as $event) + { + $wiki_page .= '|- id="' . $event['event'] . '"' . "\n"; + $wiki_page .= '| [[#' . $event['event'] . '|' . $event['event'] . ']] || ' . $event['file'] . ' || ' . implode(', ', $event['arguments']) . ' || ' . $event['since'] . ' || ' . $event['description'] . "\n"; + } + $wiki_page .= '|}' . "\n"; + + return $wiki_page; + } + + /** + * @param string $file + * @return int Number of events found in this file + * @throws \LogicException + */ + public function crawl_php_file($file) + { + $this->current_file = $file; + $this->file_lines = array(); + $content = file_get_contents($this->path . $this->current_file); + $num_events_found = 0; + + if (strpos($content, "dispatcher->trigger_event('") || strpos($content, "dispatcher->dispatch('")) + { + $this->set_content(explode("\n", $content)); + for ($i = 0, $num_lines = sizeof($this->file_lines); $i < $num_lines; $i++) + { + $event_line = false; + $found_trigger_event = strpos($this->file_lines[$i], "dispatcher->trigger_event('"); + $arguments = array(); + if ($found_trigger_event !== false) + { + $event_line = $i; + $this->set_current_event($this->get_event_name($event_line, false), $event_line); + + // Find variables of the event + $arguments = $this->get_vars_from_array(); + $doc_vars = $this->get_vars_from_docblock(); + $this->validate_vars_docblock_array($arguments, $doc_vars); + } + else + { + $found_dispatch = strpos($this->file_lines[$i], "dispatcher->dispatch('"); + if ($found_dispatch !== false) + { + $event_line = $i; + $this->set_current_event($this->get_event_name($event_line, true), $event_line); + } + } + + if ($event_line) + { + // Validate @event + $event_line_num = $this->find_event(); + $this->validate_event($this->current_event, $this->file_lines[$event_line_num]); + + // Validate @since + $since_line_num = $this->find_since(); + $since = $this->validate_since($this->file_lines[$since_line_num]); + + $changed_line_nums = $this->find_changed('changed'); + if (empty($changed_line_nums)) + { + $changed_line_nums = $this->find_changed('change'); + } + $changed_versions = array(); + if (!empty($changed_line_nums)) + { + foreach ($changed_line_nums as $changed_line_num) + { + $changed_versions[] = $this->validate_changed($this->file_lines[$changed_line_num]); + } + } + + if (!$this->version_is_filtered($since)) + { + $valid_version = false; + foreach ($changed_versions as $changed) + { + $valid_version = $valid_version || $this->version_is_filtered($changed); + } + + if (!$valid_version) + { + continue; + } + } + + // Find event description line + $description_line_num = $this->find_description(); + $description = substr(trim($this->file_lines[$description_line_num]), strlen('* ')); + + if (isset($this->events[$this->current_event])) + { + throw new \LogicException("The event '{$this->current_event}' from file " + . "'{$this->current_file}:{$event_line_num}' already exists in file " + . "'{$this->events[$this->current_event]['file']}'", 10); + } + + sort($arguments); + $this->events[$this->current_event] = array( + 'event' => $this->current_event, + 'file' => $this->current_file, + 'arguments' => $arguments, + 'since' => $since, + 'description' => $description, + ); + $num_events_found++; + } + } + } + + return $num_events_found; + } + + /** + * The version to check + * + * @param string $version + * @return bool + */ + protected function version_is_filtered($version) + { + return (!$this->min_version || phpbb_version_compare($this->min_version, $version, '<=')) + && (!$this->max_version || phpbb_version_compare($this->max_version, $version, '>=')); + } + + /** + * Find the name of the event inside the dispatch() line + * + * @param int $event_line + * @param bool $is_dispatch Do we look for dispatch() or trigger_event() ? + * @return string Name of the event + * @throws \LogicException + */ + public function get_event_name($event_line, $is_dispatch) + { + $event_text_line = $this->file_lines[$event_line]; + $event_text_line = ltrim($event_text_line, "\t "); + + if ($is_dispatch) + { + $regex = '#\$([a-z](?:[a-z0-9_]|->)*)'; + $regex .= '->dispatch\('; + $regex .= '\'' . $this->preg_match_event_name() . '\''; + $regex .= '\);#'; + } + else + { + $regex = '#extract\(\$([a-z](?:[a-z0-9_]|->)*)'; + $regex .= '->trigger_event\('; + $regex .= '\'' . $this->preg_match_event_name() . '\''; + $regex .= ', compact\(\$vars\)\)\);#'; + } + + $match = array(); + preg_match($regex, $event_text_line, $match); + if (!isset($match[2])) + { + throw new \LogicException("Can not find event name in line '{$event_text_line}' " + . "in file '{$this->current_file}:{$event_line}'", 1); + } + + return $match[2]; + } + + /** + * Returns a regex match for the event name + * + * @return string + */ + protected function preg_match_event_name() + { + return '([a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+)'; + } + + /** + * Find the $vars array + * + * @return array List of variables + * @throws \LogicException + */ + public function get_vars_from_array() + { + $line = ltrim($this->file_lines[$this->current_event_line - 1], "\t"); + if ($line === ');') + { + $vars_array = $this->get_vars_from_multi_line_array(); + } + else + { + $vars_array = $this->get_vars_from_single_line_array($line); + } + + foreach ($vars_array as $var) + { + if (!preg_match('#^([a-zA-Z_][a-zA-Z0-9_]*)$#', $var)) + { + throw new \LogicException("Found invalid var '{$var}' in array for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 3); + } + } + + sort($vars_array); + return $vars_array; + } + + /** + * Find the variables in single line array + * + * @param string $line + * @param bool $throw_multiline Throw an exception when there are too + * many arguments in one line. + * @return array List of variables + * @throws \LogicException + */ + public function get_vars_from_single_line_array($line, $throw_multiline = true) + { + $match = array(); + preg_match('#^\$vars = array\(\'([a-zA-Z0-9_\' ,]+)\'\);$#', $line, $match); + + if (isset($match[1])) + { + $vars_array = explode("', '", $match[1]); + if ($throw_multiline && sizeof($vars_array) > 6) + { + throw new \LogicException('Should use multiple lines for $vars definition ' + . "for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 2); + } + return $vars_array; + } + else + { + throw new \LogicException("Can not find '\$vars = array();'-line for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 1); + } + } + + /** + * Find the variables in single line array + * + * @return array List of variables + * @throws \LogicException + */ + public function get_vars_from_multi_line_array() + { + $current_vars_line = 2; + $var_lines = array(); + while (ltrim($this->file_lines[$this->current_event_line - $current_vars_line], "\t") !== '$vars = array(') + { + $var_lines[] = substr(trim($this->file_lines[$this->current_event_line - $current_vars_line]), 0, -1); + + $current_vars_line++; + if ($current_vars_line > $this->current_event_line) + { + // Reached the start of the file + throw new \LogicException("Can not find end of \$vars array for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 2); + } + } + + return $this->get_vars_from_single_line_array('$vars = array(' . implode(", ", $var_lines) . ');', false); + } + + /** + * Find the $vars array + * + * @return array List of variables + * @throws \LogicException + */ + public function get_vars_from_docblock() + { + $doc_vars = array(); + $current_doc_line = 1; + $found_comment_end = false; + while (ltrim($this->file_lines[$this->current_event_line - $current_doc_line], "\t") !== '/**') + { + if (ltrim($this->file_lines[$this->current_event_line - $current_doc_line], "\t ") === '*/') + { + $found_comment_end = true; + } + + if ($found_comment_end) + { + $var_line = trim($this->file_lines[$this->current_event_line - $current_doc_line]); + $var_line = preg_replace('!\s+!', ' ', $var_line); + if (strpos($var_line, '* @var ') === 0) + { + $doc_line = explode(' ', $var_line, 5); + if (sizeof($doc_line) !== 5) + { + throw new \LogicException("Found invalid line '{$this->file_lines[$this->current_event_line - $current_doc_line]}' " + . "for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 1); + } + $doc_vars[] = $doc_line[3]; + } + } + + $current_doc_line++; + if ($current_doc_line > $this->current_event_line) + { + // Reached the start of the file + throw new \LogicException("Can not find end of docblock for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 2); + } + } + + if (empty($doc_vars)) + { + // Reached the start of the file + throw new \LogicException("Can not find @var lines for event '{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 3); + } + + foreach ($doc_vars as $var) + { + if (!preg_match('#^([a-zA-Z_][a-zA-Z0-9_]*)$#', $var)) + { + throw new \LogicException("Found invalid @var '{$var}' in docblock for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 4); + } + } + + sort($doc_vars); + return $doc_vars; + } + + /** + * Find the "@since" Information line + * + * @return int Absolute line number + * @throws \LogicException + */ + public function find_since() + { + return $this->find_tag('since', array('event', 'var')); + } + + /** + * Find the "@changed" Information lines + * + * @param string $tag_name Should be 'change', not 'changed' + * @return array Absolute line numbers + * @throws \LogicException + */ + public function find_changed($tag_name) + { + $lines = array(); + $last_line = 0; + try + { + while ($line = $this->find_tag($tag_name, array('since'), $last_line)) + { + $lines[] = $line; + $last_line = $line; + } + } + catch (\LogicException $e) + { + // Not changed? No problem! + } + + return $lines; + } + + /** + * Find the "@event" Information line + * + * @return int Absolute line number + */ + public function find_event() + { + return $this->find_tag('event', array()); + } + + /** + * Find a "@*" Information line + * + * @param string $find_tag Name of the tag we are trying to find + * @param array $disallowed_tags List of tags that must not appear between + * the tag and the actual event + * @param int $skip_to_line Skip lines until this one + * @return int Absolute line number + * @throws \LogicException + */ + public function find_tag($find_tag, $disallowed_tags, $skip_to_line = 0) + { + $find_tag_line = $skip_to_line ? $this->current_event_line - $skip_to_line + 1 : 0; + $found_comment_end = ($skip_to_line) ? true : false; + while (strpos(ltrim($this->file_lines[$this->current_event_line - $find_tag_line], "\t "), '* @' . $find_tag . ' ') !== 0) + { + if ($found_comment_end && ltrim($this->file_lines[$this->current_event_line - $find_tag_line], "\t") === '/**') + { + // Reached the start of this doc block + throw new \LogicException("Can not find '@{$find_tag}' information for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 1); + } + + foreach ($disallowed_tags as $disallowed_tag) + { + if ($found_comment_end && strpos(ltrim($this->file_lines[$this->current_event_line - $find_tag_line], "\t "), '* @' . $disallowed_tag) === 0) + { + // Found @var after the @since + throw new \LogicException("Found '@{$disallowed_tag}' information after '@{$find_tag}' for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 3); + } + } + + if (ltrim($this->file_lines[$this->current_event_line - $find_tag_line], "\t ") === '*/') + { + $found_comment_end = true; + } + + $find_tag_line++; + if ($find_tag_line >= $this->current_event_line) + { + // Reached the start of the file + throw new \LogicException("Can not find '@{$find_tag}' information for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 2); + } + } + + return $this->current_event_line - $find_tag_line; + } + + /** + * Find a "@*" Information line + * + * @return int Absolute line number + * @throws \LogicException + */ + public function find_description() + { + $find_desc_line = 0; + while (ltrim($this->file_lines[$this->current_event_line - $find_desc_line], "\t") !== '/**') + { + $find_desc_line++; + if ($find_desc_line > $this->current_event_line) + { + // Reached the start of the file + throw new \LogicException("Can not find a description for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 1); + } + } + + $find_desc_line = $this->current_event_line - $find_desc_line + 1; + + $desc = trim($this->file_lines[$find_desc_line]); + if (strpos($desc, '* @') === 0 || $desc[0] !== '*' || substr($desc, 1) == '') + { + // First line of the doc block is a @-line, empty or only contains "*" + throw new \LogicException("Can not find a description for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 2); + } + + return $find_desc_line; + } + + /** + * Validate "@since" Information + * + * @param string $line + * @return string + * @throws \LogicException + */ + public function validate_since($line) + { + $match = array(); + preg_match('#^\* @since (\d+\.\d+\.\d+(?:-(?:a|b|RC|pl)\d+)?)$#', ltrim($line, "\t "), $match); + if (!isset($match[1])) + { + throw new \LogicException("Invalid '@since' information for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'"); + } + + return $match[1]; + } + + /** + * Validate "@changed" Information + * + * @param string $line + * @return string + * @throws \LogicException + */ + public function validate_changed($line) + { + $match = array(); + $line = str_replace("\t", ' ', ltrim($line, "\t ")); + preg_match('#^\* @changed (\d+\.\d+\.\d+(?:-(?:a|b|RC|pl)\d+)?)( (?:.*))?$#', $line, $match); + if (!isset($match[2])) + { + throw new \LogicException("Invalid '@changed' information for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'"); + } + + return $match[2]; + } + + /** + * Validate "@event" Information + * + * @param string $event_name + * @param string $line + * @return string + * @throws \LogicException + */ + public function validate_event($event_name, $line) + { + $event = substr(ltrim($line, "\t "), strlen('* @event ')); + + if ($event !== trim($event)) + { + throw new \LogicException("Invalid '@event' information for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 1); + } + + if ($event !== $event_name) + { + throw new \LogicException("Event name does not match '@event' tag for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'", 2); + } + + return $event; + } + + /** + * Validates that two arrays contain the same strings + * + * @param array $vars_array Variables found in the array line + * @param array $vars_docblock Variables found in the doc block + * @return null + * @throws \LogicException + */ + public function validate_vars_docblock_array($vars_array, $vars_docblock) + { + $vars_array = array_unique($vars_array); + $vars_docblock = array_unique($vars_docblock); + $sizeof_vars_array = sizeof($vars_array); + + if ($sizeof_vars_array !== sizeof($vars_docblock) || $sizeof_vars_array !== sizeof(array_intersect($vars_array, $vars_docblock))) + { + throw new \LogicException("\$vars array does not match the list of '@var' tags for event " + . "'{$this->current_event}' in file '{$this->current_file}:{$this->current_event_line}'"); + } + } +} diff --git a/phpBB/phpbb/event/recursive_event_filter_iterator.php b/phpBB/phpbb/event/recursive_event_filter_iterator.php new file mode 100644 index 0000000000..64e2e56f6a --- /dev/null +++ b/phpBB/phpbb/event/recursive_event_filter_iterator.php @@ -0,0 +1,71 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\event; + +/** +* This filter ignores directories and files starting with a dot. +* It also skips some directories that do not contain events anyway, +* such as e.g. files/, store/ and vendor/ +*/ +class recursive_event_filter_iterator extends \RecursiveFilterIterator +{ + protected $root_path; + + /** + * Construct + * + * @param \RecursiveIterator $iterator + * @param string $root_path + */ + public function __construct(\RecursiveIterator $iterator, $root_path) + { + $this->root_path = str_replace(DIRECTORY_SEPARATOR, '/', $root_path); + parent::__construct($iterator); + } + + /** + * Return the inner iterator's children contained in a recursive_event_filter_iterator + * + * @return recursive_event_filter_iterator + */ + public function getChildren() + { + return new self($this->getInnerIterator()->getChildren(), $this->root_path); + } + + /** + * {@inheritDoc} + */ + public function accept() + { + $relative_path = str_replace(DIRECTORY_SEPARATOR, '/', $this->current()); + $filename = $this->current()->getFilename(); + + return (substr($relative_path, -4) === '.php' || $this->current()->isDir()) + && $filename[0] !== '.' + && strpos($relative_path, $this->root_path . 'cache/') !== 0 + && strpos($relative_path, $this->root_path . 'develop/') !== 0 + && strpos($relative_path, $this->root_path . 'docs/') !== 0 + && strpos($relative_path, $this->root_path . 'ext/') !== 0 + && strpos($relative_path, $this->root_path . 'files/') !== 0 + && strpos($relative_path, $this->root_path . 'includes/utf/') !== 0 + && strpos($relative_path, $this->root_path . 'language/') !== 0 + && strpos($relative_path, $this->root_path . 'phpbb/db/migration/data/') !== 0 + && strpos($relative_path, $this->root_path . 'phpbb/event/') !== 0 + && strpos($relative_path, $this->root_path . 'store/') !== 0 + && strpos($relative_path, $this->root_path . 'tests/') !== 0 + && strpos($relative_path, $this->root_path . 'vendor/') !== 0 + ; + } +} diff --git a/phpBB/phpbb/exception/exception_interface.php b/phpBB/phpbb/exception/exception_interface.php new file mode 100644 index 0000000000..e8526a35f5 --- /dev/null +++ b/phpBB/phpbb/exception/exception_interface.php @@ -0,0 +1,29 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\exception; + +/** + * Interface exception_interface + * + * Define an exception which support a language var as message. + */ +interface exception_interface +{ + /** + * Return the arguments associated with the message if it's a language var. + * + * @return array + */ + public function get_parameters(); +} diff --git a/phpBB/phpbb/exception/http_exception.php b/phpBB/phpbb/exception/http_exception.php new file mode 100644 index 0000000000..0e6ffe4f59 --- /dev/null +++ b/phpBB/phpbb/exception/http_exception.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\exception; + +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; + +/** + * Class http_exception + */ +class http_exception extends runtime_exception implements HttpExceptionInterface +{ + /** + * Http status code. + * + * @var integer + */ + private $status_code; + + /** + * Additional headers to set in the response. + * + * @var array + */ + private $headers; + + /** + * Constructor + * + * @param integer $status_code The http status code. + * @param string $message The Exception message to throw (must be a language variable). + * @param array $parameters The parameters to use with the language var. + * @param \Exception $previous The previous exception used for the exception chaining. + * @param array $headers Additional headers to set in the response. + * @param integer $code The Exception code. + */ + public function __construct($status_code, $message = "", array $parameters = array(), \Exception $previous = null, array $headers = array(), $code = 0) + { + $this->status_code = $status_code; + $this->headers = $headers; + + parent::__construct($message, $parameters, $previous, $code); + } + + /** + * {@inheritdoc} + */ + public function getStatusCode() + { + return $this->status_code; + } + + /** + * {@inheritdoc} + */ + public function getHeaders() + { + return $this->headers; + } +} diff --git a/phpBB/phpbb/exception/runtime_exception.php b/phpBB/phpbb/exception/runtime_exception.php new file mode 100644 index 0000000000..6568bbf86f --- /dev/null +++ b/phpBB/phpbb/exception/runtime_exception.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\exception; + +/** + * Class runtime_exception + * + * Define an exception which support a language var as message. + */ +class runtime_exception extends \RuntimeException implements exception_interface +{ + /** + * Parameters to use with the language var. + * + * @var array + */ + private $parameters; + + /** + * Constructor + * + * @param string $message The Exception message to throw (must be a language variable). + * @param array $parameters The parameters to use with the language var. + * @param \Exception $previous The previous runtime_exception used for the runtime_exception chaining. + * @param integer $code The Exception code. + */ + public function __construct($message = "", array $parameters = array(), \Exception $previous = null, $code = 0) + { + $this->parameters = $parameters; + + parent::__construct($message, $code, $previous); + } + + /** + * {@inheritdoc} + */ + public function get_parameters() + { + return $this->parameters; + } +} diff --git a/phpBB/phpbb/extension/base.php b/phpBB/phpbb/extension/base.php new file mode 100644 index 0000000000..5bb530bad4 --- /dev/null +++ b/phpBB/phpbb/extension/base.php @@ -0,0 +1,142 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\extension; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* A base class for extensions without custom enable/disable/purge code. +*/ +class base implements \phpbb\extension\extension_interface +{ + /** @var ContainerInterface */ + protected $container; + + /** @var \phpbb\finder */ + protected $finder; + + /** @var \phpbb\db\migrator */ + protected $migrator; + + /** @var string */ + protected $extension_name; + + /** @var string */ + protected $extension_path; + + /** @var string[] */ + private $migrations = false; + + /** + * Constructor + * + * @param ContainerInterface $container Container object + * @param \phpbb\finder $extension_finder + * @param \phpbb\db\migrator $migrator + * @param string $extension_name Name of this extension (from ext.manager) + * @param string $extension_path Relative path to this extension + */ + public function __construct(ContainerInterface $container, \phpbb\finder $extension_finder, \phpbb\db\migrator $migrator, $extension_name, $extension_path) + { + $this->container = $container; + $this->extension_finder = $extension_finder; + $this->migrator = $migrator; + + $this->extension_name = $extension_name; + $this->extension_path = $extension_path; + } + + /** + * {@inheritdoc} + */ + public function is_enableable() + { + return true; + } + + /** + * Single enable step that installs any included migrations + * + * @param mixed $old_state State returned by previous call of this method + * @return false Indicates no further steps are required + */ + public function enable_step($old_state) + { + $migrations = $this->get_migration_file_list(); + + $this->migrator->set_migrations($migrations); + + $this->migrator->update(); + + return !$this->migrator->finished(); + } + + /** + * Single disable step that does nothing + * + * @param mixed $old_state State returned by previous call of this method + * @return false Indicates no further steps are required + */ + public function disable_step($old_state) + { + return false; + } + + /** + * Single purge step that reverts any included and installed migrations + * + * @param mixed $old_state State returned by previous call of this method + * @return false Indicates no further steps are required + */ + public function purge_step($old_state) + { + $migrations = $this->get_migration_file_list(); + + $this->migrator->set_migrations($migrations); + + foreach ($migrations as $migration) + { + while ($this->migrator->migration_state($migration) !== false) + { + $this->migrator->revert($migration); + + return true; + } + } + + return false; + } + + /** + * Get the list of migration files from this extension + * + * @return array + */ + protected function get_migration_file_list() + { + if ($this->migrations !== false) + { + return $this->migrations; + } + + // Only have the finder search in this extension path directory + $migrations = $this->extension_finder + ->extension_directory('/migrations') + ->find_from_extension($this->extension_name, $this->extension_path); + + $migrations = $this->extension_finder->get_classes_from_files($migrations); + + return $migrations; + } +} diff --git a/phpBB/phpbb/extension/exception.php b/phpBB/phpbb/extension/exception.php new file mode 100644 index 0000000000..3f7d251a4e --- /dev/null +++ b/phpBB/phpbb/extension/exception.php @@ -0,0 +1,25 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\extension; + +/** + * Exception class for metadata + */ +class exception extends \UnexpectedValueException +{ + public function __toString() + { + return $this->getMessage(); + } +} diff --git a/phpBB/phpbb/extension/extension_interface.php b/phpBB/phpbb/extension/extension_interface.php new file mode 100644 index 0000000000..6a6b6adb8f --- /dev/null +++ b/phpBB/phpbb/extension/extension_interface.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\extension; + +/** +* The interface extension meta classes have to implement to run custom code +* on enable/disable/purge. +*/ +interface extension_interface +{ + /** + * Indicate whether or not the extension can be enabled. + * + * @return bool + */ + public function is_enableable(); + + /** + * enable_step is executed on enabling an extension until it returns false. + * + * Calls to this function can be made in subsequent requests, when the + * function is invoked through a webserver with a too low max_execution_time. + * + * @param mixed $old_state The return value of the previous call + * of this method, or false on the first call + * @return mixed Returns false after last step, otherwise + * temporary state which is passed as an + * argument to the next step + */ + public function enable_step($old_state); + + /** + * Disables the extension. + * + * Calls to this function can be made in subsequent requests, when the + * function is invoked through a webserver with a too low max_execution_time. + * + * @param mixed $old_state The return value of the previous call + * of this method, or false on the first call + * @return mixed Returns false after last step, otherwise + * temporary state which is passed as an + * argument to the next step + */ + public function disable_step($old_state); + + /** + * purge_step is executed on purging an extension until it returns false. + * + * Calls to this function can be made in subsequent requests, when the + * function is invoked through a webserver with a too low max_execution_time. + * + * @param mixed $old_state The return value of the previous call + * of this method, or false on the first call + * @return mixed Returns false after last step, otherwise + * temporary state which is passed as an + * argument to the next step + */ + public function purge_step($old_state); +} diff --git a/phpBB/phpbb/extension/manager.php b/phpBB/phpbb/extension/manager.php new file mode 100644 index 0000000000..e7e5f83c23 --- /dev/null +++ b/phpBB/phpbb/extension/manager.php @@ -0,0 +1,592 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\extension; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* The extension manager provides means to activate/deactivate extensions. +*/ +class manager +{ + /** @var ContainerInterface */ + protected $container; + + protected $db; + protected $config; + protected $cache; + protected $user; + protected $php_ext; + protected $extensions; + protected $extension_table; + protected $phpbb_root_path; + protected $cache_name; + + /** + * Creates a manager and loads information from database + * + * @param ContainerInterface $container A container + * @param \phpbb\db\driver\driver_interface $db A database connection + * @param \phpbb\config\config $config Config object + * @param \phpbb\filesystem $filesystem + * @param \phpbb\user $user User object + * @param string $extension_table The name of the table holding extensions + * @param string $phpbb_root_path Path to the phpbb includes directory. + * @param string $php_ext php file extension, defaults to php + * @param \phpbb\cache\driver\driver_interface $cache A cache instance or null + * @param string $cache_name The name of the cache variable, defaults to _ext + */ + public function __construct(ContainerInterface $container, \phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, \phpbb\filesystem $filesystem, \phpbb\user $user, $extension_table, $phpbb_root_path, $php_ext = 'php', \phpbb\cache\driver\driver_interface $cache = null, $cache_name = '_ext') + { + $this->cache = $cache; + $this->cache_name = $cache_name; + $this->config = $config; + $this->container = $container; + $this->db = $db; + $this->extension_table = $extension_table; + $this->filesystem = $filesystem; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->user = $user; + + $this->extensions = ($this->cache) ? $this->cache->get($this->cache_name) : false; + + if ($this->extensions === false) + { + $this->load_extensions(); + } + } + + /** + * Loads all extension information from the database + * + * @return null + */ + public function load_extensions() + { + $this->extensions = array(); + + // Do not try to load any extensions if the extension table + // does not exist or when installing or updating. + // Note: database updater invokes this code, and in 3.0 + // there is no extension table therefore the rest of this function + // fails + if (defined('IN_INSTALL') || version_compare($this->config['version'], '3.1.0-dev', '<')) + { + return; + } + + $sql = 'SELECT * + FROM ' . $this->extension_table; + + $result = $this->db->sql_query($sql); + $extensions = $this->db->sql_fetchrowset($result); + $this->db->sql_freeresult($result); + + foreach ($extensions as $extension) + { + $extension['ext_path'] = $this->get_extension_path($extension['ext_name']); + $this->extensions[$extension['ext_name']] = $extension; + } + + ksort($this->extensions); + + if ($this->cache) + { + $this->cache->put($this->cache_name, $this->extensions); + } + } + + /** + * Generates the path to an extension + * + * @param string $name The name of the extension + * @param bool $phpbb_relative Whether the path should be relative to phpbb root + * @return string Path to an extension + */ + public function get_extension_path($name, $phpbb_relative = false) + { + $name = str_replace('.', '', $name); + + return (($phpbb_relative) ? $this->phpbb_root_path : '') . 'ext/' . $name . '/'; + } + + /** + * Instantiates the extension meta class for the extension with the given name + * + * @param string $name The extension name + * @return \phpbb\extension\extension_interface Instance of the extension meta class or + * \phpbb\extension\base if the class does not exist + */ + public function get_extension($name) + { + $extension_class_name = str_replace('/', '\\', $name) . '\\ext'; + + $migrator = $this->container->get('migrator'); + + if (class_exists($extension_class_name)) + { + return new $extension_class_name($this->container, $this->get_finder(), $migrator, $name, $this->get_extension_path($name, true)); + } + else + { + return new \phpbb\extension\base($this->container, $this->get_finder(), $migrator, $name, $this->get_extension_path($name, true)); + } + } + + /** + * Instantiates the metadata manager for the extension with the given name + * + * @param string $name The extension name + * @param \phpbb\template\template $template The template manager or null + * @return \phpbb\extension\metadata_manager Instance of the metadata manager + */ + public function create_extension_metadata_manager($name, \phpbb\template\template $template = null) + { + return new \phpbb\extension\metadata_manager($name, $this->config, $this, $template, $this->user, $this->phpbb_root_path); + } + + /** + * Runs a step of the extension enabling process. + * + * Allows the exentension to enable in a long running script that works + * in multiple steps across requests. State is kept for the extension + * in the extensions table. + * + * @param string $name The extension's name + * @return bool False if enabling is finished, true otherwise + */ + public function enable_step($name) + { + // ignore extensions that are already enabled + if (isset($this->extensions[$name]) && $this->extensions[$name]['ext_active']) + { + return false; + } + + $old_state = (isset($this->extensions[$name]['ext_state'])) ? unserialize($this->extensions[$name]['ext_state']) : false; + + $extension = $this->get_extension($name); + + if (!$extension->is_enableable()) + { + return false; + } + + $state = $extension->enable_step($old_state); + + $active = ($state === false); + + $extension_data = array( + 'ext_name' => $name, + 'ext_active' => $active, + 'ext_state' => serialize($state), + ); + + $this->extensions[$name] = $extension_data; + $this->extensions[$name]['ext_path'] = $this->get_extension_path($extension_data['ext_name']); + ksort($this->extensions); + + $sql = 'SELECT COUNT(ext_name) as row_count + FROM ' . $this->extension_table . " + WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; + $result = $this->db->sql_query($sql); + $count = $this->db->sql_fetchfield('row_count'); + $this->db->sql_freeresult($result); + + if ($count) + { + $sql = 'UPDATE ' . $this->extension_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " + WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + } + else + { + $sql = 'INSERT INTO ' . $this->extension_table . ' + ' . $this->db->sql_build_array('INSERT', $extension_data); + $this->db->sql_query($sql); + } + + if ($this->cache) + { + $this->cache->purge(); + } + + if ($active) + { + $this->config->increment('assets_version', 1); + } + + return !$active; + } + + /** + * Enables an extension + * + * This method completely enables an extension. But it could be long running + * so never call this in a script that has a max_execution time. + * + * @param string $name The extension's name + * @return null + */ + public function enable($name) + { + // @codingStandardsIgnoreStart + while ($this->enable_step($name)); + // @codingStandardsIgnoreEnd + } + + /** + * Disables an extension + * + * Calls the disable method on the extension's meta class to allow it to + * process the event. + * + * @param string $name The extension's name + * @return bool False if disabling is finished, true otherwise + */ + public function disable_step($name) + { + // ignore extensions that are already disabled + if (!isset($this->extensions[$name]) || !$this->extensions[$name]['ext_active']) + { + return false; + } + + $old_state = unserialize($this->extensions[$name]['ext_state']); + + $extension = $this->get_extension($name); + $state = $extension->disable_step($old_state); + + // continue until the state is false + if ($state !== false) + { + $extension_data = array( + 'ext_state' => serialize($state), + ); + $this->extensions[$name]['ext_state'] = serialize($state); + + $sql = 'UPDATE ' . $this->extension_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " + WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + + if ($this->cache) + { + $this->cache->purge(); + } + + return true; + } + + $extension_data = array( + 'ext_active' => false, + 'ext_state' => serialize(false), + ); + $this->extensions[$name]['ext_active'] = false; + $this->extensions[$name]['ext_state'] = serialize(false); + + $sql = 'UPDATE ' . $this->extension_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " + WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + + if ($this->cache) + { + $this->cache->purge(); + } + + return false; + } + + /** + * Disables an extension + * + * Disables an extension completely at once. This process could run for a + * while so never call this in a script that has a max_execution time. + * + * @param string $name The extension's name + * @return null + */ + public function disable($name) + { + // @codingStandardsIgnoreStart + while ($this->disable_step($name)); + // @codingStandardsIgnoreEnd + } + + /** + * Purge an extension + * + * Disables the extension first if active, and then calls purge on the + * extension's meta class to delete the extension's database content. + * + * @param string $name The extension's name + * @return bool False if purging is finished, true otherwise + */ + public function purge_step($name) + { + // ignore extensions that do not exist + if (!isset($this->extensions[$name])) + { + return false; + } + + // disable first if necessary + if ($this->extensions[$name]['ext_active']) + { + $this->disable($name); + } + + $old_state = unserialize($this->extensions[$name]['ext_state']); + + $extension = $this->get_extension($name); + $state = $extension->purge_step($old_state); + + // continue until the state is false + if ($state !== false) + { + $extension_data = array( + 'ext_state' => serialize($state), + ); + $this->extensions[$name]['ext_state'] = serialize($state); + + $sql = 'UPDATE ' . $this->extension_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " + WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + + if ($this->cache) + { + $this->cache->purge(); + } + + return true; + } + + unset($this->extensions[$name]); + + $sql = 'DELETE FROM ' . $this->extension_table . " + WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; + $this->db->sql_query($sql); + + if ($this->cache) + { + $this->cache->purge(); + } + + return false; + } + + /** + * Purge an extension + * + * Purges an extension completely at once. This process could run for a while + * so never call this in a script that has a max_execution time. + * + * @param string $name The extension's name + * @return null + */ + public function purge($name) + { + // @codingStandardsIgnoreStart + while ($this->purge_step($name)); + // @codingStandardsIgnoreEnd + } + + /** + * Retrieves a list of all available extensions on the filesystem + * + * @return array An array with extension names as keys and paths to the + * extension as values + */ + public function all_available() + { + $available = array(); + if (!is_dir($this->phpbb_root_path . 'ext/')) + { + return $available; + } + + $iterator = new \RecursiveIteratorIterator( + new \phpbb\recursive_dot_prefix_filter_iterator( + new \RecursiveDirectoryIterator($this->phpbb_root_path . 'ext/', \FilesystemIterator::NEW_CURRENT_AND_KEY | \FilesystemIterator::FOLLOW_SYMLINKS) + ), + \RecursiveIteratorIterator::SELF_FIRST + ); + $iterator->setMaxDepth(2); + + foreach ($iterator as $file_info) + { + if ($file_info->isFile() && $file_info->getFilename() == 'composer.json') + { + $ext_name = $iterator->getInnerIterator()->getSubPath(); + $ext_name = str_replace(DIRECTORY_SEPARATOR, '/', $ext_name); + if ($this->is_available($ext_name)) + { + $available[$ext_name] = $this->phpbb_root_path . 'ext/' . $ext_name . '/'; + } + } + } + ksort($available); + return $available; + } + + /** + * Retrieves all configured extensions. + * + * All enabled and disabled extensions are considered configured. A purged + * extension that is no longer in the database is not configured. + * + * @return array An array with extension names as keys and and the + * database stored extension information as values + */ + public function all_configured() + { + $configured = array(); + foreach ($this->extensions as $name => $data) + { + $data['ext_path'] = $this->phpbb_root_path . $data['ext_path']; + $configured[$name] = $data; + } + return $configured; + } + + /** + * Retrieves all enabled extensions. + * + * @return array An array with extension names as keys and and the + * database stored extension information as values + */ + public function all_enabled() + { + $enabled = array(); + foreach ($this->extensions as $name => $data) + { + if ($data['ext_active']) + { + $enabled[$name] = $this->phpbb_root_path . $data['ext_path']; + } + } + return $enabled; + } + + /** + * Retrieves all disabled extensions. + * + * @return array An array with extension names as keys and and the + * database stored extension information as values + */ + public function all_disabled() + { + $disabled = array(); + foreach ($this->extensions as $name => $data) + { + if (!$data['ext_active']) + { + $disabled[$name] = $this->phpbb_root_path . $data['ext_path']; + } + } + return $disabled; + } + + /** + * Check to see if a given extension is available on the filesystem + * + * @param string $name Extension name to check NOTE: Can be user input + * @return bool Depending on whether or not the extension is available + */ + public function is_available($name) + { + $md_manager = $this->create_extension_metadata_manager($name); + try + { + return $md_manager->get_metadata('all') && $md_manager->validate_enable(); + } + catch (\phpbb\extension\exception $e) + { + return false; + } + } + + /** + * Check to see if a given extension is enabled + * + * @param string $name Extension name to check + * @return bool Depending on whether or not the extension is enabled + */ + public function is_enabled($name) + { + return isset($this->extensions[$name]) && $this->extensions[$name]['ext_active']; + } + + /** + * Check to see if a given extension is disabled + * + * @param string $name Extension name to check + * @return bool Depending on whether or not the extension is disabled + */ + public function is_disabled($name) + { + return isset($this->extensions[$name]) && !$this->extensions[$name]['ext_active']; + } + + /** + * Check to see if a given extension is configured + * + * All enabled and disabled extensions are considered configured. A purged + * extension that is no longer in the database is not configured. + * + * @param string $name Extension name to check + * @return bool Depending on whether or not the extension is configured + */ + public function is_configured($name) + { + return isset($this->extensions[$name]); + } + + /** + * Check to see if a given extension is purged + * + * An extension is purged if it is available, not enabled and not disabled. + * + * @param string $name Extension name to check + * @return bool Depending on whether or not the extension is purged + */ + public function is_purged($name) + { + return $this->is_available($name) && !$this->is_configured($name); + } + + /** + * Instantiates a \phpbb\finder. + * + * @param bool $use_all_available Should we load all extensions, or just enabled ones + * @return \phpbb\finder An extension finder instance + */ + public function get_finder($use_all_available = false) + { + $finder = new \phpbb\finder($this->filesystem, $this->phpbb_root_path, $this->cache, $this->php_ext, $this->cache_name . '_finder'); + if ($use_all_available) + { + $finder->set_extensions(array_keys($this->all_available())); + } + else + { + $finder->set_extensions(array_keys($this->all_enabled())); + } + return $finder; + } +} diff --git a/phpBB/phpbb/extension/metadata_manager.php b/phpBB/phpbb/extension/metadata_manager.php new file mode 100644 index 0000000000..a09f07bed2 --- /dev/null +++ b/phpBB/phpbb/extension/metadata_manager.php @@ -0,0 +1,343 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\extension; + +/** +* The extension metadata manager validates and gets meta-data for extensions +*/ +class metadata_manager +{ + /** + * phpBB Config instance + * @var \phpbb\config\config + */ + protected $config; + + /** + * phpBB Extension Manager + * @var \phpbb\extension\manager + */ + protected $extension_manager; + + /** + * phpBB Template instance + * @var \phpbb\template\template + */ + protected $template; + + /** + * phpBB User instance + * @var \phpbb\user + */ + protected $user; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * Name (including vendor) of the extension + * @var string + */ + protected $ext_name; + + /** + * Metadata from the composer.json file + * @var array + */ + protected $metadata; + + /** + * Link (including root path) to the metadata file + * @var string + */ + protected $metadata_file; + + // @codingStandardsIgnoreStart + /** + * Creates the metadata manager + * + * @param string $ext_name Name (including vendor) of the extension + * @param \phpbb\config\config $config phpBB Config instance + * @param \phpbb\extension\manager $extension_manager An instance of the phpBB extension manager + * @param \phpbb\template\template $template phpBB Template instance or null + * @param \phpbb\user $user User instance + * @param string $phpbb_root_path Path to the phpbb includes directory. + */ + public function __construct($ext_name, \phpbb\config\config $config, \phpbb\extension\manager $extension_manager, \phpbb\template\template $template = null, \phpbb\user $user, $phpbb_root_path) + { + $this->config = $config; + $this->extension_manager = $extension_manager; + $this->template = $template; + $this->user = $user; + $this->phpbb_root_path = $phpbb_root_path; + + $this->ext_name = $ext_name; + $this->metadata = array(); + $this->metadata_file = ''; + } + // @codingStandardsIgnoreEnd + + /** + * Processes and gets the metadata requested + * + * @param string $element All for all metadata that it has and is valid, otherwise specify which section you want by its shorthand term. + * @return array Contains all of the requested metadata, throws an exception on failure + */ + public function get_metadata($element = 'all') + { + // Fetch and clean the metadata if not done yet + if ($this->metadata_file === '') + { + $this->fetch_metadata_from_file(); + } + + switch ($element) + { + case 'all': + default: + $this->validate(); + return $this->metadata; + break; + + case 'version': + case 'name': + $this->validate($element); + return $this->metadata[$element]; + break; + + case 'display-name': + return (isset($this->metadata['extra']['display-name'])) ? $this->metadata['extra']['display-name'] : $this->get_metadata('name'); + break; + } + } + + /** + * Sets the path of the metadata file, gets its contents and cleans loaded file + * + * @throws \phpbb\extension\exception + */ + private function fetch_metadata_from_file() + { + $ext_filepath = $this->extension_manager->get_extension_path($this->ext_name); + $metadata_filepath = $this->phpbb_root_path . $ext_filepath . 'composer.json'; + + $this->metadata_file = $metadata_filepath; + + if (!file_exists($this->metadata_file)) + { + throw new \phpbb\extension\exception($this->user->lang('FILE_NOT_FOUND', $this->metadata_file)); + } + + if (!($file_contents = file_get_contents($this->metadata_file))) + { + throw new \phpbb\extension\exception($this->user->lang('FILE_CONTENT_ERR', $this->metadata_file)); + } + + if (($metadata = json_decode($file_contents, true)) === null) + { + throw new \phpbb\extension\exception($this->user->lang('FILE_JSON_DECODE_ERR', $this->metadata_file)); + } + + array_walk_recursive($metadata, array($this, 'sanitize_json')); + $this->metadata = $metadata; + } + + /** + * Sanitize input from JSON array using htmlspecialchars() + * + * @param mixed $value Value of array row + * @param string $key Key of array row + */ + public function sanitize_json(&$value, $key) + { + $value = htmlspecialchars($value); + } + + /** + * Validate fields + * + * @param string $name ("all" for display and enable validation + * "display" for name, type, and authors + * "name", "type") + * @return Bool True if valid, throws an exception if invalid + * @throws \phpbb\extension\exception + */ + public function validate($name = 'display') + { + // Basic fields + $fields = array( + 'name' => '#^[a-zA-Z0-9_\x7f-\xff]{2,}/[a-zA-Z0-9_\x7f-\xff]{2,}$#', + 'type' => '#^phpbb-extension$#', + 'license' => '#.+#', + 'version' => '#.+#', + ); + + switch ($name) + { + case 'all': + $this->validate_enable(); + // no break + + case 'display': + foreach ($fields as $field => $data) + { + $this->validate($field); + } + + $this->validate_authors(); + break; + + default: + if (isset($fields[$name])) + { + if (!isset($this->metadata[$name])) + { + throw new \phpbb\extension\exception($this->user->lang('META_FIELD_NOT_SET', $name)); + } + + if (!preg_match($fields[$name], $this->metadata[$name])) + { + throw new \phpbb\extension\exception($this->user->lang('META_FIELD_INVALID', $name)); + } + } + break; + } + + return true; + } + + /** + * Validates the contents of the authors field + * + * @return boolean True when passes validation, throws exception if invalid + * @throws \phpbb\extension\exception + */ + public function validate_authors() + { + if (empty($this->metadata['authors'])) + { + throw new \phpbb\extension\exception($this->user->lang('META_FIELD_NOT_SET', 'authors')); + } + + foreach ($this->metadata['authors'] as $author) + { + if (!isset($author['name'])) + { + throw new \phpbb\extension\exception($this->user->lang('META_FIELD_NOT_SET', 'author name')); + } + } + + return true; + } + + /** + * This array handles the verification that this extension can be enabled on this board + * + * @return bool True if validation succeeded, throws an exception if invalid + * @throws \phpbb\extension\exception + */ + public function validate_enable() + { + // Check for valid directory & phpBB, PHP versions + return $this->validate_dir() && $this->validate_require_phpbb() && $this->validate_require_php(); + } + + /** + * Validates the most basic directory structure to ensure it follows <vendor>/<ext> convention. + * + * @return boolean True when passes validation, throws an exception if invalid + * @throws \phpbb\extension\exception + */ + public function validate_dir() + { + if (substr_count($this->ext_name, '/') !== 1 || $this->ext_name != $this->get_metadata('name')) + { + throw new \phpbb\extension\exception($this->user->lang('EXTENSION_DIR_INVALID')); + } + + return true; + } + + + /** + * Validates the contents of the phpbb requirement field + * + * @return boolean True when passes validation, throws an exception if invalid + * @throws \phpbb\extension\exception + */ + public function validate_require_phpbb() + { + if (!isset($this->metadata['extra']['soft-require']['phpbb/phpbb'])) + { + throw new \phpbb\extension\exception($this->user->lang('META_FIELD_NOT_SET', 'soft-require')); + } + + return true; + } + + /** + * Validates the contents of the php requirement field + * + * @return boolean True when passes validation, throws an exception if invalid + * @throws \phpbb\extension\exception + */ + public function validate_require_php() + { + if (!isset($this->metadata['require']['php'])) + { + throw new \phpbb\extension\exception($this->user->lang('META_FIELD_NOT_SET', 'require php')); + } + + return true; + } + + /** + * Outputs the metadata into the template + * + * @return null + */ + public function output_template_data() + { + $this->template->assign_vars(array( + 'META_NAME' => $this->metadata['name'], + 'META_TYPE' => $this->metadata['type'], + 'META_DESCRIPTION' => (isset($this->metadata['description'])) ? $this->metadata['description'] : '', + 'META_HOMEPAGE' => (isset($this->metadata['homepage'])) ? $this->metadata['homepage'] : '', + 'META_VERSION' => (isset($this->metadata['version'])) ? $this->metadata['version'] : '', + 'META_TIME' => (isset($this->metadata['time'])) ? $this->metadata['time'] : '', + 'META_LICENSE' => $this->metadata['license'], + + 'META_REQUIRE_PHP' => (isset($this->metadata['require']['php'])) ? $this->metadata['require']['php'] : '', + 'META_REQUIRE_PHP_FAIL' => (isset($this->metadata['require']['php'])) ? false : true, + + 'META_REQUIRE_PHPBB' => (isset($this->metadata['extra']['soft-require']['phpbb/phpbb'])) ? $this->metadata['extra']['soft-require']['phpbb/phpbb'] : '', + 'META_REQUIRE_PHPBB_FAIL' => (isset($this->metadata['extra']['soft-require']['phpbb/phpbb'])) ? false : true, + + 'META_DISPLAY_NAME' => (isset($this->metadata['extra']['display-name'])) ? $this->metadata['extra']['display-name'] : '', + )); + + foreach ($this->metadata['authors'] as $author) + { + $this->template->assign_block_vars('meta_authors', array( + 'AUTHOR_NAME' => $author['name'], + 'AUTHOR_EMAIL' => (isset($author['email'])) ? $author['email'] : '', + 'AUTHOR_HOMEPAGE' => (isset($author['homepage'])) ? $author['homepage'] : '', + 'AUTHOR_ROLE' => (isset($author['role'])) ? $author['role'] : '', + )); + } + } +} diff --git a/phpBB/phpbb/extension/provider.php b/phpBB/phpbb/extension/provider.php new file mode 100644 index 0000000000..1c42cf7b5e --- /dev/null +++ b/phpBB/phpbb/extension/provider.php @@ -0,0 +1,72 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\extension; + +/** +* Provides a set of items found in extensions. +* +* This abstract class is essentially a wrapper around item-specific +* finding logic. It handles storing the extension manager via constructor +* for the finding logic to use to find the items, and provides an +* iterator interface over the items found by the finding logic. +* +* Items could be anything, for example template paths or cron task names. +* Derived classes completely define what the items are. +*/ +abstract class provider implements \IteratorAggregate +{ + /** + * Array holding all found items + * @var array|null + */ + protected $items = null; + + /** + * An extension manager to search for items in extensions + * @var \phpbb\extension\manager + */ + protected $extension_manager; + + /** + * Constructor. Loads all available items. + * + * @param \phpbb\extension\manager $extension_manager phpBB extension manager + */ + public function __construct(\phpbb\extension\manager $extension_manager) + { + $this->extension_manager = $extension_manager; + } + + /** + * Finds items using the extension manager. + * + * @return array List of task names + */ + abstract protected function find(); + + /** + * Retrieve an iterator over all items + * + * @return \ArrayIterator An iterator for the array of template paths + */ + public function getIterator() + { + if ($this->items === null) + { + $this->items = $this->find(); + } + + return new \ArrayIterator($this->items); + } +} diff --git a/phpBB/phpbb/feed/attachments_base.php b/phpBB/phpbb/feed/attachments_base.php new file mode 100644 index 0000000000..df8f29a626 --- /dev/null +++ b/phpBB/phpbb/feed/attachments_base.php @@ -0,0 +1,97 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Abstract class for feeds displaying attachments +*/ +abstract class attachments_base extends \phpbb\feed\base +{ + /** + * Attachments that may be displayed + */ + protected $attachments = array(); + + /** + * Retrieve the list of attachments that may be displayed + * + * @param array $post_ids Specify for which post IDs to fetch the attachments (optional) + * @param array $topic_ids Specify for which topic IDs to fetch the attachments (optional) + */ + protected function fetch_attachments($post_ids = array(), $topic_ids = array()) + { + $sql_array = array( + 'SELECT' => 'a.*', + 'FROM' => array( + ATTACHMENTS_TABLE => 'a' + ), + 'WHERE' => 'a.in_message = 0 ', + 'ORDER_BY' => 'a.filetime DESC, a.post_msg_id ASC', + ); + + if (!empty($post_ids)) + { + $sql_array['WHERE'] .= 'AND ' . $this->db->sql_in_set('a.post_msg_id', $post_ids); + } + else if (!empty($topic_ids)) + { + if (isset($this->topic_id)) + { + $topic_ids[] = $this->topic_id; + } + + $sql_array['WHERE'] .= 'AND ' . $this->db->sql_in_set('a.topic_id', $topic_ids); + } + else if (isset($this->topic_id)) + { + $sql_array['WHERE'] .= 'AND a.topic_id = ' . (int) $this->topic_id; + } + else if (isset($this->forum_id)) + { + $sql_array['LEFT_JOIN'] = array( + array( + 'FROM' => array(TOPICS_TABLE => 't'), + 'ON' => 'a.topic_id = t.topic_id', + ) + ); + $sql_array['WHERE'] .= 'AND t.forum_id = ' . (int) $this->forum_id; + } + else + { + // Do not allow querying the full attachments table + throw new \RuntimeException($this->user->lang('INVALID_FEED_ATTACHMENTS')); + } + + $sql = $this->db->sql_build_query('SELECT', $sql_array); + $result = $this->db->sql_query($sql); + + // Set attachments in feed items + while ($row = $this->db->sql_fetchrow($result)) + { + $this->attachments[$row['post_msg_id']][] = $row; + } + $this->db->sql_freeresult($result); + } + + /** + * Get attachments related to a given post + * + * @param $post_id int Post id + * @return mixed Attachments related to $post_id + */ + public function get_attachments($post_id) + { + return $this->attachments[$post_id]; + } +} diff --git a/phpBB/phpbb/feed/base.php b/phpBB/phpbb/feed/base.php new file mode 100644 index 0000000000..eeea0a55df --- /dev/null +++ b/phpBB/phpbb/feed/base.php @@ -0,0 +1,296 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Base class with some generic functions and settings. +*/ +abstract class base +{ + /** + * Feed helper object + * @var \phpbb\feed\helper + */ + protected $helper; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\cache\driver\driver_interface */ + protected $cache; + + /** @var \phpbb\user */ + protected $user; + + /** @var \phpbb\auth\auth */ + protected $auth; + + /** @var \phpbb\content_visibility */ + protected $content_visibility; + + /** @var \phpbb\event\dispatcher_interface */ + protected $phpbb_dispatcher; + + /** @var string */ + protected $phpEx; + + /** + * SQL Query to be executed to get feed items + */ + var $sql = array(); + + /** + * Keys specified for retrieval of title, content, etc. + */ + var $keys = array(); + + /** + * Number of items to fetch. Usually overwritten by $config['feed_something'] + */ + var $num_items = 15; + + /** + * Separator for title elements to separate items (for example forum / topic) + */ + var $separator = "\xE2\x80\xA2"; // • + + /** + * Separator for the statistics row (Posted by, post date, replies, etc.) + */ + var $separator_stats = "\xE2\x80\x94"; // — + + /** @var mixed Query result handle */ + protected $result; + + /** + * Constructor + * + * @param \phpbb\feed\helper $helper Feed helper + * @param \phpbb\config\config $config Config object + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param \phpbb\cache\driver\driver_interface $cache Cache object + * @param \phpbb\user $user User object + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\content_visibility $content_visibility Content visibility object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object + * @param string $phpEx php file extension + */ + function __construct( + \phpbb\feed\helper $helper, + \phpbb\config\config $config, + \phpbb\db\driver\driver_interface $db, + \phpbb\cache\driver\driver_interface $cache, + \phpbb\user $user, + \phpbb\auth\auth $auth, + \phpbb\content_visibility $content_visibility, + \phpbb\event\dispatcher_interface $phpbb_dispatcher, + $phpEx + ) + { + $this->config = $config; + $this->helper = $helper; + $this->db = $db; + $this->cache = $cache; + $this->user = $user; + $this->auth = $auth; + $this->content_visibility = $content_visibility; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->phpEx = $phpEx; + + $this->set_keys(); + + // Allow num_items to be string + if (is_string($this->num_items)) + { + $this->num_items = (int) $this->config[$this->num_items]; + + // A precaution + if (!$this->num_items) + { + $this->num_items = 10; + } + } + } + + /** + * Set keys. + */ + function set_keys() + { + } + + /** + * Open feed + */ + function open() + { + } + + /** + * Close feed + */ + function close() + { + if (!empty($this->result)) + { + $this->db->sql_freeresult($this->result); + } + } + + /** + * Set key + * + * @param string $key Key + * @param mixed $value Value + */ + function set($key, $value) + { + $this->keys[$key] = $value; + } + + /** + * Get key + * + * @param string $key Key + * @return mixed + */ + function get($key) + { + return (isset($this->keys[$key])) ? $this->keys[$key] : null; + } + + function get_readable_forums() + { + static $forum_ids; + + if (!isset($forum_ids)) + { + $forum_ids = array_keys($this->auth->acl_getf('f_read', true)); + } + + return $forum_ids; + } + + function get_moderator_approve_forums() + { + static $forum_ids; + + if (!isset($forum_ids)) + { + $forum_ids = array_keys($this->auth->acl_getf('m_approve', true)); + } + + return $forum_ids; + } + + function is_moderator_approve_forum($forum_id) + { + static $forum_ids; + + if (!isset($forum_ids)) + { + $forum_ids = array_flip($this->get_moderator_approve_forums()); + } + + return (isset($forum_ids[$forum_id])) ? true : false; + } + + function get_excluded_forums() + { + static $forum_ids; + + // Matches acp/acp_board.php + $cache_name = 'feed_excluded_forum_ids'; + + if (!isset($forum_ids) && ($forum_ids = $this->cache->get('_' . $cache_name)) === false) + { + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE . ' + WHERE ' . $this->db->sql_bit_and('forum_options', FORUM_OPTION_FEED_EXCLUDE, '<> 0'); + $result = $this->db->sql_query($sql); + + $forum_ids = array(); + while ($forum_id = (int) $this->db->sql_fetchfield('forum_id')) + { + $forum_ids[$forum_id] = $forum_id; + } + $this->db->sql_freeresult($result); + + $this->cache->put('_' . $cache_name, $forum_ids); + } + + return $forum_ids; + } + + function is_excluded_forum($forum_id) + { + $forum_ids = $this->get_excluded_forums(); + + return isset($forum_ids[$forum_id]) ? true : false; + } + + function get_passworded_forums() + { + return $this->user->get_passworded_forums(); + } + + function get_item() + { + if (!isset($this->result)) + { + if (!$this->get_sql()) + { + return false; + } + + $sql_ary = $this->sql; + + /** + * Event to modify the feed item sql + * + * @event core.feed_base_modify_item_sql + * @var array sql_ary The SQL array to get the feed item data + * + * @since 3.1.10-RC1 + */ + $vars = array('sql_ary'); + extract($this->phpbb_dispatcher->trigger_event('core.feed_base_modify_item_sql', compact($vars))); + $this->sql = $sql_ary; + unset($sql_ary); + + // Query database + $sql = $this->db->sql_build_query('SELECT', $this->sql); + $this->result = $this->db->sql_query_limit($sql, $this->num_items); + } + + return $this->db->sql_fetchrow($this->result); + } + + function user_viewprofile($row) + { + $author_id = (int) $row[$this->get('author_id')]; + + if ($author_id == ANONYMOUS) + { + // Since we cannot link to a profile, we just return GUEST + // instead of $row['username'] + return $this->user->lang['GUEST']; + } + + return '<a href="' . $this->helper->append_sid('memberlist.' . $this->phpEx, 'mode=viewprofile&u=' . $author_id) . '">' . $row[$this->get('creator')] . '</a>'; + } +} diff --git a/phpBB/phpbb/feed/factory.php b/phpBB/phpbb/feed/factory.php new file mode 100644 index 0000000000..f364f06d03 --- /dev/null +++ b/phpBB/phpbb/feed/factory.php @@ -0,0 +1,127 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* Factory class to return correct object +*/ +class factory +{ + /** + * Service container object + * @var ContainerInterface + */ + protected $container; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** + * Constructor + * + * @param ContainerInterface $container Container object + * @param \phpbb\config\config $config Config object + * @param \phpbb\db\driver\driver_interface $db Database connection + */ + public function __construct(ContainerInterface $container, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db) + { + $this->container = $container; + $this->config = $config; + $this->db = $db; + } + + /** + * Return correct object for specified mode + * + * @param string $mode The feeds mode. + * @param int $forum_id Forum id specified by the script if forum feed provided. + * @param int $topic_id Topic id specified by the script if topic feed provided. + * + * @return object Returns correct feeds object for specified mode. + */ + function get_feed($mode, $forum_id, $topic_id) + { + switch ($mode) + { + case 'forums': + if (!$this->config['feed_overall_forums']) + { + return false; + } + + return $this->container->get('feed.forums'); + break; + + case 'topics': + case 'topics_new': + if (!$this->config['feed_topics_new']) + { + return false; + } + + return $this->container->get('feed.topics'); + break; + + case 'topics_active': + if (!$this->config['feed_topics_active']) + { + return false; + } + + return $this->container->get('feed.topics_active'); + break; + + case 'news': + // Get at least one news forum + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE . ' + WHERE ' . $this->db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0'); + $result = $this->db->sql_query_limit($sql, 1, 0, 600); + $s_feed_news = (int) $this->db->sql_fetchfield('forum_id'); + $this->db->sql_freeresult($result); + + if (!$s_feed_news) + { + return false; + } + + return $this->container->get('feed.news'); + break; + + default: + if ($topic_id && $this->config['feed_topic']) + { + return $this->container->get('feed.topic') + ->set_topic_id($topic_id); + } + else if ($forum_id && $this->config['feed_forum']) + { + return $this->container->get('feed.forum') + ->set_forum_id($forum_id); + } + else if ($this->config['feed_overall']) + { + return $this->container->get('feed.overall'); + } + + return false; + break; + } + } +} diff --git a/phpBB/phpbb/feed/forum.php b/phpBB/phpbb/feed/forum.php new file mode 100644 index 0000000000..6aba12a147 --- /dev/null +++ b/phpBB/phpbb/feed/forum.php @@ -0,0 +1,146 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Forum feed +* +* This will give you the last {$this->num_items} posts made +* within a specific forum. +*/ +class forum extends \phpbb\feed\post_base +{ + var $forum_id = 0; + var $forum_data = array(); + + /** + * Set the Forum ID + * + * @param int $forum_id Forum ID + * @return \phpbb\feed\forum + */ + public function set_forum_id($forum_id) + { + $this->forum_id = (int) $forum_id; + + return $this; + } + + function open() + { + // Check if forum exists + $sql = 'SELECT forum_id, forum_name, forum_password, forum_type, forum_options + FROM ' . FORUMS_TABLE . ' + WHERE forum_id = ' . $this->forum_id; + $result = $this->db->sql_query($sql); + $this->forum_data = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (empty($this->forum_data)) + { + trigger_error('NO_FORUM'); + } + + // Forum needs to be postable + if ($this->forum_data['forum_type'] != FORUM_POST) + { + trigger_error('NO_FEED'); + } + + // Make sure forum is not excluded from feed + if (phpbb_optionget(FORUM_OPTION_FEED_EXCLUDE, $this->forum_data['forum_options'])) + { + trigger_error('NO_FEED'); + } + + // Make sure we can read this forum + if (!$this->auth->acl_get('f_read', $this->forum_id)) + { + trigger_error('SORRY_AUTH_READ'); + } + + // Make sure forum is not passworded or user is authed + if ($this->forum_data['forum_password']) + { + $forum_ids_passworded = $this->get_passworded_forums(); + + if (isset($forum_ids_passworded[$this->forum_id])) + { + trigger_error('SORRY_AUTH_READ'); + } + + unset($forum_ids_passworded); + } + + parent::open(); + } + + function get_sql() + { + // Determine topics with recent activity + $sql = 'SELECT topic_id, topic_last_post_time + FROM ' . TOPICS_TABLE . ' + WHERE forum_id = ' . $this->forum_id . ' + AND topic_moved_id = 0 + AND ' . $this->content_visibility->get_visibility_sql('topic', $this->forum_id) . ' + ORDER BY topic_last_post_time DESC, topic_last_post_id DESC'; + $result = $this->db->sql_query_limit($sql, $this->num_items); + + $topic_ids = array(); + $min_post_time = 0; + while ($row = $this->db->sql_fetchrow()) + { + $topic_ids[] = (int) $row['topic_id']; + + $min_post_time = (int) $row['topic_last_post_time']; + } + $this->db->sql_freeresult($result); + + if (empty($topic_ids)) + { + return false; + } + + parent::fetch_attachments(array(), $topic_ids); + + $this->sql = array( + 'SELECT' => 'p.post_id, p.topic_id, p.post_time, p.post_edit_time, p.post_visibility, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.post_attachment, ' . + 'u.username, u.user_id', + 'FROM' => array( + POSTS_TABLE => 'p', + USERS_TABLE => 'u', + ), + 'WHERE' => $this->db->sql_in_set('p.topic_id', $topic_ids) . ' + AND ' . $this->content_visibility->get_visibility_sql('post', $this->forum_id, 'p.') . ' + AND p.post_time >= ' . $min_post_time . ' + AND p.poster_id = u.user_id', + 'ORDER_BY' => 'p.post_time DESC, p.post_id DESC', + ); + + return true; + } + + function adjust_item(&$item_row, &$row) + { + parent::adjust_item($item_row, $row); + + $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; + $item_row['forum_id'] = $this->forum_id; + } + + function get_item() + { + return ($row = parent::get_item()) ? array_merge($this->forum_data, $row) : $row; + } +} diff --git a/phpBB/phpbb/feed/forums.php b/phpBB/phpbb/feed/forums.php new file mode 100644 index 0000000000..ee14a5bc76 --- /dev/null +++ b/phpBB/phpbb/feed/forums.php @@ -0,0 +1,68 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* 'All Forums' feed +* +* This will give you a list of all postable forums where feeds are enabled +* including forum description, topic stats and post stats +*/ +class forums extends \phpbb\feed\base +{ + var $num_items = 0; + + function set_keys() + { + $this->set('title', 'forum_name'); + $this->set('text', 'forum_desc'); + $this->set('bitfield', 'forum_desc_bitfield'); + $this->set('bbcode_uid','forum_desc_uid'); + $this->set('updated', 'forum_last_post_time'); + $this->set('options', 'forum_desc_options'); + } + + function get_sql() + { + $in_fid_ary = array_diff($this->get_readable_forums(), $this->get_excluded_forums()); + if (empty($in_fid_ary)) + { + return false; + } + + // Build SQL Query + $this->sql = array( + 'SELECT' => 'f.forum_id, f.left_id, f.forum_name, f.forum_last_post_time, + f.forum_desc, f.forum_desc_bitfield, f.forum_desc_uid, f.forum_desc_options, + f.forum_topics_approved, f.forum_posts_approved', + 'FROM' => array(FORUMS_TABLE => 'f'), + 'WHERE' => 'f.forum_type = ' . FORUM_POST . ' + AND ' . $this->db->sql_in_set('f.forum_id', $in_fid_ary), + 'ORDER_BY' => 'f.left_id ASC', + ); + + return true; + } + + function adjust_item(&$item_row, &$row) + { + $item_row['link'] = $this->helper->append_sid('viewforum.' . $this->phpEx, 'f=' . $row['forum_id']); + + if ($this->config['feed_item_statistics']) + { + $item_row['statistics'] = $this->user->lang('TOTAL_TOPICS', (int) $row['forum_topics_approved']) + . ' ' . $this->separator_stats . ' ' . $this->user->lang('TOTAL_POSTS_COUNT', (int) $row['forum_posts_approved']); + } + } +} diff --git a/phpBB/phpbb/feed/helper.php b/phpBB/phpbb/feed/helper.php new file mode 100644 index 0000000000..f2030f5ced --- /dev/null +++ b/phpBB/phpbb/feed/helper.php @@ -0,0 +1,179 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Class with some helpful functions used in feeds +*/ +class helper +{ + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\user */ + protected $user; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $phpEx; + + /** + * Constructor + * + * @param \phpbb\config\config $config Config object + * @param \phpbb\user $user User object + * @param string $phpbb_root_path Root path + * @param string $phpEx PHP file extension + */ + public function __construct(\phpbb\config\config $config, \phpbb\user $user, $phpbb_root_path, $phpEx) + { + $this->config = $config; + $this->user = $user; + $this->phpbb_root_path = $phpbb_root_path; + $this->phpEx = $phpEx; + } + + /** + * Run links through append_sid(), prepend generate_board_url() and remove session id + */ + public function get_board_url() + { + static $board_url; + + if (empty($board_url)) + { + $board_url = generate_board_url(); + } + + return $board_url; + } + + /** + * Run links through append_sid(), prepend generate_board_url() and remove session id + */ + public function append_sid($url, $params) + { + return append_sid($this->get_board_url() . '/' . $url, $params, true, ''); + } + + /** + * Generate ISO 8601 date string (RFC 3339) + */ + public function format_date($time) + { + static $zone_offset; + static $offset_string; + + if (empty($offset_string)) + { + $zone_offset = $this->user->create_datetime()->getOffset(); + $offset_string = phpbb_format_timezone_offset($zone_offset); + } + + return gmdate("Y-m-d\TH:i:s", $time + $zone_offset) . $offset_string; + } + + /** + * Generate text content + * + * @param string $content is feed text content + * @param string $uid is bbcode_uid + * @param string $bitfield is bbcode bitfield + * @param int $options bbcode flag options + * @param int $forum_id is the forum id + * @param array $post_attachments is an array containing the attachments and their respective info + * @return string the html content to be printed for the feed + */ + public function generate_content($content, $uid, $bitfield, $options, $forum_id, $post_attachments) + { + if (empty($content)) + { + return ''; + } + + // Prepare some bbcodes for better parsing + $content = preg_replace("#\[quote(=".*?")?:$uid\]\s*(.*?)\s*\[/quote:$uid\]#si", "[quote$1:$uid]<br />$2<br />[/quote:$uid]", $content); + + $content = generate_text_for_display($content, $uid, $bitfield, $options); + + // Add newlines + $content = str_replace('<br />', '<br />' . "\n", $content); + + // Convert smiley Relative paths to Absolute path, Windows style + $content = str_replace($this->phpbb_root_path . $this->config['smilies_path'], $this->get_board_url() . '/' . $this->config['smilies_path'], $content); + + // Remove "Select all" link and mouse events + $content = str_replace('<a href="#" onclick="selectCode(this); return false;">' . $this->user->lang['SELECT_ALL_CODE'] . '</a>', '', $content); + $content = preg_replace('#(onkeypress|onclick)="(.*?)"#si', '', $content); + + // Firefox does not support CSS for feeds, though + + // Remove font sizes + // $content = preg_replace('#<span style="font-size: [0-9]+%; line-height: [0-9]+%;">([^>]+)</span>#iU', '\1', $content); + + // Make text strong :P + // $content = preg_replace('#<span style="font-weight: bold?">(.*?)</span>#iU', '<strong>\1</strong>', $content); + + // Italic + // $content = preg_replace('#<span style="font-style: italic?">([^<]+)</span>#iU', '<em>\1</em>', $content); + + // Underline + // $content = preg_replace('#<span style="text-decoration: underline?">([^<]+)</span>#iU', '<u>\1</u>', $content); + + // Remove embed Windows Media Streams + $content = preg_replace( '#<\!--\[if \!IE\]>-->([^[]+)<\!--<!\[endif\]-->#si', '', $content); + + // Do not use < and >, because we want to retain code contained in [code][/code] + + // Remove embed and objects + $content = preg_replace( '#<(object|embed)(.*?) (value|src)=(.*?) ([^[]+)(object|embed)>#si',' <a href=$4 target="_blank"><strong>$1</strong></a> ',$content); + + // Remove some specials html tag, because somewhere there are a mod to allow html tags ;) + $content = preg_replace( '#<(script|iframe)([^[]+)\1>#siU', ' <strong>$1</strong> ', $content); + + // Parse inline images to display with the feed + if (!empty($post_attachments)) + { + $update_count = array(); + parse_attachments($forum_id, $content, $post_attachments, $update_count); + $content .= implode('<br />', $post_attachments); + + // Convert attachments' relative path to absolute path + $content = str_replace($this->phpbb_root_path . 'download/file.' . $this->phpEx, $this->get_board_url() . '/download/file.' . $this->phpEx, $content); + } + + // Remove Comments from inline attachments [ia] + $content = preg_replace('#<dd>(.*?)</dd>#','',$content); + + // Replace some entities with their unicode counterpart + $entities = array( + ' ' => "\xC2\xA0", + '•' => "\xE2\x80\xA2", + '·' => "\xC2\xB7", + '©' => "\xC2\xA9", + ); + + $content = str_replace(array_keys($entities), array_values($entities), $content); + + // Remove CDATA blocks. ;) + $content = preg_replace('#\<\!\[CDATA\[(.*?)\]\]\>#s', '', $content); + + // Other control characters + $content = preg_replace('#(?:[\x00-\x1F\x7F]+|(?:\xC2[\x80-\x9F])+)#', '', $content); + + return $content; + } +} diff --git a/phpBB/phpbb/feed/news.php b/phpBB/phpbb/feed/news.php new file mode 100644 index 0000000000..5d4786518b --- /dev/null +++ b/phpBB/phpbb/feed/news.php @@ -0,0 +1,109 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* News feed +* +* This will give you {$this->num_items} first posts +* of all topics in the selected news forums. +*/ +class news extends \phpbb\feed\topic_base +{ + function get_news_forums() + { + static $forum_ids; + + // Matches acp/acp_board.php + $cache_name = 'feed_news_forum_ids'; + + if (!isset($forum_ids) && ($forum_ids = $this->cache->get('_' . $cache_name)) === false) + { + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE . ' + WHERE ' . $this->db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0'); + $result = $this->db->sql_query($sql); + + $forum_ids = array(); + while ($forum_id = (int) $this->db->sql_fetchfield('forum_id')) + { + $forum_ids[$forum_id] = $forum_id; + } + $this->db->sql_freeresult($result); + + $this->cache->put('_' . $cache_name, $forum_ids); + } + + return $forum_ids; + } + + function get_sql() + { + // Determine forum ids + $in_fid_ary = array_intersect($this->get_news_forums(), $this->get_readable_forums()); + if (empty($in_fid_ary)) + { + return false; + } + + $in_fid_ary = array_diff($in_fid_ary, $this->get_passworded_forums()); + if (empty($in_fid_ary)) + { + return false; + } + + // We really have to get the post ids first! + $sql = 'SELECT topic_first_post_id, topic_time + FROM ' . TOPICS_TABLE . ' + WHERE topic_moved_id = 0 + AND ' . $this->content_visibility->get_forums_visibility_sql('topic', $in_fid_ary) . ' + ORDER BY topic_time DESC'; + $result = $this->db->sql_query_limit($sql, $this->num_items); + + $post_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $post_ids[] = (int) $row['topic_first_post_id']; + } + $this->db->sql_freeresult($result); + + if (empty($post_ids)) + { + return false; + } + + parent::fetch_attachments($post_ids); + + $this->sql = array( + 'SELECT' => 'f.forum_id, f.forum_name, + t.topic_id, t.topic_title, t.topic_poster, t.topic_first_poster_name, t.topic_posts_approved, t.topic_posts_unapproved, t.topic_posts_softdeleted, t.topic_views, t.topic_time, t.topic_last_post_time, + p.post_id, p.post_time, p.post_edit_time, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.post_attachment, t.topic_visibility', + 'FROM' => array( + TOPICS_TABLE => 't', + POSTS_TABLE => 'p', + ), + 'LEFT_JOIN' => array( + array( + 'FROM' => array(FORUMS_TABLE => 'f'), + 'ON' => 'p.forum_id = f.forum_id', + ), + ), + 'WHERE' => 'p.topic_id = t.topic_id + AND ' . $this->db->sql_in_set('p.post_id', $post_ids), + 'ORDER_BY' => 'p.post_time DESC, p.post_id DESC', + ); + + return true; + } +} diff --git a/phpBB/phpbb/feed/overall.php b/phpBB/phpbb/feed/overall.php new file mode 100644 index 0000000000..1176a9c182 --- /dev/null +++ b/phpBB/phpbb/feed/overall.php @@ -0,0 +1,88 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Board wide feed (aka overall feed) +* +* This will give you the newest {$this->num_items} posts +* from the whole board. +*/ +class overall extends \phpbb\feed\post_base +{ + function get_sql() + { + $forum_ids = array_diff($this->get_readable_forums(), $this->get_excluded_forums(), $this->get_passworded_forums()); + if (empty($forum_ids)) + { + return false; + } + + // Determine topics with recent activity + $sql = 'SELECT topic_id, topic_last_post_time + FROM ' . TOPICS_TABLE . ' + WHERE topic_moved_id = 0 + AND ' . $this->content_visibility->get_forums_visibility_sql('topic', $forum_ids) . ' + ORDER BY topic_last_post_time DESC, topic_last_post_id DESC'; + $result = $this->db->sql_query_limit($sql, $this->num_items); + + $topic_ids = array(); + $min_post_time = 0; + while ($row = $this->db->sql_fetchrow()) + { + $topic_ids[] = (int) $row['topic_id']; + + $min_post_time = (int) $row['topic_last_post_time']; + } + $this->db->sql_freeresult($result); + + if (empty($topic_ids)) + { + return false; + } + + parent::fetch_attachments(array(), $topic_ids); + + // Get the actual data + $this->sql = array( + 'SELECT' => 'f.forum_id, f.forum_name, ' . + 'p.post_id, p.topic_id, p.post_time, p.post_edit_time, p.post_visibility, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.post_attachment, ' . + 'u.username, u.user_id', + 'FROM' => array( + USERS_TABLE => 'u', + POSTS_TABLE => 'p', + ), + 'LEFT_JOIN' => array( + array( + 'FROM' => array(FORUMS_TABLE => 'f'), + 'ON' => 'f.forum_id = p.forum_id', + ), + ), + 'WHERE' => $this->db->sql_in_set('p.topic_id', $topic_ids) . ' + AND ' . $this->content_visibility->get_forums_visibility_sql('post', $forum_ids, 'p.') . ' + AND p.post_time >= ' . $min_post_time . ' + AND u.user_id = p.poster_id', + 'ORDER_BY' => 'p.post_time DESC, p.post_id DESC', + ); + + return true; + } + + function adjust_item(&$item_row, &$row) + { + parent::adjust_item($item_row, $row); + + $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; + } +} diff --git a/phpBB/phpbb/feed/post_base.php b/phpBB/phpbb/feed/post_base.php new file mode 100644 index 0000000000..011775b6af --- /dev/null +++ b/phpBB/phpbb/feed/post_base.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Abstract class for post based feeds +*/ +abstract class post_base extends \phpbb\feed\attachments_base +{ + var $num_items = 'feed_limit_post'; + var $attachments = array(); + + function set_keys() + { + $this->set('title', 'post_subject'); + $this->set('title2', 'topic_title'); + + $this->set('author_id', 'user_id'); + $this->set('creator', 'username'); + $this->set('published', 'post_time'); + $this->set('updated', 'post_edit_time'); + $this->set('text', 'post_text'); + + $this->set('bitfield', 'bbcode_bitfield'); + $this->set('bbcode_uid','bbcode_uid'); + + $this->set('enable_bbcode', 'enable_bbcode'); + $this->set('enable_smilies', 'enable_smilies'); + $this->set('enable_magic_url', 'enable_magic_url'); + } + + function adjust_item(&$item_row, &$row) + { + $item_row['link'] = $this->helper->append_sid('viewtopic.' . $this->phpEx, "t={$row['topic_id']}&p={$row['post_id']}#p{$row['post_id']}"); + + if ($this->config['feed_item_statistics']) + { + $item_row['statistics'] = $this->user->lang['POSTED'] . ' ' . $this->user->lang['POST_BY_AUTHOR'] . ' ' . $this->user_viewprofile($row) + . ' ' . $this->separator_stats . ' ' . $this->user->format_date($row[$this->get('published')]) + . (($this->is_moderator_approve_forum($row['forum_id']) && (int) $row['post_visibility'] === ITEM_UNAPPROVED) ? ' ' . $this->separator_stats . ' ' . $this->user->lang['POST_UNAPPROVED'] : '') + . (($this->is_moderator_approve_forum($row['forum_id']) && (int) $row['post_visibility'] === ITEM_DELETED) ? ' ' . $this->separator_stats . ' ' . $this->user->lang['POST_DELETED'] : ''); + } + } +} diff --git a/phpBB/phpbb/feed/topic.php b/phpBB/phpbb/feed/topic.php new file mode 100644 index 0000000000..295bf3f795 --- /dev/null +++ b/phpBB/phpbb/feed/topic.php @@ -0,0 +1,123 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Topic feed for a specific topic +* +* This will give you the last {$this->num_items} posts made within this topic. +*/ +class topic extends \phpbb\feed\post_base +{ + var $topic_id = 0; + var $forum_id = 0; + var $topic_data = array(); + + /** + * Set the Topic ID + * + * @param int $topic_id Topic ID + * @return \phpbb\feed\topic + */ + public function set_topic_id($topic_id) + { + $this->topic_id = (int) $topic_id; + + return $this; + } + + function open() + { + $sql = 'SELECT f.forum_options, f.forum_password, t.topic_id, t.forum_id, t.topic_visibility, t.topic_title, t.topic_time, t.topic_views, t.topic_posts_approved, t.topic_type + FROM ' . TOPICS_TABLE . ' t + LEFT JOIN ' . FORUMS_TABLE . ' f + ON (f.forum_id = t.forum_id) + WHERE t.topic_id = ' . $this->topic_id; + $result = $this->db->sql_query($sql); + $this->topic_data = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (empty($this->topic_data)) + { + trigger_error('NO_TOPIC'); + } + + $this->forum_id = (int) $this->topic_data['forum_id']; + + // Make sure topic is either approved or user authed + if ($this->topic_data['topic_visibility'] != ITEM_APPROVED && !$this->auth->acl_get('m_approve', $this->forum_id)) + { + trigger_error('SORRY_AUTH_READ'); + } + + // Make sure forum is not excluded from feed + if (phpbb_optionget(FORUM_OPTION_FEED_EXCLUDE, $this->topic_data['forum_options'])) + { + trigger_error('NO_FEED'); + } + + // Make sure we can read this forum + if (!$this->auth->acl_get('f_read', $this->forum_id)) + { + trigger_error('SORRY_AUTH_READ'); + } + + // Make sure forum is not passworded or user is authed + if ($this->topic_data['forum_password']) + { + $forum_ids_passworded = $this->get_passworded_forums(); + + if (isset($forum_ids_passworded[$this->forum_id])) + { + trigger_error('SORRY_AUTH_READ'); + } + + unset($forum_ids_passworded); + } + + parent::open(); + } + + function get_sql() + { + parent::fetch_attachments(); + + $this->sql = array( + 'SELECT' => 'p.post_id, p.post_time, p.post_edit_time, p.post_visibility, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.post_attachment, ' . + 'u.username, u.user_id', + 'FROM' => array( + POSTS_TABLE => 'p', + USERS_TABLE => 'u', + ), + 'WHERE' => 'p.topic_id = ' . $this->topic_id . ' + AND ' . $this->content_visibility->get_visibility_sql('post', $this->forum_id, 'p.') . ' + AND p.poster_id = u.user_id', + 'ORDER_BY' => 'p.post_time DESC, p.post_id DESC', + ); + + return true; + } + + function adjust_item(&$item_row, &$row) + { + parent::adjust_item($item_row, $row); + + $item_row['forum_id'] = $this->forum_id; + } + + function get_item() + { + return ($row = parent::get_item()) ? array_merge($this->topic_data, $row) : $row; + } +} diff --git a/phpBB/phpbb/feed/topic_base.php b/phpBB/phpbb/feed/topic_base.php new file mode 100644 index 0000000000..f9ff368cba --- /dev/null +++ b/phpBB/phpbb/feed/topic_base.php @@ -0,0 +1,70 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Abstract class for topic based feeds +*/ +abstract class topic_base extends \phpbb\feed\attachments_base +{ + var $num_items = 'feed_limit_topic'; + + function set_keys() + { + $this->set('title', 'topic_title'); + $this->set('title2', 'forum_name'); + + $this->set('author_id', 'topic_poster'); + $this->set('creator', 'topic_first_poster_name'); + $this->set('published', 'post_time'); + $this->set('updated', 'post_edit_time'); + $this->set('text', 'post_text'); + + $this->set('bitfield', 'bbcode_bitfield'); + $this->set('bbcode_uid','bbcode_uid'); + + $this->set('enable_bbcode', 'enable_bbcode'); + $this->set('enable_smilies', 'enable_smilies'); + $this->set('enable_magic_url', 'enable_magic_url'); + } + + function adjust_item(&$item_row, &$row) + { + $item_row['link'] = $this->helper->append_sid('viewtopic.' . $this->phpEx, 't=' . $row['topic_id'] . '&p=' . $row['post_id'] . '#p' . $row['post_id']); + + if ($this->config['feed_item_statistics']) + { + $item_row['statistics'] = $this->user->lang['POSTED'] . ' ' . $this->user->lang['POST_BY_AUTHOR'] . ' ' . $this->user_viewprofile($row) + . ' ' . $this->separator_stats . ' ' . $this->user->format_date($row[$this->get('published')]) + . ' ' . $this->separator_stats . ' ' . $this->user->lang['REPLIES'] . ' ' . ($this->content_visibility->get_count('topic_posts', $row, $row['forum_id']) - 1) + . ' ' . $this->separator_stats . ' ' . $this->user->lang['VIEWS'] . ' ' . $row['topic_views']; + + if ($this->is_moderator_approve_forum($row['forum_id'])) + { + if ((int) $row['topic_visibility'] === ITEM_DELETED) + { + $item_row['statistics'] .= ' ' . $this->separator_stats . ' ' . $this->user->lang['TOPIC_DELETED']; + } + else if ((int) $row['topic_visibility'] === ITEM_UNAPPROVED) + { + $item_row['statistics'] .= ' ' . $this->separator_stats . ' ' . $this->user->lang['TOPIC_UNAPPROVED']; + } + else if ($row['topic_posts_unapproved']) + { + $item_row['statistics'] .= ' ' . $this->separator_stats . ' ' . $this->user->lang['POSTS_UNAPPROVED']; + } + } + } + } +} diff --git a/phpBB/phpbb/feed/topics.php b/phpBB/phpbb/feed/topics.php new file mode 100644 index 0000000000..e6416bc064 --- /dev/null +++ b/phpBB/phpbb/feed/topics.php @@ -0,0 +1,88 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* New Topics feed +* +* This will give you the last {$this->num_items} created topics +* including the first post. +*/ +class topics extends \phpbb\feed\topic_base +{ + function get_sql() + { + $forum_ids_read = $this->get_readable_forums(); + if (empty($forum_ids_read)) + { + return false; + } + + $in_fid_ary = array_diff($forum_ids_read, $this->get_excluded_forums(), $this->get_passworded_forums()); + if (empty($in_fid_ary)) + { + return false; + } + + // We really have to get the post ids first! + $sql = 'SELECT topic_first_post_id, topic_time + FROM ' . TOPICS_TABLE . ' + WHERE topic_moved_id = 0 + AND ' . $this->content_visibility->get_forums_visibility_sql('topic', $in_fid_ary) . ' + ORDER BY topic_time DESC'; + $result = $this->db->sql_query_limit($sql, $this->num_items); + + $post_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $post_ids[] = (int) $row['topic_first_post_id']; + } + $this->db->sql_freeresult($result); + + if (empty($post_ids)) + { + return false; + } + + parent::fetch_attachments($post_ids); + + $this->sql = array( + 'SELECT' => 'f.forum_id, f.forum_name, + t.topic_id, t.topic_title, t.topic_poster, t.topic_first_poster_name, t.topic_posts_approved, t.topic_posts_unapproved, t.topic_posts_softdeleted, t.topic_views, t.topic_time, t.topic_last_post_time, + p.post_id, p.post_time, p.post_edit_time, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.post_attachment, t.topic_visibility', + 'FROM' => array( + TOPICS_TABLE => 't', + POSTS_TABLE => 'p', + ), + 'LEFT_JOIN' => array( + array( + 'FROM' => array(FORUMS_TABLE => 'f'), + 'ON' => 'p.forum_id = f.forum_id', + ), + ), + 'WHERE' => 'p.topic_id = t.topic_id + AND ' . $this->db->sql_in_set('p.post_id', $post_ids), + 'ORDER_BY' => 'p.post_time DESC, p.post_id DESC', + ); + + return true; + } + + function adjust_item(&$item_row, &$row) + { + parent::adjust_item($item_row, $row); + + $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; + } +} diff --git a/phpBB/phpbb/feed/topics_active.php b/phpBB/phpbb/feed/topics_active.php new file mode 100644 index 0000000000..3b751f3233 --- /dev/null +++ b/phpBB/phpbb/feed/topics_active.php @@ -0,0 +1,133 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\feed; + +/** +* Active Topics feed +* +* This will give you the last {$this->num_items} topics +* with replies made withing the last {$this->sort_days} days +* including the last post. +*/ +class topics_active extends \phpbb\feed\topic_base +{ + var $sort_days = 7; + + function set_keys() + { + parent::set_keys(); + + $this->set('author_id', 'topic_last_poster_id'); + $this->set('creator', 'topic_last_poster_name'); + } + + function get_sql() + { + $forum_ids_read = $this->get_readable_forums(); + if (empty($forum_ids_read)) + { + return false; + } + + $in_fid_ary = array_intersect($forum_ids_read, $this->get_forum_ids()); + $in_fid_ary = array_diff($in_fid_ary, $this->get_passworded_forums()); + if (empty($in_fid_ary)) + { + return false; + } + + // Search for topics in last X days + $last_post_time_sql = ($this->sort_days) ? ' AND topic_last_post_time > ' . (time() - ($this->sort_days * 24 * 3600)) : ''; + + // We really have to get the post ids first! + $sql = 'SELECT topic_last_post_id, topic_last_post_time + FROM ' . TOPICS_TABLE . ' + WHERE topic_moved_id = 0 + AND ' . $this->content_visibility->get_forums_visibility_sql('topic', $in_fid_ary) . ' + ' . $last_post_time_sql . ' + ORDER BY topic_last_post_time DESC, topic_last_post_id DESC'; + $result = $this->db->sql_query_limit($sql, $this->num_items); + + $post_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $post_ids[] = (int) $row['topic_last_post_id']; + } + $this->db->sql_freeresult($result); + + if (empty($post_ids)) + { + return false; + } + + parent::fetch_attachments($post_ids); + + $this->sql = array( + 'SELECT' => 'f.forum_id, f.forum_name, + t.topic_id, t.topic_title, t.topic_posts_approved, t.topic_posts_unapproved, t.topic_posts_softdeleted, t.topic_views, + t.topic_last_poster_id, t.topic_last_poster_name, t.topic_last_post_time, + p.post_id, p.post_time, p.post_edit_time, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, p.post_attachment, t.topic_visibility', + 'FROM' => array( + TOPICS_TABLE => 't', + POSTS_TABLE => 'p', + ), + 'LEFT_JOIN' => array( + array( + 'FROM' => array(FORUMS_TABLE => 'f'), + 'ON' => 'p.forum_id = f.forum_id', + ), + ), + 'WHERE' => 'p.topic_id = t.topic_id + AND ' . $this->db->sql_in_set('p.post_id', $post_ids), + 'ORDER_BY' => 'p.post_time DESC, p.post_id DESC', + ); + + return true; + } + + function get_forum_ids() + { + static $forum_ids; + + $cache_name = 'feed_topic_active_forum_ids'; + + if (!isset($forum_ids) && ($forum_ids = $this->cache->get('_' . $cache_name)) === false) + { + $sql = 'SELECT forum_id + FROM ' . FORUMS_TABLE . ' + WHERE forum_type = ' . FORUM_POST . ' + AND ' . $this->db->sql_bit_and('forum_options', FORUM_OPTION_FEED_EXCLUDE, '= 0') . ' + AND ' . $this->db->sql_bit_and('forum_flags', log(FORUM_FLAG_ACTIVE_TOPICS, 2), '<> 0'); + $result = $this->db->sql_query($sql); + + $forum_ids = array(); + while ($forum_id = (int) $this->db->sql_fetchfield('forum_id')) + { + $forum_ids[$forum_id] = $forum_id; + } + $this->db->sql_freeresult($result); + + $this->cache->put('_' . $cache_name, $forum_ids, 180); + } + + return $forum_ids; + } + + function adjust_item(&$item_row, &$row) + { + parent::adjust_item($item_row, $row); + + $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; + } +} diff --git a/phpBB/phpbb/file_downloader.php b/phpBB/phpbb/file_downloader.php new file mode 100644 index 0000000000..ab9505a14c --- /dev/null +++ b/phpBB/phpbb/file_downloader.php @@ -0,0 +1,120 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +class file_downloader +{ + /** @var string Error string */ + protected $error_string = ''; + + /** @var int Error number */ + protected $error_number = 0; + + /** + * Retrieve contents from remotely stored file + * + * @param string $host File host + * @param string $directory Directory file is in + * @param string $filename Filename of file to retrieve + * @param int $port Port to connect to; default: 80 + * @param int $timeout Connection timeout in seconds; default: 6 + * + * @return mixed File data as string if file can be read and there is no + * timeout, false if there were errors or the connection timed out + * + * @throws \phpbb\exception\runtime_exception If data can't be retrieved and no error + * message is returned + */ + public function get($host, $directory, $filename, $port = 80, $timeout = 6) + { + // Set default values for error variables + $this->error_number = 0; + $this->error_string = ''; + + if ($socket = @fsockopen(($port == 443 ? 'tls://' : '') . $host, $port, $this->error_number, $this->error_string, $timeout)) + { + @fputs($socket, "GET $directory/$filename HTTP/1.0\r\n"); + @fputs($socket, "HOST: $host\r\n"); + @fputs($socket, "Connection: close\r\n\r\n"); + + $timer_stop = time() + $timeout; + stream_set_timeout($socket, $timeout); + + $file_info = ''; + $get_info = false; + + while (!@feof($socket)) + { + if ($get_info) + { + $file_info .= @fread($socket, 1024); + } + else + { + $line = @fgets($socket, 1024); + if ($line == "\r\n") + { + $get_info = true; + } + else if (stripos($line, '404 not found') !== false) + { + throw new \phpbb\exception\runtime_exception('FILE_NOT_FOUND', array($filename)); + } + } + + $stream_meta_data = stream_get_meta_data($socket); + + if (!empty($stream_meta_data['timed_out']) || time() >= $timer_stop) + { + throw new \phpbb\exception\runtime_exception('FSOCK_TIMEOUT'); + } + } + @fclose($socket); + } + else + { + if ($this->error_string) + { + $this->error_string = utf8_convert_message($this->error_string); + return false; + } + else + { + throw new \phpbb\exception\runtime_exception('FSOCK_DISABLED'); + } + } + + return $file_info; + } + + /** + * Get error string + * + * @return string Error string + */ + public function get_error_string() + { + return $this->error_string; + } + + /** + * Get error number + * + * @return int Error number + */ + public function get_error_number() + { + return $this->error_number; + } +} diff --git a/phpBB/phpbb/filesystem.php b/phpBB/phpbb/filesystem.php new file mode 100644 index 0000000000..77517082e5 --- /dev/null +++ b/phpBB/phpbb/filesystem.php @@ -0,0 +1,50 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* A class with various functions that are related to paths, files and the filesystem +*/ +class filesystem +{ + /** + * Eliminates useless . and .. components from specified path. + * + * @param string $path Path to clean + * @return string Cleaned path + */ + public function clean_path($path) + { + $exploded = explode('/', $path); + $filtered = array(); + foreach ($exploded as $part) + { + if ($part === '.' && !empty($filtered)) + { + continue; + } + + if ($part === '..' && !empty($filtered) && $filtered[sizeof($filtered) - 1] !== '.' && $filtered[sizeof($filtered) - 1] !== '..') + { + array_pop($filtered); + } + else + { + $filtered[] = $part; + } + } + $path = implode('/', $filtered); + return $path; + } +} diff --git a/phpBB/phpbb/finder.php b/phpBB/phpbb/finder.php new file mode 100644 index 0000000000..28f28825ba --- /dev/null +++ b/phpBB/phpbb/finder.php @@ -0,0 +1,547 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* The finder provides a simple way to locate files in the core and a set of extensions +*/ +class finder +{ + protected $extensions; + protected $filesystem; + protected $phpbb_root_path; + protected $cache; + protected $php_ext; + + /** + * The cache variable name used to store $this->cached_queries in $this->cache. + * + * Allows the use of multiple differently configured finders with the same cache. + * @var string + */ + protected $cache_name; + + /** + * An associative array, containing all search parameters set in methods. + * @var array + */ + protected $query; + + /** + * A map from md5 hashes of serialized queries to their previously retrieved + * results. + * @var array + */ + protected $cached_queries; + + /** + * Creates a new finder instance with its dependencies + * + * @param \phpbb\filesystem $filesystem Filesystem instance + * @param string $phpbb_root_path Path to the phpbb root directory + * @param \phpbb\cache\driver\driver_interface $cache A cache instance or null + * @param string $php_ext php file extension + * @param string $cache_name The name of the cache variable, defaults to + * _ext_finder + */ + public function __construct(\phpbb\filesystem $filesystem, $phpbb_root_path = '', \phpbb\cache\driver\driver_interface $cache = null, $php_ext = 'php', $cache_name = '_ext_finder') + { + $this->filesystem = $filesystem; + $this->phpbb_root_path = $phpbb_root_path; + $this->cache = $cache; + $this->php_ext = $php_ext; + $this->cache_name = $cache_name; + + $this->query = array( + 'core_path' => false, + 'core_suffix' => false, + 'core_prefix' => false, + 'core_directory' => false, + 'extension_suffix' => false, + 'extension_prefix' => false, + 'extension_directory' => false, + ); + $this->extensions = array(); + + $this->cached_queries = ($this->cache) ? $this->cache->get($this->cache_name) : false; + } + + /** + * Set the array of extensions + * + * @param array $extensions A list of extensions that should be searched aswell + * @param bool $replace_list Should the list be emptied before adding the extensions + * @return \phpbb\finder This object for chaining calls + */ + public function set_extensions(array $extensions, $replace_list = true) + { + if ($replace_list) + { + $this->extensions = array(); + } + + foreach ($extensions as $ext_name) + { + $this->extensions[$ext_name] = $this->phpbb_root_path . 'ext/' . $ext_name . '/'; + } + return $this; + } + + /** + * Sets a core path to be searched in addition to extensions + * + * @param string $core_path The path relative to phpbb_root_path + * @return \phpbb\finder This object for chaining calls + */ + public function core_path($core_path) + { + $this->query['core_path'] = $core_path; + return $this; + } + + /** + * Sets the suffix all files found in extensions and core must match. + * + * There is no default file extension, so to find PHP files only, you will + * have to specify .php as a suffix. However when using get_classes, the .php + * file extension is automatically added to suffixes. + * + * @param string $suffix A filename suffix + * @return \phpbb\finder This object for chaining calls + */ + public function suffix($suffix) + { + $this->core_suffix($suffix); + $this->extension_suffix($suffix); + return $this; + } + + /** + * Sets a suffix all files found in extensions must match + * + * There is no default file extension, so to find PHP files only, you will + * have to specify .php as a suffix. However when using get_classes, the .php + * file extension is automatically added to suffixes. + * + * @param string $extension_suffix A filename suffix + * @return \phpbb\finder This object for chaining calls + */ + public function extension_suffix($extension_suffix) + { + $this->query['extension_suffix'] = $extension_suffix; + return $this; + } + + /** + * Sets a suffix all files found in the core path must match + * + * There is no default file extension, so to find PHP files only, you will + * have to specify .php as a suffix. However when using get_classes, the .php + * file extension is automatically added to suffixes. + * + * @param string $core_suffix A filename suffix + * @return \phpbb\finder This object for chaining calls + */ + public function core_suffix($core_suffix) + { + $this->query['core_suffix'] = $core_suffix; + return $this; + } + + /** + * Sets the prefix all files found in extensions and core must match + * + * @param string $prefix A filename prefix + * @return \phpbb\finder This object for chaining calls + */ + public function prefix($prefix) + { + $this->core_prefix($prefix); + $this->extension_prefix($prefix); + return $this; + } + + /** + * Sets a prefix all files found in extensions must match + * + * @param string $extension_prefix A filename prefix + * @return \phpbb\finder This object for chaining calls + */ + public function extension_prefix($extension_prefix) + { + $this->query['extension_prefix'] = $extension_prefix; + return $this; + } + + /** + * Sets a prefix all files found in the core path must match + * + * @param string $core_prefix A filename prefix + * @return \phpbb\finder This object for chaining calls + */ + public function core_prefix($core_prefix) + { + $this->query['core_prefix'] = $core_prefix; + return $this; + } + + /** + * Sets a directory all files found in extensions and core must be contained in + * + * Automatically sets the core_directory if its value does not differ from + * the current directory. + * + * @param string $directory + * @return \phpbb\finder This object for chaining calls + */ + public function directory($directory) + { + $this->core_directory($directory); + $this->extension_directory($directory); + return $this; + } + + /** + * Sets a directory all files found in extensions must be contained in + * + * @param string $extension_directory + * @return \phpbb\finder This object for chaining calls + */ + public function extension_directory($extension_directory) + { + $this->query['extension_directory'] = $this->sanitise_directory($extension_directory); + return $this; + } + + /** + * Sets a directory all files found in the core path must be contained in + * + * @param string $core_directory + * @return \phpbb\finder This object for chaining calls + */ + public function core_directory($core_directory) + { + $this->query['core_directory'] = $this->sanitise_directory($core_directory); + return $this; + } + + /** + * Removes occurances of /./ and makes sure path ends without trailing slash + * + * @param string $directory A directory pattern + * @return string A cleaned up directory pattern + */ + protected function sanitise_directory($directory) + { + $directory = $this->filesystem->clean_path($directory); + $dir_len = strlen($directory); + + if ($dir_len > 1 && $directory[$dir_len - 1] === '/') + { + $directory = substr($directory, 0, -1); + } + + return $directory; + } + + /** + * Finds classes matching the configured options if they follow phpBB naming rules. + * + * The php file extension is automatically added to suffixes. + * + * Note: If a file is matched but contains a class name not following the + * phpBB naming rules an incorrect class name will be returned. + * + * @param bool $cache Whether the result should be cached + * @return array An array of found class names + */ + public function get_classes($cache = true) + { + $this->query['extension_suffix'] .= '.' . $this->php_ext; + $this->query['core_suffix'] .= '.' . $this->php_ext; + + $files = $this->find($cache, false); + + return $this->get_classes_from_files($files); + } + + /** + * Get class names from a list of files + * + * @param array $files Array of files (from find()) + * @return array Array of class names + */ + public function get_classes_from_files($files) + { + $classes = array(); + foreach ($files as $file => $ext_name) + { + $class = substr($file, 0, -strlen('.' . $this->php_ext)); + if ($ext_name === '/' && preg_match('#^includes/#', $file)) + { + $class = preg_replace('#^includes/#', '', $class); + $classes[] = 'phpbb_' . str_replace('/', '_', $class); + } + else + { + $class = preg_replace('#^ext/#', '', $class); + $classes[] = '\\' . str_replace('/', '\\', $class); + } + } + return $classes; + } + + /** + * Finds all directories matching the configured options + * + * @param bool $cache Whether the result should be cached + * @param bool $extension_keys Whether the result should have extension name as array key + * @return array An array of paths to found directories + */ + public function get_directories($cache = true, $extension_keys = false) + { + return $this->find_with_root_path($cache, true, $extension_keys); + } + + /** + * Finds all files matching the configured options. + * + * @param bool $cache Whether the result should be cached + * @return array An array of paths to found files + */ + public function get_files($cache = true) + { + return $this->find_with_root_path($cache, false); + } + + /** + * A wrapper around the general find which prepends a root path to results + * + * @param bool $cache Whether the result should be cached + * @param bool $is_dir Directories will be returned when true, only files + * otherwise + * @param bool $extension_keys If true, result will be associative array + * with extension name as key + * @return array An array of paths to found items + */ + protected function find_with_root_path($cache = true, $is_dir = false, $extension_keys = false) + { + $items = $this->find($cache, $is_dir); + + $result = array(); + foreach ($items as $item => $ext_name) + { + if ($extension_keys) + { + $result[$ext_name] = $this->phpbb_root_path . $item; + } + else + { + $result[] = $this->phpbb_root_path . $item; + } + } + + return $result; + } + + /** + * Finds all file system entries matching the configured options + * + * @param bool $cache Whether the result should be cached + * @param bool $is_dir Directories will be returned when true, only files + * otherwise + * @return array An array of paths to found items + */ + public function find($cache = true, $is_dir = false) + { + $extensions = $this->extensions; + if ($this->query['core_path']) + { + $extensions['/'] = $this->phpbb_root_path . $this->query['core_path']; + } + + $files = array(); + $file_list = $this->find_from_paths($extensions, $cache, $is_dir); + + foreach ($file_list as $file) + { + $files[$file['named_path']] = $file['ext_name']; + } + + return $files; + } + + /** + * Finds all file system entries matching the configured options for one + * specific extension + * + * @param string $extension_name Name of the extension + * @param string $extension_path Relative path to the extension root directory + * @param bool $cache Whether the result should be cached + * @param bool $is_dir Directories will be returned when true, only files + * otherwise + * @return array An array of paths to found items + */ + public function find_from_extension($extension_name, $extension_path, $cache = true, $is_dir = false) + { + $extensions = array( + $extension_name => $extension_path, + ); + + $files = array(); + $file_list = $this->find_from_paths($extensions, $cache, $is_dir); + + foreach ($file_list as $file) + { + $files[$file['named_path']] = $file['ext_name']; + } + + return $files; + } + + /** + * Finds all file system entries matching the configured options from + * an array of paths + * + * @param array $extensions Array of extensions (name => full relative path) + * @param bool $cache Whether the result should be cached + * @param bool $is_dir Directories will be returned when true, only files + * otherwise + * @return array An array of paths to found items + */ + public function find_from_paths($extensions, $cache = true, $is_dir = false) + { + $this->query['is_dir'] = $is_dir; + $query = md5(serialize($this->query) . serialize($extensions)); + + if (!defined('DEBUG') && $cache && isset($this->cached_queries[$query])) + { + return $this->cached_queries[$query]; + } + + $files = array(); + + foreach ($extensions as $name => $path) + { + $ext_name = $name; + + if (!file_exists($path)) + { + continue; + } + + if ($name === '/') + { + $location = $this->query['core_path']; + $name = ''; + $suffix = $this->query['core_suffix']; + $prefix = $this->query['core_prefix']; + $directory = $this->query['core_directory']; + } + else + { + $location = 'ext/'; + $name .= '/'; + $suffix = $this->query['extension_suffix']; + $prefix = $this->query['extension_prefix']; + $directory = $this->query['extension_directory']; + } + + // match only first directory if leading slash is given + if ($directory === '/') + { + $directory_pattern = '^' . preg_quote(DIRECTORY_SEPARATOR, '#'); + } + else if ($directory && $directory[0] === '/') + { + if (!$is_dir) + { + $path .= substr($directory, 1); + } + $directory_pattern = '^' . preg_quote(str_replace('/', DIRECTORY_SEPARATOR, $directory) . DIRECTORY_SEPARATOR, '#'); + } + else + { + $directory_pattern = preg_quote(DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $directory) . DIRECTORY_SEPARATOR, '#'); + } + if ($is_dir) + { + $directory_pattern .= '$'; + } + $directory_pattern = '#' . $directory_pattern . '#'; + + if (is_dir($path)) + { + $iterator = new \RecursiveIteratorIterator( + new \phpbb\recursive_dot_prefix_filter_iterator( + new \RecursiveDirectoryIterator( + $path, + \FilesystemIterator::SKIP_DOTS + ) + ), + \RecursiveIteratorIterator::SELF_FIRST + ); + + foreach ($iterator as $file_info) + { + $filename = $file_info->getFilename(); + + if ($file_info->isDir() == $is_dir) + { + if ($is_dir) + { + $relative_path = $iterator->getInnerIterator()->getSubPath() . DIRECTORY_SEPARATOR . basename($filename) . DIRECTORY_SEPARATOR; + if ($relative_path[0] !== DIRECTORY_SEPARATOR) + { + $relative_path = DIRECTORY_SEPARATOR . $relative_path; + } + } + else + { + $relative_path = $iterator->getInnerIterator()->getSubPathname(); + if ($directory && $directory[0] === '/') + { + $relative_path = str_replace('/', DIRECTORY_SEPARATOR, $directory) . DIRECTORY_SEPARATOR . $relative_path; + } + else + { + $relative_path = DIRECTORY_SEPARATOR . $relative_path; + } + } + + if ((!$suffix || substr($relative_path, -strlen($suffix)) === $suffix) && + (!$prefix || substr($filename, 0, strlen($prefix)) === $prefix) && + (!$directory || preg_match($directory_pattern, $relative_path))) + { + $files[] = array( + 'named_path' => str_replace(DIRECTORY_SEPARATOR, '/', $location . $name . substr($relative_path, 1)), + 'ext_name' => $ext_name, + 'path' => str_replace(array(DIRECTORY_SEPARATOR, $this->phpbb_root_path), array('/', ''), $file_info->getPath()) . '/', + 'filename' => $filename, + ); + } + } + } + } + } + + if ($cache && $this->cache) + { + $this->cached_queries[$query] = $files; + $this->cache->put($this->cache_name, $this->cached_queries); + } + + return $files; + } +} diff --git a/phpBB/phpbb/groupposition/exception.php b/phpBB/phpbb/groupposition/exception.php new file mode 100644 index 0000000000..956c7238f2 --- /dev/null +++ b/phpBB/phpbb/groupposition/exception.php @@ -0,0 +1,18 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\groupposition; + +class exception extends \Exception +{ +} diff --git a/phpBB/phpbb/groupposition/groupposition_interface.php b/phpBB/phpbb/groupposition/groupposition_interface.php new file mode 100644 index 0000000000..3bd3fcce90 --- /dev/null +++ b/phpBB/phpbb/groupposition/groupposition_interface.php @@ -0,0 +1,80 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\groupposition; + +/** +* Interface to manage group positions in various places of phpbb +* +* The interface provides simple methods to add, delete and move a group +*/ +interface groupposition_interface +{ + /** + * Returns the value for a given group, if the group exists. + * @param int $group_id group_id of the group to be selected + * @return int position of the group + */ + public function get_group_value($group_id); + + /** + * Get number of groups displayed + * + * @return int value of the last item displayed + */ + public function get_group_count(); + + /** + * Addes a group by group_id + * + * @param int $group_id group_id of the group to be added + * @return bool True if the group was added successfully + */ + public function add_group($group_id); + + /** + * Deletes a group by group_id + * + * @param int $group_id group_id of the group to be deleted + * @param bool $skip_group Skip setting the value for this group, to save the query, when you need to update it anyway. + * @return bool True if the group was deleted successfully + */ + public function delete_group($group_id, $skip_group = false); + + /** + * Moves a group up by group_id + * + * @param int $group_id group_id of the group to be moved + * @return bool True if the group was moved successfully + */ + public function move_up($group_id); + + /** + * Moves a group down by group_id + * + * @param int $group_id group_id of the group to be moved + * @return bool True if the group was moved successfully + */ + public function move_down($group_id); + + /** + * Moves a group up/down + * + * @param int $group_id group_id of the group to be moved + * @param int $delta number of steps: + * - positive = move up + * - negative = move down + * @return bool True if the group was moved successfully + */ + public function move($group_id, $delta); +} diff --git a/phpBB/phpbb/groupposition/legend.php b/phpBB/phpbb/groupposition/legend.php new file mode 100644 index 0000000000..efea3389d4 --- /dev/null +++ b/phpBB/phpbb/groupposition/legend.php @@ -0,0 +1,243 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\groupposition; + +/** +* Legend group position class +* +* group_legend is an ascending list 1, 2, ..., n for groups which are displayed. 1 is the first group, n the last. +* If the value is 0 (self::GROUP_DISABLED) the group is not displayed. +*/ +class legend implements \phpbb\groupposition\groupposition_interface +{ + /** + * Group is not displayed + */ + const GROUP_DISABLED = 0; + + /** + * Database object + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Constructor + * + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\user $user) + { + $this->db = $db; + $this->user = $user; + } + + /** + * Returns the group_legend for a given group, if the group exists. + * + * @param int $group_id group_id of the group to be selected + * @return int position of the group + * @throws \phpbb\groupposition\exception + */ + public function get_group_value($group_id) + { + $sql = 'SELECT group_legend + FROM ' . GROUPS_TABLE . ' + WHERE group_id = ' . (int) $group_id; + $result = $this->db->sql_query($sql); + $current_value = $this->db->sql_fetchfield('group_legend'); + $this->db->sql_freeresult($result); + + if ($current_value === false) + { + // Group not found. + throw new \phpbb\groupposition\exception('NO_GROUP'); + } + + return (int) $current_value; + } + + /** + * Get number of groups, displayed on the legend + * + * @return int value of the last item displayed + */ + public function get_group_count() + { + $sql = 'SELECT group_legend + FROM ' . GROUPS_TABLE . ' + ORDER BY group_legend DESC'; + $result = $this->db->sql_query_limit($sql, 1); + $group_count = (int) $this->db->sql_fetchfield('group_legend'); + $this->db->sql_freeresult($result); + + return $group_count; + } + + /** + * {@inheritDoc} + */ + public function add_group($group_id) + { + $current_value = $this->get_group_value($group_id); + + if ($current_value == self::GROUP_DISABLED) + { + // Group is currently not displayed, add it at the end. + $next_value = 1 + $this->get_group_count(); + + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_legend = ' . $next_value . ' + WHERE group_legend = ' . self::GROUP_DISABLED . ' + AND group_id = ' . (int) $group_id; + $this->db->sql_query($sql); + return true; + } + + return false; + } + + /** + * Deletes a group by setting the field to self::GROUP_DISABLED and closing the gap in the list. + * + * @param int $group_id group_id of the group to be deleted + * @param bool $skip_group Skip setting the value for this group, to save the query, when you need to update it anyway. + * @return bool True if the group was deleted successfully + */ + public function delete_group($group_id, $skip_group = false) + { + $current_value = $this->get_group_value($group_id); + + if ($current_value != self::GROUP_DISABLED) + { + $this->db->sql_transaction('begin'); + + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_legend = group_legend - 1 + WHERE group_legend > ' . $current_value; + $this->db->sql_query($sql); + + if (!$skip_group) + { + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_legend = ' . self::GROUP_DISABLED . ' + WHERE group_id = ' . (int) $group_id; + $this->db->sql_query($sql); + } + + $this->db->sql_transaction('commit'); + + return true; + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function move_up($group_id) + { + return $this->move($group_id, 1); + } + + /** + * {@inheritDoc} + */ + public function move_down($group_id) + { + return $this->move($group_id, -1); + } + + /** + * {@inheritDoc} + */ + public function move($group_id, $delta) + { + $delta = (int) $delta; + if (!$delta) + { + return false; + } + + $move_up = ($delta > 0) ? true : false; + $current_value = $this->get_group_value($group_id); + + if ($current_value != self::GROUP_DISABLED) + { + $this->db->sql_transaction('begin'); + + // First we move all groups between our current value and the target value up/down 1, + // so we have a gap for our group to move. + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_legend = group_legend' . (($move_up) ? ' + 1' : ' - 1') . ' + WHERE group_legend > ' . self::GROUP_DISABLED . ' + AND group_legend' . (($move_up) ? ' >= ' : ' <= ') . ($current_value - $delta) . ' + AND group_legend' . (($move_up) ? ' < ' : ' > ') . $current_value; + $this->db->sql_query($sql); + + // Because there might be fewer groups above/below the group than we wanted to move, + // we use the number of changed groups, to update the group. + $delta = (int) $this->db->sql_affectedrows(); + + if ($delta) + { + // And now finally, when we moved some other groups and built a gap, + // we can move the desired group to it. + $sql = 'UPDATE ' . GROUPS_TABLE . ' + SET group_legend = group_legend ' . (($move_up) ? ' - ' : ' + ') . $delta . ' + WHERE group_id = ' . (int) $group_id; + $this->db->sql_query($sql); + + $this->db->sql_transaction('commit'); + + return true; + } + + $this->db->sql_transaction('commit'); + } + + return false; + } + + /** + * Get group type language var + * + * @param int $group_type group_type from the groups-table + * @return string name of the language variable for the given group-type. + */ + static public function group_type_language($group_type) + { + switch ($group_type) + { + case GROUP_OPEN: + return 'GROUP_REQUEST'; + case GROUP_CLOSED: + return 'GROUP_CLOSED'; + case GROUP_HIDDEN: + return 'GROUP_HIDDEN'; + case GROUP_SPECIAL: + return 'GROUP_SPECIAL'; + case GROUP_FREE: + return 'GROUP_OPEN'; + } + } +} diff --git a/phpBB/phpbb/groupposition/teampage.php b/phpBB/phpbb/groupposition/teampage.php new file mode 100644 index 0000000000..2985c51525 --- /dev/null +++ b/phpBB/phpbb/groupposition/teampage.php @@ -0,0 +1,597 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\groupposition; + +/** +* Teampage group position class +* +* Teampage position is an ascending list 1, 2, ..., n for items which are displayed. 1 is the first item, n the last. +*/ +class teampage implements \phpbb\groupposition\groupposition_interface +{ + /** + * Group is not displayed + */ + const GROUP_DISABLED = 0; + + /** + * No parent item + */ + const NO_PARENT = 0; + + /** + * Database object + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Cache object + * @var \phpbb\cache\driver\driver_interface + */ + protected $cache; + + /** + * Constructor + * + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\user $user User object + * @param \phpbb\cache\driver\driver_interface $cache Cache object + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\user $user, \phpbb\cache\driver\driver_interface $cache) + { + $this->db = $db; + $this->user = $user; + $this->cache = $cache; + } + + /** + * Returns the teampage position for a given group, if the group exists. + * + * @param int $group_id group_id of the group to be selected + * @return int position of the group + * @throws \phpbb\groupposition\exception + */ + public function get_group_value($group_id) + { + // The join is required to ensure that the group itself exists + $sql = 'SELECT g.group_id, t.teampage_position + FROM ' . GROUPS_TABLE . ' g + LEFT JOIN ' . TEAMPAGE_TABLE . ' t + ON (t.group_id = g.group_id) + WHERE g.group_id = ' . (int) $group_id; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row === false) + { + // Group not found. + throw new \phpbb\groupposition\exception('NO_GROUP'); + } + + return (int) $row['teampage_position']; + } + + /** + * Returns the row for a given group, if the group exists. + * + * @param int $group_id group_id of the group to be selected + * @return array Data row of the group + * @throws \phpbb\groupposition\exception + */ + public function get_group_values($group_id) + { + // The join is required to ensure that the group itself exists + $sql = 'SELECT * + FROM ' . GROUPS_TABLE . ' g + LEFT JOIN ' . TEAMPAGE_TABLE . ' t + ON (t.group_id = g.group_id) + WHERE g.group_id = ' . (int) $group_id; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row === false) + { + // Group not found. + throw new \phpbb\groupposition\exception('NO_GROUP'); + } + + return $row; + } + + /** + * Returns the teampage position for a given teampage item, if the item exists. + * + * @param int $teampage_id Teampage_id of the selected item + * @return int Teampage position of the item + * @throws \phpbb\groupposition\exception + */ + public function get_teampage_value($teampage_id) + { + $sql = 'SELECT teampage_position + FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_id = ' . (int) $teampage_id; + $result = $this->db->sql_query($sql); + $current_value = $this->db->sql_fetchfield('teampage_position'); + $this->db->sql_freeresult($result); + + if ($current_value === false) + { + // Group not found. + throw new \phpbb\groupposition\exception('NO_GROUP'); + } + + return (int) $current_value; + } + + /** + * Returns the teampage row for a given teampage item, if the item exists. + * + * @param int $teampage_id Teampage_id of the selected item + * @return array Teampage row of the item + * @throws \phpbb\groupposition\exception + */ + public function get_teampage_values($teampage_id) + { + $sql = 'SELECT teampage_position, teampage_parent + FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_id = ' . (int) $teampage_id; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row === false) + { + // Group not found. + throw new \phpbb\groupposition\exception('NO_GROUP'); + } + + return $row; + } + + + /** + * {@inheritDoc} + */ + public function get_group_count() + { + $sql = 'SELECT teampage_position + FROM ' . TEAMPAGE_TABLE . ' + ORDER BY teampage_position DESC'; + $result = $this->db->sql_query_limit($sql, 1); + $group_count = (int) $this->db->sql_fetchfield('teampage_position'); + $this->db->sql_freeresult($result); + + return $group_count; + } + + /** + * {@inheritDoc} + */ + public function add_group($group_id) + { + return $this->add_group_teampage($group_id, self::NO_PARENT); + } + + /** + * Adds a group by group_id + * + * @param int $group_id group_id of the group to be added + * @param int $parent_id Teampage ID of the parent item + * @return bool True if the group was added successfully + */ + public function add_group_teampage($group_id, $parent_id) + { + $current_value = $this->get_group_value($group_id); + + if ($current_value == self::GROUP_DISABLED) + { + if ($parent_id != self::NO_PARENT) + { + // Check, whether the given parent is a category + $sql = 'SELECT teampage_id + FROM ' . TEAMPAGE_TABLE . ' + WHERE group_id = 0 + AND teampage_id = ' . (int) $parent_id; + $result = $this->db->sql_query_limit($sql, 1); + $parent_is_category = (bool) $this->db->sql_fetchfield('teampage_id'); + $this->db->sql_freeresult($result); + + if ($parent_is_category) + { + // Get value of last child from this parent and add group there + $sql = 'SELECT teampage_position + FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_parent = ' . (int) $parent_id . ' + OR teampage_id = ' . (int) $parent_id . ' + ORDER BY teampage_position DESC'; + $result = $this->db->sql_query_limit($sql, 1); + $new_position = (int) $this->db->sql_fetchfield('teampage_position'); + $this->db->sql_freeresult($result); + + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position + 1 + WHERE teampage_position > ' . $new_position; + $this->db->sql_query($sql); + } + } + else + { + // Add group at the end + $new_position = $this->get_group_count(); + } + + $sql_ary = array( + 'group_id' => $group_id, + 'teampage_position' => $new_position + 1, + 'teampage_parent' => $parent_id, + ); + + $sql = 'INSERT INTO ' . TEAMPAGE_TABLE . ' ' . $this->db->sql_build_array('INSERT', $sql_ary); + $this->db->sql_query($sql); + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return true; + } + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return false; + } + + /** + * Adds a new category + * + * @param string $category_name Name of the category to be added + * @return bool True if the category was added successfully + */ + public function add_category_teampage($category_name) + { + if ($category_name === '') + { + return false; + } + + $num_entries = $this->get_group_count(); + + $sql_ary = array( + 'group_id' => 0, + 'teampage_position' => $num_entries + 1, + 'teampage_parent' => 0, + 'teampage_name' => truncate_string($category_name, 255, 255), + ); + + $sql = 'INSERT INTO ' . TEAMPAGE_TABLE . ' ' . $this->db->sql_build_array('INSERT', $sql_ary); + $this->db->sql_query($sql); + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return true; + } + + /** + * Deletes a group from the list and closes the gap in the position list. + * + * @param int $group_id group_id of the group to be deleted + * @param bool $skip_group Skip setting the value for this group, to save the query, when you need to update it anyway. + * @return bool True if the group was deleted successfully + */ + public function delete_group($group_id, $skip_group = false) + { + $current_value = $this->get_group_value($group_id); + + if ($current_value != self::GROUP_DISABLED) + { + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position - 1 + WHERE teampage_position > ' . $current_value; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . TEAMPAGE_TABLE . ' + WHERE group_id = ' . $group_id; + $this->db->sql_query($sql); + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return true; + } + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return false; + } + + /** + * Deletes an item from the list and closes the gap in the position list. + * + * @param int $teampage_id teampage_id of the item to be deleted + * @param bool $skip_group Skip setting the group to GROUP_DISABLED, to save the query, when you need to update it anyway. + * @return bool True if the item was deleted successfully + */ + public function delete_teampage($teampage_id, $skip_group = false) + { + $current_value = $this->get_teampage_value($teampage_id); + + if ($current_value != self::GROUP_DISABLED) + { + $sql = 'DELETE FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_id = ' . $teampage_id . ' + OR teampage_parent = ' . $teampage_id; + $this->db->sql_query($sql); + + $delta = (int) $this->db->sql_affectedrows(); + + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position - ' . $delta . ' + WHERE teampage_position > ' . $current_value; + $this->db->sql_query($sql); + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return true; + } + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return false; + } + + /** + * {@inheritDoc} + */ + public function move_up($group_id) + { + return $this->move($group_id, 1); + } + + /** + * Moves an item up by teampage_id + * + * @param int $teampage_id teampage_id of the item to be move + * @return bool True if the group was moved successfully + */ + public function move_up_teampage($teampage_id) + { + return $this->move_teampage($teampage_id, 1); + } + + /** + * {@inheritDoc} + */ + public function move_down($group_id) + { + return $this->move($group_id, -1); + } + + /** + * Moves an item down by teampage_id + * + * @param int $teampage_id teampage_id of the item to be moved + * @return bool True if the group was moved successfully + */ + public function move_down_teampage($teampage_id) + { + return $this->move_teampage($teampage_id, -1); + } + + /** + * {@inheritDoc} + */ + public function move($group_id, $delta) + { + $delta = (int) $delta; + if (!$delta) + { + return false; + } + + $move_up = ($delta > 0) ? true : false; + $data = $this->get_group_values($group_id); + + $current_value = (int) $data['teampage_position']; + if ($current_value != self::GROUP_DISABLED) + { + $this->db->sql_transaction('begin'); + + if (!$move_up && $data['teampage_parent'] == self::NO_PARENT) + { + // If we move items down, we need to grab the one sibling more, + // so we do not ignore the children of the previous sibling. + // We will remove the additional sibling later on. + $delta = abs($delta) + 1; + } + + $sql = 'SELECT teampage_position + FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_parent = ' . (int) $data['teampage_parent'] . ' + AND teampage_position' . (($move_up) ? ' < ' : ' > ') . $current_value . ' + ORDER BY teampage_position' . (($move_up) ? ' DESC' : ' ASC'); + $result = $this->db->sql_query_limit($sql, $delta); + + $sibling_count = 0; + $sibling_limit = $delta; + + // Reset the delta, as we recalculate the new real delta + $delta = 0; + while ($row = $this->db->sql_fetchrow($result)) + { + $sibling_count++; + $delta = $current_value - $row['teampage_position']; + + if (!$move_up && $data['teampage_parent'] == self::NO_PARENT && $sibling_count == $sibling_limit) + { + // Remove the additional sibling we added previously + $delta++; + } + } + $this->db->sql_freeresult($result); + + if ($delta) + { + // First we move all items between our current value and the target value up/down 1, + // so we have a gap for our item to move. + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position' . (($move_up) ? ' + 1' : ' - 1') . ' + WHERE teampage_position' . (($move_up) ? ' >= ' : ' <= ') . ($current_value - $delta) . ' + AND teampage_position' . (($move_up) ? ' < ' : ' > ') . $current_value; + $this->db->sql_query($sql); + + // And now finally, when we moved some other items and built a gap, + // we can move the desired item to it. + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position ' . (($move_up) ? ' - ' : ' + ') . abs($delta) . ' + WHERE group_id = ' . (int) $group_id; + $this->db->sql_query($sql); + + $this->db->sql_transaction('commit'); + $this->cache->destroy('sql', TEAMPAGE_TABLE); + + return true; + } + + $this->db->sql_transaction('commit'); + } + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return false; + } + + /** + * Moves an item up/down + * + * @param int $teampage_id teampage_id of the item to be moved + * @param int $delta number of steps: + * - positive = move up + * - negative = move down + * @return bool True if the group was moved successfully + */ + public function move_teampage($teampage_id, $delta) + { + $delta = (int) $delta; + if (!$delta) + { + return false; + } + + $move_up = ($delta > 0) ? true : false; + $data = $this->get_teampage_values($teampage_id); + + $current_value = (int) $data['teampage_position']; + if ($current_value != self::GROUP_DISABLED) + { + $this->db->sql_transaction('begin'); + + if (!$move_up && $data['teampage_parent'] == self::NO_PARENT) + { + // If we move items down, we need to grab the one sibling more, + // so we do not ignore the children of the previous sibling. + // We will remove the additional sibling later on. + $delta = abs($delta) + 1; + } + + $sql = 'SELECT teampage_id, teampage_position + FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_parent = ' . (int) $data['teampage_parent'] . ' + AND teampage_position' . (($move_up) ? ' < ' : ' > ') . $current_value . ' + ORDER BY teampage_position' . (($move_up) ? ' DESC' : ' ASC'); + $result = $this->db->sql_query_limit($sql, $delta); + + $sibling_count = 0; + $sibling_limit = $delta; + + // Reset the delta, as we recalculate the new real delta + $delta = 0; + while ($row = $this->db->sql_fetchrow($result)) + { + $sibling_count++; + $delta = $current_value - $row['teampage_position']; + + // Remove the additional sibling we added previously + // But only, if we included it, this is not be the case + // when we reached the end of our list + if (!$move_up && $data['teampage_parent'] == self::NO_PARENT && $sibling_count == $sibling_limit) + { + $delta++; + } + } + $this->db->sql_freeresult($result); + + if ($delta) + { + $sql = 'SELECT COUNT(teampage_id) as num_items + FROM ' . TEAMPAGE_TABLE . ' + WHERE teampage_id = ' . (int) $teampage_id . ' + OR teampage_parent = ' . (int) $teampage_id; + $result = $this->db->sql_query($sql); + $num_items = (int) $this->db->sql_fetchfield('num_items'); + $this->db->sql_freeresult($result); + + // First we move all items between our current value and the target value up/down 1, + // so we have a gap for our item to move. + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position' . (($move_up) ? ' + ' : ' - ') . $num_items . ' + WHERE teampage_position' . (($move_up) ? ' >= ' : ' <= ') . ($current_value - $delta) . ' + AND teampage_position' . (($move_up) ? ' < ' : ' > ') . $current_value . ' + AND NOT (teampage_id = ' . (int) $teampage_id . ' + OR teampage_parent = ' . (int) $teampage_id . ')'; + $this->db->sql_query($sql); + + $delta = (!$move_up && $data['teampage_parent'] == self::NO_PARENT) ? (abs($delta) - ($num_items - 1)) : abs($delta); + + // And now finally, when we moved some other items and built a gap, + // we can move the desired item to it. + $sql = 'UPDATE ' . TEAMPAGE_TABLE . ' + SET teampage_position = teampage_position ' . (($move_up) ? ' - ' : ' + ') . $delta . ' + WHERE teampage_id = ' . (int) $teampage_id . ' + OR teampage_parent = ' . (int) $teampage_id; + $this->db->sql_query($sql); + + $this->db->sql_transaction('commit'); + $this->cache->destroy('sql', TEAMPAGE_TABLE); + + return true; + } + + $this->db->sql_transaction('commit'); + } + + $this->cache->destroy('sql', TEAMPAGE_TABLE); + return false; + } + + /** + * Get group type language var + * + * @param int $group_type group_type from the groups-table + * @return string name of the language variable for the given group-type. + */ + static public function group_type_language($group_type) + { + switch ($group_type) + { + case GROUP_OPEN: + return 'GROUP_REQUEST'; + case GROUP_CLOSED: + return 'GROUP_CLOSED'; + case GROUP_HIDDEN: + return 'GROUP_HIDDEN'; + case GROUP_SPECIAL: + return 'GROUP_SPECIAL'; + case GROUP_FREE: + return 'GROUP_OPEN'; + } + } +} diff --git a/phpBB/phpbb/hook/finder.php b/phpBB/phpbb/hook/finder.php new file mode 100644 index 0000000000..a3d02d3aa0 --- /dev/null +++ b/phpBB/phpbb/hook/finder.php @@ -0,0 +1,80 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\hook; + +/** +* The hook finder locates installed hooks. +*/ +class finder +{ + protected $phpbb_root_path; + protected $cache; + protected $php_ext; + + /** + * Creates a new finder instance. + * + * @param string $phpbb_root_path Path to the phpbb root directory + * @param string $php_ext php file extension + * @param \phpbb\cache\driver\driver_interface $cache A cache instance or null + */ + public function __construct($phpbb_root_path, $php_ext, \phpbb\cache\driver\driver_interface $cache = null) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->cache = $cache; + $this->php_ext = $php_ext; + } + + /** + * Finds all hook files. + * + * @param bool $cache Whether the result should be cached + * @return array An array of paths to found hook files + */ + public function find($cache = true) + { + if (!defined('DEBUG') && $cache && $this->cache) + { + $hook_files = $this->cache->get('_hooks'); + if ($hook_files !== false) + { + return $hook_files; + } + } + + $hook_files = array(); + + // Now search for hooks... + $dh = @opendir($this->phpbb_root_path . 'includes/hooks/'); + + if ($dh) + { + while (($file = readdir($dh)) !== false) + { + if (strpos($file, 'hook_') === 0 && substr($file, -strlen('.' . $this->php_ext)) === '.' . $this->php_ext) + { + $hook_files[] = substr($file, 0, -(strlen($this->php_ext) + 1)); + } + } + closedir($dh); + } + + if ($cache && $this->cache) + { + $this->cache->put('_hooks', $hook_files); + } + + return $hook_files; + } +} diff --git a/phpBB/phpbb/json_response.php b/phpBB/phpbb/json_response.php new file mode 100644 index 0000000000..5219cd0c32 --- /dev/null +++ b/phpBB/phpbb/json_response.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* JSON class +*/ +class json_response +{ + /** + * Send the data to the client and exit the script. + * + * @param array $data Any additional data to send. + * @param bool $exit Will exit the script if true. + */ + public function send($data, $exit = true) + { + header('Content-Type: application/json'); + echo json_encode($data); + + if ($exit) + { + garbage_collection(); + exit_handler(); + } + } +} diff --git a/phpBB/phpbb/lock/db.php b/phpBB/phpbb/lock/db.php new file mode 100644 index 0000000000..85ba9a7aa3 --- /dev/null +++ b/phpBB/phpbb/lock/db.php @@ -0,0 +1,146 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\lock; + +/** +* Database locking class +*/ +class db +{ + /** + * Name of the config variable this lock uses + * @var string + */ + private $config_name; + + /** + * Unique identifier for this lock. + * + * @var string + */ + private $unique_id; + + /** + * Stores the state of this lock + * @var bool + */ + private $locked; + + /** + * The phpBB configuration + * @var \phpbb\config\config + */ + private $config; + + /** + * A database connection + * @var \phpbb\db\driver\driver_interface + */ + private $db; + + /** + * Creates a named released instance of the lock. + * + * You have to call acquire() to actually create the lock. + * + * @param string $config_name A config variable to be used for locking + * @param \phpbb\config\config $config The phpBB configuration + * @param \phpbb\db\driver\driver_interface $db A database connection + */ + public function __construct($config_name, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db) + { + $this->config_name = $config_name; + $this->config = $config; + $this->db = $db; + } + + /** + * Tries to acquire the lock by updating + * the configuration variable in the database. + * + * As a lock may only be held by one process at a time, lock + * acquisition may fail if another process is holding the lock + * or if another process obtained the lock but never released it. + * Locks are forcibly released after a timeout of 1 hour. + * + * @return bool true if lock was acquired + * false otherwise + */ + public function acquire() + { + if ($this->locked) + { + return false; + } + + if (!isset($this->config[$this->config_name])) + { + $this->config->set($this->config_name, '0', false); + } + $lock_value = $this->config[$this->config_name]; + + // make sure lock cannot be acquired by multiple processes + if ($lock_value) + { + // if the other process is running more than an hour already we have to assume it + // aborted without cleaning the lock + $time = explode(' ', $lock_value); + $time = $time[0]; + + if ($time + 3600 >= time()) + { + return false; + } + } + + $this->unique_id = time() . ' ' . unique_id(); + + // try to update the config value, if it was already modified by another + // process we failed to acquire the lock. + $this->locked = $this->config->set_atomic($this->config_name, $lock_value, $this->unique_id, false); + + return $this->locked; + } + + /** + * Does this process own the lock? + * + * @return bool true if lock is owned + * false otherwise + */ + public function owns_lock() + { + return (bool) $this->locked; + } + + /** + * Releases the lock. + * + * The lock must have been previously obtained, that is, acquire() call + * was issued and returned true. + * + * Note: Attempting to release a lock that is already released, + * that is, calling release() multiple times, is harmless. + * + * @return null + */ + public function release() + { + if ($this->locked) + { + $this->config->set_atomic($this->config_name, $this->unique_id, '0', false); + $this->locked = false; + } + } +} diff --git a/phpBB/phpbb/lock/flock.php b/phpBB/phpbb/lock/flock.php new file mode 100644 index 0000000000..df88e1490a --- /dev/null +++ b/phpBB/phpbb/lock/flock.php @@ -0,0 +1,141 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\lock; + +/** +* File locking class +*/ +class flock +{ + /** + * Path to the file to which access is controlled + * + * @var string + */ + private $path; + + /** + * File pointer for the lock file + * @var string + */ + private $lock_fp; + + /** + * Constructor. + * + * You have to call acquire() to actually acquire the lock. + * + * @param string $path Path to the file to which access is controlled + */ + public function __construct($path) + { + $this->path = $path; + $this->lock_fp = null; + } + + /** + * Tries to acquire the lock. + * + * If the lock is already held by another process, this call will block + * until the other process releases the lock. If a lock is acquired and + * is not released before script finishes but the process continues to + * live (apache/fastcgi) then subsequent processes trying to acquire + * the same lock will be blocked forever. + * + * If the lock is already held by the same process via another instance + * of this class, this call will block forever. + * + * If flock function is disabled in php or fails to work, lock + * acquisition will fail and false will be returned. + * + * @return bool true if lock was acquired + * false otherwise + */ + public function acquire() + { + if ($this->lock_fp) + { + return false; + } + + // For systems that can't have two processes opening + // one file for writing simultaneously + if (file_exists($this->path . '.lock')) + { + $mode = 'rb'; + } + else + { + $mode = 'wb'; + } + + $this->lock_fp = @fopen($this->path . '.lock', $mode); + + if ($mode == 'wb') + { + if (!$this->lock_fp) + { + // Two processes may attempt to create lock file at the same time. + // Have the losing process try opening the lock file again for reading + // on the assumption that the winning process created it + $mode = 'rb'; + $this->lock_fp = @fopen($this->path . '.lock', $mode); + } + else + { + // Only need to set mode when the lock file is written + @chmod($this->path . '.lock', 0666); + } + } + + if ($this->lock_fp) + { + @flock($this->lock_fp, LOCK_EX); + } + + return (bool) $this->lock_fp; + } + + /** + * Does this process own the lock? + * + * @return bool true if lock is owned + * false otherwise + */ + public function owns_lock() + { + return (bool) $this->lock_fp; + } + + /** + * Releases the lock. + * + * The lock must have been previously obtained, that is, acquire() call + * was issued and returned true. + * + * Note: Attempting to release a lock that is already released, + * that is, calling release() multiple times, is harmless. + * + * @return null + */ + public function release() + { + if ($this->lock_fp) + { + @flock($this->lock_fp, LOCK_UN); + fclose($this->lock_fp); + $this->lock_fp = null; + } + } +} diff --git a/phpBB/phpbb/log/log.php b/phpBB/phpbb/log/log.php new file mode 100644 index 0000000000..8f199cd931 --- /dev/null +++ b/phpBB/phpbb/log/log.php @@ -0,0 +1,982 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\log; + +/** +* This class is used to add entries into the log table. +*/ +class log implements \phpbb\log\log_interface +{ + /** + * If set, administrative user profile links will be returned and messages + * will not be censored. + * @var bool + */ + protected $is_in_admin; + + /** + * An array with the disabled log types. Logs of such types will not be + * added when add_log() is called. + * @var array + */ + protected $disabled_types; + + /** + * Keeps the total log count of the last call to get_logs() + * @var int + */ + protected $entry_count; + + /** + * Keeps the offset of the last valid page of the last call to get_logs() + * @var int + */ + protected $last_page_offset; + + /** + * The table we use to store our logs. + * @var string + */ + protected $log_table; + + /** + * Database object + * @var \phpbb\db\driver\driver + */ + protected $db; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Auth object + * @var \phpbb\auth\auth + */ + protected $auth; + + /** + * Event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $dispatcher; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * Admin root path + * @var string + */ + protected $phpbb_admin_path; + + /** + * PHP Extension + * @var string + */ + protected $php_ext; + + /** + * Constructor + * + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\user $user User object + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher + * @param string $phpbb_root_path Root path + * @param string $relative_admin_path Relative admin root path + * @param string $php_ext PHP Extension + * @param string $log_table Name of the table we use to store our logs + */ + public function __construct($db, $user, $auth, $phpbb_dispatcher, $phpbb_root_path, $relative_admin_path, $php_ext, $log_table) + { + $this->db = $db; + $this->user = $user; + $this->auth = $auth; + $this->dispatcher = $phpbb_dispatcher; + $this->phpbb_root_path = $phpbb_root_path; + $this->phpbb_admin_path = $this->phpbb_root_path . $relative_admin_path; + $this->php_ext = $php_ext; + $this->log_table = $log_table; + + /* + * IN_ADMIN is set after the session is created, + * so we need to take ADMIN_START into account as well, otherwise + * it will not work for the \phpbb\log\log object we create in common.php + */ + $this->set_is_admin((defined('ADMIN_START') && ADMIN_START) || (defined('IN_ADMIN') && IN_ADMIN)); + $this->enable(); + } + + /** + * Set is_in_admin in order to return administrative user profile links + * in get_logs() + * + * @param bool $is_in_admin Are we called from within the acp? + * @return null + */ + public function set_is_admin($is_in_admin) + { + $this->is_in_admin = (bool) $is_in_admin; + } + + /** + * Returns the is_in_admin option + * + * @return bool + */ + public function get_is_admin() + { + return $this->is_in_admin; + } + + /** + * Set table name + * + * @param string $log_table Can overwrite the table to use for the logs + * @return null + */ + public function set_log_table($log_table) + { + $this->log_table = $log_table; + } + + /** + * {@inheritDoc} + */ + public function is_enabled($type = '') + { + if ($type == '' || $type == 'all') + { + return !isset($this->disabled_types['all']); + } + return !isset($this->disabled_types[$type]) && !isset($this->disabled_types['all']); + } + + /** + * {@inheritDoc} + */ + public function disable($type = '') + { + if (is_array($type)) + { + foreach ($type as $disable_type) + { + $this->disable($disable_type); + } + return; + } + + // Empty string is an equivalent for all types. + if ($type == '') + { + $type = 'all'; + } + $this->disabled_types[$type] = true; + } + + /** + * {@inheritDoc} + */ + public function enable($type = '') + { + if (is_array($type)) + { + foreach ($type as $enable_type) + { + $this->enable($enable_type); + } + return; + } + + if ($type == '' || $type == 'all') + { + $this->disabled_types = array(); + return; + } + unset($this->disabled_types[$type]); + } + + /** + * {@inheritDoc} + */ + public function add($mode, $user_id, $log_ip, $log_operation, $log_time = false, $additional_data = array()) + { + if (!$this->is_enabled($mode)) + { + return false; + } + + if ($log_time == false) + { + $log_time = time(); + } + + $sql_ary = array( + 'user_id' => !empty($user_id) ? $user_id : ANONYMOUS, + 'log_ip' => !empty($log_ip) ? $log_ip : '', + 'log_time' => $log_time, + 'log_operation' => $log_operation, + ); + + switch ($mode) + { + case 'admin': + $sql_ary += array( + 'log_type' => LOG_ADMIN, + 'log_data' => (!empty($additional_data)) ? serialize($additional_data) : '', + ); + break; + + case 'mod': + $forum_id = isset($additional_data['forum_id']) ? (int) $additional_data['forum_id'] : 0; + unset($additional_data['forum_id']); + $topic_id = isset($additional_data['topic_id']) ? (int) $additional_data['topic_id'] : 0; + unset($additional_data['topic_id']); + $sql_ary += array( + 'log_type' => LOG_MOD, + 'forum_id' => $forum_id, + 'topic_id' => $topic_id, + 'log_data' => (!empty($additional_data)) ? serialize($additional_data) : '', + ); + break; + + case 'user': + $reportee_id = (int) $additional_data['reportee_id']; + unset($additional_data['reportee_id']); + + $sql_ary += array( + 'log_type' => LOG_USERS, + 'reportee_id' => $reportee_id, + 'log_data' => (!empty($additional_data)) ? serialize($additional_data) : '', + ); + break; + + case 'critical': + $sql_ary += array( + 'log_type' => LOG_CRITICAL, + 'log_data' => (!empty($additional_data)) ? serialize($additional_data) : '', + ); + break; + } + + /** + * Allows to modify log data before we add it to the database + * + * NOTE: if sql_ary does not contain a log_type value, the entry will + * not be stored in the database. So ensure to set it, if needed. + * + * @event core.add_log + * @var string mode Mode of the entry we log + * @var int user_id ID of the user who triggered the log + * @var string log_ip IP of the user who triggered the log + * @var string log_operation Language key of the log operation + * @var int log_time Timestamp, when the log was added + * @var array additional_data Array with additional log data + * @var array sql_ary Array with log data we insert into the + * database. If sql_ary[log_type] is not set, + * we won't add the entry to the database. + * @since 3.1.0-a1 + */ + $vars = array( + 'mode', + 'user_id', + 'log_ip', + 'log_operation', + 'log_time', + 'additional_data', + 'sql_ary', + ); + extract($this->dispatcher->trigger_event('core.add_log', compact($vars))); + + // We didn't find a log_type, so we don't save it in the database. + if (!isset($sql_ary['log_type'])) + { + return false; + } + + $this->db->sql_query('INSERT INTO ' . $this->log_table . ' ' . $this->db->sql_build_array('INSERT', $sql_ary)); + + return $this->db->sql_nextid(); + } + + /** + * {@inheritDoc} + */ + public function delete($mode, $conditions = array()) + { + switch ($mode) + { + case 'admin': + $log_type = LOG_ADMIN; + break; + + case 'mod': + $log_type = LOG_MOD; + break; + + case 'user': + $log_type = LOG_USERS; + break; + + case 'users': + $log_type = LOG_USERS; + break; + + case 'critical': + $log_type = LOG_CRITICAL; + break; + + default: + $log_type = false; + } + + /** + * Allows to modify log data before we delete it from the database + * + * NOTE: if sql_ary does not contain a log_type value, the entry will + * not be deleted in the database. So ensure to set it, if needed. + * + * @event core.delete_log + * @var string mode Mode of the entry we log + * @var string log_type Type ID of the log (should be different than false) + * @var array conditions An array of conditions, 3 different forms are accepted + * 1) <key> => <value> transformed into 'AND <key> = <value>' (value should be an integer) + * 2) <key> => array(<operator>, <value>) transformed into 'AND <key> <operator> <value>' (values can't be an array) + * 3) <key> => array('IN' => array(<values>)) transformed into 'AND <key> IN <values>' + * A special field, keywords, can also be defined. In this case only the log entries that have the keywords in log_operation or log_data will be deleted. + * @since 3.1.0-b4 + */ + $vars = array( + 'mode', + 'log_type', + 'conditions', + ); + extract($this->dispatcher->trigger_event('core.delete_log', compact($vars))); + + if ($log_type === false) + { + return; + } + + $sql_where = 'WHERE log_type = ' . $log_type; + + if (isset($conditions['keywords'])) + { + $sql_where .= $this->generate_sql_keyword($conditions['keywords'], ''); + + unset($conditions['keywords']); + } + + foreach ($conditions as $field => $field_value) + { + $sql_where .= ' AND '; + + if (is_array($field_value) && sizeof($field_value) == 2 && !is_array($field_value[1])) + { + $sql_where .= $field . ' ' . $field_value[0] . ' ' . $field_value[1]; + } + else if (is_array($field_value) && isset($field_value['IN']) && is_array($field_value['IN'])) + { + $sql_where .= $this->db->sql_in_set($field, $field_value['IN']); + } + else + { + $sql_where .= $field . ' = ' . $field_value; + } + } + + $sql = 'DELETE FROM ' . $this->log_table . " + $sql_where"; + $this->db->sql_query($sql); + + $this->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_CLEAR_' . strtoupper($mode)); + } + + /** + * {@inheritDoc} + */ + public function get_logs($mode, $count_logs = true, $limit = 0, $offset = 0, $forum_id = 0, $topic_id = 0, $user_id = 0, $log_time = 0, $sort_by = 'l.log_time DESC', $keywords = '') + { + $this->entry_count = 0; + $this->last_page_offset = $offset; + + $topic_id_list = $reportee_id_list = array(); + + $profile_url = ($this->get_is_admin() && $this->phpbb_admin_path) ? append_sid("{$this->phpbb_admin_path}index.{$this->php_ext}", 'i=users&mode=overview') : append_sid("{$this->phpbb_root_path}memberlist.{$this->php_ext}", 'mode=viewprofile'); + + switch ($mode) + { + case 'admin': + $log_type = LOG_ADMIN; + $sql_additional = ''; + break; + + case 'mod': + $log_type = LOG_MOD; + $sql_additional = ''; + + if ($topic_id) + { + $sql_additional = 'AND l.topic_id = ' . (int) $topic_id; + } + else if (is_array($forum_id)) + { + $sql_additional = 'AND ' . $this->db->sql_in_set('l.forum_id', array_map('intval', $forum_id)); + } + else if ($forum_id) + { + $sql_additional = 'AND l.forum_id = ' . (int) $forum_id; + } + break; + + case 'user': + $log_type = LOG_USERS; + $sql_additional = 'AND l.reportee_id = ' . (int) $user_id; + break; + + case 'users': + $log_type = LOG_USERS; + $sql_additional = ''; + break; + + case 'critical': + $log_type = LOG_CRITICAL; + $sql_additional = ''; + break; + + default: + $log_type = false; + $sql_additional = ''; + } + + /** + * Overwrite log type and limitations before we count and get the logs + * + * NOTE: if log_type is false, no entries will be returned. + * + * @event core.get_logs_modify_type + * @var string mode Mode of the entries we display + * @var bool count_logs Do we count all matching entries? + * @var int limit Limit the number of entries + * @var int offset Offset when fetching the entries + * @var mixed forum_id Limit entries to the forum_id, + * can also be an array of forum_ids + * @var int topic_id Limit entries to the topic_id + * @var int user_id Limit entries to the user_id + * @var int log_time Limit maximum age of log entries + * @var string sort_by SQL order option + * @var string keywords Will only return entries that have the + * keywords in log_operation or log_data + * @var string profile_url URL to the users profile + * @var int log_type Limit logs to a certain type. If log_type + * is false, no entries will be returned. + * @var string sql_additional Additional conditions for the entries, + * e.g.: 'AND l.forum_id = 1' + * @since 3.1.0-a1 + */ + $vars = array( + 'mode', + 'count_logs', + 'limit', + 'offset', + 'forum_id', + 'topic_id', + 'user_id', + 'log_time', + 'sort_by', + 'keywords', + 'profile_url', + 'log_type', + 'sql_additional', + ); + extract($this->dispatcher->trigger_event('core.get_logs_modify_type', compact($vars))); + + if ($log_type === false) + { + $this->last_page_offset = 0; + return array(); + } + + $sql_keywords = ''; + if (!empty($keywords)) + { + // Get the SQL condition for our keywords + $sql_keywords = $this->generate_sql_keyword($keywords); + } + + $get_logs_sql_ary = array( + 'SELECT' => 'l.*, u.username, u.username_clean, u.user_colour', + 'FROM' => array( + $this->log_table => 'l', + USERS_TABLE => 'u', + ), + 'WHERE' => 'l.log_type = ' . (int) $log_type . " + AND l.user_id = u.user_id + $sql_keywords + $sql_additional", + + 'ORDER_BY' => $sort_by, + ); + + if ($log_time) + { + $get_logs_sql_ary['WHERE'] = 'l.log_time >= ' . (int) $log_time . ' + AND ' . $get_logs_sql_ary['WHERE']; + } + + /** + * Modify the query to obtain the logs data + * + * @event core.get_logs_main_query_before + * @var array get_logs_sql_ary The array in the format of the query builder with the query + * to get the log count and the log list + * @var string mode Mode of the entries we display + * @var bool count_logs Do we count all matching entries? + * @var int limit Limit the number of entries + * @var int offset Offset when fetching the entries + * @var mixed forum_id Limit entries to the forum_id, + * can also be an array of forum_ids + * @var int topic_id Limit entries to the topic_id + * @var int user_id Limit entries to the user_id + * @var int log_time Limit maximum age of log entries + * @var string sort_by SQL order option + * @var string keywords Will only return entries that have the + * keywords in log_operation or log_data + * @var string profile_url URL to the users profile + * @var int log_type Limit logs to a certain type. If log_type + * is false, no entries will be returned. + * @var string sql_additional Additional conditions for the entries, + * e.g.: 'AND l.forum_id = 1' + * @since 3.1.5-RC1 + */ + $vars = array( + 'get_logs_sql_ary', + 'mode', + 'count_logs', + 'limit', + 'offset', + 'forum_id', + 'topic_id', + 'user_id', + 'log_time', + 'sort_by', + 'keywords', + 'profile_url', + 'log_type', + 'sql_additional', + ); + extract($this->dispatcher->trigger_event('core.get_logs_main_query_before', compact($vars))); + + if ($count_logs) + { + $count_logs_sql_ary = $get_logs_sql_ary; + + $count_logs_sql_ary['SELECT'] = 'COUNT(l.log_id) AS total_entries'; + unset($count_logs_sql_ary['ORDER_BY']); + + $sql = $this->db->sql_build_query('SELECT', $count_logs_sql_ary); + $result = $this->db->sql_query($sql); + $this->entry_count = (int) $this->db->sql_fetchfield('total_entries'); + $this->db->sql_freeresult($result); + + if ($this->entry_count == 0) + { + // Save the queries, because there are no logs to display + $this->last_page_offset = 0; + return array(); + } + + // Return the user to the last page that is valid + while ($this->last_page_offset >= $this->entry_count) + { + $this->last_page_offset = max(0, $this->last_page_offset - $limit); + } + } + + $sql = $this->db->sql_build_query('SELECT', $get_logs_sql_ary); + $result = $this->db->sql_query_limit($sql, $limit, $this->last_page_offset); + + $i = 0; + $log = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $row['forum_id'] = (int) $row['forum_id']; + if ($row['topic_id']) + { + $topic_id_list[] = (int) $row['topic_id']; + } + + if ($row['reportee_id']) + { + $reportee_id_list[] = (int) $row['reportee_id']; + } + + $log_entry_data = array( + 'id' => (int) $row['log_id'], + + 'reportee_id' => (int) $row['reportee_id'], + 'reportee_username' => '', + 'reportee_username_full'=> '', + + 'user_id' => (int) $row['user_id'], + 'username' => $row['username'], + 'username_full' => get_username_string('full', $row['user_id'], $row['username'], $row['user_colour'], false, $profile_url), + + 'ip' => $row['log_ip'], + 'time' => (int) $row['log_time'], + 'forum_id' => (int) $row['forum_id'], + 'topic_id' => (int) $row['topic_id'], + + 'viewforum' => ($row['forum_id'] && $this->auth->acl_get('f_read', $row['forum_id'])) ? append_sid("{$this->phpbb_root_path}viewforum.{$this->php_ext}", 'f=' . $row['forum_id']) : false, + 'action' => (isset($this->user->lang[$row['log_operation']])) ? $row['log_operation'] : '{' . ucfirst(str_replace('_', ' ', $row['log_operation'])) . '}', + ); + + /** + * Modify the entry's data before it is returned + * + * @event core.get_logs_modify_entry_data + * @var array row Entry data from the database + * @var array log_entry_data Entry's data which is returned + * @since 3.1.0-a1 + */ + $vars = array('row', 'log_entry_data'); + extract($this->dispatcher->trigger_event('core.get_logs_modify_entry_data', compact($vars))); + + $log[$i] = $log_entry_data; + + if (!empty($row['log_data'])) + { + $log_data_ary = unserialize($row['log_data']); + $log_data_ary = ($log_data_ary !== false) ? $log_data_ary : array(); + + if (isset($this->user->lang[$row['log_operation']])) + { + // Check if there are more occurrences of % than + // arguments, if there are we fill out the arguments + // array. It doesn't matter if we add more arguments than + // placeholders. + $num_args = 0; + if (!is_array($this->user->lang[$row['log_operation']])) + { + $num_args = substr_count($this->user->lang[$row['log_operation']], '%'); + } + else + { + foreach ($this->user->lang[$row['log_operation']] as $case => $plural_string) + { + $num_args = max($num_args, substr_count($plural_string, '%')); + } + } + + if (($num_args - sizeof($log_data_ary)) > 0) + { + $log_data_ary = array_merge($log_data_ary, array_fill(0, $num_args - sizeof($log_data_ary), '')); + } + + $lang_arguments = array_merge(array($log[$i]['action']), $log_data_ary); + $log[$i]['action'] = call_user_func_array(array($this->user, 'lang'), $lang_arguments); + + // If within the admin panel we do not censor text out + if ($this->get_is_admin()) + { + $log[$i]['action'] = bbcode_nl2br($log[$i]['action']); + } + else + { + $log[$i]['action'] = bbcode_nl2br(censor_text($log[$i]['action'])); + } + } + else if (!empty($log_data_ary)) + { + $log[$i]['action'] .= '<br />' . implode('', $log_data_ary); + } + + /* Apply make_clickable... has to be seen if it is for good. :/ + // Seems to be not for the moment, reconsider later... + $log[$i]['action'] = make_clickable($log[$i]['action']); + */ + } + else + { + $log[$i]['action'] = $this->user->lang($log[$i]['action']); + } + + $i++; + } + $this->db->sql_freeresult($result); + + /** + * Get some additional data after we got all log entries + * + * @event core.get_logs_get_additional_data + * @var array log Array with all our log entries + * @var array topic_id_list Array of topic ids, for which we + * get the permission data + * @var array reportee_id_list Array of additional user IDs we + * get the username strings for + * @since 3.1.0-a1 + */ + $vars = array('log', 'topic_id_list', 'reportee_id_list'); + extract($this->dispatcher->trigger_event('core.get_logs_get_additional_data', compact($vars))); + + if (sizeof($topic_id_list)) + { + $topic_auth = $this->get_topic_auth($topic_id_list); + + foreach ($log as $key => $row) + { + $log[$key]['viewtopic'] = (isset($topic_auth['f_read'][$row['topic_id']])) ? append_sid("{$this->phpbb_root_path}viewtopic.{$this->php_ext}", 'f=' . $topic_auth['f_read'][$row['topic_id']] . '&t=' . $row['topic_id']) : false; + $log[$key]['viewlogs'] = (isset($topic_auth['m_'][$row['topic_id']])) ? append_sid("{$this->phpbb_root_path}mcp.{$this->php_ext}", 'i=logs&mode=topic_logs&t=' . $row['topic_id'], true, $this->user->session_id) : false; + } + } + + if (sizeof($reportee_id_list)) + { + $reportee_data_list = $this->get_reportee_data($reportee_id_list); + + foreach ($log as $key => $row) + { + if (!isset($reportee_data_list[$row['reportee_id']])) + { + continue; + } + + $log[$key]['reportee_username'] = $reportee_data_list[$row['reportee_id']]['username']; + $log[$key]['reportee_username_full'] = get_username_string('full', $row['reportee_id'], $reportee_data_list[$row['reportee_id']]['username'], $reportee_data_list[$row['reportee_id']]['user_colour'], false, $profile_url); + } + } + + /** + * Allow modifying or execute extra final filter on log entries + * + * @event core.get_logs_after + * @var array log Array with all our log entries + * @var array topic_id_list Array of topic ids, for which we + * get the permission data + * @var array reportee_id_list Array of additional user IDs we + * get the username strings for + * @var string mode Mode of the entries we display + * @var bool count_logs Do we count all matching entries? + * @var int limit Limit the number of entries + * @var int offset Offset when fetching the entries + * @var mixed forum_id Limit entries to the forum_id, + * can also be an array of forum_ids + * @var int topic_id Limit entries to the topic_id + * @var int user_id Limit entries to the user_id + * @var int log_time Limit maximum age of log entries + * @var string sort_by SQL order option + * @var string keywords Will only return entries that have the + * keywords in log_operation or log_data + * @var string profile_url URL to the users profile + * @var int log_type The type of logs it was filtered + * @since 3.1.3-RC1 + */ + $vars = array( + 'log', + 'topic_id_list', + 'reportee_id_list', + 'mode', + 'count_logs', + 'limit', + 'offset', + 'forum_id', + 'topic_id', + 'user_id', + 'log_time', + 'sort_by', + 'keywords', + 'profile_url', + 'log_type', + ); + extract($this->dispatcher->trigger_event('core.get_logs_after', compact($vars))); + + return $log; + } + + /** + * Generates a sql condition for the specified keywords + * + * @param string $keywords The keywords the user specified to search for + * @param string $table_alias The alias of the logs' table ('l.' by default) + * @param string $statement_operator The operator used to prefix the statement ('AND' by default) + * + * @return string Returns the SQL condition searching for the keywords + */ + protected function generate_sql_keyword($keywords, $table_alias = 'l.', $statement_operator = 'AND') + { + // Use no preg_quote for $keywords because this would lead to sole + // backslashes being added. We also use an OR connection here for + // spaces and the | string. Currently, regex is not supported for + // searching (but may come later). + $keywords = preg_split('#[\s|]+#u', utf8_strtolower($keywords), 0, PREG_SPLIT_NO_EMPTY); + $sql_keywords = ''; + + if (!empty($keywords)) + { + $keywords_pattern = array(); + + // Build pattern and keywords... + for ($i = 0, $num_keywords = sizeof($keywords); $i < $num_keywords; $i++) + { + $keywords_pattern[] = preg_quote($keywords[$i], '#'); + $keywords[$i] = $this->db->sql_like_expression($this->db->get_any_char() . $keywords[$i] . $this->db->get_any_char()); + } + + $keywords_pattern = '#' . implode('|', $keywords_pattern) . '#ui'; + + $operations = array(); + foreach ($this->user->lang as $key => $value) + { + if (substr($key, 0, 4) == 'LOG_') + { + if (is_array($value)) + { + foreach ($value as $plural_value) + { + if (preg_match($keywords_pattern, $plural_value)) + { + $operations[] = $key; + break; + } + } + } + else if (preg_match($keywords_pattern, $value)) + { + $operations[] = $key; + } + } + } + + $sql_keywords = ' ' . $statement_operator . ' ('; + if (!empty($operations)) + { + $sql_keywords .= $this->db->sql_in_set($table_alias . 'log_operation', $operations) . ' OR '; + } + $sql_lower = $this->db->sql_lower_text($table_alias . 'log_data'); + $sql_keywords .= " $sql_lower " . implode(" OR $sql_lower ", $keywords) . ')'; + } + + return $sql_keywords; + } + + /** + * Determine whether the user is allowed to read and/or moderate the forum of the topic + * + * @param array $topic_ids Array with the topic ids + * + * @return array Returns an array with two keys 'm_' and 'read_f' which are also an array of topic_id => forum_id sets when the permissions are given. Sample: + * array( + * 'permission' => array( + * topic_id => forum_id + * ), + * ), + */ + protected function get_topic_auth(array $topic_ids) + { + $forum_auth = array('f_read' => array(), 'm_' => array()); + $topic_ids = array_unique($topic_ids); + + $sql_ary = array( + 'SELECT' => 'topic_id, forum_id', + 'FROM' => array( + TOPICS_TABLE => 't', + ), + 'WHERE' => $this->db->sql_in_set('topic_id', array_map('intval', $topic_ids)), + ); + + /** + * Allow modifying SQL query before topic data is retrieved. + * + * @event core.phpbb_log_get_topic_auth_sql_before + * @var array topic_ids Array with unique topic IDs + * @var array sql_ary SQL array + * @since 3.1.11-RC1 + */ + $vars = array( + 'topic_ids', + 'sql_ary', + ); + extract($this->dispatcher->trigger_event('core.phpbb_log_get_topic_auth_sql_before', compact($vars))); + + $sql = $this->db->sql_build_query('SELECT', $sql_ary); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $row['topic_id'] = (int) $row['topic_id']; + $row['forum_id'] = (int) $row['forum_id']; + + if ($this->auth->acl_get('f_read', $row['forum_id'])) + { + $forum_auth['f_read'][$row['topic_id']] = $row['forum_id']; + } + + if ($this->auth->acl_gets('a_', 'm_', $row['forum_id'])) + { + $forum_auth['m_'][$row['topic_id']] = $row['forum_id']; + } + } + $this->db->sql_freeresult($result); + + return $forum_auth; + } + + /** + * Get the data for all reportee from the database + * + * @param array $reportee_ids Array with the user ids of the reportees + * + * @return array Returns an array with the reportee data + */ + protected function get_reportee_data(array $reportee_ids) + { + $reportee_ids = array_unique($reportee_ids); + $reportee_data_list = array(); + + $sql = 'SELECT user_id, username, user_colour + FROM ' . USERS_TABLE . ' + WHERE ' . $this->db->sql_in_set('user_id', $reportee_ids); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $reportee_data_list[$row['user_id']] = $row; + } + $this->db->sql_freeresult($result); + + return $reportee_data_list; + } + + /** + * {@inheritDoc} + */ + public function get_log_count() + { + return ($this->entry_count) ? $this->entry_count : 0; + } + + /** + * {@inheritDoc} + */ + public function get_valid_offset() + { + return ($this->last_page_offset) ? $this->last_page_offset : 0; + } +} diff --git a/phpBB/phpbb/log/log_interface.php b/phpBB/phpbb/log/log_interface.php new file mode 100644 index 0000000000..5932f722aa --- /dev/null +++ b/phpBB/phpbb/log/log_interface.php @@ -0,0 +1,114 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\log; + +/** +* The interface for the log-system. +*/ +interface log_interface +{ + /** + * This function returns the state of the log system. + * + * @param string $type The log type we want to check. Empty to get + * global log status. + * + * @return bool True if log for the type is enabled + */ + public function is_enabled($type = ''); + + /** + * Disable log + * + * This function allows disabling the log system or parts of it, for this + * page call. When add_log is called and the type is disabled, + * the log will not be added to the database. + * + * @param mixed $type The log type we want to disable. Empty to + * disable all logs. Can also be an array of types. + * + * @return null + */ + public function disable($type = ''); + + /** + * Enable log + * + * This function allows re-enabling the log system. + * + * @param mixed $type The log type we want to enable. Empty to + * enable all logs. Can also be an array of types. + * + * @return null + */ + public function enable($type = ''); + + /** + * Adds a log entry to the database + * + * @param string $mode The mode defines which log_type is used and from which log the entry is retrieved + * @param int $user_id User ID of the user + * @param string $log_ip IP address of the user + * @param string $log_operation Name of the operation + * @param int $log_time Timestamp when the log entry was added, if empty time() will be used + * @param array $additional_data More arguments can be added, depending on the log_type + * + * @return int|bool Returns the log_id, if the entry was added to the database, false otherwise. + */ + public function add($mode, $user_id, $log_ip, $log_operation, $log_time = false, $additional_data = array()); + + /** + * Delete entries in the logs + * + * @param string $mode The mode defines which log_type is used and from which log the entries are deleted + * @param array $conditions An array of conditions, 3 different forms are accepted + * 1) <key> => <value> transformed into 'AND <key> = <value>' (value should be an integer) + * 2) <key> => array(<operator>, <value>) transformed into 'AND <key> <operator> <value>' (values can't be an array) + * 3) <key> => array('IN' => array(<values>)) transformed into 'AND <key> IN <values>' + * A special field, keywords, can also be defined. In this case only the log entries that have the keywords in log_operation or log_data will be deleted. + */ + public function delete($mode, $conditions = array()); + + /** + * Grab the logs from the database + * + * @param string $mode The mode defines which log_type is used and ifrom which log the entry is retrieved + * @param bool $count_logs Shall we count all matching log entries? + * @param int $limit Limit the number of entries that are returned + * @param int $offset Offset when fetching the log entries, f.e. when paginating + * @param mixed $forum_id Restrict the log entries to the given forum_id (can also be an array of forum_ids) + * @param int $topic_id Restrict the log entries to the given topic_id + * @param int $user_id Restrict the log entries to the given user_id + * @param int $log_time Only get log entries newer than the given timestamp + * @param string $sort_by SQL order option, e.g. 'l.log_time DESC' + * @param string $keywords Will only return log entries that have the keywords in log_operation or log_data + * + * @return array The result array with the logs + */ + public function get_logs($mode, $count_logs = true, $limit = 0, $offset = 0, $forum_id = 0, $topic_id = 0, $user_id = 0, $log_time = 0, $sort_by = 'l.log_time DESC', $keywords = ''); + + /** + * Get total log count + * + * @return int Returns the number of matching logs from the last call to get_logs() + */ + public function get_log_count(); + + /** + * Get offset of the last valid page + * + * @return int Returns the offset of the last valid page from the last call to get_logs() + */ + public function get_valid_offset(); +} diff --git a/phpBB/phpbb/log/null.php b/phpBB/phpbb/log/null.php new file mode 100644 index 0000000000..baa78895ea --- /dev/null +++ b/phpBB/phpbb/log/null.php @@ -0,0 +1,81 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\log; + +/** +* Null logger +*/ +class null implements log_interface +{ + /** + * {@inheritdoc} + */ + public function is_enabled($type = '') + { + return false; + } + + /** + * {@inheritdoc} + */ + public function disable($type = '') + { + } + + /** + * {@inheritdoc} + */ + public function enable($type = '') + { + } + + /** + * {@inheritdoc} + */ + public function add($mode, $user_id, $log_ip, $log_operation, $log_time = false, $additional_data = array()) + { + return false; + } + + /** + * {@inheritdoc} + */ + public function delete($mode, $conditions = array()) + { + } + + /** + * {@inheritdoc} + */ + public function get_logs($mode, $count_logs = true, $limit = 0, $offset = 0, $forum_id = 0, $topic_id = 0, $user_id = 0, $log_time = 0, $sort_by = 'l.log_time DESC', $keywords = '') + { + return array(); + } + + /** + * {@inheritdoc} + */ + public function get_log_count() + { + return 0; + } + + /** + * {@inheritdoc} + */ + public function get_valid_offset() + { + return 0; + } +} diff --git a/phpBB/phpbb/message/admin_form.php b/phpBB/phpbb/message/admin_form.php new file mode 100644 index 0000000000..96b8d3499e --- /dev/null +++ b/phpBB/phpbb/message/admin_form.php @@ -0,0 +1,192 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\message; + +/** +* Class admin_form +* Displays a message to the user and allows him to send an email +*/ +class admin_form extends form +{ + /** @var \phpbb\config\db_text */ + protected $config_text; + + /** @var string */ + protected $subject; + /** @var string */ + protected $sender_name; + /** @var string */ + protected $sender_address; + + /** + * Construct + * + * @param \phpbb\auth\auth $auth + * @param \phpbb\config\config $config + * @param \phpbb\config\db_text $config_text + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\user $user + * @param string $phpbb_root_path + * @param string $phpEx + */ + public function __construct(\phpbb\auth\auth $auth, \phpbb\config\config $config, \phpbb\config\db_text $config_text, \phpbb\db\driver\driver_interface $db, \phpbb\user $user, $phpbb_root_path, $phpEx) + { + parent::__construct($auth, $config, $db, $user, $phpbb_root_path, $phpEx); + $this->config_text = $config_text; + } + + /** + * {inheritDoc} + */ + public function check_allow() + { + $error = parent::check_allow(); + if ($error) + { + return $error; + } + + if (!$this->config['contact_admin_form_enable']) + { + return 'NO_CONTACT_PAGE'; + } + + return false; + } + + /** + * {inheritDoc} + */ + public function bind(\phpbb\request\request_interface $request) + { + parent::bind($request); + + $this->subject = $request->variable('subject', '', true); + $this->sender_address = $request->variable('email', ''); + $this->sender_name = $request->variable('name', '', true); + } + + /** + * {inheritDoc} + */ + public function submit(\messenger $messenger) + { + if (!$this->subject) + { + $this->errors[] = $this->user->lang['EMPTY_SUBJECT_EMAIL']; + } + if (!$this->body) + { + $this->errors[] = $this->user->lang['EMPTY_MESSAGE_EMAIL']; + } + + if ($this->user->data['is_registered']) + { + $this->message->set_sender_from_user($this->user); + $this->sender_name = $this->user->data['username']; + $this->sender_address = $this->user->data['user_email']; + } + else + { + if (!$this->sender_name) + { + $this->errors[] = $this->user->lang['EMPTY_SENDER_NAME']; + } + + if (!function_exists('validate_data')) + { + require($this->phpbb_root_path . 'includes/functions_user.' . $this->phpEx); + } + + $validate_array = validate_data( + array( + 'email' => $this->sender_address, + ), + array( + 'email' => array( + array('string', false, 6, 60), + array('email'), + ), + ) + ); + + foreach ($validate_array as $error) + { + $this->errors[] = $this->user->lang[$error]; + } + + $this->message->set_sender($this->user->ip, $this->sender_name, $this->sender_address, $this->user->lang_name); + $this->message->set_sender_notify_type(NOTIFY_EMAIL); + } + + $this->message->set_template('contact_admin'); + $this->message->set_subject($this->subject); + $this->message->set_body($this->body); + $this->message->add_recipient( + $this->user->lang['ADMINISTRATOR'], + $this->config['board_contact'], + $this->config['default_lang'], + NOTIFY_EMAIL + ); + + $this->message->set_template_vars(array( + 'FROM_EMAIL_ADDRESS' => $this->sender_address, + 'FROM_IP_ADDRESS' => $this->user->ip, + 'S_IS_REGISTERED' => $this->user->data['is_registered'], + + 'U_FROM_PROFILE' => generate_board_url() . '/memberlist.' . $this->phpEx . '?mode=viewprofile&u=' . $this->user->data['user_id'], + )); + + parent::submit($messenger); + } + + /** + * {inheritDoc} + */ + public function render(\phpbb\template\template $template) + { + $l_admin_info = $this->config_text->get('contact_admin_info'); + if ($l_admin_info) + { + $contact_admin_data = $this->config_text->get_array(array( + 'contact_admin_info', + 'contact_admin_info_uid', + 'contact_admin_info_bitfield', + 'contact_admin_info_flags', + )); + + $l_admin_info = generate_text_for_display( + $contact_admin_data['contact_admin_info'], + $contact_admin_data['contact_admin_info_uid'], + $contact_admin_data['contact_admin_info_bitfield'], + $contact_admin_data['contact_admin_info_flags'] + ); + } + + $template->assign_vars(array( + 'S_CONTACT_ADMIN' => true, + 'S_CONTACT_FORM' => $this->config['contact_admin_form_enable'], + 'S_IS_REGISTERED' => $this->user->data['is_registered'], + 'S_POST_ACTION' => append_sid($this->phpbb_root_path . 'memberlist.' . $this->phpEx, 'mode=contactadmin'), + + 'CONTACT_INFO' => $l_admin_info, + 'MESSAGE' => $this->body, + 'SUBJECT' => $this->subject, + 'NAME' => $this->sender_name, + 'EMAIL' => $this->sender_address, + )); + + parent::render($template); + } +} diff --git a/phpBB/phpbb/message/form.php b/phpBB/phpbb/message/form.php new file mode 100644 index 0000000000..21d4de0b4d --- /dev/null +++ b/phpBB/phpbb/message/form.php @@ -0,0 +1,175 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\message; + +/** +* Abstract class form +*/ +abstract class form +{ + /** @var \phpbb\auth\auth */ + protected $auth; + /** @var \phpbb\config\config */ + protected $config; + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + /** @var \phpbb\message\message */ + protected $message; + /** @var \phpbb\user */ + protected $user; + + /** @var string */ + protected $phpbb_root_path; + /** @var string */ + protected $phpEx; + + /** @var array */ + protected $errors = array(); + /** @var bool */ + protected $cc_sender; + /** @var string */ + protected $body; + + /** + * Construct + * + * @param \phpbb\auth\auth $auth + * @param \phpbb\config\config $config + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\user $user + * @param string $phpbb_root_path + * @param string $phpEx + */ + public function __construct(\phpbb\auth\auth $auth, \phpbb\config\config $config, \phpbb\db\driver\driver_interface $db, \phpbb\user $user, $phpbb_root_path, $phpEx) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->phpEx = $phpEx; + $this->user = $user; + $this->auth = $auth; + $this->config = $config; + $this->db = $db; + + $this->message = new message($config['server_name']); + $this->message->set_sender_from_user($this->user); + } + + /** + * Returns the title for the email form page + * + * @return string + */ + public function get_page_title() + { + return $this->user->lang['SEND_EMAIL']; + } + + /** + * Returns the file name of the form template + * + * @return string + */ + public function get_template_file() + { + return 'memberlist_email.html'; + } + + /** + * Checks whether the user is allowed to use the form + * + * @return false|string Error string if not allowed, false otherwise + */ + public function check_allow() + { + if (!$this->config['email_enable']) + { + return 'EMAIL_DISABLED'; + } + + if (time() - $this->user->data['user_emailtime'] < $this->config['flood_interval']) + { + return 'FLOOD_EMAIL_LIMIT'; + } + + return false; + } + + /** + * Get the return link after the message has been sent + * + * @return string + */ + public function get_return_message() + { + return sprintf($this->user->lang['RETURN_INDEX'], '<a href="' . append_sid($this->phpbb_root_path . 'index.' . $this->phpEx) . '">', '</a>'); + } + + /** + * Bind the values of the request to the form + * + * @param \phpbb\request\request_interface $request + * @return null + */ + public function bind(\phpbb\request\request_interface $request) + { + $this->cc_sender = $request->is_set_post('cc_sender'); + $this->body = $request->variable('message', '', true); + } + + /** + * Submit form, generate the email and send it + * + * @param \messenger $messenger + * @return null + */ + public function submit(\messenger $messenger) + { + if (!check_form_key('memberlist_email')) + { + $this->errors[] = 'FORM_INVALID'; + } + + if (!sizeof($this->errors)) + { + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_emailtime = ' . time() . ' + WHERE user_id = ' . $this->user->data['user_id']; + $this->db->sql_query($sql); + + if ($this->cc_sender && $this->user->data['is_registered']) + { + $this->message->cc_sender(); + } + + $this->message->send($messenger, phpbb_get_board_contact($this->config, $this->phpEx)); + + meta_refresh(3, append_sid($this->phpbb_root_path . 'index.' . $this->phpEx)); + trigger_error($this->user->lang['EMAIL_SENT'] . '<br /><br />' . $this->get_return_message()); + } + } + + /** + * Render the template of the form + * + * @param \phpbb\template\template $template + * @return null + */ + public function render(\phpbb\template\template $template) + { + add_form_key('memberlist_email'); + + $template->assign_vars(array( + 'ERROR_MESSAGE' => (sizeof($this->errors)) ? implode('<br />', $this->errors) : '', + )); + } +} diff --git a/phpBB/phpbb/message/message.php b/phpBB/phpbb/message/message.php new file mode 100644 index 0000000000..5fd24b542e --- /dev/null +++ b/phpBB/phpbb/message/message.php @@ -0,0 +1,282 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\message; + +/** +* Class message +* Holds all information for an email and sends it in the end +*/ +class message +{ + /** @var string */ + protected $server_name; + + /** @var string */ + protected $subject = ''; + /** @var string */ + protected $body = ''; + /** @var string */ + protected $template = ''; + /** @var array */ + protected $template_vars = array(); + + /** @var string */ + protected $sender_ip = ''; + /** @var string */ + protected $sender_name = ''; + /** @var string */ + protected $sender_address = ''; + /** @var string */ + protected $sender_lang = ''; + /** @var string */ + protected $sender_id = ''; + /** @var string */ + protected $sender_username = ''; + /** @var string */ + protected $sender_jabber = ''; + /** @var int */ + protected $sender_notify_type = NOTIFY_EMAIL; + + /** @var array */ + protected $recipients; + + /** + * Construct + * + * @param string $server_name Used for AntiAbuse header + */ + public function __construct($server_name) + { + $this->server_name = $server_name; + } + + /** + * Set the subject of the email + * + * @param string $subject + * @return null + */ + public function set_subject($subject) + { + $this->subject = $subject; + } + + /** + * Set the body of the email text + * + * @param string $body + * @return null + */ + public function set_body($body) + { + $this->body = $body; + } + + /** + * Set the name of the email template to use + * + * @param string $template + * @return null + */ + public function set_template($template) + { + $this->template = $template; + } + + /** + * Set the array with the "template" data for the email + * + * @param array $template_vars + * @return null + */ + public function set_template_vars($template_vars) + { + $this->template_vars = $template_vars; + } + + /** + * Add a recipient from \phpbb\user + * + * @param array $user + * @return null + */ + public function add_recipient_from_user_row(array $user) + { + $this->add_recipient( + $user['username'], + $user['user_email'], + $user['user_lang'], + $user['user_notify_type'], + $user['username'], + $user['user_jabber'] + ); + } + + /** + * Add a recipient + * + * @param string $recipient_name Displayed sender name + * @param string $recipient_address Email address + * @param string $recipient_lang + * @param int $recipient_notify_type Used notification methods (Jabber, Email, ...) + * @param string $recipient_username User Name (used for AntiAbuse header) + * @param string $recipient_jabber + * @return null + */ + public function add_recipient($recipient_name, $recipient_address, $recipient_lang, $recipient_notify_type = NOTIFY_EMAIL, $recipient_username = '', $recipient_jabber = '') + { + $this->recipients[] = array( + 'name' => $recipient_name, + 'address' => $recipient_address, + 'lang' => $recipient_lang, + 'username' => $recipient_username, + 'jabber' => $recipient_jabber, + 'notify_type' => $recipient_notify_type, + 'to_name' => $recipient_name, + ); + } + + /** + * Set the senders data from \phpbb\user object + * + * @param \phpbb\user $user + * @return null + */ + public function set_sender_from_user($user) + { + $this->set_sender( + $user->ip, + $user->data['username'], + $user->data['user_email'], + $user->lang_name, + $user->data['user_id'], + $user->data['username'], + $user->data['user_jabber'] + ); + + $this->set_sender_notify_type($user->data['user_notify_type']); + } + + /** + * Set the senders data + * + * @param string $sender_ip + * @param string $sender_name Displayed sender name + * @param string $sender_address Email address + * @param string $sender_lang + * @param int $sender_id User ID + * @param string $sender_username User Name (used for AntiAbuse header) + * @param string $sender_jabber + * @return null + */ + public function set_sender($sender_ip, $sender_name, $sender_address, $sender_lang = '', $sender_id = 0, $sender_username = '', $sender_jabber = '') + { + $this->sender_ip = $sender_ip; + $this->sender_name = $sender_name; + $this->sender_address = $sender_address; + $this->sender_lang = $sender_lang; + $this->sender_id = $sender_id; + $this->sender_username = $sender_username; + $this->sender_jabber = $sender_jabber; + } + + /** + * Which notification type should be used? Jabber, Email, ...? + * + * @param int $sender_notify_type + * @return null + */ + public function set_sender_notify_type($sender_notify_type) + { + $this->sender_notify_type = $sender_notify_type; + } + + /** + * Ok, now the same email if CC specified, but without exposing the user's email address + * + * @return null + */ + public function cc_sender() + { + if (!sizeof($this->recipients)) + { + trigger_error('No email recipients specified'); + } + if (!$this->sender_address) + { + trigger_error('No email sender specified'); + } + + $this->recipients[] = array( + 'lang' => $this->sender_lang, + 'address' => $this->sender_address, + 'name' => $this->sender_name, + 'username' => $this->sender_username, + 'jabber' => $this->sender_jabber, + 'notify_type' => $this->sender_notify_type, + 'to_name' => $this->recipients[0]['to_name'], + ); + } + + /** + * Send the email + * + * @param \messenger $messenger + * @param string $contact + * @return null + */ + public function send(\messenger $messenger, $contact) + { + if (!sizeof($this->recipients)) + { + return; + } + + foreach ($this->recipients as $recipient) + { + $messenger->template($this->template, $recipient['lang']); + $messenger->replyto($this->sender_address); + $messenger->to($recipient['address'], $recipient['name']); + $messenger->im($recipient['jabber'], $recipient['username']); + + $messenger->headers('X-AntiAbuse: Board servername - ' . $this->server_name); + $messenger->headers('X-AntiAbuse: User IP - ' . $this->sender_ip); + + if ($this->sender_id) + { + $messenger->headers('X-AntiAbuse: User_id - ' . $this->sender_id); + } + if ($this->sender_username) + { + $messenger->headers('X-AntiAbuse: Username - ' . $this->sender_username); + } + + $messenger->subject(htmlspecialchars_decode($this->subject)); + + $messenger->assign_vars(array( + 'BOARD_CONTACT' => $contact, + 'TO_USERNAME' => htmlspecialchars_decode($recipient['to_name']), + 'FROM_USERNAME' => htmlspecialchars_decode($this->sender_name), + 'MESSAGE' => htmlspecialchars_decode($this->body)) + ); + + if (sizeof($this->template_vars)) + { + $messenger->assign_vars($this->template_vars); + } + + $messenger->send($recipient['notify_type']); + } + } +} diff --git a/phpBB/phpbb/message/topic_form.php b/phpBB/phpbb/message/topic_form.php new file mode 100644 index 0000000000..174643bb81 --- /dev/null +++ b/phpBB/phpbb/message/topic_form.php @@ -0,0 +1,158 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\message; + +/** +* Class topic_form +* Form used to send topics as notification emails +*/ +class topic_form extends form +{ + /** @var int */ + protected $topic_id; + /** @var array */ + protected $topic_row; + /** @var string */ + protected $recipient_address; + /** @var string */ + protected $recipient_name; + /** @var string */ + protected $recipient_lang; + + /** + * Get the data of the topic + * + * @param int $topic_id + * @return false|array false if the topic does not exist, array otherwise + */ + protected function get_topic_row($topic_id) + { + $sql = 'SELECT forum_id, topic_title + FROM ' . TOPICS_TABLE . ' + WHERE topic_id = ' . (int) $topic_id; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + return $row; + } + + /** + * {inheritDoc} + */ + public function check_allow() + { + $error = parent::check_allow(); + if ($error) + { + return $error; + } + + if (!$this->auth->acl_get('u_sendemail')) + { + return 'NO_EMAIL'; + } + + if (!$this->topic_row) + { + return 'NO_TOPIC'; + } + + if (!$this->auth->acl_get('f_read', $this->topic_row['forum_id'])) + { + return 'SORRY_AUTH_READ'; + } + + if (!$this->auth->acl_get('f_email', $this->topic_row['forum_id'])) + { + return 'NO_EMAIL'; + } + + return false; + } + + /** + * {inheritDoc} + */ + public function bind(\phpbb\request\request_interface $request) + { + parent::bind($request); + + $this->topic_id = $request->variable('t', 0); + $this->recipient_address = $request->variable('email', ''); + $this->recipient_name = $request->variable('name', '', true); + $this->recipient_lang = $request->variable('lang', $this->config['default_lang']); + + $this->topic_row = $this->get_topic_row($this->topic_id); + } + + /** + * {inheritDoc} + */ + public function submit(\messenger $messenger) + { + if (!$this->recipient_address || !preg_match('/^' . get_preg_expression('email') . '$/i', $this->recipient_address)) + { + $this->errors[] = $this->user->lang['EMPTY_ADDRESS_EMAIL']; + } + + if (!$this->recipient_name) + { + $this->errors[] = $this->user->lang['EMPTY_NAME_EMAIL']; + } + + $this->message->set_template('email_notify'); + $this->message->set_template_vars(array( + 'TOPIC_NAME' => htmlspecialchars_decode($this->topic_row['topic_title']), + 'U_TOPIC' => generate_board_url() . '/viewtopic.' . $this->phpEx . '?f=' . $this->topic_row['forum_id'] . '&t=' . $this->topic_id, + )); + $this->message->set_body($this->body); + $this->message->add_recipient( + $this->recipient_name, + $this->recipient_address, + $this->recipient_lang, + NOTIFY_EMAIL + ); + $this->message->set_sender_notify_type(NOTIFY_EMAIL); + + parent::submit($messenger); + } + + /** + * {inheritDoc} + */ + public function get_return_message() + { + return sprintf($this->user->lang['RETURN_TOPIC'], '<a href="' . append_sid($this->phpbb_root_path . 'viewtopic.' . $this->phpEx, 'f=' . $this->topic_row['forum_id'] . '&t=' . $this->topic_id) . '">', '</a>'); + } + + /** + * {inheritDoc} + */ + public function render(\phpbb\template\template $template) + { + parent::render($template); + + $this->user->add_lang('viewtopic'); + $template->assign_vars(array( + 'EMAIL' => $this->recipient_address, + 'NAME' => $this->recipient_name, + 'S_LANG_OPTIONS' => language_select($this->recipient_lang), + 'MESSAGE' => $this->body, + + 'L_EMAIL_BODY_EXPLAIN' => $this->user->lang['EMAIL_TOPIC_EXPLAIN'], + 'S_POST_ACTION' => append_sid($this->phpbb_root_path . 'memberlist.' . $this->phpEx, 'mode=email&t=' . $this->topic_id)) + ); + } +} diff --git a/phpBB/phpbb/message/user_form.php b/phpBB/phpbb/message/user_form.php new file mode 100644 index 0000000000..007e575407 --- /dev/null +++ b/phpBB/phpbb/message/user_form.php @@ -0,0 +1,136 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\message; + +/** +* Class user_form +* Allows users to send emails to other users +*/ +class user_form extends form +{ + /** @var int */ + protected $recipient_id; + /** @var array */ + protected $recipient_row; + /** @var string */ + protected $subject; + + /** + * Get the data of the recipient + * + * @param int $user_id + * @return false|array false if the user does not exist, array otherwise + */ + protected function get_user_row($user_id) + { + $sql = 'SELECT user_id, username, user_colour, user_email, user_allow_viewemail, user_lang, user_jabber, user_notify_type + FROM ' . USERS_TABLE . ' + WHERE user_id = ' . (int) $user_id . ' + AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')'; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + return $row; + } + + /** + * {inheritDoc} + */ + public function check_allow() + { + $error = parent::check_allow(); + if ($error) + { + return $error; + } + + if (!$this->auth->acl_get('u_sendemail')) + { + return 'NO_EMAIL'; + } + + if ($this->recipient_id == ANONYMOUS || !$this->config['board_email_form']) + { + return 'NO_EMAIL'; + } + + if (!$this->recipient_row) + { + return 'NO_USER'; + } + + // Can we send email to this user? + if (!$this->recipient_row['user_allow_viewemail'] && !$this->auth->acl_get('a_user')) + { + return 'NO_EMAIL'; + } + + return false; + } + + /** + * {inheritDoc} + */ + public function bind(\phpbb\request\request_interface $request) + { + parent::bind($request); + + $this->recipient_id = $request->variable('u', 0); + $this->subject = $request->variable('subject', '', true); + + $this->recipient_row = $this->get_user_row($this->recipient_id); + } + + /** + * {inheritDoc} + */ + public function submit(\messenger $messenger) + { + if (!$this->subject) + { + $this->errors[] = $this->user->lang['EMPTY_SUBJECT_EMAIL']; + } + + if (!$this->body) + { + $this->errors[] = $this->user->lang['EMPTY_MESSAGE_EMAIL']; + } + + $this->message->set_template('profile_send_email'); + $this->message->set_subject($this->subject); + $this->message->set_body($this->body); + $this->message->add_recipient_from_user_row($this->recipient_row); + + parent::submit($messenger); + } + + /** + * {inheritDoc} + */ + public function render(\phpbb\template\template $template) + { + parent::render($template); + + $template->assign_vars(array( + 'S_SEND_USER' => true, + 'S_POST_ACTION' => append_sid($this->phpbb_root_path . 'memberlist.' . $this->phpEx, 'mode=email&u=' . $this->recipient_id), + + 'L_SEND_EMAIL_USER' => $this->user->lang('SEND_EMAIL_USER', $this->recipient_row['username']), + 'USERNAME_FULL' => get_username_string('full', $this->recipient_row['user_id'], $this->recipient_row['username'], $this->recipient_row['user_colour']), + 'SUBJECT' => $this->subject, + 'MESSAGE' => $this->body, + )); + } +} diff --git a/phpBB/phpbb/mimetype/content_guesser.php b/phpBB/phpbb/mimetype/content_guesser.php new file mode 100644 index 0000000000..f3ad7f5f41 --- /dev/null +++ b/phpBB/phpbb/mimetype/content_guesser.php @@ -0,0 +1,33 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\mimetype; + +class content_guesser extends guesser_base +{ + /** + * {@inheritdoc} + */ + public function is_supported() + { + return function_exists('mime_content_type') && is_callable('mime_content_type'); + } + + /** + * {@inheritdoc} + */ + public function guess($file, $file_name = '') + { + return mime_content_type($file); + } +} diff --git a/phpBB/phpbb/mimetype/extension_guesser.php b/phpBB/phpbb/mimetype/extension_guesser.php new file mode 100644 index 0000000000..9e36c07f91 --- /dev/null +++ b/phpBB/phpbb/mimetype/extension_guesser.php @@ -0,0 +1,509 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\mimetype; + +class extension_guesser extends guesser_base +{ + /** + * @var file extension map + */ + protected $extension_map = array( + '3dm' => 'x-world/x-3dmf', + '3dmf' => 'x-world/x-3dmf', + 'a' => 'application/octet-stream', + 'aab' => 'application/x-authorware-bin', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abc' => 'text/vnd.abc', + 'acgi' => 'text/html', + 'afl' => 'video/animaflex', + 'ai' => 'application/postscript', + 'aif' => 'audio/aiff', + 'aifc' => 'audio/aiff', + 'aiff' => 'audio/aiff', + 'aim' => 'application/x-aim', + 'aip' => 'text/x-audiosoft-intra', + 'ani' => 'application/x-navi-animation', + 'aos' => 'application/x-nokia-9000-communicator-add-on-software', + 'aps' => 'application/mime', + 'arc' => 'application/octet-stream', + 'arj' => 'application/arj', + 'art' => 'image/x-jg', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'asp' => 'text/asp', + 'asx' => 'video/x-ms-asf', + 'au' => 'audio/x-au', + 'avi' => 'video/avi', + 'avs' => 'video/avs-video', + 'bcpio' => 'application/x-bcpio', + 'bin' => 'application/x-binary', + 'bm' => 'image/bmp', + 'bmp' => 'image/bmp', + 'boo' => 'application/book', + 'book' => 'application/book', + 'boz' => 'application/x-bzip2', + 'bsh' => 'application/x-bsh', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c++' => 'text/x-c', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cc' => 'text/plain', + 'ccad' => 'application/clariscad', + 'cco' => 'application/x-cocoa', + 'cdf' => 'application/cdf', + 'cer' => 'application/x-x509-ca-cert', + 'cha' => 'application/x-chat', + 'chat' => 'application/x-chat', + 'class' => 'application/java', + 'com' => 'application/octet-stream', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpp' => 'text/x-c', + 'cpt' => 'application/x-cpt', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'csh' => 'application/x-csh', + 'css' => 'text/css', + 'cxx' => 'text/plain', + 'dcr' => 'application/x-director', + 'deepv' => 'application/x-deepv', + 'def' => 'text/plain', + 'der' => 'application/x-x509-ca-cert', + 'dif' => 'video/x-dv', + 'dir' => 'application/x-director', + 'dl' => 'video/dl', + 'doc' => 'application/msword', + 'dot' => 'application/msword', + 'dp' => 'application/commonground', + 'drw' => 'application/drafting', + 'dump' => 'application/octet-stream', + 'dv' => 'video/x-dv', + 'dvi' => 'application/x-dvi', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/x-dwg', + 'dxf' => 'image/x-dwg', + 'dxr' => 'application/x-director', + 'el' => 'text/x-script.elisp', + 'elc' => 'application/x-elc', + 'env' => 'application/x-envoy', + 'eps' => 'application/postscript', + 'es' => 'application/x-esrehber', + 'etx' => 'text/x-setext', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'f' => 'text/x-fortran', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fdf' => 'application/vnd.fdf', + 'fif' => 'image/fif', + 'fli' => 'video/x-fli', + 'flo' => 'image/florian', + 'flx' => 'text/vnd.fmi.flexstor', + 'fmf' => 'video/x-atomic3d-feature', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frl' => 'application/freeloader', + 'funk' => 'audio/make', + 'g' => 'text/plain', + 'g3' => 'image/g3fax', + 'gif' => 'image/gif', + 'gl' => 'video/x-gl', + 'gsd' => 'audio/x-gsm', + 'gsm' => 'audio/x-gsm', + 'gsp' => 'application/x-gsp', + 'gss' => 'application/x-gss', + 'gtar' => 'application/x-gtar', + 'gz' => 'application/x-gzip', + 'gzip' => 'application/x-gzip', + 'h' => 'text/x-h', + 'hdf' => 'application/x-hdf', + 'help' => 'application/x-helpfile', + 'hgl' => 'application/vnd.hp-hpgl', + 'hh' => 'text/x-h', + 'hlb' => 'text/x-script', + 'hlp' => 'application/hlp', + 'hpg' => 'application/vnd.hp-hpgl', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hqx' => 'application/x-binhex40', + 'hta' => 'application/hta', + 'htc' => 'text/x-component', + 'htm' => 'text/html', + 'html' => 'text/html', + 'htmls' => 'text/html', + 'htt' => 'text/webviewhtml', + 'htx' => 'text/html', + 'ice' => 'x-conference/x-cooltalk', + 'ico' => 'image/x-icon', + 'idc' => 'text/plain', + 'ief' => 'image/ief', + 'iefs' => 'image/ief', + 'iges' => 'application/iges', + 'igs' => 'application/iges', + 'ima' => 'application/x-ima', + 'imap' => 'application/x-httpd-imap', + 'inf' => 'application/inf', + 'ins' => 'application/x-internett-signup', + 'ip' => 'application/x-ip2', + 'isu' => 'video/x-isvideo', + 'it' => 'audio/it', + 'iv' => 'application/x-inventor', + 'ivr' => 'i-world/i-vrml', + 'ivy' => 'application/x-livescreen', + 'jam' => 'audio/x-jam', + 'jav' => 'text/plain', + 'jav' => 'text/x-java-source', + 'java' => 'text/x-java-source', + 'jcm' => 'application/x-java-commerce', + 'jfif' => 'image/jpeg', + 'jfif-tbnl' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'jps' => 'image/x-jps', + 'js' => 'application/x-javascript', + 'jut' => 'image/jutvision', + 'kar' => 'audio/midi', + 'ksh' => 'text/x-script.ksh', + 'la' => 'audio/x-nspaudio', + 'lam' => 'audio/x-liveaudio', + 'latex' => 'application/x-latex', + 'lha' => 'application/x-lha', + 'lhx' => 'application/octet-stream', + 'list' => 'text/plain', + 'lma' => 'audio/x-nspaudio', + 'log' => 'text/plain', + 'lsp' => 'text/x-script.lisp', + 'lst' => 'text/plain', + 'lsx' => 'text/x-la-asf', + 'ltx' => 'application/x-latex', + 'lzh' => 'application/x-lzh', + 'lzx' => 'application/x-lzx', + 'm' => 'text/x-m', + 'm1v' => 'video/mpeg', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3u' => 'audio/x-mpequrl', + 'man' => 'application/x-troff-man', + 'map' => 'application/x-navimap', + 'mar' => 'text/plain', + 'mbd' => 'application/mbedlet', + 'mc$' => 'application/x-magic-cap-package-1.0', + 'mcd' => 'application/x-mathcad', + 'mcf' => 'text/mcf', + 'mcp' => 'application/netmc', + 'me' => 'application/x-troff-me', + 'mht' => 'message/rfc822', + 'mhtml' => 'message/rfc822', + 'mid' => 'audio/x-midi', + 'midi' => 'audio/x-midi', + 'mif' => 'application/x-mif', + 'mime' => 'www/mime', + 'mjf' => 'audio/x-vnd.audioexplosion.mjuicemediafile', + 'mjpg' => 'video/x-motion-jpeg', + 'mm' => 'application/x-meme', + 'mme' => 'application/base64', + 'mod' => 'audio/x-mod', + 'moov' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/x-mpeg', + 'mp3' => 'audio/x-mpeg-3', + 'mpa' => 'audio/mpeg', + 'mpc' => 'application/x-project', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpga' => 'audio/mpeg', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/x-project', + 'mpv' => 'application/x-project', + 'mpx' => 'application/x-project', + 'mrc' => 'application/marc', + 'ms' => 'application/x-troff-ms', + 'mv' => 'video/x-sgi-movie', + 'my' => 'audio/make', + 'mzz' => 'application/x-vnd.audioexplosion.mzz', + 'nap' => 'image/naplps', + 'naplps' => 'image/naplps', + 'nc' => 'application/x-netcdf', + 'ncm' => 'application/vnd.nokia.configuration-message', + 'nif' => 'image/x-niff', + 'niff' => 'image/x-niff', + 'nix' => 'application/x-mix-transfer', + 'nsc' => 'application/x-conference', + 'nvd' => 'application/x-navidoc', + 'o' => 'application/octet-stream', + 'oda' => 'application/oda', + 'omc' => 'application/x-omc', + 'omcd' => 'application/x-omcdatamaker', + 'omcr' => 'application/x-omcregerator', + 'p' => 'text/x-pascal', + 'p10' => 'application/x-pkcs10', + 'p12' => 'application/x-pkcs12', + 'p7a' => 'application/x-pkcs7-signature', + 'p7c' => 'application/x-pkcs7-mime', + 'p7m' => 'application/x-pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'part' => 'application/pro_eng', + 'pas' => 'text/pascal', + 'pbm' => 'image/x-portable-bitmap', + 'pcl' => 'application/x-pcl', + 'pct' => 'image/x-pict', + 'pcx' => 'image/x-pcx', + 'pdb' => 'chemical/x-pdb', + 'pdf' => 'application/pdf', + 'pfunk' => 'audio/make.my.funk', + 'pgm' => 'image/x-portable-greymap', + 'pic' => 'image/pict', + 'pict' => 'image/pict', + 'pkg' => 'application/x-newton-compatible-pkg', + 'pko' => 'application/vnd.ms-pki.pko', + 'pl' => 'text/x-script.perl', + 'plx' => 'application/x-pixclscript', + 'pm' => 'text/x-script.perl-module', + 'pm4' => 'application/x-pagemaker', + 'pm5' => 'application/x-pagemaker', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'pot' => 'application/mspowerpoint', + 'pov' => 'model/x-pov', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/mspowerpoint', + 'ppt' => 'application/mspowerpoint', + 'ppz' => 'application/mspowerpoint', + 'pre' => 'application/x-freelance', + 'prt' => 'application/pro_eng', + 'ps' => 'application/postscript', + 'psd' => 'application/octet-stream', + 'pvu' => 'paleovu/x-pv', + 'pwz' => 'application/vnd.ms-powerpoint', + 'py' => 'text/x-script.phyton', + 'pyc' => 'applicaiton/x-bytecode.python', + 'qcp' => 'audio/vnd.qcelp', + 'qd3' => 'x-world/x-3dmf', + 'qd3d' => 'x-world/x-3dmf', + 'qif' => 'image/x-quicktime', + 'qt' => 'video/quicktime', + 'qtc' => 'video/x-qtc', + 'qti' => 'image/x-quicktime', + 'qtif' => 'image/x-quicktime', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'ras' => 'image/x-cmu-raster', + 'rast' => 'image/cmu-raster', + 'rexx' => 'text/x-script.rexx', + 'rf' => 'image/vnd.rn-realflash', + 'rgb' => 'image/x-rgb', + 'rm' => 'audio/x-pn-realaudio', + 'rmi' => 'audio/mid', + 'rmm' => 'audio/x-pn-realaudio', + 'rmp' => 'audio/x-pn-realaudio', + 'rng' => 'application/vnd.nokia.ringing-tone', + 'rnx' => 'application/vnd.rn-realplayer', + 'roff' => 'application/x-troff', + 'rp' => 'image/vnd.rn-realpix', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rt' => 'text/richtext', + 'rtf' => 'text/richtext', + 'rtx' => 'text/richtext', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saveme' => 'application/octet-stream', + 'sbk' => 'application/x-tbook', + 'scm' => 'video/x-scm', + 'sdml' => 'text/plain', + 'sdp' => 'application/x-sdp', + 'sdr' => 'application/sounder', + 'sea' => 'application/x-sea', + 'set' => 'application/set', + 'sgm' => 'text/x-sgml', + 'sgml' => 'text/x-sgml', + 'sh' => 'text/x-script.sh', + 'shar' => 'application/x-shar', + 'shtml' => 'text/x-server-parsed-html', + 'sid' => 'audio/x-psid', + 'sit' => 'application/x-stuffit', + 'skd' => 'application/x-koan', + 'skm' => 'application/x-koan', + 'skp' => 'application/x-koan', + 'skt' => 'application/x-koan', + 'sl' => 'application/x-seelogo', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'snd' => 'audio/x-adpcm', + 'sol' => 'application/solids', + 'spc' => 'text/x-speech', + 'spl' => 'application/futuresplash', + 'spr' => 'application/x-sprite', + 'sprite' => 'application/x-sprite', + 'src' => 'application/x-wais-source', + 'ssi' => 'text/x-server-parsed-html', + 'ssm' => 'application/streamingmedia', + 'sst' => 'application/vnd.ms-pki.certstore', + 'step' => 'application/step', + 'stl' => 'application/vnd.ms-pki.stl', + 'stp' => 'application/step', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svf' => 'image/x-dwg', + 'svr' => 'application/x-world', + 'swf' => 'application/x-shockwave-flash', + 't' => 'application/x-troff', + 'talk' => 'text/x-speech', + 'tar' => 'application/x-tar', + 'tbk' => 'application/x-tbook', + 'tcl' => 'text/x-script.tcl', + 'tcsh' => 'text/x-script.tcsh', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tgz' => 'application/x-compressed', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tr' => 'application/x-troff', + 'tsi' => 'audio/tsp-audio', + 'tsp' => 'audio/tsplayer', + 'tsv' => 'text/tab-separated-values', + 'turbot' => 'image/florian', + 'txt' => 'text/plain', + 'uil' => 'text/x-uil', + 'uni' => 'text/uri-list', + 'unis' => 'text/uri-list', + 'unv' => 'application/i-deas', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'ustar' => 'multipart/x-ustar', + 'uu' => 'text/x-uuencode', + 'uue' => 'text/x-uuencode', + 'vcd' => 'application/x-cdlink', + 'vcs' => 'text/x-vcalendar', + 'vda' => 'application/vda', + 'vdo' => 'video/vdo', + 'vew' => 'application/groupwise', + 'viv' => 'video/vivo', + 'vivo' => 'video/vivo', + 'vmd' => 'application/vocaltec-media-desc', + 'vmf' => 'application/vocaltec-media-file', + 'voc' => 'audio/voc', + 'vos' => 'video/vosaic', + 'vox' => 'audio/voxware', + 'vqe' => 'audio/x-twinvq-plugin', + 'vqf' => 'audio/x-twinvq', + 'vql' => 'audio/x-twinvq-plugin', + 'vrml' => 'application/x-vrml', + 'vrt' => 'x-world/x-vrt', + 'vsd' => 'application/x-visio', + 'vst' => 'application/x-visio', + 'vsw' => 'application/x-visio', + 'w60' => 'application/wordperfect6.0', + 'w61' => 'application/wordperfect6.1', + 'w6w' => 'application/msword', + 'wav' => 'audio/wav', + 'wb1' => 'application/x-qpro', + 'wbmp' => 'image/vnd.wap.wbmp', + 'web' => 'application/vnd.xara', + 'wiz' => 'application/msword', + 'wk1' => 'application/x-123', + 'wmf' => 'windows/metafile', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'word' => 'application/msword', + 'wp' => 'application/wordperfect', + 'wp5' => 'application/wordperfect', + 'wp6' => 'application/wordperfect', + 'wpd' => 'application/wordperfect', + 'wq1' => 'application/x-lotus', + 'wri' => 'application/mswrite', + 'wrl' => 'model/vrml', + 'wrz' => 'model/vrml', + 'wsc' => 'text/scriplet', + 'wsrc' => 'application/x-wais-source', + 'wtk' => 'application/x-wintalk', + 'xbm' => 'image/xbm', + 'xdr' => 'video/x-amt-demorun', + 'xgz' => 'xgl/drawing', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/excel', + 'xla' => 'application/excel', + 'xlb' => 'application/excel', + 'xlc' => 'application/excel', + 'xld' => 'application/excel', + 'xlk' => 'application/excel', + 'xll' => 'application/excel', + 'xlm' => 'application/excel', + 'xls' => 'application/excel', + 'xlt' => 'application/excel', + 'xlv' => 'application/excel', + 'xlw' => 'application/excel', + 'xm' => 'audio/xm', + 'xml' => 'text/xml', + 'xmz' => 'xgl/movie', + 'xpix' => 'application/x-vnd.ls-xpix', + 'xpm' => 'image/xpm', + 'x-png' => 'image/png', + 'xsr' => 'video/x-amt-showrun', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-pdb', + 'z' => 'application/x-compressed', + 'zip' => 'application/x-zip-compressed', + 'zoo' => 'application/octet-stream', + 'zsh' => 'text/x-script.zsh', + ); + + /** + * {@inheritdoc} + */ + public function is_supported() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function guess($file, $file_name = '') + { + $file_name = (empty($file_name)) ? $file : $file_name; + return $this->map_extension_to_type($file_name); + } + + /** + * Map extension of supplied file_name to mime type + * + * @param string $file_name Path to file or filename + * + * @return string|null Mimetype if known or null if not + */ + protected function map_extension_to_type($file_name) + { + $extension = pathinfo($file_name, PATHINFO_EXTENSION); + + if (isset($this->extension_map[$extension])) + { + return $this->extension_map[$extension]; + } + else + { + return null; + } + } +} diff --git a/phpBB/phpbb/mimetype/guesser.php b/phpBB/phpbb/mimetype/guesser.php new file mode 100644 index 0000000000..8baa77089b --- /dev/null +++ b/phpBB/phpbb/mimetype/guesser.php @@ -0,0 +1,156 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\mimetype; + +class guesser +{ + /** + * @const Default priority for mimetype guessers + */ + const PRIORITY_DEFAULT = 0; + + /** + * @var array guessers + */ + protected $guessers; + + /** + * Construct a mimetype guesser object + * + * @param array $mimetype_guessers Mimetype guesser service collection + */ + public function __construct($mimetype_guessers) + { + $this->register_guessers($mimetype_guessers); + } + + /** + * Register MimeTypeGuessers and sort them by priority + * + * @param array $mimetype_guessers Mimetype guesser service collection + * + * @throws \LogicException If incorrect or not mimetype guessers have + * been supplied to class + */ + protected function register_guessers($mimetype_guessers) + { + foreach ($mimetype_guessers as $guesser) + { + $is_supported = (method_exists($guesser, 'is_supported')) ? 'is_supported' : ''; + $is_supported = (method_exists($guesser, 'isSupported')) ? 'isSupported' : $is_supported; + + if (empty($is_supported)) + { + throw new \LogicException('Incorrect mimetype guesser supplied.'); + } + + if ($guesser->$is_supported()) + { + $this->guessers[] = $guesser; + } + } + + if (empty($this->guessers)) + { + throw new \LogicException('No mimetype guesser supplied.'); + } + + // Sort guessers by priority + usort($this->guessers, array($this, 'sort_priority')); + } + + /** + * Sort the priority of supplied guessers + * This is a compare function for usort. A guesser with higher priority + * should be used first and vice versa. usort() orders the array values + * from low to high depending on what the comparison function returns + * to it. Return value should be smaller than 0 if value a is smaller + * than value b. This has been reversed in the comparision function in + * order to sort the guessers from high to low. + * Method has been set to public in order to allow proper testing. + * + * @param object $guesser_a Mimetype guesser a + * @param object $guesser_b Mimetype guesser b + * + * @return int If both guessers have the same priority 0, bigger + * than 0 if first guesser has lower priority, and lower + * than 0 if first guesser has higher priority + */ + public function sort_priority($guesser_a, $guesser_b) + { + $priority_a = (int) (method_exists($guesser_a, 'get_priority')) ? $guesser_a->get_priority() : self::PRIORITY_DEFAULT; + $priority_b = (int) (method_exists($guesser_b, 'get_priority')) ? $guesser_b->get_priority() : self::PRIORITY_DEFAULT; + + return $priority_b - $priority_a; + } + + /** + * Guess mimetype of supplied file + * + * @param string $file Path to file + * @param string $file_name The real file name + * + * @return string Guess for mimetype of file + */ + public function guess($file, $file_name = '') + { + if (!is_file($file)) + { + return false; + } + + if (!is_readable($file)) + { + return false; + } + + $mimetype = 'application/octet-stream'; + + foreach ($this->guessers as $guesser) + { + $mimetype_guess = $guesser->guess($file, $file_name); + + $mimetype = $this->choose_mime_type($mimetype, $mimetype_guess); + } + // Return any mimetype if we got a result or the fallback value + return $mimetype; + } + + /** + * Choose the best mime type based on the current mime type and the guess + * If a guesser returns nulls or application/octet-stream, we will keep + * the current guess. Guesses with a slash inside them will be favored over + * already existing ones. However, any guess that will pass the first check + * will always overwrite the default application/octet-stream. + * + * @param string $mime_type The current mime type + * @param string $guess The current mime type guess + * + * @return string The best mime type based on current mime type and guess + */ + public function choose_mime_type($mime_type, $guess) + { + if ($guess === null || $guess == 'application/octet-stream') + { + return $mime_type; + } + + if ($mime_type == 'application/octet-stream' || strpos($guess, '/') !== false) + { + $mime_type = $guess; + } + + return $mime_type; + } +} diff --git a/phpBB/phpbb/mimetype/guesser_base.php b/phpBB/phpbb/mimetype/guesser_base.php new file mode 100644 index 0000000000..225dfd57dc --- /dev/null +++ b/phpBB/phpbb/mimetype/guesser_base.php @@ -0,0 +1,38 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\mimetype; + +abstract class guesser_base implements guesser_interface +{ + /** + * @var int Guesser Priority + */ + protected $priority; + + /** + * {@inheritdoc} + */ + public function get_priority() + { + return $this->priority; + } + + /** + * {@inheritdoc} + */ + public function set_priority($priority) + { + $this->priority = $priority; + } +} diff --git a/phpBB/phpbb/mimetype/guesser_interface.php b/phpBB/phpbb/mimetype/guesser_interface.php new file mode 100644 index 0000000000..a4005287e4 --- /dev/null +++ b/phpBB/phpbb/mimetype/guesser_interface.php @@ -0,0 +1,50 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\mimetype; + +interface guesser_interface +{ + /** + * Returns whether this guesser is supported on the current OS + * + * @return bool True if guesser is supported, false if not + */ + public function is_supported(); + + /** + * Guess mimetype of supplied file + * + * @param string $file Path to file + * @param string $file_name The real file name + * + * @return string Guess for mimetype of file + */ + public function guess($file, $file_name = ''); + + /** + * Get the guesser priority + * + * @return int Guesser priority + */ + public function get_priority(); + + /** + * Set the guesser priority + * + * @param int Guesser priority + * + * @return void + */ + public function set_priority($priority); +} diff --git a/phpBB/phpbb/notification/exception.php b/phpBB/phpbb/notification/exception.php new file mode 100644 index 0000000000..83c4526df7 --- /dev/null +++ b/phpBB/phpbb/notification/exception.php @@ -0,0 +1,26 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification; + +/** +* Notifications exception +*/ + +class exception extends \Exception +{ + public function __toString() + { + return $this->getMessage(); + } +} diff --git a/phpBB/phpbb/notification/manager.php b/phpBB/phpbb/notification/manager.php new file mode 100644 index 0000000000..f5663f4b34 --- /dev/null +++ b/phpBB/phpbb/notification/manager.php @@ -0,0 +1,990 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** +* Notifications service class +*/ +class manager +{ + /** @var array */ + protected $notification_types; + + /** @var array */ + protected $subscription_types; + + /** @var array */ + protected $notification_methods; + + /** @var ContainerInterface */ + protected $phpbb_container; + + /** @var \phpbb\user_loader */ + protected $user_loader; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\event\dispatcher_interface */ + protected $phpbb_dispatcher; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\cache\service */ + protected $cache; + + /** @var \phpbb\user */ + protected $user; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** @var string */ + protected $notification_types_table; + + /** @var string */ + protected $notifications_table; + + /** @var string */ + protected $user_notifications_table; + + /** + * Notification Constructor + * + * @param array $notification_types + * @param array $notification_methods + * @param ContainerInterface $phpbb_container + * @param \phpbb\user_loader $user_loader + * @param \phpbb\config\config $config + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\cache\service $cache + * @param \phpbb\user $user + * @param string $phpbb_root_path + * @param string $php_ext + * @param string $notification_types_table + * @param string $notifications_table + * @param string $user_notifications_table + * + * @return \phpbb\notification\manager + */ + public function __construct($notification_types, $notification_methods, ContainerInterface $phpbb_container, \phpbb\user_loader $user_loader, \phpbb\config\config $config, \phpbb\event\dispatcher_interface $phpbb_dispatcher, \phpbb\db\driver\driver_interface $db, \phpbb\cache\service $cache, $user, $phpbb_root_path, $php_ext, $notification_types_table, $notifications_table, $user_notifications_table) + { + $this->notification_types = $notification_types; + $this->notification_methods = $notification_methods; + $this->phpbb_container = $phpbb_container; + + $this->user_loader = $user_loader; + $this->config = $config; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->db = $db; + $this->cache = $cache; + $this->user = $user; + + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + + $this->notification_types_table = $notification_types_table; + $this->notifications_table = $notifications_table; + $this->user_notifications_table = $user_notifications_table; + } + + /** + * Load the user's notifications + * + * @param array $options Optional options to control what notifications are loaded + * notification_id Notification id to load (or array of notification ids) + * user_id User id to load notifications for (Default: $user->data['user_id']) + * order_by Order by (Default: notification_time) + * order_dir Order direction (Default: DESC) + * limit Number of notifications to load (Default: 5) + * start Notifications offset (Default: 0) + * all_unread Load all unread notifications? If set to true, count_unread is set to true (Default: false) + * count_unread Count all unread notifications? (Default: false) + * count_total Count all notifications? (Default: false) + * @return array Array of information based on the request with keys: + * 'notifications' array of notification type objects + * 'unread_count' number of unread notifications the user has if count_unread is true in the options + * 'total_count' number of notifications the user has if count_total is true in the options + */ + public function load_notifications(array $options = array()) + { + // Merge default options + $options = array_merge(array( + 'notification_id' => false, + 'user_id' => $this->user->data['user_id'], + 'order_by' => 'notification_time', + 'order_dir' => 'DESC', + 'limit' => 0, + 'start' => 0, + 'all_unread' => false, + 'count_unread' => false, + 'count_total' => false, + ), $options); + + // If all_unread, count_unread must be true + $options['count_unread'] = ($options['all_unread']) ? true : $options['count_unread']; + + // Anonymous users and bots never receive notifications + if ($options['user_id'] == $this->user->data['user_id'] && ($this->user->data['user_id'] == ANONYMOUS || $this->user->data['user_type'] == USER_IGNORE)) + { + return array( + 'notifications' => array(), + 'unread_count' => 0, + 'total_count' => 0, + ); + } + + $notifications = $user_ids = array(); + $load_special = array(); + $total_count = $unread_count = 0; + + if ($options['count_unread']) + { + // Get the total number of unread notifications + $sql = 'SELECT COUNT(n.notification_id) AS unread_count + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.user_id = ' . (int) $options['user_id'] . ' + AND n.notification_read = 0 + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1'; + $result = $this->db->sql_query($sql); + $unread_count = (int) $this->db->sql_fetchfield('unread_count'); + $this->db->sql_freeresult($result); + } + + if ($options['count_total']) + { + // Get the total number of notifications + $sql = 'SELECT COUNT(n.notification_id) AS total_count + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.user_id = ' . (int) $options['user_id'] . ' + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1'; + $result = $this->db->sql_query($sql); + $total_count = (int) $this->db->sql_fetchfield('total_count'); + $this->db->sql_freeresult($result); + } + + if (!$options['count_total'] || $total_count) + { + $rowset = array(); + $selected_unread_count = 0; + + // Get the main notifications + $sql = 'SELECT n.*, nt.notification_type_name + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.user_id = ' . (int) $options['user_id'] . + (($options['notification_id']) ? ' AND ' . $this->db->sql_in_set('n.notification_id', $options['notification_id']) : '') . ' + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1 + ORDER BY n.' . $this->db->sql_escape($options['order_by']) . ' ' . $this->db->sql_escape($options['order_dir']); + $result = $this->db->sql_query_limit($sql, $options['limit'], $options['start']); + + while ($row = $this->db->sql_fetchrow($result)) + { + $rowset[$row['notification_id']] = $row; + $selected_unread_count += (int) !$row['notification_read']; + } + $this->db->sql_freeresult($result); + + // Get all unread notifications + if ($selected_unread_count < $unread_count && $options['all_unread'] && !empty($rowset)) + { + $sql = 'SELECT n.*, nt.notification_type_name + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.user_id = ' . (int) $options['user_id'] . ' + AND n.notification_read = 0 + AND ' . $this->db->sql_in_set('n.notification_id', array_keys($rowset), true) . ' + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1 + ORDER BY n.' . $this->db->sql_escape($options['order_by']) . ' ' . $this->db->sql_escape($options['order_dir']); + $result = $this->db->sql_query_limit($sql, $options['limit'], $options['start']); + + while ($row = $this->db->sql_fetchrow($result)) + { + $rowset[$row['notification_id']] = $row; + } + $this->db->sql_freeresult($result); + } + + foreach ($rowset as $row) + { + $notification = $this->get_item_type_class($row['notification_type_name'], $row); + + // Array of user_ids to query all at once + $user_ids = array_merge($user_ids, $notification->users_to_query()); + + // Some notification types also require querying additional tables themselves + if (!isset($load_special[$row['notification_type_name']])) + { + $load_special[$row['notification_type_name']] = array(); + } + $load_special[$row['notification_type_name']] = array_merge($load_special[$row['notification_type_name']], $notification->get_load_special()); + + $notifications[$row['notification_id']] = $notification; + } + + $this->user_loader->load_users($user_ids); + + // Allow each type to load its own special items + foreach ($load_special as $item_type => $data) + { + $item_class = $this->get_item_type_class($item_type); + + $item_class->load_special($data, $notifications); + } + } + + return array( + 'notifications' => $notifications, + 'unread_count' => $unread_count, + 'total_count' => $total_count, + ); + } + + /** + * Mark notifications read + * + * @param bool|string|array $notification_type_name Type identifier or array of item types (only acceptable if the $data is identical for the specified types). False to mark read for all item types + * @param bool|int|array $item_id Item id or array of item ids. False to mark read for all item ids + * @param bool|int|array $user_id User id or array of user ids. False to mark read for all user ids + * @param bool|int $time Time at which to mark all notifications prior to as read. False to mark all as read. (Default: False) + */ + public function mark_notifications_read($notification_type_name, $item_id, $user_id, $time = false) + { + $time = ($time !== false) ? $time : time(); + + $sql = 'UPDATE ' . $this->notifications_table . " + SET notification_read = 1 + WHERE notification_time <= " . (int) $time . + (($notification_type_name !== false) ? ' AND ' . $this->db->sql_in_set('notification_type_id', $this->get_notification_type_ids($notification_type_name)) : '') . + (($user_id !== false) ? ' AND ' . $this->db->sql_in_set('user_id', $user_id) : '') . + (($item_id !== false) ? ' AND ' . $this->db->sql_in_set('item_id', $item_id) : ''); + $this->db->sql_query($sql); + } + + /** + * Mark notifications read from a parent identifier + * + * @param string|array $notification_type_name Type identifier or array of item types (only acceptable if the $data is identical for the specified types) + * @param bool|int|array $item_parent_id Item parent id or array of item parent ids. False to mark read for all item parent ids + * @param bool|int|array $user_id User id or array of user ids. False to mark read for all user ids + * @param bool|int $time Time at which to mark all notifications prior to as read. False to mark all as read. (Default: False) + */ + public function mark_notifications_read_by_parent($notification_type_name, $item_parent_id, $user_id, $time = false) + { + $time = ($time !== false) ? $time : time(); + + $sql = 'UPDATE ' . $this->notifications_table . " + SET notification_read = 1 + WHERE notification_time <= " . (int) $time . + (($notification_type_name !== false) ? ' AND ' . $this->db->sql_in_set('notification_type_id', $this->get_notification_type_ids($notification_type_name)) : '') . + (($item_parent_id !== false) ? ' AND ' . $this->db->sql_in_set('item_parent_id', $item_parent_id, false, true) : '') . + (($user_id !== false) ? ' AND ' . $this->db->sql_in_set('user_id', $user_id) : ''); + $this->db->sql_query($sql); + } + + /** + * Mark notifications read + * + * @param int|array $notification_id Notification id or array of notification ids. + * @param bool|int $time Time at which to mark all notifications prior to as read. False to mark all as read. (Default: False) + */ + public function mark_notifications_read_by_id($notification_id, $time = false) + { + $time = ($time !== false) ? $time : time(); + + $sql = 'UPDATE ' . $this->notifications_table . " + SET notification_read = 1 + WHERE notification_time <= " . (int) $time . ' + AND ' . $this->db->sql_in_set('notification_id', $notification_id); + $this->db->sql_query($sql); + } + + /** + * Add a notification + * + * @param string|array $notification_type_name Type identifier or array of item types (only acceptable if the $data is identical for the specified types) + * Note: If you send an array of types, any user who could receive multiple notifications from this single item will only receive + * a single notification. If they MUST receive multiple notifications, call this function multiple times instead of sending an array + * @param array $data Data specific for this type that will be inserted + * @param array $options Optional options to control what notifications are loaded + * ignore_users array of data to specify which users should not receive certain types of notifications + * @return array Information about what users were notified and how they were notified + */ + public function add_notifications($notification_type_name, $data, array $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + if (is_array($notification_type_name)) + { + $notified_users = array(); + $temp_options = $options; + + foreach ($notification_type_name as $type) + { + $temp_options['ignore_users'] = $options['ignore_users'] + $notified_users; + $notified_users += $this->add_notifications($type, $data, $temp_options); + } + + return $notified_users; + } + + $item_id = $this->get_item_type_class($notification_type_name)->get_item_id($data); + + // find out which users want to receive this type of notification + $notify_users = $this->get_item_type_class($notification_type_name)->find_users_for_notification($data, $options); + + /** + * Allow filtering the notify_users array for a notification that is about to be sent. + * Here, $notify_users is already filtered by f_read and the ignored list included in the options variable + * + * @event core.notification_manager_add_notifications + * @var string notification_type_name The forum id from where the topic belongs + * @var array data Data specific for the notification_type_name used will be inserted + * @var array notify_users The array of userid that are going to be notified for this notification. Set to array() to cancel. + * @var array options The options that were used when this method was called (read only) + * + * @since 3.1.3-RC1 + */ + $vars = array( + 'notification_type_name', + 'data', + 'notify_users', + 'options', + ); + extract($this->phpbb_dispatcher->trigger_event('core.notification_manager_add_notifications', compact($vars))); + + $this->add_notifications_for_users($notification_type_name, $data, $notify_users); + + return $notify_users; + } + + /** + * Add a notification for specific users + * + * @param string|array $notification_type_name Type identifier or array of item types (only acceptable if the $data is identical for the specified types) + * @param array $data Data specific for this type that will be inserted + * @param array $notify_users User list to notify + */ + public function add_notifications_for_users($notification_type_name, $data, $notify_users) + { + if (is_array($notification_type_name)) + { + foreach ($notification_type_name as $type) + { + $this->add_notifications_for_users($type, $data, $notify_users); + } + + return; + } + + $notification_type_id = $this->get_notification_type_id($notification_type_name); + + $item_id = $this->get_item_type_class($notification_type_name)->get_item_id($data); + + $user_ids = array(); + $notification_objects = $notification_methods = array(); + + // Never send notifications to the anonymous user! + unset($notify_users[ANONYMOUS]); + + // Make sure not to send new notifications to users who've already been notified about this item + // This may happen when an item was added, but now new users are able to see the item + $sql = 'SELECT n.user_id + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.notification_type_id = ' . (int) $notification_type_id . ' + AND n.item_id = ' . (int) $item_id . ' + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1'; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + unset($notify_users[$row['user_id']]); + } + $this->db->sql_freeresult($result); + + if (!sizeof($notify_users)) + { + return; + } + + // Allow notifications to perform actions before creating the insert array (such as run a query to cache some data needed for all notifications) + $notification = $this->get_item_type_class($notification_type_name); + $pre_create_data = $notification->pre_create_insert_array($data, $notify_users); + unset($notification); + + $insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, $this->notifications_table); + + // Go through each user so we can insert a row in the DB and then notify them by their desired means + foreach ($notify_users as $user => $methods) + { + $notification = $this->get_item_type_class($notification_type_name); + + $notification->user_id = (int) $user; + + // Insert notification row using buffer. + $insert_buffer->insert($notification->create_insert_array($data, $pre_create_data)); + + // Users are needed to send notifications + $user_ids = array_merge($user_ids, $notification->users_to_query()); + + foreach ($methods as $method) + { + // setup the notification methods and add the notification to the queue + if ($method) // blank means we just insert it as a notification, but do not notify them by any other means + { + if (!isset($notification_methods[$method])) + { + $notification_methods[$method] = $this->get_method_class($method); + } + + $notification_methods[$method]->add_to_queue($notification); + } + } + } + + $insert_buffer->flush(); + + // We need to load all of the users to send notifications + $this->user_loader->load_users($user_ids); + + // run the queue for each method to send notifications + foreach ($notification_methods as $method) + { + $method->notify(); + } + } + + /** + * Update a notification + * + * @param string|array $notification_type_name Type identifier or array of item types (only acceptable if the $data is identical for the specified types) + * @param array $data Data specific for this type that will be updated + */ + public function update_notifications($notification_type_name, $data) + { + if (is_array($notification_type_name)) + { + foreach ($notification_type_name as $type) + { + $this->update_notifications($type, $data); + } + + return; + } + + $notification = $this->get_item_type_class($notification_type_name); + + // Allow the notifications class to over-ride the update_notifications functionality + if (method_exists($notification, 'update_notifications')) + { + // Return False to over-ride the rest of the update + if ($notification->update_notifications($data) === false) + { + return; + } + } + + $notification_type_id = $this->get_notification_type_id($notification_type_name); + $item_id = $notification->get_item_id($data); + $update_array = $notification->create_update_array($data); + + $sql = 'UPDATE ' . $this->notifications_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $update_array) . ' + WHERE notification_type_id = ' . (int) $notification_type_id . ' + AND item_id = ' . (int) $item_id; + $this->db->sql_query($sql); + } + + /** + * Delete a notification + * + * @param string|array $notification_type_name Type identifier or array of item types (only acceptable if the $item_id is identical for the specified types) + * @param int|array $item_id Identifier within the type (or array of ids) + * @param mixed $parent_id Parent identifier within the type (or array of ids), used in combination with item_id if specified (Default: false; not checked) + */ + public function delete_notifications($notification_type_name, $item_id, $parent_id = false) + { + if (is_array($notification_type_name)) + { + foreach ($notification_type_name as $type) + { + $this->delete_notifications($type, $item_id, $parent_id); + } + + return; + } + + $notification_type_id = $this->get_notification_type_id($notification_type_name); + + $sql = 'DELETE FROM ' . $this->notifications_table . ' + WHERE notification_type_id = ' . (int) $notification_type_id . ' + AND ' . $this->db->sql_in_set('item_id', $item_id) . + (($parent_id !== false) ? ' AND ' . $this->db->sql_in_set('item_parent_id', $parent_id) : ''); + $this->db->sql_query($sql); + } + + /** + * Get all of the subscription types + * + * @return array Array of item types + */ + public function get_subscription_types() + { + if ($this->subscription_types === null) + { + $this->subscription_types = array(); + + foreach ($this->notification_types as $type_name => $data) + { + $type = $this->get_item_type_class($type_name); + + if ($type instanceof \phpbb\notification\type\type_interface && $type->is_available()) + { + $options = array_merge(array( + 'id' => $type->get_type(), + 'lang' => 'NOTIFICATION_TYPE_' . strtoupper($type->get_type()), + 'group' => 'NOTIFICATION_GROUP_MISCELLANEOUS', + ), (($type::$notification_option !== false) ? $type::$notification_option : array())); + + $this->subscription_types[$options['group']][$options['id']] = $options; + } + } + + // Move Miscellaneous to the very last section + if (isset($this->subscription_types['NOTIFICATION_GROUP_MISCELLANEOUS'])) + { + $miscellaneous = $this->subscription_types['NOTIFICATION_GROUP_MISCELLANEOUS']; + unset($this->subscription_types['NOTIFICATION_GROUP_MISCELLANEOUS']); + $this->subscription_types['NOTIFICATION_GROUP_MISCELLANEOUS'] = $miscellaneous; + } + } + + return $this->subscription_types; + } + + /** + * Get all of the subscription methods + * + * @return array Array of methods + */ + public function get_subscription_methods() + { + $subscription_methods = array(); + + foreach ($this->notification_methods as $method_name => $data) + { + $method = $this->get_method_class($method_name); + + if ($method instanceof \phpbb\notification\method\method_interface && $method->is_available()) + { + $subscription_methods[$method_name] = array( + 'id' => $method->get_type(), + 'lang' => str_replace('.', '_', strtoupper($method->get_type())), + ); + } + } + + return $subscription_methods; + } + + + /** + * Get user's notification data + * + * @param int $user_id The user_id of the user to get the notifications for + * + * @return array User's notification + */ + protected function get_user_notifications($user_id) + { + $sql = 'SELECT method, notify, item_type + FROM ' . $this->user_notifications_table . ' + WHERE user_id = ' . (int) $user_id . ' + AND item_id = 0'; + + $result = $this->db->sql_query($sql); + $user_notifications = array(); + + while ($row = $this->db->sql_fetchrow($result)) + { + $user_notifications[$row['item_type']][] = $row; + } + + $this->db->sql_freeresult($result); + + return $user_notifications; + } + + /** + * Get global subscriptions (item_id = 0) + * + * @param bool|int $user_id The user_id to add the subscription for (bool false for current user) + * + * @return array Subscriptions + */ + public function get_global_subscriptions($user_id = false) + { + $user_id = ($user_id === false) ? $this->user->data['user_id'] : $user_id; + + $subscriptions = array(); + + $user_notifications = $this->get_user_notifications($user_id); + + foreach ($this->get_subscription_types() as $types) + { + foreach ($types as $id => $type) + { + + if (empty($user_notifications[$id])) + { + // No rows at all, default to '' + $subscriptions[$id] = array(''); + } + else + { + foreach ($user_notifications[$id] as $user_notification) + { + if (!$user_notification['notify']) + { + continue; + } + + if (!isset($subscriptions[$id])) + { + $subscriptions[$id] = array(); + } + + $subscriptions[$id][] = $user_notification['method']; + } + } + } + } + + return $subscriptions; + } + + /** + * Add a subscription + * + * @param string $item_type Type identifier of the subscription + * @param int $item_id The id of the item + * @param string $method The method of the notification e.g. '', 'email', or 'jabber' + * @param bool|int $user_id The user_id to add the subscription for (bool false for current user) + */ + public function add_subscription($item_type, $item_id = 0, $method = '', $user_id = false) + { + if ($method !== '') + { + // Make sure to subscribe them to the base subscription + $this->add_subscription($item_type, $item_id, '', $user_id); + } + + $user_id = ($user_id === false) ? $this->user->data['user_id'] : $user_id; + + $sql = 'SELECT notify + FROM ' . $this->user_notifications_table . " + WHERE item_type = '" . $this->db->sql_escape($item_type) . "' + AND item_id = " . (int) $item_id . ' + AND user_id = ' .(int) $user_id . " + AND method = '" . $this->db->sql_escape($method) . "'"; + $this->db->sql_query($sql); + $current = $this->db->sql_fetchfield('notify'); + $this->db->sql_freeresult(); + + if ($current === false) + { + $sql = 'INSERT INTO ' . $this->user_notifications_table . ' ' . + $this->db->sql_build_array('INSERT', array( + 'item_type' => $item_type, + 'item_id' => (int) $item_id, + 'user_id' => (int) $user_id, + 'method' => $method, + 'notify' => 1, + )); + $this->db->sql_query($sql); + } + else if (!$current) + { + $sql = 'UPDATE ' . $this->user_notifications_table . " + SET notify = 1 + WHERE item_type = '" . $this->db->sql_escape($item_type) . "' + AND item_id = " . (int) $item_id . ' + AND user_id = ' .(int) $user_id . " + AND method = '" . $this->db->sql_escape($method) . "'"; + $this->db->sql_query($sql); + } + } + + /** + * Delete a subscription + * + * @param string $item_type Type identifier of the subscription + * @param int $item_id The id of the item + * @param string $method The method of the notification e.g. '', 'email', or 'jabber' + * @param bool|int $user_id The user_id to add the subscription for (bool false for current user) + */ + public function delete_subscription($item_type, $item_id = 0, $method = '', $user_id = false) + { + $user_id = ($user_id === false) ? $this->user->data['user_id'] : $user_id; + + // If no method, make sure that no other notification methods for this item are selected before deleting + if ($method === '') + { + $sql = 'SELECT COUNT(*) as num_notifications + FROM ' . $this->user_notifications_table . " + WHERE item_type = '" . $this->db->sql_escape($item_type) . "' + AND item_id = " . (int) $item_id . ' + AND user_id = ' .(int) $user_id . " + AND method <> '' + AND notify = 1"; + $this->db->sql_query($sql); + $num_notifications = $this->db->sql_fetchfield('num_notifications'); + $this->db->sql_freeresult(); + + if ($num_notifications) + { + return; + } + } + + $sql = 'UPDATE ' . $this->user_notifications_table . " + SET notify = 0 + WHERE item_type = '" . $this->db->sql_escape($item_type) . "' + AND item_id = " . (int) $item_id . ' + AND user_id = ' .(int) $user_id . " + AND method = '" . $this->db->sql_escape($method) . "'"; + $this->db->sql_query($sql); + + if (!$this->db->sql_affectedrows()) + { + $sql = 'INSERT INTO ' . $this->user_notifications_table . ' ' . + $this->db->sql_build_array('INSERT', array( + 'item_type' => $item_type, + 'item_id' => (int) $item_id, + 'user_id' => (int) $user_id, + 'method' => $method, + 'notify' => 0, + )); + $this->db->sql_query($sql); + } + } + + /** + * Disable all notifications of a certain type + * + * This should be called when an extension which has notification types + * is disabled so that all those notifications are hidden and do not + * cause errors + * + * @param string $notification_type_name Type identifier of the subscription + */ + public function disable_notifications($notification_type_name) + { + $sql = 'UPDATE ' . $this->notification_types_table . " + SET notification_type_enabled = 0 + WHERE notification_type_name = '" . $this->db->sql_escape($notification_type_name) . "'"; + $this->db->sql_query($sql); + } + + /** + * Purge all notifications of a certain type + * + * This should be called when an extension which has notification types + * is purged so that all those notifications are removed + * + * @param string $notification_type_name Type identifier of the subscription + */ + public function purge_notifications($notification_type_name) + { + // If a notification is never used, its type will not be added to the database + // nor its id cached. If this method is called by an extension during the + // purge step, and that extension never used its notifications, + // get_notification_type_id() will throw an exception. However, + // because no notification type was added to the database, + // there is nothing to delete, so we can silently drop the exception. + try + { + $notification_type_id = $this->get_notification_type_id($notification_type_name); + + $sql = 'DELETE FROM ' . $this->notifications_table . ' + WHERE notification_type_id = ' . (int) $notification_type_id; + $this->db->sql_query($sql); + + $sql = 'DELETE FROM ' . $this->notification_types_table . ' + WHERE notification_type_id = ' . (int) $notification_type_id; + $this->db->sql_query($sql); + + $this->cache->destroy('notification_type_ids'); + } + catch (\phpbb\notification\exception $e) + { + // Continue + } + } + + /** + * Enable all notifications of a certain type + * + * This should be called when an extension which has notification types + * that was disabled is re-enabled so that all those notifications that + * were hidden are shown again + * + * @param string $notification_type_name Type identifier of the subscription + */ + public function enable_notifications($notification_type_name) + { + $sql = 'UPDATE ' . $this->notification_types_table . " + SET notification_type_enabled = 1 + WHERE notification_type_name = '" . $this->db->sql_escape($notification_type_name) . "'"; + $this->db->sql_query($sql); + } + + /** + * Delete all notifications older than a certain time + * + * @param int $timestamp Unix timestamp to delete all notifications that were created before + * @param bool $only_read True (default) to only prune read notifications + */ + public function prune_notifications($timestamp, $only_read = true) + { + $sql = 'DELETE FROM ' . $this->notifications_table . ' + WHERE notification_time < ' . (int) $timestamp . + (($only_read) ? ' AND notification_read = 1' : ''); + $this->db->sql_query($sql); + + $this->config->set('read_notification_last_gc', time(), false); + } + + /** + * Helper to get the notifications item type class and set it up + */ + public function get_item_type_class($notification_type_name, $data = array()) + { + $item = $this->load_object($notification_type_name); + + $item->set_initial_data($data); + + return $item; + } + + /** + * Helper to get the notifications method class and set it up + */ + public function get_method_class($method_name) + { + return $this->load_object($method_name); + } + + /** + * Helper to load objects (notification types/methods) + */ + protected function load_object($object_name) + { + $object = $this->phpbb_container->get($object_name); + + if (method_exists($object, 'set_notification_manager')) + { + $object->set_notification_manager($this); + } + + return $object; + } + + /** + * Get the notification type id from the name + * + * @param string $notification_type_name The name + * @return int the notification_type_id + * @throws \phpbb\notification\exception + */ + public function get_notification_type_id($notification_type_name) + { + $notification_type_ids = $this->cache->get('notification_type_ids'); + + $this->db->sql_transaction('begin'); + + if ($notification_type_ids === false) + { + $notification_type_ids = array(); + + $sql = 'SELECT notification_type_id, notification_type_name + FROM ' . $this->notification_types_table; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $notification_type_ids[$row['notification_type_name']] = (int) $row['notification_type_id']; + } + $this->db->sql_freeresult($result); + + $this->cache->put('notification_type_ids', $notification_type_ids); + } + + if (!isset($notification_type_ids[$notification_type_name])) + { + if (!isset($this->notification_types[$notification_type_name]) && !isset($this->notification_types['notification.type.' . $notification_type_name])) + { + $this->db->sql_transaction('rollback'); + throw new \phpbb\notification\exception($this->user->lang('NOTIFICATION_TYPE_NOT_EXIST', $notification_type_name)); + } + + $sql = 'INSERT INTO ' . $this->notification_types_table . ' ' . $this->db->sql_build_array('INSERT', array( + 'notification_type_name' => $notification_type_name, + 'notification_type_enabled' => 1, + )); + $this->db->sql_query($sql); + + $notification_type_ids[$notification_type_name] = (int) $this->db->sql_nextid(); + + $this->cache->put('notification_type_ids', $notification_type_ids); + } + + $this->db->sql_transaction('commit'); + + return $notification_type_ids[$notification_type_name]; + } + + /** + * Get notification type ids (as an array) + * + * @param string|array $notification_type_names Notification type names + * @return array Array of integers + */ + public function get_notification_type_ids($notification_type_names) + { + if (!is_array($notification_type_names)) + { + $notification_type_names = array($notification_type_names); + } + + $notification_type_ids = array(); + + foreach ($notification_type_names as $name) + { + $notification_type_ids[$name] = $this->get_notification_type_id($name); + } + + return $notification_type_ids; + } +} diff --git a/phpBB/phpbb/notification/method/base.php b/phpBB/phpbb/notification/method/base.php new file mode 100644 index 0000000000..6ee1d2984a --- /dev/null +++ b/phpBB/phpbb/notification/method/base.php @@ -0,0 +1,113 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\method; + +/** +* Base notifications method class +*/ +abstract class base implements \phpbb\notification\method\method_interface +{ + /** @var \phpbb\notification\manager */ + protected $notification_manager; + + /** @var \phpbb\user_loader */ + protected $user_loader; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\cache\driver\driver_interface */ + protected $cache; + + /** @var \phpbb\template\template */ + protected $template; + + /** @var \phpbb\extension\manager */ + protected $extension_manager; + + /** @var \phpbb\user */ + protected $user; + + /** @var \phpbb\auth\auth */ + protected $auth; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** + * Queue of messages to be sent + * + * @var array + */ + protected $queue = array(); + + /** + * Notification Method Base Constructor + * + * @param \phpbb\user_loader $user_loader + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\cache\driver\driver_interface $cache + * @param \phpbb\user $user + * @param \phpbb\auth\auth $auth + * @param \phpbb\config\config $config + * @param string $phpbb_root_path + * @param string $php_ext + * @return \phpbb\notification\method\base + */ + public function __construct(\phpbb\user_loader $user_loader, \phpbb\db\driver\driver_interface $db, \phpbb\cache\driver\driver_interface $cache, $user, \phpbb\auth\auth $auth, \phpbb\config\config $config, $phpbb_root_path, $php_ext) + { + $this->user_loader = $user_loader; + $this->db = $db; + $this->cache = $cache; + $this->user = $user; + $this->auth = $auth; + $this->config = $config; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * Set notification manager (required) + * + * @param \phpbb\notification\manager $notification_manager + */ + public function set_notification_manager(\phpbb\notification\manager $notification_manager) + { + $this->notification_manager = $notification_manager; + } + + /** + * Add a notification to the queue + * + * @param \phpbb\notification\type\type_interface $notification + */ + public function add_to_queue(\phpbb\notification\type\type_interface $notification) + { + $this->queue[] = $notification; + } + + /** + * Empty the queue + */ + protected function empty_queue() + { + $this->queue = array(); + } +} diff --git a/phpBB/phpbb/notification/method/email.php b/phpBB/phpbb/notification/method/email.php new file mode 100644 index 0000000000..a4b93bc85c --- /dev/null +++ b/phpBB/phpbb/notification/method/email.php @@ -0,0 +1,49 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\method; + +/** +* Email notification method class +* This class handles sending emails for notifications +*/ + +class email extends \phpbb\notification\method\messenger_base +{ + /** + * Get notification method name + * + * @return string + */ + public function get_type() + { + return 'notification.method.email'; + } + + /** + * Is this method available for the user? + * This is checked on the notifications options + */ + public function is_available() + { + return $this->config['email_enable'] && $this->user->data['user_email']; + } + + /** + * Parse the queue and notify the users + */ + public function notify() + { + return $this->notify_using_messenger(NOTIFY_EMAIL); + } +} diff --git a/phpBB/phpbb/notification/method/jabber.php b/phpBB/phpbb/notification/method/jabber.php new file mode 100644 index 0000000000..09f186e3ca --- /dev/null +++ b/phpBB/phpbb/notification/method/jabber.php @@ -0,0 +1,66 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\method; + +/** +* Jabber notification method class +* This class handles sending Jabber messages for notifications +*/ + +class jabber extends \phpbb\notification\method\messenger_base +{ + /** + * Get notification method name + * + * @return string + */ + public function get_type() + { + return 'notification.method.jabber'; + } + + /** + * Is this method available for the user? + * This is checked on the notifications options + */ + public function is_available() + { + return ($this->global_available() && $this->user->data['user_jabber']); + } + + /** + * Is this method available at all? + * This is checked before notifications are sent + */ + public function global_available() + { + return !( + empty($this->config['jab_enable']) || + empty($this->config['jab_host']) || + empty($this->config['jab_username']) || + empty($this->config['jab_password']) || + !@extension_loaded('xml') + ); + } + + public function notify() + { + if (!$this->global_available()) + { + return; + } + + return $this->notify_using_messenger(NOTIFY_IM, 'short/'); + } +} diff --git a/phpBB/phpbb/notification/method/messenger_base.php b/phpBB/phpbb/notification/method/messenger_base.php new file mode 100644 index 0000000000..0bfbfd6b02 --- /dev/null +++ b/phpBB/phpbb/notification/method/messenger_base.php @@ -0,0 +1,96 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\method; + +/** +* Abstract notification method handling email and jabber notifications +* using the phpBB messenger. +*/ +abstract class messenger_base extends \phpbb\notification\method\base +{ + /** + * Notify using phpBB messenger + * + * @param int $notify_method Notify method for messenger (e.g. NOTIFY_IM) + * @param string $template_dir_prefix Base directory to prepend to the email template name + * + * @return null + */ + protected function notify_using_messenger($notify_method, $template_dir_prefix = '') + { + if (empty($this->queue)) + { + return; + } + + // Load all users we want to notify (we need their email address) + $user_ids = $users = array(); + foreach ($this->queue as $notification) + { + $user_ids[] = $notification->user_id; + } + + // We do not send emails to banned users + if (!function_exists('phpbb_get_banned_user_ids')) + { + include($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext); + } + $banned_users = phpbb_get_banned_user_ids($user_ids); + + // Load all the users we need + $this->user_loader->load_users($user_ids); + + // Load the messenger + if (!class_exists('messenger')) + { + include($this->phpbb_root_path . 'includes/functions_messenger.' . $this->php_ext); + } + $messenger = new \messenger(); + $board_url = generate_board_url(); + + // Time to go through the queue and send emails + foreach ($this->queue as $notification) + { + if ($notification->get_email_template() === false) + { + continue; + } + + $user = $this->user_loader->get_user($notification->user_id); + + if ($user['user_type'] == USER_IGNORE || ($user['user_type'] == USER_INACTIVE && $user['user_inactive_reason'] == INACTIVE_MANUAL) || in_array($notification->user_id, $banned_users)) + { + continue; + } + + $messenger->template($notification->get_email_template(), $user['user_lang'], '', $template_dir_prefix); + + $messenger->set_addresses($user); + + $messenger->assign_vars(array_merge(array( + 'USERNAME' => $user['username'], + + 'U_NOTIFICATION_SETTINGS' => generate_board_url() . '/ucp.' . $this->php_ext . '?i=ucp_notifications&mode=notification_options', + ), $notification->get_email_template_variables())); + + $messenger->send($notify_method); + } + + // Save the queue in the messenger class (has to be called or these emails could be lost?) + $messenger->save_queue(); + + // We're done, empty the queue + $this->empty_queue(); + } +} diff --git a/phpBB/phpbb/notification/method/method_interface.php b/phpBB/phpbb/notification/method/method_interface.php new file mode 100644 index 0000000000..76b0de179c --- /dev/null +++ b/phpBB/phpbb/notification/method/method_interface.php @@ -0,0 +1,45 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\method; + +/** +* Base notifications method interface +*/ +interface method_interface +{ + /** + * Get notification method name + * + * @return string + */ + public function get_type(); + + /** + * Is this method available for the user? + * This is checked on the notifications options + */ + public function is_available(); + + /** + * Add a notification to the queue + * + * @param \phpbb\notification\type\type_interface $notification + */ + public function add_to_queue(\phpbb\notification\type\type_interface $notification); + + /** + * Parse the queue and notify the users + */ + public function notify(); +} diff --git a/phpBB/phpbb/notification/type/admin_activate_user.php b/phpBB/phpbb/notification/type/admin_activate_user.php new file mode 100644 index 0000000000..7c5c18aa47 --- /dev/null +++ b/phpBB/phpbb/notification/type/admin_activate_user.php @@ -0,0 +1,169 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Admin activation notifications class +* This class handles notifications for users requiring admin activation +*/ + +class admin_activate_user extends \phpbb\notification\type\base +{ + /** + * {@inheritdoc} + */ + public function get_type() + { + return 'notification.type.admin_activate_user'; + } + + /** + * {@inheritdoc} + */ + protected $language_key = 'NOTIFICATION_ADMIN_ACTIVATE_USER'; + + /** + * {@inheritdoc} + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_ADMIN_ACTIVATE_USER', + 'group' => 'NOTIFICATION_GROUP_ADMINISTRATION', + ); + + /** + * {@inheritdoc} + */ + public function is_available() + { + return ($this->auth->acl_get('a_user') && $this->config['require_activation'] == USER_ACTIVATION_ADMIN); + } + + /** + * {@inheritdoc} + */ + public static function get_item_id($user) + { + return (int) $user['user_id']; + } + + /** + * {@inheritdoc} + */ + public static function get_item_parent_id($post) + { + return 0; + } + + /** + * {@inheritdoc} + */ + public function find_users_for_notification($user, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + // Grab admins that have permission to administer users. + $admin_ary = $this->auth->acl_get_list(false, 'a_user', false); + $users = (!empty($admin_ary[0]['a_user'])) ? $admin_ary[0]['a_user'] : array(); + + // Grab founders + $sql = 'SELECT user_id + FROM ' . USERS_TABLE . ' + WHERE user_type = ' . USER_FOUNDER; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $users[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + if (empty($users)) + { + return array(); + } + $users = array_unique($users); + + return $this->check_user_notification_options($users, $options); + } + + /** + * {@inheritdoc} + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->item_id, false, true); + } + + /** + * {@inheritdoc} + */ + public function get_title() + { + $username = $this->user_loader->get_username($this->item_id, 'no_profile'); + + return $this->user->lang($this->language_key, $username); + } + + /** + * {@inheritdoc} + */ + public function get_email_template() + { + return 'admin_activate'; + } + + /** + * {@inheritdoc} + */ + public function get_email_template_variables() + { + $board_url = generate_board_url(); + $username = $this->user_loader->get_username($this->item_id, 'username'); + + return array( + 'USERNAME' => htmlspecialchars_decode($username), + 'U_USER_DETAILS' => "{$board_url}/memberlist.{$this->php_ext}?mode=viewprofile&u={$this->item_id}", + 'U_ACTIVATE' => "{$board_url}/ucp.{$this->php_ext}?mode=activate&u={$this->item_id}&k={$this->get_data('user_actkey')}", + ); + } + + /** + * {@inheritdoc} + */ + public function get_url() + { + return $this->user_loader->get_username($this->item_id, 'profile'); + } + + /** + * {@inheritdoc} + */ + public function users_to_query() + { + return array($this->item_id); + } + + /** + * {@inheritdoc} + */ + public function create_insert_array($user, $pre_create_data) + { + $this->set_data('user_actkey', $user['user_actkey']); + $this->notification_time = $user['user_regdate']; + + return parent::create_insert_array($user, $pre_create_data); + } +} diff --git a/phpBB/phpbb/notification/type/approve_post.php b/phpBB/phpbb/notification/type/approve_post.php new file mode 100644 index 0000000000..5760c12166 --- /dev/null +++ b/phpBB/phpbb/notification/type/approve_post.php @@ -0,0 +1,146 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Post approved notifications class +* This class handles notifications for posts when they are approved (to their authors) +*/ + +class approve_post extends \phpbb\notification\type\post +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.approve_post'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_POST_APPROVED'; + + /** + * Inherit notification read status from post. + * + * @var bool + */ + protected $inherit_read_status = false; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'moderation_queue', + 'lang' => 'NOTIFICATION_TYPE_MODERATION_QUEUE', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Is available + */ + public function is_available() + { + return !$this->auth->acl_get('m_approve'); + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from submit_post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $users = array(); + $users[$post['poster_id']] = array(''); + + return $this->get_authorised_recipients(array_keys($users), $post['forum_id'], array_merge($options, array( + 'item_type' => static::$notification_option['id'], + ))); + } + + /** + * Pre create insert array function + * This allows you to perform certain actions, like run a query + * and load data, before create_insert_array() is run. The data + * returned from this function will be sent to create_insert_array(). + * + * @param array $post Post data from submit_post + * @param array $notify_users Notify users list + * Formated from find_users_for_notification() + * @return array Whatever you want to send to create_insert_array(). + */ + public function pre_create_insert_array($post, $notify_users) + { + // In the parent class, this is used to check if the post is already + // read by a user and marks the notification read if it was marked read. + // Returning an empty array in effect, forces it to be marked as unread + // (and also saves a query) + return array(); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('post_subject', $post['post_subject']); + + $data = parent::create_insert_array($post, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'post_approved'; + } + + /** + * {inheritDoc} + */ + public function get_redirect_url() + { + return $this->get_url(); + } +} diff --git a/phpBB/phpbb/notification/type/approve_topic.php b/phpBB/phpbb/notification/type/approve_topic.php new file mode 100644 index 0000000000..26e51bf9cd --- /dev/null +++ b/phpBB/phpbb/notification/type/approve_topic.php @@ -0,0 +1,136 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Topic approved notifications class +* This class handles notifications for topics when they are approved (for authors) +*/ + +class approve_topic extends \phpbb\notification\type\topic +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.approve_topic'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_TOPIC_APPROVED'; + + /** + * Inherit notification read status from topic. + * + * @var bool + */ + protected $inherit_read_status = false; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'moderation_queue', + 'lang' => 'NOTIFICATION_TYPE_MODERATION_QUEUE', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Is available + */ + public function is_available() + { + return !$this->auth->acl_get('m_approve'); + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from submit_post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $users = array(); + $users[$post['poster_id']] = array(''); + + return $this->get_authorised_recipients(array_keys($users), $post['forum_id'], array_merge($options, array( + 'item_type' => static::$notification_option['id'], + ))); + } + + /** + * Pre create insert array function + * This allows you to perform certain actions, like run a query + * and load data, before create_insert_array() is run. The data + * returned from this function will be sent to create_insert_array(). + * + * @param array $post Post data from submit_post + * @param array $notify_users Notify users list + * Formated from find_users_for_notification() + * @return array Whatever you want to send to create_insert_array(). + */ + public function pre_create_insert_array($post, $notify_users) + { + // In the parent class, this is used to check if the post is already + // read by a user and marks the notification read if it was marked read. + // Returning an empty array in effect, forces it to be marked as unread + // (and also saves a query) + return array(); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $data = parent::create_insert_array($post, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'topic_approved'; + } +} diff --git a/phpBB/phpbb/notification/type/base.php b/phpBB/phpbb/notification/type/base.php new file mode 100644 index 0000000000..4ead06071e --- /dev/null +++ b/phpBB/phpbb/notification/type/base.php @@ -0,0 +1,569 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Base notifications class +*/ +abstract class base implements \phpbb\notification\type\type_interface +{ + /** @var \phpbb\notification\manager */ + protected $notification_manager; + + /** @var \phpbb\user_loader */ + protected $user_loader; + + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\cache\driver\driver_interface */ + protected $cache; + + /** @var \phpbb\template\template */ + protected $template; + + /** @var \phpbb\user */ + protected $user; + + /** @var \phpbb\auth\auth */ + protected $auth; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $php_ext; + + /** @var string */ + protected $notification_types_table; + + /** @var string */ + protected $notifications_table; + + /** @var string */ + protected $user_notifications_table; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use its default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = false; + + /** + * The notification_type_id, set upon creation of the class + * This is the notification_type_id from the notification_types table + * + * @var int + */ + protected $notification_type_id; + + /** + * Indentification data + * notification_type_id - ID of the item type (auto generated, from notification types table) + * item_id - ID of the item (e.g. post_id, msg_id) + * item_parent_id - Parent item id (ex: for topic => forum_id, for post => topic_id, etc) + * user_id + * notification_read + * notification_time + * notification_data (special serialized field that each notification type can use to store stuff) + * + * @var array $data Notification row from the database + * This must be private, all interaction should use __get(), __set(), get_data(), set_data() + */ + private $data = array(); + + /** + * Notification Type Base Constructor + * + * @param \phpbb\user_loader $user_loader + * @param \phpbb\db\driver\driver_interface $db + * @param \phpbb\cache\driver\driver_interface $cache + * @param \phpbb\user $user + * @param \phpbb\auth\auth $auth + * @param \phpbb\config\config $config + * @param string $phpbb_root_path + * @param string $php_ext + * @param string $notification_types_table + * @param string $notifications_table + * @param string $user_notifications_table + * @return \phpbb\notification\type\base + */ + public function __construct(\phpbb\user_loader $user_loader, \phpbb\db\driver\driver_interface $db, \phpbb\cache\driver\driver_interface $cache, $user, \phpbb\auth\auth $auth, \phpbb\config\config $config, $phpbb_root_path, $php_ext, $notification_types_table, $notifications_table, $user_notifications_table) + { + $this->user_loader = $user_loader; + $this->db = $db; + $this->cache = $cache; + $this->user = $user; + $this->auth = $auth; + $this->config = $config; + + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + + $this->notification_types_table = $notification_types_table; + $this->notifications_table = $notifications_table; + $this->user_notifications_table = $user_notifications_table; + } + + /** + * Set notification manager (required) + * + * @param \phpbb\notification\manager $notification_manager + */ + public function set_notification_manager(\phpbb\notification\manager $notification_manager) + { + $this->notification_manager = $notification_manager; + + $this->notification_type_id = $this->notification_manager->get_notification_type_id($this->get_type()); + } + + /** + * Set initial data from the database + * + * @param array $data Row directly from the database + */ + public function set_initial_data($data = array()) + { + // The row from the database (unless this is a new notification we're going to add) + $this->data = $data; + $this->data['notification_data'] = (isset($this->data['notification_data'])) ? unserialize($this->data['notification_data']) : array(); + } + + /** + * Magic method to get data from this notification + * + * @param mixed $name + * @return mixed + */ + public function __get($name) + { + return (!isset($this->data[$name])) ? null : $this->data[$name]; + } + + + /** + * Magic method to set data on this notification + * + * @param mixed $name + * @param mixed $value + * + * @return null + */ + public function __set($name, $value) + { + $this->data[$name] = $value; + } + + + /** + * Magic method to get a string of this notification + * + * Primarily for testing + * + * @return mixed + */ + public function __toString() + { + return (!empty($this->data)) ? var_export($this->data, true) : $this->get_type(); + } + + /** + * Get special data (only important for the classes that extend this) + * + * @param string $name Name of the variable to get + * @return mixed + */ + protected function get_data($name) + { + return ($name === false) ? $this->data['notification_data'] : ((isset($this->data['notification_data'][$name])) ? $this->data['notification_data'][$name] : null); + } + + /** + * Set special data (only important for the classes that extend this) + * + * @param string $name Name of the variable to set + * @param mixed $value Value to set to the variable + * @return mixed + */ + protected function set_data($name, $value) + { + $this->data['notification_data'][$name] = $value; + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $type_data Data unique to this notification type + * @param array $pre_create_data Data from pre_create_insert_array() + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($type_data, $pre_create_data = array()) + { + // Defaults + $this->data = array_merge(array( + 'item_id' => static::get_item_id($type_data), + 'notification_type_id' => $this->notification_type_id, + 'item_parent_id' => static::get_item_parent_id($type_data), + + 'notification_time' => time(), + 'notification_read' => false, + + 'notification_data' => array(), + ), $this->data); + + $data = $this->data; + + $data['notification_data'] = serialize($data['notification_data']); + + return $data; + } + + /** + * Function for preparing the data for update in an SQL query + * (The service handles insertion) + * + * @param array $type_data Data unique to this notification type + * @return array Array of data ready to be updated in the database + */ + public function create_update_array($type_data) + { + $data = $this->create_insert_array($type_data); + + // Unset data unique to each row + unset( + $data['notification_time'], // Also unsetting time, since it always tries to change the time to current (if you actually need to change the time, over-ride this function) + $data['notification_id'], + $data['notification_read'], + $data['user_id'] + ); + + return $data; + } + + /** + * Mark this item read + * + * @param bool $return True to return a string containing the SQL code to update this item, False to execute it (Default: False) + * @return string|null If $return is False, nothing will be returned, else the sql code to update this item + */ + public function mark_read($return = false) + { + return $this->mark(false, $return); + } + + /** + * Mark this item unread + * + * @param bool $return True to return a string containing the SQL code to update this item, False to execute it (Default: False) + * @return string|null If $return is False, nothing will be returned, else the sql code to update this item + */ + public function mark_unread($return = false) + { + return $this->mark(true, $return); + } + + /** + * {inheritDoc} + */ + public function get_redirect_url() + { + return $this->get_url(); + } + + /** + * Prepare to output the notification to the template + * + * @return array Template variables + */ + public function prepare_for_display() + { + $mark_hash = generate_link_hash('mark_notification_read'); + + if ($this->get_url()) + { + $u_mark_read = append_sid($this->phpbb_root_path . 'index.' . $this->php_ext, 'mark_notification=' . $this->notification_id . '&hash=' . $mark_hash); + } + else + { + $redirect = (($this->user->page['page_dir']) ? $this->user->page['page_dir'] . '/' : '') . $this->user->page['page_name'] . (($this->user->page['query_string']) ? '?' . $this->user->page['query_string'] : ''); + + $u_mark_read = append_sid($this->phpbb_root_path . 'index.' . $this->php_ext, 'mark_notification=' . $this->notification_id . '&hash=' . $mark_hash . '&redirect=' . urlencode($redirect)); + } + + return array( + 'NOTIFICATION_ID' => $this->notification_id, + 'STYLING' => $this->get_style_class(), + 'AVATAR' => $this->get_avatar(), + 'FORMATTED_TITLE' => $this->get_title(), + 'REFERENCE' => $this->get_reference(), + 'FORUM' => $this->get_forum(), + 'REASON' => $this->get_reason(), + 'URL' => $this->get_url(), + 'TIME' => $this->user->format_date($this->notification_time), + 'UNREAD' => !$this->notification_read, + 'U_MARK_READ' => (!$this->notification_read) ? $u_mark_read : '', + ); + } + + /** + * -------------- Fall back functions ------------------- + */ + + /** + * URL to unsubscribe to this notification (fall back) + * + * @param string|bool $method Method name to unsubscribe from (email|jabber|etc), False to unsubscribe from all notifications for this item + */ + public function get_unsubscribe_url($method = false) + { + return false; + } + + /** + * Get the CSS style class of the notification (fall back) + * + * @return string + */ + public function get_style_class() + { + return ''; + } + + /** + * Get the user's avatar (fall back) + * + * @return string + */ + public function get_avatar() + { + return ''; + } + + /** + * Get the reference of the notifcation (fall back) + * + * @return string + */ + public function get_reference() + { + return ''; + } + + /** + * Get the forum of the notification reference (fall back) + * + * @return string + */ + public function get_forum() + { + return ''; + } + + /** + * Get the reason for the notifcation (fall back) + * + * @return string + */ + public function get_reason() + { + return ''; + } + + /** + * Get the special items to load (fall back) + * + * @return array + */ + public function get_load_special() + { + return array(); + } + + /** + * Load the special items (fall back) + */ + public function load_special($data, $notifications) + { + return; + } + + /** + * Is available (fall back) + * + * @return bool + */ + public function is_available() + { + return true; + } + + /** + * Pre create insert array function (fall back) + * + * @return array + */ + public function pre_create_insert_array($type_data, $notify_users) + { + return array(); + } + + /** + * -------------- Helper functions ------------------- + */ + + /** + * Find the users who want to receive notifications (helper) + * + * @param array $user_ids User IDs to check if they want to receive notifications + * (Bool False to check all users besides anonymous and bots (USER_IGNORE)) + * + * @return array + */ + protected function check_user_notification_options($user_ids = false, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + 'item_type' => $this->get_type(), + 'item_id' => 0, // Global by default + ), $options); + + if ($user_ids === false) + { + $user_ids = array(); + + $sql = 'SELECT user_id + FROM ' . USERS_TABLE . ' + WHERE user_id <> ' . ANONYMOUS . ' + AND user_type <> ' . USER_IGNORE; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $user_ids[] = $row['user_id']; + } + $this->db->sql_freeresult($result); + } + + if (empty($user_ids)) + { + return array(); + } + + $rowset = $resulting_user_ids = array(); + + $sql = 'SELECT user_id, method, notify + FROM ' . $this->user_notifications_table . ' + WHERE ' . $this->db->sql_in_set('user_id', $user_ids) . " + AND item_type = '" . $this->db->sql_escape($options['item_type']) . "' + AND item_id = " . (int) $options['item_id']; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $resulting_user_ids[] = $row['user_id']; + + if (!$row['notify'] || (isset($options['ignore_users'][$row['user_id']]) && in_array($row['method'], $options['ignore_users'][$row['user_id']]))) + { + continue; + } + + if (!isset($rowset[$row['user_id']])) + { + $rowset[$row['user_id']] = array(); + } + + $rowset[$row['user_id']][] = $row['method']; + } + + $this->db->sql_freeresult($result); + + foreach ($user_ids as $user_id) + { + if (!in_array($user_id, $resulting_user_ids) && !isset($options['ignore_users'][$user_id])) + { + // No rows at all for this user, default to '' + $rowset[$user_id] = array(''); + } + } + + return $rowset; + } + + /** + * Mark this item read/unread helper + * + * @param bool $unread Unread (True/False) (Default: False) + * @param bool $return True to return a string containing the SQL code to update this item, False to execute it (Default: False) + * @return string|null If $return is False, nothing will be returned, else the sql code to update this item + */ + protected function mark($unread = true, $return = false) + { + $this->notification_read = (bool) !$unread; + + $where = array( + 'notification_type_id = ' . (int) $this->notification_type_id, + 'item_id = ' . (int) $this->item_id, + 'user_id = ' . (int) $this->user_id, + ); + $where = implode(' AND ', $where); + + if ($return) + { + return $where; + } + + $sql = 'UPDATE ' . $this->notifications_table . ' + SET notification_read = ' . (int) $this->notification_read . ' + WHERE ' . $where; + $this->db->sql_query($sql); + } + + /** + * Get a list of users that are authorised to receive notifications + * + * @param array $users Array of users that have subscribed to a notification + * @param int $forum_id Forum ID of the forum + * @param array $options Array of notification options + * @param bool $sort Whether the users array should be sorted. Default: false + * @return array Array of users that are authorised recipients + */ + protected function get_authorised_recipients($users, $forum_id, $options, $sort = false) + { + if (empty($users)) + { + return array(); + } + + $users = array_unique($users); + + if ($sort) + { + sort($users); + } + + $auth_read = $this->auth->acl_get_list($users, 'f_read', $forum_id); + + if (empty($auth_read)) + { + return array(); + } + + return $this->check_user_notification_options($auth_read[$forum_id]['f_read'], $options); + } +} diff --git a/phpBB/phpbb/notification/type/bookmark.php b/phpBB/phpbb/notification/type/bookmark.php new file mode 100644 index 0000000000..1626add22c --- /dev/null +++ b/phpBB/phpbb/notification/type/bookmark.php @@ -0,0 +1,132 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Bookmark updating notifications class +* This class handles notifications for replies to a bookmarked topic +*/ + +class bookmark extends \phpbb\notification\type\post +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.bookmark'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_BOOKMARK'; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_BOOKMARK', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Is available + */ + public function is_available() + { + return $this->config['allow_bookmarks']; + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from submit_post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $users = array(); + + $sql = 'SELECT user_id + FROM ' . BOOKMARKS_TABLE . ' + WHERE ' . $this->db->sql_in_set('topic_id', $post['topic_id']) . ' + AND user_id <> ' . (int) $post['poster_id']; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $users[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + $notify_users = $this->get_authorised_recipients($users, $post['forum_id'], $options, true); + + if (empty($notify_users)) + { + return array(); + } + + // Try to find the users who already have been notified about replies and have not read the topic since and just update their notifications + $update_notifications = array(); + $sql = 'SELECT n.* + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.notification_type_id = ' . (int) $this->notification_type_id . ' + AND n.item_parent_id = ' . (int) static::get_item_parent_id($post) . ' + AND n.notification_read = 0 + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1'; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + // Do not create a new notification + unset($notify_users[$row['user_id']]); + + $notification = $this->notification_manager->get_item_type_class($this->get_type(), $row); + $update_responders = $notification->add_responders($post); + if (!empty($update_responders)) + { + $sql = 'UPDATE ' . $this->notifications_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $update_responders) . ' + WHERE notification_id = ' . $row['notification_id']; + $this->db->sql_query($sql); + } + } + $this->db->sql_freeresult($result); + + return $notify_users; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'bookmark'; + } +} diff --git a/phpBB/phpbb/notification/type/disapprove_post.php b/phpBB/phpbb/notification/type/disapprove_post.php new file mode 100644 index 0000000000..6c7bcbcaee --- /dev/null +++ b/phpBB/phpbb/notification/type/disapprove_post.php @@ -0,0 +1,156 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Post disapproved notifications class +* This class handles notifications for posts when they are disapproved (for authors) +*/ + +class disapprove_post extends \phpbb\notification\type\approve_post +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.disapprove_post'; + } + + /** + * Get the CSS style class of the notification + * + * @return string + */ + public function get_style_class() + { + return 'notification-disapproved'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_POST_DISAPPROVED'; + + /** + * Inherit notification read status from post. + * + * @var bool + */ + protected $inherit_read_status = false; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'moderation_queue', + 'lang' => 'NOTIFICATION_TYPE_MODERATION_QUEUE', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + return $this->user->lang($this->language_key); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('topic_title')) + ); + } + + /** + * Get the reason for the disapproval notification + * + * @return string + */ + public function get_reason() + { + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->get_data('disapprove_reason') + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return ''; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + return array_merge(parent::get_email_template_variables(), array( + 'REASON' => htmlspecialchars_decode($this->get_data('disapprove_reason')), + )); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('disapprove_reason', $post['disapprove_reason']); + + $data = parent::create_insert_array($post); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'post_disapproved'; + } +} diff --git a/phpBB/phpbb/notification/type/disapprove_topic.php b/phpBB/phpbb/notification/type/disapprove_topic.php new file mode 100644 index 0000000000..efa5eb7ecd --- /dev/null +++ b/phpBB/phpbb/notification/type/disapprove_topic.php @@ -0,0 +1,156 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Topic disapproved notifications class +* This class handles notifications for topics when they are disapproved (for authors) +*/ + +class disapprove_topic extends \phpbb\notification\type\approve_topic +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.disapprove_topic'; + } + + /** + * Get the CSS style class of the notification + * + * @return string + */ + public function get_style_class() + { + return 'notification-disapproved'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_TOPIC_DISAPPROVED'; + + /** + * Inherit notification read status from topic. + * + * @var bool + */ + protected $inherit_read_status = false; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'moderation_queue', + 'lang' => 'NOTIFICATION_TYPE_MODERATION_QUEUE', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + return $this->user->lang($this->language_key); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('topic_title')) + ); + } + + /** + * Get the reason for the disapproval notification + * + * @return string + */ + public function get_reason() + { + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->get_data('disapprove_reason') + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return ''; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + return array_merge(parent::get_email_template_variables(), array( + 'REASON' => htmlspecialchars_decode($this->get_data('disapprove_reason')), + )); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('disapprove_reason', $post['disapprove_reason']); + + $data = parent::create_insert_array($post, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'topic_disapproved'; + } +} diff --git a/phpBB/phpbb/notification/type/group_request.php b/phpBB/phpbb/notification/type/group_request.php new file mode 100644 index 0000000000..96bfc86322 --- /dev/null +++ b/phpBB/phpbb/notification/type/group_request.php @@ -0,0 +1,161 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +class group_request extends \phpbb\notification\type\base +{ + /** + * {@inheritdoc} + */ + public function get_type() + { + return 'notification.type.group_request'; + } + + /** + * {@inheritdoc} + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_GROUP_REQUEST', + ); + + /** + * {@inheritdoc} + */ + public function is_available() + { + // Leader of any groups? + $sql = 'SELECT group_id + FROM ' . USER_GROUP_TABLE . ' + WHERE user_id = ' . (int) $this->user->data['user_id'] . ' + AND group_leader = 1'; + $result = $this->db->sql_query_limit($sql, 1); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + return (!empty($row)) ? true : false; + } + + /** + * {@inheritdoc} + */ + public static function get_item_id($group) + { + return (int) $group['user_id']; + } + + /** + * {@inheritdoc} + */ + public static function get_item_parent_id($group) + { + // Group id is the parent + return (int) $group['group_id']; + } + + /** + * {@inheritdoc} + */ + public function find_users_for_notification($group, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $sql = 'SELECT user_id + FROM ' . USER_GROUP_TABLE . ' + WHERE group_leader = 1 + AND group_id = ' . (int) $group['group_id']; + $result = $this->db->sql_query($sql); + + $user_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $user_ids[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + $this->user_loader->load_users($user_ids); + + return $this->check_user_notification_options($user_ids, $options); + } + + /** + * {@inheritdoc} + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->item_id, false, true); + } + + /** + * {@inheritdoc} + */ + public function get_title() + { + $username = $this->user_loader->get_username($this->item_id, 'no_profile'); + + return $this->user->lang('NOTIFICATION_GROUP_REQUEST', $username, $this->get_data('group_name')); + } + + /** + * {@inheritdoc} + */ + public function get_email_template() + { + return 'group_request'; + } + + /** + * {@inheritdoc} + */ + public function get_email_template_variables() + { + $user_data = $this->user_loader->get_user($this->item_id); + + return array( + 'GROUP_NAME' => htmlspecialchars_decode($this->get_data('group_name')), + 'REQUEST_USERNAME' => htmlspecialchars_decode($user_data['username']), + + 'U_PENDING' => generate_board_url() . "/ucp.{$this->php_ext}?i=groups&mode=manage&action=list&g={$this->item_parent_id}", + 'U_GROUP' => generate_board_url() . "/memberlist.{$this->php_ext}?mode=group&g={$this->item_parent_id}", + ); + } + + /** + * {@inheritdoc} + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'ucp.' . $this->php_ext, "i=groups&mode=manage&action=list&g={$this->item_parent_id}"); + } + + /** + * {@inheritdoc} + */ + public function users_to_query() + { + return array($this->item_id); + } + + /** + * {@inheritdoc} + */ + public function create_insert_array($group, $pre_create_data = array()) + { + $this->set_data('group_name', $group['group_name']); + + return parent::create_insert_array($group, $pre_create_data); + } +} diff --git a/phpBB/phpbb/notification/type/group_request_approved.php b/phpBB/phpbb/notification/type/group_request_approved.php new file mode 100644 index 0000000000..d284046ffa --- /dev/null +++ b/phpBB/phpbb/notification/type/group_request_approved.php @@ -0,0 +1,116 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +class group_request_approved extends \phpbb\notification\type\base +{ + /** + * {@inheritdoc} + */ + public function get_type() + { + return 'notification.type.group_request_approved'; + } + + /** + * {@inheritdoc} + */ + public function is_available() + { + return false; + } + + /** + * {@inheritdoc} + */ + public static function get_item_id($group) + { + return (int) $group['group_id']; + } + + /** + * {@inheritdoc} + */ + public static function get_item_parent_id($group) + { + return 0; + } + + /** + * {@inheritdoc} + */ + public function find_users_for_notification($group, $options = array()) + { + $users = array(); + + $group['user_ids'] = (!is_array($group['user_ids'])) ? array($group['user_ids']) : $group['user_ids']; + + foreach ($group['user_ids'] as $user_id) + { + $users[$user_id] = array(''); + } + + return $users; + } + + /** + * {@inheritdoc} + */ + public function get_title() + { + return $this->user->lang('NOTIFICATION_GROUP_REQUEST_APPROVED', $this->get_data('group_name')); + } + + /** + * {@inheritdoc} + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'memberlist.' . $this->php_ext, "mode=group&g={$this->item_id}"); + } + + /** + * {@inheritdoc} + */ + public function create_insert_array($group, $pre_create_data = array()) + { + $this->set_data('group_name', $group['group_name']); + + return parent::create_insert_array($group, $pre_create_data); + } + + /** + * {@inheritdoc} + */ + public function users_to_query() + { + return array(); + } + + /** + * {@inheritdoc} + */ + public function get_email_template() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function get_email_template_variables() + { + return array(); + } +} diff --git a/phpBB/phpbb/notification/type/pm.php b/phpBB/phpbb/notification/type/pm.php new file mode 100644 index 0000000000..d2f34f95d0 --- /dev/null +++ b/phpBB/phpbb/notification/type/pm.php @@ -0,0 +1,195 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Private message notifications class +* This class handles notifications for private messages +*/ + +class pm extends \phpbb\notification\type\base +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.pm'; + } + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_PM', + ); + + /** + * Is available + */ + public function is_available() + { + return ($this->config['allow_privmsg'] && $this->auth->acl_get('u_readpm')); + } + + /** + * Get the id of the + * + * @param array $pm The data from the private message + */ + public static function get_item_id($pm) + { + return (int) $pm['msg_id']; + } + + /** + * Get the id of the parent + * + * @param array $pm The data from the pm + */ + public static function get_item_parent_id($pm) + { + // No parent + return 0; + } + + /** + * Find the users who want to receive notifications + * + * @param array $pm Data from submit_pm + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($pm, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + if (!sizeof($pm['recipients'])) + { + return array(); + } + + unset($pm['recipients'][$pm['from_user_id']]); + + $this->user_loader->load_users(array_keys($pm['recipients'])); + + return $this->check_user_notification_options(array_keys($pm['recipients']), $options); + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('from_user_id'), false, true); + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + $username = $this->user_loader->get_username($this->get_data('from_user_id'), 'no_profile'); + + return $this->user->lang('NOTIFICATION_PM', $username); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + $this->get_data('message_subject') + ); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'privmsg_notify'; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + $user_data = $this->user_loader->get_user($this->get_data('from_user_id')); + + return array( + 'AUTHOR_NAME' => htmlspecialchars_decode($user_data['username']), + 'SUBJECT' => htmlspecialchars_decode(censor_text($this->get_data('message_subject'))), + + 'U_VIEW_MESSAGE' => generate_board_url() . '/ucp.' . $this->php_ext . "?i=pm&mode=view&p={$this->item_id}", + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'ucp.' . $this->php_ext, "i=pm&mode=view&p={$this->item_id}"); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + return array($this->get_data('from_user_id')); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $pm Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($pm, $pre_create_data = array()) + { + $this->set_data('from_user_id', $pm['from_user_id']); + + $this->set_data('message_subject', $pm['message_subject']); + + return parent::create_insert_array($pm, $pre_create_data); + } +} diff --git a/phpBB/phpbb/notification/type/post.php b/phpBB/phpbb/notification/type/post.php new file mode 100644 index 0000000000..2969da550d --- /dev/null +++ b/phpBB/phpbb/notification/type/post.php @@ -0,0 +1,452 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Post notifications class +* This class handles notifications for replies to a topic +*/ + +class post extends \phpbb\notification\type\base +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.post'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_POST'; + + /** + * Inherit notification read status from post. + * + * @var bool + */ + protected $inherit_read_status = true; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_POST', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Is available + */ + public function is_available() + { + return $this->config['allow_topic_notify']; + } + + /** + * Get the id of the item + * + * @param array $post The data from the post + */ + public static function get_item_id($post) + { + return (int) $post['post_id']; + } + + /** + * Get the id of the parent + * + * @param array $post The data from the post + */ + public static function get_item_parent_id($post) + { + return (int) $post['topic_id']; + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from submit_post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $users = array(); + + $sql = 'SELECT user_id + FROM ' . TOPICS_WATCH_TABLE . ' + WHERE topic_id = ' . (int) $post['topic_id'] . ' + AND notify_status = ' . NOTIFY_YES . ' + AND user_id <> ' . (int) $post['poster_id']; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $users[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + $sql = 'SELECT user_id + FROM ' . FORUMS_WATCH_TABLE . ' + WHERE forum_id = ' . (int) $post['forum_id'] . ' + AND notify_status = ' . NOTIFY_YES . ' + AND user_id <> ' . (int) $post['poster_id']; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $users[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + $notify_users = $this->get_authorised_recipients($users, $post['forum_id'], $options, true); + + if (empty($notify_users)) + { + return array(); + } + + // Try to find the users who already have been notified about replies and have not read the topic since and just update their notifications + $update_notifications = array(); + $sql = 'SELECT n.* + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.notification_type_id = ' . (int) $this->notification_type_id . ' + AND n.item_parent_id = ' . (int) static::get_item_parent_id($post) . ' + AND n.notification_read = 0 + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1'; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + // Do not create a new notification + unset($notify_users[$row['user_id']]); + + $notification = $this->notification_manager->get_item_type_class($this->get_type(), $row); + $update_responders = $notification->add_responders($post); + if (!empty($update_responders)) + { + $sql = 'UPDATE ' . $this->notifications_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $update_responders) . ' + WHERE notification_id = ' . $row['notification_id']; + $this->db->sql_query($sql); + } + } + $this->db->sql_freeresult($result); + + return $notify_users; + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('poster_id'), false, true); + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + $responders = $this->get_data('responders'); + $usernames = array(); + + if (!is_array($responders)) + { + $responders = array(); + } + + $responders = array_merge(array(array( + 'poster_id' => $this->get_data('poster_id'), + 'username' => $this->get_data('post_username'), + )), $responders); + + $responders_cnt = sizeof($responders); + $responders = $this->trim_user_ary($responders); + $trimmed_responders_cnt = $responders_cnt - sizeof($responders); + + foreach ($responders as $responder) + { + if ($responder['username']) + { + $usernames[] = $responder['username']; + } + else + { + $usernames[] = $this->user_loader->get_username($responder['poster_id'], 'no_profile'); + } + } + + if ($trimmed_responders_cnt > 20) + { + $usernames[] = $this->user->lang('NOTIFICATION_MANY_OTHERS'); + } + else if ($trimmed_responders_cnt) + { + $usernames[] = $this->user->lang('NOTIFICATION_X_OTHERS', $trimmed_responders_cnt); + } + + return $this->user->lang( + $this->language_key, + phpbb_generate_string_list($usernames, $this->user), + $responders_cnt + ); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('topic_title')) + ); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'topic_notify'; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + if ($this->get_data('post_username')) + { + $username = $this->get_data('post_username'); + } + else + { + $username = $this->user_loader->get_username($this->get_data('poster_id'), 'username'); + } + + return array( + 'AUTHOR_NAME' => htmlspecialchars_decode($username), + 'POST_SUBJECT' => htmlspecialchars_decode(censor_text($this->get_data('post_subject'))), + 'TOPIC_TITLE' => htmlspecialchars_decode(censor_text($this->get_data('topic_title'))), + + 'U_VIEW_POST' => generate_board_url() . "/viewtopic.{$this->php_ext}?p={$this->item_id}#p{$this->item_id}", + 'U_NEWEST_POST' => generate_board_url() . "/viewtopic.{$this->php_ext}?f={$this->get_data('forum_id')}&t={$this->item_parent_id}&e=1&view=unread#unread", + 'U_TOPIC' => generate_board_url() . "/viewtopic.{$this->php_ext}?f={$this->get_data('forum_id')}&t={$this->item_parent_id}", + 'U_VIEW_TOPIC' => generate_board_url() . "/viewtopic.{$this->php_ext}?f={$this->get_data('forum_id')}&t={$this->item_parent_id}", + 'U_FORUM' => generate_board_url() . "/viewforum.{$this->php_ext}?f={$this->get_data('forum_id')}", + 'U_STOP_WATCHING_TOPIC' => generate_board_url() . "/viewtopic.{$this->php_ext}?uid={$this->user_id}&f={$this->get_data('forum_id')}&t={$this->item_parent_id}&unwatch=topic", + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'viewtopic.' . $this->php_ext, "p={$this->item_id}#p{$this->item_id}"); + } + + /** + * {inheritDoc} + */ + public function get_redirect_url() + { + return append_sid($this->phpbb_root_path . 'viewtopic.' . $this->php_ext, "t={$this->item_parent_id}&view=unread#unread"); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + $responders = $this->get_data('responders'); + $users = array( + $this->get_data('poster_id'), + ); + + if (is_array($responders)) + { + foreach ($responders as $responder) + { + $users[] = $responder['poster_id']; + } + } + + return $this->trim_user_ary($users); + } + + /** + * Trim the user array passed down to 3 users if the array contains + * more than 4 users. + * + * @param array $users Array of users + * @return array Trimmed array of user_ids + */ + public function trim_user_ary($users) + { + if (sizeof($users) > 4) + { + array_splice($users, 3); + } + return $users; + } + + /** + * Pre create insert array function + * This allows you to perform certain actions, like run a query + * and load data, before create_insert_array() is run. The data + * returned from this function will be sent to create_insert_array(). + * + * @param array $post Post data from submit_post + * @param array $notify_users Notify users list + * Formated from find_users_for_notification() + * @return array Whatever you want to send to create_insert_array(). + */ + public function pre_create_insert_array($post, $notify_users) + { + if (!sizeof($notify_users) || !$this->inherit_read_status) + { + return array(); + } + + $tracking_data = array(); + $sql = 'SELECT user_id, mark_time FROM ' . TOPICS_TRACK_TABLE . ' + WHERE topic_id = ' . (int) $post['topic_id'] . ' + AND ' . $this->db->sql_in_set('user_id', array_keys($notify_users)); + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $tracking_data[$row['user_id']] = $row['mark_time']; + } + $this->db->sql_freeresult($result); + + return $tracking_data; + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('poster_id', $post['poster_id']); + + $this->set_data('topic_title', $post['topic_title']); + + $this->set_data('post_subject', $post['post_subject']); + + $this->set_data('post_username', (($post['poster_id'] == ANONYMOUS) ? $post['post_username'] : '')); + + $this->set_data('forum_id', $post['forum_id']); + + $this->set_data('forum_name', $post['forum_name']); + + $this->notification_time = $post['post_time']; + + // Topics can be "read" before they are public (while awaiting approval). + // Make sure that if the user has read the topic, it's marked as read in the notification + if ($this->inherit_read_status && isset($pre_create_data[$this->user_id]) && $pre_create_data[$this->user_id] >= $this->notification_time) + { + $this->notification_read = true; + } + + return parent::create_insert_array($post, $pre_create_data); + } + + /** + * Add responders to the notification + * + * @param mixed $post + */ + public function add_responders($post) + { + // Do not add them as a responder if they were the original poster that created the notification + if ($this->get_data('poster_id') == $post['poster_id']) + { + return array(); + } + + $responders = $this->get_data('responders'); + + $responders = ($responders === null) ? array() : $responders; + + // Do not add more than 25 responders, + // we trim the username list to "a, b, c and x others" anyway + // so there is no use to add all of them anyway. + if (sizeof($responders) > 25) + { + return array(); + } + + foreach ($responders as $responder) + { + // Do not add them as a responder multiple times + if ($responder['poster_id'] == $post['poster_id']) + { + return array(); + } + } + + $responders[] = array( + 'poster_id' => $post['poster_id'], + 'username' => (($post['poster_id'] == ANONYMOUS) ? $post['post_username'] : ''), + ); + + $this->set_data('responders', $responders); + + $serialized_data = serialize($this->get_data(false)); + + // If the data is longer then 4000 characters, it would cause a SQL error. + // We don't add the username to the list if this is the case. + if (utf8_strlen($serialized_data) >= 4000) + { + return array(); + } + + return array('notification_data' => $serialized_data); + } +} diff --git a/phpBB/phpbb/notification/type/post_in_queue.php b/phpBB/phpbb/notification/type/post_in_queue.php new file mode 100644 index 0000000000..5832c99cd2 --- /dev/null +++ b/phpBB/phpbb/notification/type/post_in_queue.php @@ -0,0 +1,160 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Post in queue notifications class +* This class handles notifications for posts that are put in the moderation queue (for moderators) +*/ + +class post_in_queue extends \phpbb\notification\type\post +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.post_in_queue'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_POST_IN_QUEUE'; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'notification.type.needs_approval', + 'lang' => 'NOTIFICATION_TYPE_IN_MODERATION_QUEUE', + 'group' => 'NOTIFICATION_GROUP_MODERATION', + ); + + /** + * Permission to check for (in find_users_for_notification) + * + * @var string Permission name + */ + protected $permission = 'm_approve'; + + /** + * Is available + */ + public function is_available() + { + $has_permission = $this->auth->acl_getf($this->permission, true); + + return (!empty($has_permission)); + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from the post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + // 0 is for global moderator permissions + $auth_approve = $this->auth->acl_get_list(false, $this->permission, array($post['forum_id'], 0)); + + if (empty($auth_approve)) + { + return array(); + } + + $has_permission = array(); + + if (isset($auth_approve[$post['forum_id']][$this->permission])) + { + $has_permission = $auth_approve[$post['forum_id']][$this->permission]; + } + + if (isset($auth_approve[0][$this->permission])) + { + $has_permission = array_unique(array_merge($has_permission, $auth_approve[0][$this->permission])); + } + sort($has_permission); + + $auth_read = $this->auth->acl_get_list($has_permission, 'f_read', $post['forum_id']); + if (empty($auth_read)) + { + return array(); + } + + return $this->check_user_notification_options($auth_read[$post['forum_id']]['f_read'], array_merge($options, array( + 'item_type' => static::$notification_option['id'], + ))); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'mcp.' . $this->php_ext, "i=queue&mode=approve_details&f={$this->get_data('forum_id')}&p={$this->item_id}"); + } + + /** + * {inheritDoc} + */ + public function get_redirect_url() + { + return parent::get_url(); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $data = parent::create_insert_array($post, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'post_in_queue'; + } +} diff --git a/phpBB/phpbb/notification/type/quote.php b/phpBB/phpbb/notification/type/quote.php new file mode 100644 index 0000000000..2732cb84e4 --- /dev/null +++ b/phpBB/phpbb/notification/type/quote.php @@ -0,0 +1,190 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Post quoting notifications class +* This class handles notifying users when they have been quoted in a post +*/ + +class quote extends \phpbb\notification\type\post +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.quote'; + } + + /** + * regular expression to match to find usernames + * + * @var string + */ + protected static $regular_expression_match = '#\[quote="(.+?)"#'; + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_QUOTE'; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_QUOTE', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Is available + */ + public function is_available() + { + return true; + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from submit_post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $usernames = false; + preg_match_all(static::$regular_expression_match, $post['post_text'], $usernames); + + if (empty($usernames[1])) + { + return array(); + } + + $usernames[1] = array_unique($usernames[1]); + + $usernames = array_map('utf8_clean_string', $usernames[1]); + + $users = array(); + + $sql = 'SELECT user_id + FROM ' . USERS_TABLE . ' + WHERE ' . $this->db->sql_in_set('username_clean', $usernames) . ' + AND user_id <> ' . (int) $post['poster_id']; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $users[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + return $this->get_authorised_recipients($users, $post['forum_id'], $options, true); + } + + /** + * Update a notification + * + * @param array $post Data specific for this type that will be updated + */ + public function update_notifications($post) + { + $old_notifications = array(); + $sql = 'SELECT n.user_id + FROM ' . $this->notifications_table . ' n, ' . $this->notification_types_table . ' nt + WHERE n.notification_type_id = ' . (int) $this->notification_type_id . ' + AND n.item_id = ' . static::get_item_id($post) . ' + AND nt.notification_type_id = n.notification_type_id + AND nt.notification_type_enabled = 1'; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $old_notifications[] = $row['user_id']; + } + $this->db->sql_freeresult($result); + + // Find the new users to notify + $notifications = $this->find_users_for_notification($post); + + // Find the notifications we must delete + $remove_notifications = array_diff($old_notifications, array_keys($notifications)); + + // Find the notifications we must add + $add_notifications = array(); + foreach (array_diff(array_keys($notifications), $old_notifications) as $user_id) + { + $add_notifications[$user_id] = $notifications[$user_id]; + } + + // Add the necessary notifications + $this->notification_manager->add_notifications_for_users($this->get_type(), $post, $add_notifications); + + // Remove the necessary notifications + if (!empty($remove_notifications)) + { + $sql = 'DELETE FROM ' . $this->notifications_table . ' + WHERE notification_type_id = ' . (int) $this->notification_type_id . ' + AND item_id = ' . static::get_item_id($post) . ' + AND ' . $this->db->sql_in_set('user_id', $remove_notifications); + $this->db->sql_query($sql); + } + + // return true to continue with the update code in the notifications service (this will update the rest of the notifications) + return true; + } + + /** + * {inheritDoc} + */ + public function get_redirect_url() + { + return $this->get_url(); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'quote'; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + $user_data = $this->user_loader->get_user($this->get_data('poster_id')); + + return array_merge(parent::get_email_template_variables(), array( + 'AUTHOR_NAME' => htmlspecialchars_decode($user_data['username']), + )); + } +} diff --git a/phpBB/phpbb/notification/type/report_pm.php b/phpBB/phpbb/notification/type/report_pm.php new file mode 100644 index 0000000000..fc39623c5c --- /dev/null +++ b/phpBB/phpbb/notification/type/report_pm.php @@ -0,0 +1,259 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Private message reported notifications class +* This class handles notifications for private messages when they are reported +*/ + +class report_pm extends \phpbb\notification\type\pm +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.report_pm'; + } + + /** + * Get the CSS style class of the notification + * + * @return string + */ + public function get_style_class() + { + return 'notification-reported'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_REPORT_PM'; + + /** + * Permission to check for (in find_users_for_notification) + * + * @var string Permission name + */ + protected $permission = 'm_pm_report'; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'notification.type.report', + 'lang' => 'NOTIFICATION_TYPE_REPORT', + 'group' => 'NOTIFICATION_GROUP_MODERATION', + ); + + /** + * Get the id of the parent + * + * @param array $pm The data from the pm + */ + public static function get_item_parent_id($pm) + { + return (int) $pm['report_id']; + } + + /** + * Is this type available to the current user (defines whether or not it will be shown in the UCP Edit notification options) + * + * @return bool True/False whether or not this is available to the user + */ + public function is_available() + { + $m_approve = $this->auth->acl_getf($this->permission, true); + + return (!empty($m_approve)); + } + + + /** + * Find the users who want to receive notifications + * (copied from post_in_queue) + * + * @param array $post Data from the post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + // Global + $post['forum_id'] = 0; + + $auth_approve = $this->auth->acl_get_list(false, $this->permission, $post['forum_id']); + + if (empty($auth_approve)) + { + return array(); + } + + if (($key = array_search($this->user->data['user_id'], $auth_approve[$post['forum_id']][$this->permission]))) + { + unset($auth_approve[$post['forum_id']][$this->permission][$key]); + } + + return $this->check_user_notification_options($auth_approve[$post['forum_id']][$this->permission], array_merge($options, array( + 'item_type' => static::$notification_option['id'], + ))); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'report_pm'; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + $user_data = $this->user_loader->get_user($this->get_data('reporter_id')); + + return array( + 'AUTHOR_NAME' => htmlspecialchars_decode($user_data['username']), + 'SUBJECT' => htmlspecialchars_decode(censor_text($this->get_data('message_subject'))), + + 'U_VIEW_REPORT' => generate_board_url() . "mcp.{$this->php_ext}?r={$this->item_parent_id}&i=pm_reports&mode=pm_report_details", + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'mcp.' . $this->php_ext, "r={$this->item_parent_id}&i=pm_reports&mode=pm_report_details"); + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + $this->user->add_lang('mcp'); + + $username = $this->user_loader->get_username($this->get_data('reporter_id'), 'no_profile'); + + return $this->user->lang( + $this->language_key, + $username + ); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('message_subject')) + ); + } + + /** + * Get the reason for the notification + * + * @return string + */ + public function get_reason() + { + if ($this->get_data('report_text')) + { + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->get_data('report_text') + ); + } + + if (isset($this->user->lang[$this->get_data('reason_title')])) + { + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->user->lang[$this->get_data('reason_title')] + ); + } + + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->get_data('reason_description') + ); + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('reporter_id'), false, true); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + return array($this->get_data('reporter_id')); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('reporter_id', $this->user->data['user_id']); + $this->set_data('reason_title', strtoupper($post['reason_title'])); + $this->set_data('reason_description', $post['reason_description']); + $this->set_data('report_text', $post['report_text']); + + return parent::create_insert_array($post, $pre_create_data); + } +} diff --git a/phpBB/phpbb/notification/type/report_pm_closed.php b/phpBB/phpbb/notification/type/report_pm_closed.php new file mode 100644 index 0000000000..1c99db60c3 --- /dev/null +++ b/phpBB/phpbb/notification/type/report_pm_closed.php @@ -0,0 +1,165 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* PM report closed notifications class +* This class handles notifications for when reports are closed on PMs (for the one who reported the PM) +*/ + +class report_pm_closed extends \phpbb\notification\type\pm +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.report_pm_closed'; + } + + /** + * Email template to use to send notifications + * + * @var string + */ + public $email_template = ''; + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_REPORT_CLOSED'; + + public function is_available() + { + return false; + } + + /** + * Find the users who want to receive notifications + * + * @param array $pm Data from submit_pm + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($pm, $options = array()) + { + if ($pm['reporter'] == $this->user->data['user_id']) + { + return array(); + } + + return array($pm['reporter'] => array('')); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return false; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + return array(); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return ''; + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + $username = $this->user_loader->get_username($this->get_data('closer_id'), 'no_profile'); + + return $this->user->lang( + $this->language_key, + $username + ); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('message_subject')) + ); + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('closer_id'), false, true); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + return array($this->get_data('closer_id')); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $pm PM Data + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($pm, $pre_create_data = array()) + { + $this->set_data('closer_id', $pm['closer_id']); + + $data = parent::create_insert_array($pm, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } +} diff --git a/phpBB/phpbb/notification/type/report_post.php b/phpBB/phpbb/notification/type/report_post.php new file mode 100644 index 0000000000..aed31e8642 --- /dev/null +++ b/phpBB/phpbb/notification/type/report_post.php @@ -0,0 +1,230 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Reported post notifications class +* This class handles notifications for reported posts +*/ +class report_post extends \phpbb\notification\type\post_in_queue +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.report_post'; + } + + /** + * Get the CSS style class of the notification + * + * @return string + */ + public function get_style_class() + { + return 'notification-reported'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_REPORT_POST'; + + /** + * Inherit notification read status from post. + * + * @var bool + */ + protected $inherit_read_status = false; + + /** + * Permission to check for (in find_users_for_notification) + * + * @var string Permission name + */ + protected $permission = 'm_report'; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id' and 'lang') + */ + public static $notification_option = array( + 'id' => 'notification.type.report', + 'lang' => 'NOTIFICATION_TYPE_REPORT', + 'group' => 'NOTIFICATION_GROUP_MODERATION', + ); + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from the post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + $notify_users = parent::find_users_for_notification($post, $options); + + // never notify reporter + unset($notify_users[$this->user->data['user_id']]); + + return $notify_users; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'report_post'; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + $board_url = generate_board_url(); + + return array( + 'POST_SUBJECT' => htmlspecialchars_decode(censor_text($this->get_data('post_subject'))), + 'TOPIC_TITLE' => htmlspecialchars_decode(censor_text($this->get_data('topic_title'))), + + 'U_VIEW_REPORT' => "{$board_url}/mcp.{$this->php_ext}?f={$this->get_data('forum_id')}&p={$this->item_id}&i=reports&mode=report_details#reports", + 'U_VIEW_POST' => "{$board_url}/viewtopic.{$this->php_ext}?p={$this->item_id}#p{$this->item_id}", + 'U_NEWEST_POST' => "{$board_url}/viewtopic.{$this->php_ext}?f={$this->get_data('forum_id')}&t={$this->item_parent_id}&view=unread#unread", + 'U_TOPIC' => "{$board_url}/viewtopic.{$this->php_ext}?f={$this->get_data('forum_id')}&t={$this->item_parent_id}", + 'U_VIEW_TOPIC' => "{$board_url}/viewtopic.{$this->php_ext}?f={$this->get_data('forum_id')}&t={$this->item_parent_id}", + 'U_FORUM' => "{$board_url}/viewforum.{$this->php_ext}?f={$this->get_data('forum_id')}", + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'mcp.' . $this->php_ext, "f={$this->get_data('forum_id')}&p={$this->item_id}&i=reports&mode=report_details#reports"); + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + $this->user->add_lang('mcp'); + + $username = $this->user_loader->get_username($this->get_data('reporter_id'), 'no_profile'); + + return $this->user->lang( + $this->language_key, + $username + ); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('post_subject')) + ); + } + + /** + * Get the reason for the notification + * + * @return string + */ + public function get_reason() + { + if ($this->get_data('report_text')) + { + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->get_data('report_text') + ); + } + + if (isset($this->user->lang[$this->get_data('reason_title')])) + { + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->user->lang[$this->get_data('reason_title')] + ); + } + + return $this->user->lang( + 'NOTIFICATION_REASON', + $this->get_data('reason_description') + ); + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('reporter_id'), false, true); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + return array($this->get_data('reporter_id')); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('reporter_id', $this->user->data['user_id']); + $this->set_data('reason_title', strtoupper($post['reason_title'])); + $this->set_data('reason_description', $post['reason_description']); + $this->set_data('report_text', $post['report_text']); + + return parent::create_insert_array($post, $pre_create_data); + } +} diff --git a/phpBB/phpbb/notification/type/report_post_closed.php b/phpBB/phpbb/notification/type/report_post_closed.php new file mode 100644 index 0000000000..3f4378628b --- /dev/null +++ b/phpBB/phpbb/notification/type/report_post_closed.php @@ -0,0 +1,172 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Post report closed notifications class +* This class handles notifications for when reports are closed on posts (for the one who reported the post) +*/ + +class report_post_closed extends \phpbb\notification\type\post +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.report_post_closed'; + } + + /** + * Email template to use to send notifications + * + * @var string + */ + public $email_template = ''; + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_REPORT_CLOSED'; + + /** + * Inherit notification read status from post. + * + * @var bool + */ + protected $inherit_read_status = false; + + public function is_available() + { + return false; + } + + /** + * Find the users who want to receive notifications + * + * @param array $post Data from submit_post + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($post, $options = array()) + { + if ($post['reporter'] == $this->user->data['user_id']) + { + return array(); + } + + return array($post['reporter'] => array('')); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return false; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + return array(); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return ''; + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + $username = $this->user_loader->get_username($this->get_data('closer_id'), 'no_profile'); + + return $this->user->lang( + $this->language_key, + $username + ); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('post_subject')) + ); + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('closer_id'), false, true); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + return array($this->get_data('closer_id')); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('closer_id', $post['closer_id']); + + $data = parent::create_insert_array($post, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } +} diff --git a/phpBB/phpbb/notification/type/topic.php b/phpBB/phpbb/notification/type/topic.php new file mode 100644 index 0000000000..fb08a9eee1 --- /dev/null +++ b/phpBB/phpbb/notification/type/topic.php @@ -0,0 +1,295 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Topic notifications class +* This class handles notifications for new topics +*/ + +class topic extends \phpbb\notification\type\base +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.topic'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_TOPIC'; + + /** + * Inherit notification read status from topic. + * + * @var bool + */ + protected $inherit_read_status = true; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'lang' => 'NOTIFICATION_TYPE_TOPIC', + 'group' => 'NOTIFICATION_GROUP_POSTING', + ); + + /** + * Is available + */ + public function is_available() + { + return $this->config['allow_forum_notify']; + } + + /** + * Get the id of the item + * + * @param array $post The data from the post + */ + public static function get_item_id($post) + { + return (int) $post['topic_id']; + } + + /** + * Get the id of the parent + * + * @param array $post The data from the post + */ + public static function get_item_parent_id($post) + { + return (int) $post['forum_id']; + } + + /** + * Find the users who want to receive notifications + * + * @param array $topic Data from the topic + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($topic, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + $users = array(); + + $sql = 'SELECT user_id + FROM ' . FORUMS_WATCH_TABLE . ' + WHERE forum_id = ' . (int) $topic['forum_id'] . ' + AND notify_status = ' . NOTIFY_YES . ' + AND user_id <> ' . (int) $topic['poster_id']; + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $users[] = (int) $row['user_id']; + } + $this->db->sql_freeresult($result); + + return $this->get_authorised_recipients($users, $topic['forum_id'], $options); + } + + /** + * Get the user's avatar + */ + public function get_avatar() + { + return $this->user_loader->get_avatar($this->get_data('poster_id'), false, true); + } + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title() + { + if ($this->get_data('post_username')) + { + $username = $this->get_data('post_username'); + } + else + { + $username = $this->user_loader->get_username($this->get_data('poster_id'), 'no_profile'); + } + + return $this->user->lang( + $this->language_key, + $username + ); + } + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference() + { + return $this->user->lang( + 'NOTIFICATION_REFERENCE', + censor_text($this->get_data('topic_title')) + ); + } + + /** + * Get the forum of the notification reference + * + * @return string + */ + public function get_forum() + { + return $this->user->lang( + 'NOTIFICATION_FORUM', + $this->get_data('forum_name') + ); + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'newtopic_notify'; + } + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables() + { + $board_url = generate_board_url(); + + if ($this->get_data('post_username')) + { + $username = $this->get_data('post_username'); + } + else + { + $username = $this->user_loader->get_username($this->get_data('poster_id'), 'username'); + } + + return array( + 'AUTHOR_NAME' => htmlspecialchars_decode($username), + 'FORUM_NAME' => htmlspecialchars_decode($this->get_data('forum_name')), + 'TOPIC_TITLE' => htmlspecialchars_decode(censor_text($this->get_data('topic_title'))), + + 'U_TOPIC' => "{$board_url}/viewtopic.{$this->php_ext}?f={$this->item_parent_id}&t={$this->item_id}", + 'U_VIEW_TOPIC' => "{$board_url}/viewtopic.{$this->php_ext}?f={$this->item_parent_id}&t={$this->item_id}", + 'U_FORUM' => "{$board_url}/viewforum.{$this->php_ext}?f={$this->item_parent_id}", + 'U_STOP_WATCHING_FORUM' => "{$board_url}/viewforum.{$this->php_ext}?uid={$this->user_id}&f={$this->item_parent_id}&unwatch=forum", + ); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'viewtopic.' . $this->php_ext, "f={$this->item_parent_id}&t={$this->item_id}"); + } + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query() + { + return array($this->get_data('poster_id')); + } + + /** + * Pre create insert array function + * This allows you to perform certain actions, like run a query + * and load data, before create_insert_array() is run. The data + * returned from this function will be sent to create_insert_array(). + * + * @param array $post Post data from submit_post + * @param array $notify_users Notify users list + * Formated from find_users_for_notification() + * @return array Whatever you want to send to create_insert_array(). + */ + public function pre_create_insert_array($post, $notify_users) + { + if (!sizeof($notify_users) || !$this->inherit_read_status) + { + return array(); + } + + $tracking_data = array(); + $sql = 'SELECT user_id, mark_time FROM ' . TOPICS_TRACK_TABLE . ' + WHERE topic_id = ' . (int) $post['topic_id'] . ' + AND ' . $this->db->sql_in_set('user_id', array_keys($notify_users)); + $result = $this->db->sql_query($sql); + while ($row = $this->db->sql_fetchrow($result)) + { + $tracking_data[$row['user_id']] = $row['mark_time']; + } + $this->db->sql_freeresult($result); + + return $tracking_data; + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $post Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($post, $pre_create_data = array()) + { + $this->set_data('poster_id', $post['poster_id']); + + $this->set_data('topic_title', $post['topic_title']); + + $this->set_data('post_username', (($post['poster_id'] == ANONYMOUS) ? $post['post_username'] : '')); + + $this->set_data('forum_name', $post['forum_name']); + + $this->notification_time = $post['post_time']; + + // Topics can be "read" before they are public (while awaiting approval). + // Make sure that if the user has read the topic, it's marked as read in the notification + if ($this->inherit_read_status && isset($pre_create_data[$this->user_id]) && $pre_create_data[$this->user_id] >= $this->notification_time) + { + $this->notification_read = true; + } + + return parent::create_insert_array($post, $pre_create_data); + } +} diff --git a/phpBB/phpbb/notification/type/topic_in_queue.php b/phpBB/phpbb/notification/type/topic_in_queue.php new file mode 100644 index 0000000000..6e57b9ac0c --- /dev/null +++ b/phpBB/phpbb/notification/type/topic_in_queue.php @@ -0,0 +1,152 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Topic in queue notifications class +* This class handles notifications for topics when they are put in the moderation queue (for moderators) +*/ + +class topic_in_queue extends \phpbb\notification\type\topic +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type() + { + return 'notification.type.topic_in_queue'; + } + + /** + * Language key used to output the text + * + * @var string + */ + protected $language_key = 'NOTIFICATION_TOPIC_IN_QUEUE'; + + /** + * Notification option data (for outputting to the user) + * + * @var bool|array False if the service should use it's default data + * Array of data (including keys 'id', 'lang', and 'group') + */ + public static $notification_option = array( + 'id' => 'notification.type.needs_approval', + 'lang' => 'NOTIFICATION_TYPE_IN_MODERATION_QUEUE', + 'group' => 'NOTIFICATION_GROUP_MODERATION', + ); + + /** + * Permission to check for (in find_users_for_notification) + * + * @var string Permission name + */ + protected $permission = 'm_approve'; + + /** + * Is available + */ + public function is_available() + { + $has_permission = $this->auth->acl_getf($this->permission, true); + + return (!empty($has_permission)); + } + + /** + * Find the users who want to receive notifications + * + * @param array $topic Data from the topic + * @param array $options Options for finding users for notification + * + * @return array + */ + public function find_users_for_notification($topic, $options = array()) + { + $options = array_merge(array( + 'ignore_users' => array(), + ), $options); + + // 0 is for global moderator permissions + $auth_approve = $this->auth->acl_get_list(false, 'm_approve', array($topic['forum_id'], 0)); + + if (empty($auth_approve)) + { + return array(); + } + + $has_permission = array(); + + if (isset($auth_approve[$topic['forum_id']][$this->permission])) + { + $has_permission = $auth_approve[$topic['forum_id']][$this->permission]; + } + + if (isset($auth_approve[0][$this->permission])) + { + $has_permission = array_unique(array_merge($has_permission, $auth_approve[0][$this->permission])); + } + sort($has_permission); + + $auth_read = $this->auth->acl_get_list($has_permission, 'f_read', $topic['forum_id']); + if (empty($auth_read)) + { + return array(); + } + + return $this->check_user_notification_options($auth_read[$topic['forum_id']]['f_read'], array_merge($options, array( + 'item_type' => static::$notification_option['id'], + ))); + } + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url() + { + return append_sid($this->phpbb_root_path . 'mcp.' . $this->php_ext, "i=queue&mode=approve_details&f={$this->item_parent_id}&t={$this->item_id}"); + } + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $topic Data from submit_post + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($topic, $pre_create_data = array()) + { + $data = parent::create_insert_array($topic, $pre_create_data); + + $this->notification_time = $data['notification_time'] = time(); + + return $data; + } + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template() + { + return 'topic_in_queue'; + } +} diff --git a/phpBB/phpbb/notification/type/type_interface.php b/phpBB/phpbb/notification/type/type_interface.php new file mode 100644 index 0000000000..5c5a110836 --- /dev/null +++ b/phpBB/phpbb/notification/type/type_interface.php @@ -0,0 +1,214 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\notification\type; + +/** +* Base notifications interface +*/ +interface type_interface +{ + /** + * Get notification type name + * + * @return string + */ + public function get_type(); + + /** + * Set initial data from the database + * + * @param array $data Row directly from the database + */ + public function set_initial_data($data); + + /** + * Get the id of the item + * + * @param array $type_data The type specific data + */ + public static function get_item_id($type_data); + + /** + * Get the id of the parent + * + * @param array $type_data The type specific data + */ + public static function get_item_parent_id($type_data); + + /** + * Is this type available to the current user (defines whether or not it will be shown in the UCP Edit notification options) + * + * @return bool True/False whether or not this is available to the user + */ + public function is_available(); + + /** + * Find the users who want to receive notifications + * + * @param array $type_data The type specific data + * @param array $options Options for finding users for notification + * ignore_users => array of users and user types that should not receive notifications from this type because they've already been notified + * e.g.: array(2 => array(''), 3 => array('', 'email'), ...) + * + * @return array + */ + public function find_users_for_notification($type_data, $options); + + /** + * Users needed to query before this notification can be displayed + * + * @return array Array of user_ids + */ + public function users_to_query(); + + /** + * Get the special items to load + * + * @return array Data will be combined sent to load_special() so you can run a single query and get data required for this notification type + */ + public function get_load_special(); + + /** + * Load the special items + * + * @param array $data Data from get_load_special() + * @param array $notifications Array of notifications (key is notification_id, value is the notification objects) + */ + public function load_special($data, $notifications); + + /** + * Get the CSS style class of the notification + * + * @return string + */ + public function get_style_class(); + + /** + * Get the HTML formatted title of this notification + * + * @return string + */ + public function get_title(); + + /** + * Get the HTML formatted reference of the notification + * + * @return string + */ + public function get_reference(); + + /** + * Get the forum of the notification reference + * + * @return string + */ + public function get_forum(); + + /** + * Get the url to this item + * + * @return string URL + */ + public function get_url(); + + /** + * Get the url to redirect after the item has been marked as read + * + * @return string URL + */ + public function get_redirect_url(); + + /** + * URL to unsubscribe to this notification + * + * @param string|bool $method Method name to unsubscribe from (email|jabber|etc), False to unsubscribe from all notifications for this item + */ + public function get_unsubscribe_url($method); + + /** + * Get the user's avatar (the user who caused the notification typically) + * + * @return string + */ + public function get_avatar(); + + /** + * Prepare to output the notification to the template + */ + public function prepare_for_display(); + + /** + * Get email template + * + * @return string|bool + */ + public function get_email_template(); + + /** + * Get email template variables + * + * @return array + */ + public function get_email_template_variables(); + + /** + * Pre create insert array function + * This allows you to perform certain actions, like run a query + * and load data, before create_insert_array() is run. The data + * returned from this function will be sent to create_insert_array(). + * + * @param array $type_data The type specific data + * @param array $notify_users Notify users list + * Formated from find_users_for_notification() + * @return array Whatever you want to send to create_insert_array(). + */ + public function pre_create_insert_array($type_data, $notify_users); + + /** + * Function for preparing the data for insertion in an SQL query + * (The service handles insertion) + * + * @param array $type_data The type specific data + * @param array $pre_create_data Data from pre_create_insert_array() + * + * @return array Array of data ready to be inserted into the database + */ + public function create_insert_array($type_data, $pre_create_data); + + /** + * Function for preparing the data for update in an SQL query + * (The service handles insertion) + * + * @param array $type_data Data unique to this notification type + * + * @return array Array of data ready to be updated in the database + */ + public function create_update_array($type_data); + + /** + * Mark this item read + * + * @param bool $return True to return a string containing the SQL code to update this item, False to execute it (Default: False) + * @return string + */ + public function mark_read($return); + + /** + * Mark this item unread + * + * @param bool $return True to return a string containing the SQL code to update this item, False to execute it (Default: False) + * @return string + */ + public function mark_unread($return); +} diff --git a/phpBB/phpbb/pagination.php b/phpBB/phpbb/pagination.php new file mode 100644 index 0000000000..7a81c25ad2 --- /dev/null +++ b/phpBB/phpbb/pagination.php @@ -0,0 +1,357 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +class pagination +{ + /** @var \phpbb\template\template */ + protected $template; + + /** @var \phpbb\user */ + protected $user; + + /** @var \phpbb\controller\helper */ + protected $helper; + + /** @var \phpbb\event\dispatcher_interface */ + protected $phpbb_dispatcher; + + /** + * Constructor + * + * @param \phpbb\template\template $template + * @param \phpbb\user $user + * @param \phpbb\controller\helper $helper + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher + */ + public function __construct(\phpbb\template\template $template, \phpbb\user $user, \phpbb\controller\helper $helper, \phpbb\event\dispatcher_interface $phpbb_dispatcher) + { + $this->template = $template; + $this->user = $user; + $this->helper = $helper; + $this->phpbb_dispatcher = $phpbb_dispatcher; + } + + /** + * Generate a pagination link based on the url and the page information + * + * @param string $base_url is url prepended to all links generated within the function + * If you use page numbers inside your controller route, base_url should contains a placeholder (%d) + * for the page. Also be sure to specify the pagination path information into the start_name argument + * @param string $on_page is the page for which we want to generate the link + * @param string $start_name is the name of the parameter containing the first item of the given page (example: start=20) + * If you use page numbers inside your controller route, start name should be the string + * that should be removed for the first page (example: /page/%d) + * @param int $per_page the number of items, posts, etc. to display per page, used to determine the number of pages to produce + * @return string URL for the requested page + */ + protected function generate_page_link($base_url, $on_page, $start_name, $per_page) + { + // A listener can set this variable to the new pagination URL + // to override the generate_page_link() function generated value + $generate_page_link_override = false; + + /** + * Execute code and/or override generate_page_link() + * + * To override the generate_page_link() function generated value + * set $generate_page_link_override to the new URL value + * + * @event core.pagination_generate_page_link + * @var string base_url is url prepended to all links generated within the function + * If you use page numbers inside your controller route, base_url should contains a placeholder (%d) + * for the page. Also be sure to specify the pagination path information into the start_name argument + * @var string on_page is the page for which we want to generate the link + * @var string start_name is the name of the parameter containing the first item of the given page (example: start=20) + * If you use page numbers inside your controller route, start name should be the string + * that should be removed for the first page (example: /page/%d) + * @var int per_page the number of items, posts, etc. to display per page, used to determine the number of pages to produce + * @var bool|string generate_page_link_override Shall we return custom pagination link (string URL) or not (false) + * @since 3.1.0-RC5 + */ + $vars = array('base_url', 'on_page', 'start_name', 'per_page', 'generate_page_link_override'); + extract($this->phpbb_dispatcher->trigger_event('core.pagination_generate_page_link', compact($vars))); + + if ($generate_page_link_override) + { + return $generate_page_link_override; + } + + if (!is_string($base_url)) + { + if (is_array($base_url['routes'])) + { + $route = ($on_page > 1) ? $base_url['routes'][1] : $base_url['routes'][0]; + } + else + { + $route = $base_url['routes']; + } + $params = (isset($base_url['params'])) ? $base_url['params'] : array(); + $is_amp = (isset($base_url['is_amp'])) ? $base_url['is_amp'] : true; + $session_id = (isset($base_url['session_id'])) ? $base_url['session_id'] : false; + + if ($on_page > 1 || !is_array($base_url['routes'])) + { + $params[$start_name] = (int) $on_page; + } + + return $this->helper->route($route, $params, $is_amp, $session_id); + } + else + { + $url_delim = (strpos($base_url, '?') === false) ? '?' : ((strpos($base_url, '?') === strlen($base_url) - 1) ? '' : '&'); + return ($on_page > 1) ? $base_url . $url_delim . $start_name . '=' . (($on_page - 1) * $per_page) : $base_url; + } + } + + /** + * Generate template rendered pagination + * Allows full control of rendering of pagination with the template + * + * @param string $base_url is url prepended to all links generated within the function + * If you use page numbers inside your controller route, base_url should contains a placeholder (%d) + * for the page. Also be sure to specify the pagination path information into the start_name argument + * @param string $block_var_name is the name assigned to the pagination data block within the template (example: <!-- BEGIN pagination -->) + * @param string $start_name is the name of the parameter containing the first item of the given page (example: start=20) + * If you use page numbers inside your controller route, start name should be the string + * that should be removed for the first page (example: /page/%d) + * @param int $num_items the total number of items, posts, etc., used to determine the number of pages to produce + * @param int $per_page the number of items, posts, etc. to display per page, used to determine the number of pages to produce + * @param int $start the item which should be considered currently active, used to determine the page we're on + * @param bool $reverse_count determines whether we weight display of the list towards the start (false) or end (true) of the list + * @param bool $ignore_on_page decides whether we enable an active (unlinked) item, used primarily for embedded lists + * @return null + */ + public function generate_template_pagination($base_url, $block_var_name, $start_name, $num_items, $per_page, $start = 1, $reverse_count = false, $ignore_on_page = false) + { + $total_pages = ceil($num_items / $per_page); + $on_page = $this->get_on_page($per_page, $start); + $u_previous_page = $u_next_page = ''; + + if ($total_pages > 1) + { + if ($reverse_count) + { + $start_page = ($total_pages > 5) ? $total_pages - 4 : 1; + $end_page = $total_pages; + } + else + { + // What we're doing here is calculating what the "start" and "end" pages should be. We + // do this by assuming pagination is "centered" around the currently active page with + // the three previous and three next page links displayed. Anything more than that and + // we display the ellipsis, likewise anything less. + // + // $start_page is the page at which we start creating the list. When we have five or less + // pages we start at page 1 since there will be no ellipsis displayed. Anymore than that + // and we calculate the start based on the active page. This is the min/max calculation. + // First (max) would we end up starting on a page less than 1? Next (min) would we end + // up starting so close to the end that we'd not display our minimum number of pages. + // + // $end_page is the last page in the list to display. Like $start_page we use a min/max to + // determine this number. Again at most five pages? Then just display them all. More than + // five and we first (min) determine whether we'd end up listing more pages than exist. + // We then (max) ensure we're displaying the minimum number of pages. + $start_page = ($total_pages > 5) ? min(max(1, $on_page - 2), $total_pages - 4) : 1; + $end_page = ($total_pages > 5) ? max(min($total_pages, $on_page + 2), 5) : $total_pages; + } + + if ($on_page != 1) + { + $u_previous_page = $this->generate_page_link($base_url, $on_page - 1, $start_name, $per_page); + + $this->template->assign_block_vars($block_var_name, array( + 'PAGE_NUMBER' => '', + 'PAGE_URL' => $u_previous_page, + 'S_IS_CURRENT' => false, + 'S_IS_PREV' => true, + 'S_IS_NEXT' => false, + 'S_IS_ELLIPSIS' => false, + )); + } + + // This do...while exists purely to negate the need for start and end assign_block_vars, i.e. + // to display the first and last page in the list plus any ellipsis. We use this loop to jump + // around a little within the list depending on where we're starting (and ending). + $at_page = 1; + do + { + // We decide whether to display the ellipsis during the loop. The ellipsis is always + // displayed as either the second or penultimate item in the list. So are we at either + // of those points and of course do we even need to display it, i.e. is the list starting + // on at least page 3 and ending three pages before the final item. + $this->template->assign_block_vars($block_var_name, array( + 'PAGE_NUMBER' => $at_page, + 'PAGE_URL' => $this->generate_page_link($base_url, $at_page, $start_name, $per_page), + 'S_IS_CURRENT' => (!$ignore_on_page && $at_page == $on_page), + 'S_IS_NEXT' => false, + 'S_IS_PREV' => false, + 'S_IS_ELLIPSIS' => ($at_page == 2 && $start_page > 2) || ($at_page == $total_pages - 1 && $end_page < $total_pages - 1), + )); + + // We may need to jump around in the list depending on whether we have or need to display + // the ellipsis. Are we on page 2 and are we more than one page away from the start + // of the list? Yes? Then we jump to the start of the list. Likewise are we at the end of + // the list and are there more than two pages left in total? Yes? Then jump to the penultimate + // page (so we can display the ellipsis next pass). Else, increment the counter and keep + // going + if ($at_page == 2 && $at_page < $start_page - 1) + { + $at_page = $start_page; + } + else if ($at_page == $end_page && $end_page < $total_pages - 1) + { + $at_page = $total_pages - 1; + } + else + { + $at_page++; + } + } + while ($at_page <= $total_pages); + + if ($on_page != $total_pages) + { + $u_next_page = $this->generate_page_link($base_url, $on_page + 1, $start_name, $per_page); + + $this->template->assign_block_vars($block_var_name, array( + 'PAGE_NUMBER' => '', + 'PAGE_URL' => $u_next_page, + 'S_IS_CURRENT' => false, + 'S_IS_PREV' => false, + 'S_IS_NEXT' => true, + 'S_IS_ELLIPSIS' => false, + )); + } + } + + // If the block_var_name is a nested block, we will use the last (most + // inner) block as a prefix for the template variables. If the last block + // name is pagination, the prefix is empty. If the rest of the + // block_var_name is not empty, we will modify the last row of that block + // and add our pagination items. + $tpl_block_name = $tpl_prefix = ''; + if (strrpos($block_var_name, '.') !== false) + { + $tpl_block_name = substr($block_var_name, 0, strrpos($block_var_name, '.')); + $tpl_prefix = strtoupper(substr($block_var_name, strrpos($block_var_name, '.') + 1)); + } + else + { + $tpl_prefix = strtoupper($block_var_name); + } + $tpl_prefix = ($tpl_prefix == 'PAGINATION') ? '' : $tpl_prefix . '_'; + + $template_array = array( + $tpl_prefix . 'BASE_URL' => is_string($base_url) ? $base_url : '',//@todo: Fix this for routes + $tpl_prefix . 'START_NAME' => $start_name, + $tpl_prefix . 'PER_PAGE' => $per_page, + 'U_' . $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page != 1) ? $u_previous_page : '', + 'U_' . $tpl_prefix . 'NEXT_PAGE' => ($on_page != $total_pages) ? $u_next_page : '', + $tpl_prefix . 'TOTAL_PAGES' => $total_pages, + $tpl_prefix . 'CURRENT_PAGE' => $on_page, + $tpl_prefix . 'PAGE_NUMBER' => $this->on_page($num_items, $per_page, $start), + ); + + if ($tpl_block_name) + { + $this->template->alter_block_array($tpl_block_name, $template_array, true, 'change'); + } + else + { + $this->template->assign_vars($template_array); + } + } + + /** + * Get current page number + * + * @param int $per_page the number of items, posts, etc. per page + * @param int $start the item which should be considered currently active, used to determine the page we're on + * @return int Current page number + */ + public function get_on_page($per_page, $start) + { + return floor($start / $per_page) + 1; + } + + /** + * Return current page + * + * @param int $num_items the total number of items, posts, topics, etc. + * @param int $per_page the number of items, posts, etc. per page + * @param int $start the item which should be considered currently active, used to determine the page we're on + * @return string Descriptive pagination string (e.g. "page 1 of 10") + */ + public function on_page($num_items, $per_page, $start) + { + $on_page = $this->get_on_page($per_page, $start); + return $this->user->lang('PAGE_OF', $on_page, max(ceil($num_items / $per_page), 1)); + } + + /** + * Get current page number + * + * @param int $start the item which should be considered currently active, used to determine the page we're on + * @param int $per_page the number of items, posts, etc. per page + * @param int $num_items the total number of items, posts, topics, etc. + * @return int Current page number + */ + public function validate_start($start, $per_page, $num_items) + { + if ($start < 0 || $start >= $num_items) + { + return ($start < 0 || $num_items <= 0) ? 0 : floor(($num_items - 1) / $per_page) * $per_page; + } + + return $start; + } + + /** + * Get new start when searching from the end + * + * If the user is trying to reach late pages, start searching from the end. + * + * @param int $start the item which should be considered currently active, used to determine the page we're on + * @param int $limit the number of items, posts, etc. to display + * @param int $num_items the total number of items, posts, topics, etc. + * @return int Current page number + */ + public function reverse_start($start, $limit, $num_items) + { + return max(0, $num_items - $limit - $start); + } + + /** + * Get new item limit when searching from the end + * + * If the user is trying to reach late pages, start searching from the end. + * In this case the items to display might be lower then the actual per_page setting. + * + * @param int $start the item which should be considered currently active, used to determine the page we're on + * @param int $per_page the number of items, posts, etc. per page + * @param int $num_items the total number of items, posts, topics, etc. + * @return int Current page number + */ + public function reverse_limit($start, $per_page, $num_items) + { + if ($start + $per_page > $num_items) + { + return min($per_page, max(1, $num_items - $start)); + } + + return $per_page; + } +} diff --git a/phpBB/phpbb/passwords/driver/base.php b/phpBB/phpbb/passwords/driver/base.php new file mode 100644 index 0000000000..fd07a61bf4 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/base.php @@ -0,0 +1,62 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +abstract class base implements driver_interface +{ + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\passwords\driver\helper */ + protected $helper; + + /** @var driver name */ + protected $name; + + /** + * Constructor of passwords driver object + * + * @param \phpbb\config\config $config phpBB config + * @param \phpbb\passwords\driver\helper $helper Password driver helper + */ + public function __construct(\phpbb\config\config $config, helper $helper) + { + $this->config = $config; + $this->helper = $helper; + } + + /** + * {@inheritdoc} + */ + public function is_supported() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function get_settings_only($hash, $full = false) + { + return false; + } +} diff --git a/phpBB/phpbb/passwords/driver/bcrypt.php b/phpBB/phpbb/passwords/driver/bcrypt.php new file mode 100644 index 0000000000..eab1c3d569 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/bcrypt.php @@ -0,0 +1,105 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class bcrypt extends base +{ + const PREFIX = '$2a$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $salt = '') + { + // The 2x and 2y prefixes of bcrypt might not be supported + // Revert to 2a if this is the case + $prefix = (!$this->is_supported()) ? '$2a$' : $this->get_prefix(); + + // Do not support 8-bit characters with $2a$ bcrypt + // Also see http://www.php.net/security/crypt_blowfish.php + if ($prefix === self::PREFIX) + { + if (ord($password[strlen($password)-1]) & 128) + { + return false; + } + } + + if ($salt == '') + { + $salt = $prefix . '10$' . $this->get_random_salt(); + } + + $hash = crypt($password, $salt); + if (strlen($hash) < 60) + { + return false; + } + return $hash; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + $salt = substr($hash, 0, 29); + if (strlen($salt) != 29) + { + return false; + } + + if ($this->helper->string_compare($hash, $this->hash($password, $salt))) + { + return true; + } + return false; + } + + /** + * Get a random salt value with a length of 22 characters + * + * @return string Salt for password hashing + */ + protected function get_random_salt() + { + return $this->helper->hash_encode64($this->helper->get_random_salt(22), 22); + } + + /** + * {@inheritdoc} + */ + public function get_settings_only($hash, $full = false) + { + if ($full) + { + $pos = stripos($hash, '$', 1) + 1; + $length = 22 + (strripos($hash, '$') + 1 - $pos); + } + else + { + $pos = strripos($hash, '$') + 1; + $length = 22; + } + return substr($hash, $pos, $length); + } +} diff --git a/phpBB/phpbb/passwords/driver/bcrypt_2y.php b/phpBB/phpbb/passwords/driver/bcrypt_2y.php new file mode 100644 index 0000000000..c710e0d04a --- /dev/null +++ b/phpBB/phpbb/passwords/driver/bcrypt_2y.php @@ -0,0 +1,35 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class bcrypt_2y extends bcrypt +{ + const PREFIX = '$2y$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_supported() + { + return (version_compare(PHP_VERSION, '5.3.7', '<')) ? false : true; + } +} diff --git a/phpBB/phpbb/passwords/driver/bcrypt_wcf2.php b/phpBB/phpbb/passwords/driver/bcrypt_wcf2.php new file mode 100644 index 0000000000..0eee98d7b7 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/bcrypt_wcf2.php @@ -0,0 +1,84 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class bcrypt_wcf2 extends base +{ + const PREFIX = '$wcf2$'; + + /** @var \phpbb\passwords\driver\bcrypt */ + protected $bcrypt; + + /** @var \phpbb\passwords\driver\helper */ + protected $helper; + + /** + * Constructor of passwords driver object + * + * @param \phpbb\passwords\driver\bcrypt $bcrypt Salted md5 driver + * @param \phpbb\passwords\driver\helper $helper Password driver helper + */ + public function __construct(\phpbb\passwords\driver\bcrypt $bcrypt, helper $helper) + { + $this->bcrypt = $bcrypt; + $this->helper = $helper; + } + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (empty($hash) || strlen($hash) != 60) + { + return false; + } + else + { + $salt = substr($hash, 0, 29); + + if (strlen($salt) != 29) + { + return false; + } + // Works for standard WCF 2.x, i.e. WBB4 and similar + return $this->helper->string_compare($hash, $this->bcrypt->hash($this->bcrypt->hash($password, $salt), $salt)); + } + } +} diff --git a/phpBB/phpbb/passwords/driver/convert_password.php b/phpBB/phpbb/passwords/driver/convert_password.php new file mode 100644 index 0000000000..eb70434df2 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/convert_password.php @@ -0,0 +1,43 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class convert_password extends base +{ + const PREFIX = '$CP$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + return false; + } +} diff --git a/phpBB/phpbb/passwords/driver/driver_interface.php b/phpBB/phpbb/passwords/driver/driver_interface.php new file mode 100644 index 0000000000..3974484f13 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/driver_interface.php @@ -0,0 +1,69 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +interface driver_interface +{ + /** + * Check if hash type is supported + * + * @return bool True if supported, false if not + */ + public function is_supported(); + + /** + * Check if hash type is a legacy hash type + * + * @return bool True if it's a legacy hash type, false if not + */ + public function is_legacy(); + + /** + * Returns the hash prefix + * + * @return string Hash prefix + */ + public function get_prefix(); + + /** + * Hash the password + * + * @param string $password The password that should be hashed + * + * @return bool|string Password hash or false if something went wrong + * during hashing + */ + public function hash($password); + + /** + * Check the password against the supplied hash + * + * @param string $password The password to check + * @param string $hash The password hash to check against + * @param array $user_row User's row in users table + * + * @return bool True if password is correct, else false + */ + public function check($password, $hash, $user_row = array()); + + /** + * Get only the settings of the specified hash + * + * @param string $hash Password hash + * @param bool $full Return full settings or only settings + * related to the salt + * @return string String containing the hash settings + */ + public function get_settings_only($hash, $full = false); +} diff --git a/phpBB/phpbb/passwords/driver/helper.php b/phpBB/phpbb/passwords/driver/helper.php new file mode 100644 index 0000000000..f80c3e3df6 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/helper.php @@ -0,0 +1,177 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class helper +{ + /** + * @var \phpbb\config\config + */ + protected $config; + + /** + * base64 alphabet + * @var string + */ + public $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + + /** + * Construct a driver helper object + * + * @param \phpbb\config\config $config phpBB configuration + */ + public function __construct(\phpbb\config\config $config) + { + $this->config = $config; + } + + /** + * Base64 encode hash + * + * @param string $input Input string + * @param int $count Input string length + * + * @return string base64 encoded string + */ + public function hash_encode64($input, $count) + { + $output = ''; + $i = 0; + + do + { + $value = ord($input[$i++]); + $output .= $this->itoa64[$value & 0x3f]; + + if ($i < $count) + { + $value |= ord($input[$i]) << 8; + } + + $output .= $this->itoa64[($value >> 6) & 0x3f]; + + if ($i++ >= $count) + { + break; + } + + if ($i < $count) + { + $value |= ord($input[$i]) << 16; + } + + $output .= $this->itoa64[($value >> 12) & 0x3f]; + + if ($i++ >= $count) + { + break; + } + + $output .= $this->itoa64[($value >> 18) & 0x3f]; + } + while ($i < $count); + + return $output; + } + + /** + * Return unique id + * + * @param string $extra Additional entropy + * + * @return string Unique id + */ + public function unique_id($extra = 'c') + { + static $dss_seeded = false; + + $val = $this->config['rand_seed'] . microtime(); + $val = md5($val); + $this->config['rand_seed'] = md5($this->config['rand_seed'] . $val . $extra); + + if ($dss_seeded !== true && ($this->config['rand_seed_last_update'] < time() - rand(1,10))) + { + $this->config->set('rand_seed_last_update', time(), true); + $this->config->set('rand_seed', $this->config['rand_seed'], true); + $dss_seeded = true; + } + + return substr($val, 4, 16); + } + + /** + * Get random salt with specified length + * + * @param int $length Salt length + * @param string $rand_seed Seed for random data (optional). For tests. + * + * @return string Random salt with specified length + */ + public function get_random_salt($length, $rand_seed = '/dev/urandom') + { + $random = ''; + + if (($fh = @fopen($rand_seed, 'rb'))) + { + $random = fread($fh, $length); + fclose($fh); + } + + if (strlen($random) < $length) + { + $random = ''; + $random_state = $this->unique_id(); + + for ($i = 0; $i < $length; $i += 16) + { + $random_state = md5($this->unique_id() . $random_state); + $random .= pack('H*', md5($random_state)); + } + $random = substr($random, 0, $length); + } + return $random; + } + + /** + * Compare two strings byte by byte + * + * @param string $string_a The first string + * @param string $string_b The second string + * + * @return bool True if strings are the same, false if not + */ + public function string_compare($string_a, $string_b) + { + // Return if input variables are not strings or if length does not match + if (!is_string($string_a) || !is_string($string_b) || strlen($string_a) != strlen($string_b)) + { + return false; + } + + // Use hash_equals() if it's available + if (function_exists('hash_equals')) + { + return hash_equals($string_a, $string_b); + } + + $difference = 0; + + for ($i = 0; $i < strlen($string_a) && $i < strlen($string_b); $i++) + { + $difference |= ord($string_a[$i]) ^ ord($string_b[$i]); + } + + return $difference === 0; + } +} diff --git a/phpBB/phpbb/passwords/driver/md5_mybb.php b/phpBB/phpbb/passwords/driver/md5_mybb.php new file mode 100644 index 0000000000..f631ceae78 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/md5_mybb.php @@ -0,0 +1,60 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class md5_mybb extends base +{ + const PREFIX = '$md5_mybb$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (empty($hash) || strlen($hash) != 32 || !isset($user_row['user_passwd_salt'])) + { + return false; + } + else + { + // Works for myBB 1.1.x, 1.2.x, 1.4.x, 1.6.x + return $this->helper->string_compare($hash, md5(md5($user_row['user_passwd_salt']) . md5($password))); + } + } +} diff --git a/phpBB/phpbb/passwords/driver/md5_phpbb2.php b/phpBB/phpbb/passwords/driver/md5_phpbb2.php new file mode 100644 index 0000000000..bd8cc51e5a --- /dev/null +++ b/phpBB/phpbb/passwords/driver/md5_phpbb2.php @@ -0,0 +1,123 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class md5_phpbb2 extends base +{ + const PREFIX = '$md5_phpbb2$'; + + /** @var \phpbb\request\request phpBB request object */ + protected $request; + + /** @var \phpbb\passwords\driver\salted_md5 */ + protected $salted_md5; + + /** @var \phpbb\passwords\driver\helper */ + protected $helper; + + /** @var string phpBB root path */ + protected $phpbb_root_path; + + /** @var string php file extension */ + protected $php_ext; + + /** + * Constructor of passwords driver object + * + * @param \phpbb\request\request $request phpBB request object + * @param \phpbb\passwords\driver\salted_md5 $salted_md5 Salted md5 driver + * @param \phpbb\passwords\driver\helper $helper Driver helper + * @param string $phpbb_root_path phpBB root path + * @param string $php_ext PHP file extension + */ + public function __construct($request, salted_md5 $salted_md5, helper $helper, $phpbb_root_path, $php_ext) + { + $this->request = $request; + $this->salted_md5 = $salted_md5; + $this->helper = $helper; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + } + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (strlen($hash) != 32 && strlen($hash) != 34) + { + return false; + } + + // enable super globals to get literal value + // this is needed to prevent unicode normalization + $super_globals_disabled = $this->request->super_globals_disabled(); + if ($super_globals_disabled) + { + $this->request->enable_super_globals(); + } + + // in phpBB2 passwords were used exactly as they were sent, with addslashes applied + $password_old_format = isset($_REQUEST['password']) ? (string) $_REQUEST['password'] : ''; + $password_old_format = (!STRIP) ? addslashes($password_old_format) : $password_old_format; + $password_new_format = $this->request->variable('password', '', true); + + if ($super_globals_disabled) + { + $this->request->disable_super_globals(); + } + + if ($password == $password_new_format) + { + if (!function_exists('utf8_to_cp1252')) + { + include($this->phpbb_root_path . 'includes/utf/data/recode_basic.' . $this->php_ext); + } + + if ($this->helper->string_compare(md5($password_old_format), $hash) || $this->helper->string_compare(md5(\utf8_to_cp1252($password_old_format)), $hash) + || $this->salted_md5->check(md5($password_old_format), $hash) === true + || $this->salted_md5->check(md5(\utf8_to_cp1252($password_old_format)), $hash) === true) + { + return true; + } + } + + return false; + } +} diff --git a/phpBB/phpbb/passwords/driver/md5_vb.php b/phpBB/phpbb/passwords/driver/md5_vb.php new file mode 100644 index 0000000000..280b7114c7 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/md5_vb.php @@ -0,0 +1,60 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class md5_vb extends base +{ + const PREFIX = '$md5_vb$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (empty($hash) || strlen($hash) != 32 || !isset($user_row['user_passwd_salt'])) + { + return false; + } + else + { + // Works for vB 3.8.x, 4.x.x, 5.0.x + return $this->helper->string_compare($hash, md5(md5($password) . $user_row['user_passwd_salt'])); + } + } +} diff --git a/phpBB/phpbb/passwords/driver/phpass.php b/phpBB/phpbb/passwords/driver/phpass.php new file mode 100644 index 0000000000..bef8355276 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/phpass.php @@ -0,0 +1,27 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class phpass extends salted_md5 +{ + const PREFIX = '$P$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } +} diff --git a/phpBB/phpbb/passwords/driver/salted_md5.php b/phpBB/phpbb/passwords/driver/salted_md5.php new file mode 100644 index 0000000000..38d6d9cd2c --- /dev/null +++ b/phpBB/phpbb/passwords/driver/salted_md5.php @@ -0,0 +1,169 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +/** +* +* @version Version 0.1 / slightly modified for phpBB 3.1.x (using $H$ as hash type identifier) +* +* Portable PHP password hashing framework. +* +* Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in +* the public domain. +* +* There's absolutely no warranty. +* +* The homepage URL for this framework is: +* +* http://www.openwall.com/phpass/ +* +* Please be sure to update the Version line if you edit this file in any way. +* It is suggested that you leave the main version number intact, but indicate +* your project name (after the slash) and add your own revision information. +* +* Please do not change the "private" password hashing method implemented in +* here, thereby making your hashes incompatible. However, if you must, please +* change the hash type identifier (the "$P$") to something different. +* +* Obviously, since this code is in the public domain, the above are not +* requirements (there can be none), but merely suggestions. +* +*/ + +class salted_md5 extends base +{ + const PREFIX = '$H$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $setting = '') + { + if ($setting) + { + if (($settings = $this->get_hash_settings($setting)) === false) + { + // Return md5 of password if settings do not + // comply with our standards. This will only + // happen if pre-determined settings are + // directly passed to the driver. The manager + // will not do this. Same as the old hashing + // implementation in phpBB 3.0 + return md5($password); + } + } + else + { + $settings = $this->get_hash_settings($this->generate_salt()); + } + + $hash = md5($settings['salt'] . $password, true); + do + { + $hash = md5($hash . $password, true); + } + while (--$settings['count']); + + $output = $settings['full']; + $output .= $this->helper->hash_encode64($hash, 16); + + return $output; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (strlen($hash) !== 34) + { + return md5($password) === $hash; + } + + return $this->helper->string_compare($hash, $this->hash($password, $hash)); + } + + /** + * Generate salt for hashing method + * + * @return string Salt for hashing method + */ + protected function generate_salt() + { + $count = 6; + + $random = $this->helper->get_random_salt($count); + + $salt = $this->get_prefix(); + $salt .= $this->helper->itoa64[min($count + 5, 30)]; + $salt .= $this->helper->hash_encode64($random, $count); + + return $salt; + } + + /** + * Get hash settings + * + * @param string $hash The hash that contains the settings + * + * @return bool|array Array containing the count_log2, salt, and full + * hash settings string or false if supplied hash is empty + * or contains incorrect settings + */ + public function get_hash_settings($hash) + { + if (empty($hash)) + { + return false; + } + + $count_log2 = strpos($this->helper->itoa64, $hash[3]); + $salt = substr($hash, 4, 8); + + if ($count_log2 < 7 || $count_log2 > 30 || strlen($salt) != 8) + { + return false; + } + + return array( + 'count' => 1 << $count_log2, + 'salt' => $salt, + 'full' => substr($hash, 0, 12), + ); + } + + /** + * {@inheritdoc} + */ + public function get_settings_only($hash, $full = false) + { + return substr($hash, 3, 9); + } +} diff --git a/phpBB/phpbb/passwords/driver/sha1.php b/phpBB/phpbb/passwords/driver/sha1.php new file mode 100644 index 0000000000..1abead42cd --- /dev/null +++ b/phpBB/phpbb/passwords/driver/sha1.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class sha1 extends base +{ + const PREFIX = '$sha1$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + return (strlen($hash) == 40) ? $this->helper->string_compare($hash, sha1($password)) : false; + } +} diff --git a/phpBB/phpbb/passwords/driver/sha1_smf.php b/phpBB/phpbb/passwords/driver/sha1_smf.php new file mode 100644 index 0000000000..b30d87265e --- /dev/null +++ b/phpBB/phpbb/passwords/driver/sha1_smf.php @@ -0,0 +1,51 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class sha1_smf extends base +{ + const PREFIX = '$smf$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + return (isset($user_row['login_name'])) ? sha1(strtolower($user_row['login_name']) . $password) : false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + return (strlen($hash) == 40) ? $this->helper->string_compare($hash, $this->hash($password, $user_row)) : false; + } +} diff --git a/phpBB/phpbb/passwords/driver/sha1_wcf1.php b/phpBB/phpbb/passwords/driver/sha1_wcf1.php new file mode 100644 index 0000000000..68006486c4 --- /dev/null +++ b/phpBB/phpbb/passwords/driver/sha1_wcf1.php @@ -0,0 +1,60 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class sha1_wcf1 extends base +{ + const PREFIX = '$wcf1$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (empty($hash) || strlen($hash) != 40 || !isset($user_row['user_passwd_salt'])) + { + return false; + } + else + { + // Works for standard WCF 1.x, i.e. WBB3 and similar + return $this->helper->string_compare($hash, sha1($user_row['user_passwd_salt'] . sha1($user_row['user_passwd_salt'] . sha1($password)))); + } + } +} diff --git a/phpBB/phpbb/passwords/driver/sha_xf1.php b/phpBB/phpbb/passwords/driver/sha_xf1.php new file mode 100644 index 0000000000..9d8f01796e --- /dev/null +++ b/phpBB/phpbb/passwords/driver/sha_xf1.php @@ -0,0 +1,68 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords\driver; + +class sha_xf1 extends base +{ + const PREFIX = '$xf1$'; + + /** + * {@inheritdoc} + */ + public function get_prefix() + { + return self::PREFIX; + } + + /** + * {@inheritdoc} + */ + public function is_legacy() + { + return true; + } + + /** + * {@inheritdoc} + */ + public function hash($password, $user_row = '') + { + // Do not support hashing + return false; + } + + /** + * {@inheritdoc} + */ + public function check($password, $hash, $user_row = array()) + { + if (empty($hash) || (strlen($hash) != 40 && strlen($hash) != 64) || !isset($user_row['user_passwd_salt'])) + { + return false; + } + else + { + // Works for xenforo 1.0, 1.1 + if ($this->helper->string_compare($hash, sha1(sha1($password) . $user_row['user_passwd_salt'])) + || $this->helper->string_compare($hash, hash('sha256', hash('sha256', $password) . $user_row['user_passwd_salt']))) + { + return true; + } + else + { + return false; + } + } + } +} diff --git a/phpBB/phpbb/passwords/helper.php b/phpBB/phpbb/passwords/helper.php new file mode 100644 index 0000000000..c2a49202cd --- /dev/null +++ b/phpBB/phpbb/passwords/helper.php @@ -0,0 +1,104 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords; + +class helper +{ + /** + * Get hash settings from combined hash + * + * @param string $hash Password hash of combined hash + * + * @return array An array containing the hash settings for the hash + * types in successive order as described by the combined + * password hash or an empty array if hash does not + * properly fit the combined hash format + */ + public function get_combined_hash_settings($hash) + { + $output = array(); + + preg_match('#^\$([a-zA-Z0-9\\\]*?)\$#', $hash, $match); + $hash_settings = substr($hash, strpos($hash, $match[1]) + strlen($match[1]) + 1); + $matches = explode('\\', $match[1]); + foreach ($matches as $cur_type) + { + $dollar_position = strpos($hash_settings, '$'); + $output[] = substr($hash_settings, 0, ($dollar_position != false) ? $dollar_position : strlen($hash_settings)); + $hash_settings = substr($hash_settings, $dollar_position + 1); + } + + return $output; + } + + /** + * Combine hash prefixes, settings, and actual hash + * + * @param array $data Array containing the keys 'prefix' and 'settings'. + * It will hold the prefixes and settings + * @param string $type Data type of the supplied value + * @param string $value Value that should be put into the data array + * + * @return string|null Return complete combined hash if type is neither + * 'prefix' nor 'settings', nothing if it is + */ + public function combine_hash_output(&$data, $type, $value) + { + if ($type == 'prefix') + { + $data[$type] .= ($data[$type] !== '$') ? '\\' : ''; + $data[$type] .= str_replace('$', '', $value); + } + else if ($type == 'settings') + { + $data[$type] .= ($data[$type] !== '$') ? '$' : ''; + $data[$type] .= $value; + } + else + { + // Return full hash + return $data['prefix'] . $data['settings'] . '$' . $value; + } + } + + /** + * Rebuild hash for hashing functions + * + * @param string $prefix Hash prefix + * @param string $settings Hash settings + * + * @return string Rebuilt hash for hashing functions + */ + public function rebuild_hash($prefix, $settings) + { + $rebuilt_hash = $prefix; + if (strpos($settings, '\\') !== false) + { + $settings = str_replace('\\', '$', $settings); + } + $rebuilt_hash .= $settings; + return $rebuilt_hash; + } + + /** + * Obtain only the actual hash after the prefixes + * + * @param string $hash The full password hash + * @return string Actual hash (incl. settings) + */ + public function obtain_hash_only($hash) + { + return substr($hash, strripos($hash, '$') + 1); + } +} diff --git a/phpBB/phpbb/passwords/manager.php b/phpBB/phpbb/passwords/manager.php new file mode 100644 index 0000000000..aa9147ecf4 --- /dev/null +++ b/phpBB/phpbb/passwords/manager.php @@ -0,0 +1,366 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\passwords; + +class manager +{ + /** + * Default hashing method + */ + protected $type = false; + + /** + * Hashing algorithm type map + * Will be used to map hash prefix to type + */ + protected $type_map = false; + + /** + * Service collection of hashing algorithms + * Needs to be public for passwords helper + */ + public $algorithms = false; + + /** + * Password convert flag. Signals that password should be converted + */ + public $convert_flag = false; + + /** + * Passwords helper + * @var \phpbb\passwords\helper + */ + protected $helper; + + /** + * phpBB configuration + * @var \phpbb\config\config + */ + protected $config; + + /** + * Construct a passwords object + * + * @param \phpbb\config\config $config phpBB configuration + * @param array $hashing_algorithms Hashing driver + * service collection + * @param \phpbb\passwords\helper $helper Passwords helper object + * @param array $defaults List of default driver types + */ + public function __construct(\phpbb\config\config $config, $hashing_algorithms, helper $helper, $defaults) + { + $this->config = $config; + $this->helper = $helper; + + $this->fill_type_map($hashing_algorithms); + $this->register_default_type($defaults); + } + + /** + * Register default type + * Will register the first supported type from the list of default types + * + * @param array $defaults List of default types in order from first to + * use to last to use + */ + protected function register_default_type($defaults) + { + foreach ($defaults as $type) + { + if ($this->algorithms[$type]->is_supported()) + { + $this->type = $this->algorithms[$type]->get_prefix(); + break; + } + } + } + + /** + * Fill algorithm type map + * + * @param \phpbb\di\service_collection $hashing_algorithms + */ + protected function fill_type_map($hashing_algorithms) + { + foreach ($hashing_algorithms as $algorithm) + { + if (!isset($this->type_map[$algorithm->get_prefix()])) + { + $this->type_map[$algorithm->get_prefix()] = $algorithm; + } + } + $this->algorithms = $hashing_algorithms; + } + + /** + * Get the algorithm specified by a specific prefix + * + * @param string $prefix Password hash prefix + * + * @return object|bool The hash type object or false if prefix is not + * supported + */ + protected function get_algorithm($prefix) + { + if (isset($this->type_map[$prefix])) + { + return $this->type_map[$prefix]; + } + else + { + return false; + } + } + + /** + * Detect the hash type of the supplied hash + * + * @param string $hash Password hash that should be checked + * + * @return object|bool The hash type object or false if the specified + * type is not supported + */ + public function detect_algorithm($hash) + { + /* + * preg_match() will also show hashing algos like $2a\H$, which + * is a combination of bcrypt and phpass. Legacy algorithms + * like md5 will not be matched by this and need to be treated + * differently. + */ + if (!preg_match('#^\$([a-zA-Z0-9\\\]*?)\$#', $hash, $match)) + { + return false; + } + + // Be on the lookout for multiple hashing algorithms + // 2 is correct: H\2a > 2, H\P > 2 + if (strlen($match[1]) > 2) + { + $hash_types = explode('\\', $match[1]); + $return_ary = array(); + foreach ($hash_types as $type) + { + // we do not support the same hashing + // algorithm more than once + if (isset($return_ary[$type])) + { + return false; + } + + $return_ary[$type] = $this->get_algorithm('$' . $type . '$'); + + if (empty($return_ary[$type])) + { + return false; + } + } + return $return_ary; + } + + // get_algorithm() will automatically return false if prefix + // is not supported + return $this->get_algorithm($match[0]); + } + + /** + * Hash supplied password + * + * @param string $password Password that should be hashed + * @param string $type Hash type. Will default to standard hash type if + * none is supplied + * @return string|bool Password hash of supplied password or false if + * if something went wrong during hashing + */ + public function hash($password, $type = '') + { + if (strlen($password) > 4096) + { + // If the password is too huge, we will simply reject it + // and not let the server try to hash it. + return false; + } + + // Try to retrieve algorithm by service name if type doesn't + // start with dollar sign + if (!is_array($type) && strpos($type, '$') !== 0 && isset($this->algorithms[$type])) + { + $type = $this->algorithms[$type]->get_prefix(); + } + + $type = ($type === '') ? $this->type : $type; + + if (is_array($type)) + { + return $this->combined_hash_password($password, $type); + } + + if (isset($this->type_map[$type])) + { + $hashing_algorithm = $this->type_map[$type]; + } + else + { + return false; + } + + return $hashing_algorithm->hash($password); + } + + /** + * Check supplied password against hash and set convert_flag if password + * needs to be converted to different format (preferrably newer one) + * + * @param string $password Password that should be checked + * @param string $hash Stored hash + * @param array $user_row User's row in users table + * @return string|bool True if password is correct, false if not + */ + public function check($password, $hash, $user_row = array()) + { + if (strlen($password) > 4096) + { + // If the password is too huge, we will simply reject it + // and not let the server try to hash it. + return false; + } + + // Empty hashes can't be checked + if (empty($hash)) + { + return false; + } + + // First find out what kind of hash we're dealing with + $stored_hash_type = $this->detect_algorithm($hash); + if ($stored_hash_type == false) + { + // Still check MD5 hashes as that is what the installer + // will default to for the admin user + return $this->get_algorithm('$H$')->check($password, $hash); + } + + // Multiple hash passes needed + if (is_array($stored_hash_type)) + { + $correct = $this->check_combined_hash($password, $stored_hash_type, $hash); + $this->convert_flag = ($correct === true) ? true : false; + return $correct; + } + + if ($stored_hash_type->get_prefix() !== $this->type) + { + $this->convert_flag = true; + } + else + { + $this->convert_flag = false; + } + + // Check all legacy hash types if prefix is $CP$ + if ($stored_hash_type->get_prefix() === '$CP$') + { + // Remove $CP$ prefix for proper checking + $hash = substr($hash, 4); + + foreach ($this->type_map as $algorithm) + { + if ($algorithm->is_legacy() && $algorithm->check($password, $hash, $user_row) === true) + { + return true; + } + } + } + + return $stored_hash_type->check($password, $hash); + } + + /** + * Create combined hash from already hashed password + * + * @param string $password_hash Complete current password hash + * @param string $type Type of the hashing algorithm the password hash + * should be combined with + * @return string|bool Combined password hash if combined hashing was + * successful, else false + */ + public function combined_hash_password($password_hash, $type) + { + $data = array( + 'prefix' => '$', + 'settings' => '$', + ); + $hash_settings = $this->helper->get_combined_hash_settings($password_hash); + $hash = $hash_settings[0]; + + // Put settings of current hash into data array + $stored_hash_type = $this->detect_algorithm($password_hash); + $this->helper->combine_hash_output($data, 'prefix', $stored_hash_type->get_prefix()); + $this->helper->combine_hash_output($data, 'settings', $stored_hash_type->get_settings_only($password_hash)); + + // Hash current hash with the defined types + foreach ($type as $cur_type) + { + if (isset($this->algorithms[$cur_type])) + { + $new_hash_type = $this->algorithms[$cur_type]; + } + else + { + $new_hash_type = $this->get_algorithm($cur_type); + } + + if (!$new_hash_type) + { + return false; + } + + $new_hash = $new_hash_type->hash(str_replace($stored_hash_type->get_settings_only($password_hash), '', $hash)); + $this->helper->combine_hash_output($data, 'prefix', $new_hash_type->get_prefix()); + $this->helper->combine_hash_output($data, 'settings', substr(str_replace('$', '\\', $new_hash_type->get_settings_only($new_hash, true)), 0)); + $hash = str_replace($new_hash_type->get_settings_only($new_hash), '', $this->helper->obtain_hash_only($new_hash)); + } + return $this->helper->combine_hash_output($data, 'hash', $hash); + } + + /** + * Check combined password hash against the supplied password + * + * @param string $password Password entered by user + * @param array $stored_hash_type An array containing the hash types + * as described by stored password hash + * @param string $hash Stored password hash + * + * @return bool True if password is correct, false if not + */ + public function check_combined_hash($password, $stored_hash_type, $hash) + { + $i = 0; + $data = array( + 'prefix' => '$', + 'settings' => '$', + ); + $hash_settings = $this->helper->get_combined_hash_settings($hash); + foreach ($stored_hash_type as $key => $hash_type) + { + $rebuilt_hash = $this->helper->rebuild_hash($hash_type->get_prefix(), $hash_settings[$i]); + $this->helper->combine_hash_output($data, 'prefix', $key); + $this->helper->combine_hash_output($data, 'settings', $hash_settings[$i]); + $cur_hash = $hash_type->hash($password, $rebuilt_hash); + $password = str_replace($rebuilt_hash, '', $cur_hash); + $i++; + } + return ($hash === $this->helper->combine_hash_output($data, 'hash', $password)); + } +} diff --git a/phpBB/phpbb/path_helper.php b/phpBB/phpbb/path_helper.php new file mode 100644 index 0000000000..5400c1c5a6 --- /dev/null +++ b/phpBB/phpbb/path_helper.php @@ -0,0 +1,492 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* A class with various functions that are related to paths, files and the filesystem +*/ +class path_helper +{ + /** @var \phpbb\symfony_request */ + protected $symfony_request; + + /** @var \phpbb\filesystem */ + protected $filesystem; + + /** @var \phpbb\request\request_interface */ + protected $request; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $adm_relative_path; + + /** @var string */ + protected $php_ext; + + /** @var string */ + protected $web_root_path; + + /** + * Constructor + * + * @param \phpbb\symfony_request $symfony_request + * @param \phpbb\filesystem $filesystem + * @param \phpbb\request\request_interface $request + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $php_ext PHP file extension + * @param mixed $adm_relative_path Relative path admin path to adm/ root + */ + public function __construct(\phpbb\symfony_request $symfony_request, \phpbb\filesystem $filesystem, \phpbb\request\request_interface $request, $phpbb_root_path, $php_ext, $adm_relative_path = null) + { + $this->symfony_request = $symfony_request; + $this->filesystem = $filesystem; + $this->request = $request; + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + $this->adm_relative_path = $adm_relative_path; + } + + /** + * Get the phpBB root path + * + * @return string + */ + public function get_phpbb_root_path() + { + return $this->phpbb_root_path; + } + + /** + * Get the adm root path + * + * @return string + */ + public function get_adm_relative_path() + { + return $this->adm_relative_path; + } + + /** + * Get the php extension + * + * @return string + */ + public function get_php_ext() + { + return $this->php_ext; + } + + /** + * Update a web path to the correct relative root path + * + * This replaces $phpbb_root_path . some_url with + * get_web_root_path() . some_url + * + * @param string $path The path to be updated + * @return string + */ + public function update_web_root_path($path) + { + if (strpos($path, $this->phpbb_root_path) === 0) + { + $path = substr($path, strlen($this->phpbb_root_path)); + + $web_root_path = $this->get_web_root_path(); + if (substr($web_root_path, -8) === 'app.php/' && substr($path, 0, 7) === 'app.php') + { + $path = substr($path, 8); + } + + return $this->filesystem->clean_path($web_root_path . $path); + } + + return $path; + } + + /** + * Strips away the web root path and prepends the normal root path + * + * This replaces get_web_root_path() . some_url with + * $phpbb_root_path . some_url + * + * @param string $path The path to be updated + * @return string + */ + public function remove_web_root_path($path) + { + if (strpos($path, $this->get_web_root_path()) === 0) + { + $path = substr($path, strlen($this->get_web_root_path())); + + return $this->phpbb_root_path . $path; + } + + return $path; + } + + /** + * Get a relative root path from the current URL + * + * @return string + */ + public function get_web_root_path() + { + if ($this->symfony_request === null) + { + return $this->phpbb_root_path; + } + + if (null !== $this->web_root_path) + { + return $this->web_root_path; + } + + // We do not need to escape $path_info, $request_uri and $script_name because we can not find their content in the result. + // Path info (e.g. /foo/bar) + $path_info = $this->filesystem->clean_path($this->symfony_request->getPathInfo()); + + // Full request URI (e.g. phpBB/app.php/foo/bar) + $request_uri = $this->symfony_request->getRequestUri(); + + // Script name URI (e.g. phpBB/app.php) + $script_name = $this->symfony_request->getScriptName(); + + /* + * If the path info is empty but we're using app.php, then we + * might be using an empty route like app.php/ which is + * supported by symfony's routing + */ + if ($path_info === '/' && preg_match('/app\.' . $this->php_ext . '\/$/', $request_uri)) + { + return $this->web_root_path = $this->filesystem->clean_path('./../' . $this->phpbb_root_path); + } + + /* + * If the path info is empty (single /), then we're not using + * a route like app.php/foo/bar + */ + if ($path_info === '/') + { + return $this->web_root_path = $this->phpbb_root_path; + } + + /* + * Check AJAX request: + * If the current request is a AJAX we need to fix the paths. + * We need to get the root path based on the Referer, so we can use + * the generated URLs in the template of the Referer. If we do not + * generate the relative path based on the Referer, but based on the + * currently requested URL, the generated URLs will not point to the + * intended locations: + * Referer desired URL desired relative root path + * memberlist.php faq.php ./ + * memberlist.php app.php/foo/bar ./ + * app.php/foo memberlist.php ../ + * app.php/foo app.php/fox ../ + * app.php/foo/bar memberlist.php ../../ + * ../page.php memberlist.php ./phpBB/ + * ../sub/page.php memberlist.php ./../phpBB/ + * + * The referer must be specified as a parameter in the query. + */ + if ($this->request->is_ajax() && $this->symfony_request->get('_referer')) + { + // We need to escape $absolute_board_url because it can be partially concatenated to the result. + $absolute_board_url = $this->request->escape($this->symfony_request->getSchemeAndHttpHost() . $this->symfony_request->getBasePath(), true); + + $referer_web_root_path = $this->get_web_root_path_from_ajax_referer( + $this->symfony_request->get('_referer'), + $absolute_board_url + ); + return $this->web_root_path = $this->phpbb_root_path . $referer_web_root_path; + } + + // How many corrections might we need? + $corrections = substr_count($path_info, '/'); + + /* + * If the script name (e.g. phpBB/app.php) does not exists in the + * requestUri (e.g. phpBB/app.php/foo/template), then we are rewriting + * the URL. So we must reduce the slash count by 1. + */ + if (strpos($request_uri, $script_name) !== 0) + { + $corrections--; + } + + // Prepend ../ to the phpbb_root_path as many times as / exists in path_info + $this->web_root_path = $this->filesystem->clean_path( + './' . str_repeat('../', $corrections) . $this->phpbb_root_path + ); + return $this->web_root_path; + } + + /** + * Get the web root path of the referer form an ajax request + * + * @param string $absolute_referer_url + * @param string $absolute_board_url + * @return string + */ + public function get_web_root_path_from_ajax_referer($absolute_referer_url, $absolute_board_url) + { + // If the board URL is in the beginning of the referer, this means + // we the referer is in the board URL or a subdirectory of it. + // So we just need to count the / (slashes) in the left over part of + // the referer and prepend ../ the the current root_path, to get the + // web root path of the referer. + if (strpos($absolute_referer_url, $absolute_board_url) === 0) + { + $relative_referer_path = substr($absolute_referer_url, strlen($absolute_board_url)); + $has_params = strpos($relative_referer_path, '?'); + if ($has_params !== false) + { + $relative_referer_path = substr($relative_referer_path, 0, $has_params); + } + $corrections = substr_count($relative_referer_path, '/'); + return $this->phpbb_root_path . str_repeat('../', $corrections - 1); + } + + // If not, it's a bit more complicated. We go to the parent directory + // of the referer until we find the remaining referer in the board URL. + // Foreach directory we need to add a ../ to the fixed root_path. + // When we finally found it, we need to remove the remaining referer + // from the board URL, to get the boards root path. + // If the then append these two strings, we get our fixed web root path. + $fixed_root_path = ''; + $referer_dir = $absolute_referer_url; + $has_params = strpos($referer_dir, '?'); + if ($has_params !== false) + { + $referer_dir = substr($referer_dir, 0, $has_params); + } + + // If we do not find a slash at the end of the referer, we come + // from a file. So the first dirname() does not need a traversal + // path correction. + if (substr($referer_dir, -1) !== '/') + { + $referer_dir = dirname($referer_dir); + } + + while (($dir_position = strpos($absolute_board_url, $referer_dir)) !== 0) + { + $fixed_root_path .= '../'; + $referer_dir = dirname($referer_dir); + + // Just return phpbb_root_path if we reach the top directory + if ($referer_dir === '.') + { + return $this->phpbb_root_path; + } + } + + $fixed_root_path .= substr($absolute_board_url, strlen($referer_dir) + 1); + // Add trailing slash + return $this->phpbb_root_path . $fixed_root_path . '/'; + } + + /** + * Eliminates useless . and .. components from specified URL + * + * @param string $url URL to clean + * + * @return string Cleaned URL + */ + public function clean_url($url) + { + $delimiter_position = strpos($url, '://'); + // URL should contain :// but it shouldn't start with it. + // Do not clean URLs that do not fit these constraints. + if (empty($delimiter_position)) + { + return $url; + } + $scheme = substr($url, 0, $delimiter_position) . '://'; + // Add length of URL delimiter to position + $path = substr($url, $delimiter_position + 3); + + return $scheme . $this->filesystem->clean_path($path); + } + + /** + * Glue URL parameters together + * + * @param array $params URL parameters in the form of array(name => value) + * @return string Returns the glued string, e.g. name1=value1&name2&name3=value3 + */ + public function glue_url_params($params) + { + $_params = array(); + + foreach ($params as $key => $value) + { + // some parameters do not have value + if ($value !== null) + { + $_params[] = $key . '=' . $value; + } + else + { + $_params[] = $key; + } + } + return implode('&', $_params); + } + + /** + * Get the base and parameters of a URL + * + * @param string $url URL to break apart + * @param bool $is_amp Is the parameter separator &. Defaults to true. + * @return array Returns the base and parameters in the form of array('base' => string, 'params' => array(name => value)) + */ + public function get_url_parts($url, $is_amp = true) + { + $separator = ($is_amp) ? '&' : '&'; + $params = array(); + + if (strpos($url, '?') !== false) + { + $base = substr($url, 0, strpos($url, '?')); + $args = substr($url, strlen($base) + 1); + $args = ($args) ? explode($separator, $args) : array(); + + foreach ($args as $argument) + { + if (empty($argument)) + { + continue; + } + + // some parameters don't have value + if (strpos($argument, '=') !== false) + { + list($key, $value) = explode('=', $argument, 2); + } + else + { + $key = $argument; + $value = null; + } + + if ($key === '') + { + continue; + } + + $params[$key] = $value; + } + } + else + { + $base = $url; + } + + return array( + 'base' => $base, + 'params' => $params, + ); + } + + /** + * Strip parameters from an already built URL. + * + * @param string $url URL to strip parameters from + * @param array|string $strip Parameters to strip. + * @param bool $is_amp Is the parameter separator &. Defaults to true. + * @return string Returns the new URL. + */ + public function strip_url_params($url, $strip, $is_amp = true) + { + $url_parts = $this->get_url_parts($url, $is_amp); + $params = $url_parts['params']; + + if (!is_array($strip)) + { + $strip = array($strip); + } + + if (!empty($params)) + { + // Strip the parameters off + foreach ($strip as $param) + { + unset($params[$param]); + } + } + + return $url_parts['base'] . (($params) ? '?' . $this->glue_url_params($params) : ''); + } + + /** + * Append parameters to an already built URL. + * + * @param string $url URL to append parameters to + * @param array $new_params Parameters to add in the form of array(name => value) + * @param bool $is_amp Is the parameter separator &. Defaults to true. + * @return string Returns the new URL. + */ + public function append_url_params($url, $new_params, $is_amp = true) + { + $url_parts = $this->get_url_parts($url, $is_amp); + $params = array_merge($url_parts['params'], $new_params); + + // Move the sid to the end if it's set + if (isset($params['sid'])) + { + $sid = $params['sid']; + unset($params['sid']); + $params['sid'] = $sid; + } + + return $url_parts['base'] . (($params) ? '?' . $this->glue_url_params($params) : ''); + } + + /** + * Get a valid page + * + * @param string $page The page to verify + * @param bool $mod_rewrite Whether mod_rewrite is enabled, default: false + * + * @return string A valid page based on given page and mod_rewrite + */ + public function get_valid_page($page, $mod_rewrite = false) + { + // We need to be cautious here. + // On some situations, the redirect path is an absolute URL, sometimes a relative path + // For a relative path, let's prefix it with $phpbb_root_path to point to the correct location, + // else we use the URL directly. + $url_parts = parse_url($page); + + // URL + if ($url_parts === false || empty($url_parts['scheme']) || empty($url_parts['host'])) + { + // Remove 'app.php/' from the page, when rewrite is enabled. + // Treat app.php as a reserved file name and remove on mod rewrite + // even if it might not be in the phpBB root. + if ($mod_rewrite && ($app_position = strpos($page, 'app.' . $this->php_ext . '/')) !== false) + { + $page = substr($page, 0, $app_position) . substr($page, $app_position + strlen('app.' . $this->php_ext . '/')); + } + + // Remove preceding slashes from page name and prepend root path + $page = $this->get_phpbb_root_path() . ltrim($page, '/\\'); + } + + return $page; + } +} diff --git a/phpBB/phpbb/permissions.php b/phpBB/phpbb/permissions.php new file mode 100644 index 0000000000..e75476f59b --- /dev/null +++ b/phpBB/phpbb/permissions.php @@ -0,0 +1,362 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +class permissions +{ + /** + * Event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $dispatcher; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Constructor + * + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher + * @param \phpbb\user $user User Object + */ + public function __construct(\phpbb\event\dispatcher_interface $phpbb_dispatcher, \phpbb\user $user) + { + $this->dispatcher = $phpbb_dispatcher; + $this->user = $user; + + $categories = $this->categories; + $types = $this->types; + $permissions = $this->permissions; + + /** + * Allows to specify additional permission categories, types and permissions + * + * @event core.permissions + * @var array types Array with permission types (a_, u_, m_, etc.) + * @var array categories Array with permission categories (pm, post, settings, misc, etc.) + * @var array permissions Array with permissions. Each Permission has the following layout: + * '<type><permission>' => array( + * 'lang' => 'Language Key with a Short description', // Optional, if not set, + * // the permissions identifier '<type><permission>' is used with + * // all uppercase. + * 'cat' => 'Identifier of the category, the permission should be displayed in', + * ), + * Example: + * 'u_viewprofile' => array( + * 'lang' => 'ACL_U_VIEWPROFILE', + * 'cat' => 'profile', + * ), + * @since 3.1.0-a1 + */ + $vars = array('types', 'categories', 'permissions'); + extract($phpbb_dispatcher->trigger_event('core.permissions', compact($vars))); + + $this->categories = $categories; + $this->types = $types; + $this->permissions = $permissions; + } + + /** + * Returns an array with all the permission categories (pm, post, settings, misc, etc.) + * + * @return array Layout: cat-identifier => Language key + */ + public function get_categories() + { + return $this->categories; + } + + /** + * Returns the language string of a permission category + * + * @param string $category Identifier of the category + * @return string Language string + */ + public function get_category_lang($category) + { + return $this->user->lang($this->categories[$category]); + } + + /** + * Returns an array with all the permission types (a_, u_, m_, etc.) + * + * @return array Layout: type-identifier => Language key + */ + public function get_types() + { + return $this->types; + } + + /** + * Returns the language string of a permission type + * + * @param string $type Identifier of the type + * @param mixed $scope Scope of the type (should be 'global', 'local' or false) + * @return string Language string + */ + public function get_type_lang($type, $scope = false) + { + if ($scope && isset($this->types[$scope][$type])) + { + $lang_key = $this->types[$scope][$type]; + } + else if (isset($this->types[$type])) + { + $lang_key = $this->types[$type]; + } + else + { + $lang_key = 'ACL_TYPE_' . strtoupper(($scope) ? $scope . '_' . $type : $type); + } + + return $this->user->lang($lang_key); + } + + /** + * Returns an array with all the permissions. + * Each Permission has the following layout: + * '<type><permission>' => array( + * 'lang' => 'Language Key with a Short description', // Optional, if not set, + * // the permissions identifier '<type><permission>' is used with + * // all uppercase. + * 'cat' => 'Identifier of the category, the permission should be displayed in', + * ), + * Example: + * 'u_viewprofile' => array( + * 'lang' => 'ACL_U_VIEWPROFILE', + * 'cat' => 'profile', + * ), + * + * @return array + */ + public function get_permissions() + { + return $this->permissions; + } + + /** + * Returns the category of a permission + * + * @param string $permission Identifier of the permission + * @return string Returns the category identifier of the permission + */ + public function get_permission_category($permission) + { + return (isset($this->permissions[$permission]['cat'])) ? $this->permissions[$permission]['cat'] : 'misc'; + } + + /** + * Checks if a category has been defined + * + * @param string $category Identifier of the category + * @return bool True if the category is defined, false otherwise + */ + public function category_defined($category) + { + return isset($this->categories[$category]); + } + + /** + * Checks if a permission has been defined + * + * @param string $permission Identifier of the permission + * @return bool True if the permission is defined, false otherwise + */ + public function permission_defined($permission) + { + return isset($this->permissions[$permission]); + } + + /** + * Returns the language string of a permission + * + * @param string $permission Identifier of the permission + * @return string Language string + */ + public function get_permission_lang($permission) + { + return (isset($this->permissions[$permission]['lang'])) ? $this->user->lang($this->permissions[$permission]['lang']) : $this->user->lang('ACL_' . strtoupper($permission)); + } + + protected $types = array( + 'u_' => 'ACL_TYPE_U_', + 'a_' => 'ACL_TYPE_A_', + 'm_' => 'ACL_TYPE_M_', + 'f_' => 'ACL_TYPE_F_', + 'global' => array( + 'm_' => 'ACL_TYPE_GLOBAL_M_', + ), + ); + + protected $categories = array( + 'actions' => 'ACL_CAT_ACTIONS', + 'content' => 'ACL_CAT_CONTENT', + 'forums' => 'ACL_CAT_FORUMS', + 'misc' => 'ACL_CAT_MISC', + 'permissions' => 'ACL_CAT_PERMISSIONS', + 'pm' => 'ACL_CAT_PM', + 'polls' => 'ACL_CAT_POLLS', + 'post' => 'ACL_CAT_POST', + 'post_actions' => 'ACL_CAT_POST_ACTIONS', + 'posting' => 'ACL_CAT_POSTING', + 'profile' => 'ACL_CAT_PROFILE', + 'settings' => 'ACL_CAT_SETTINGS', + 'topic_actions' => 'ACL_CAT_TOPIC_ACTIONS', + 'user_group' => 'ACL_CAT_USER_GROUP', + ); + + protected $permissions = array( + // User Permissions + 'u_viewprofile' => array('lang' => 'ACL_U_VIEWPROFILE', 'cat' => 'profile'), + 'u_chgname' => array('lang' => 'ACL_U_CHGNAME', 'cat' => 'profile'), + 'u_chgpasswd' => array('lang' => 'ACL_U_CHGPASSWD', 'cat' => 'profile'), + 'u_chgemail' => array('lang' => 'ACL_U_CHGEMAIL', 'cat' => 'profile'), + 'u_chgavatar' => array('lang' => 'ACL_U_CHGAVATAR', 'cat' => 'profile'), + 'u_chggrp' => array('lang' => 'ACL_U_CHGGRP', 'cat' => 'profile'), + 'u_chgprofileinfo' => array('lang' => 'ACL_U_CHGPROFILEINFO', 'cat' => 'profile'), + + 'u_attach' => array('lang' => 'ACL_U_ATTACH', 'cat' => 'post'), + 'u_download' => array('lang' => 'ACL_U_DOWNLOAD', 'cat' => 'post'), + 'u_savedrafts' => array('lang' => 'ACL_U_SAVEDRAFTS', 'cat' => 'post'), + 'u_chgcensors' => array('lang' => 'ACL_U_CHGCENSORS', 'cat' => 'post'), + 'u_sig' => array('lang' => 'ACL_U_SIG', 'cat' => 'post'), + + 'u_sendpm' => array('lang' => 'ACL_U_SENDPM', 'cat' => 'pm'), + 'u_masspm' => array('lang' => 'ACL_U_MASSPM', 'cat' => 'pm'), + 'u_masspm_group'=> array('lang' => 'ACL_U_MASSPM_GROUP', 'cat' => 'pm'), + 'u_readpm' => array('lang' => 'ACL_U_READPM', 'cat' => 'pm'), + 'u_pm_edit' => array('lang' => 'ACL_U_PM_EDIT', 'cat' => 'pm'), + 'u_pm_delete' => array('lang' => 'ACL_U_PM_DELETE', 'cat' => 'pm'), + 'u_pm_forward' => array('lang' => 'ACL_U_PM_FORWARD', 'cat' => 'pm'), + 'u_pm_emailpm' => array('lang' => 'ACL_U_PM_EMAILPM', 'cat' => 'pm'), + 'u_pm_printpm' => array('lang' => 'ACL_U_PM_PRINTPM', 'cat' => 'pm'), + 'u_pm_attach' => array('lang' => 'ACL_U_PM_ATTACH', 'cat' => 'pm'), + 'u_pm_download' => array('lang' => 'ACL_U_PM_DOWNLOAD', 'cat' => 'pm'), + 'u_pm_bbcode' => array('lang' => 'ACL_U_PM_BBCODE', 'cat' => 'pm'), + 'u_pm_smilies' => array('lang' => 'ACL_U_PM_SMILIES', 'cat' => 'pm'), + 'u_pm_img' => array('lang' => 'ACL_U_PM_IMG', 'cat' => 'pm'), + 'u_pm_flash' => array('lang' => 'ACL_U_PM_FLASH', 'cat' => 'pm'), + + 'u_sendemail' => array('lang' => 'ACL_U_SENDEMAIL', 'cat' => 'misc'), + 'u_sendim' => array('lang' => 'ACL_U_SENDIM', 'cat' => 'misc'), + 'u_ignoreflood' => array('lang' => 'ACL_U_IGNOREFLOOD', 'cat' => 'misc'), + 'u_hideonline' => array('lang' => 'ACL_U_HIDEONLINE', 'cat' => 'misc'), + 'u_viewonline' => array('lang' => 'ACL_U_VIEWONLINE', 'cat' => 'misc'), + 'u_search' => array('lang' => 'ACL_U_SEARCH', 'cat' => 'misc'), + + // Forum Permissions + 'f_list' => array('lang' => 'ACL_F_LIST', 'cat' => 'actions'), + 'f_read' => array('lang' => 'ACL_F_READ', 'cat' => 'actions'), + 'f_search' => array('lang' => 'ACL_F_SEARCH', 'cat' => 'actions'), + 'f_subscribe' => array('lang' => 'ACL_F_SUBSCRIBE', 'cat' => 'actions'), + 'f_print' => array('lang' => 'ACL_F_PRINT', 'cat' => 'actions'), + 'f_email' => array('lang' => 'ACL_F_EMAIL', 'cat' => 'actions'), + 'f_bump' => array('lang' => 'ACL_F_BUMP', 'cat' => 'actions'), + 'f_user_lock' => array('lang' => 'ACL_F_USER_LOCK', 'cat' => 'actions'), + 'f_download' => array('lang' => 'ACL_F_DOWNLOAD', 'cat' => 'actions'), + 'f_report' => array('lang' => 'ACL_F_REPORT', 'cat' => 'actions'), + + 'f_post' => array('lang' => 'ACL_F_POST', 'cat' => 'post'), + 'f_sticky' => array('lang' => 'ACL_F_STICKY', 'cat' => 'post'), + 'f_announce' => array('lang' => 'ACL_F_ANNOUNCE', 'cat' => 'post'), + 'f_reply' => array('lang' => 'ACL_F_REPLY', 'cat' => 'post'), + 'f_edit' => array('lang' => 'ACL_F_EDIT', 'cat' => 'post'), + 'f_delete' => array('lang' => 'ACL_F_DELETE', 'cat' => 'post'), + 'f_softdelete' => array('lang' => 'ACL_F_SOFTDELETE', 'cat' => 'post'), + 'f_ignoreflood' => array('lang' => 'ACL_F_IGNOREFLOOD', 'cat' => 'post'), + 'f_postcount' => array('lang' => 'ACL_F_POSTCOUNT', 'cat' => 'post'), + 'f_noapprove' => array('lang' => 'ACL_F_NOAPPROVE', 'cat' => 'post'), + + 'f_attach' => array('lang' => 'ACL_F_ATTACH', 'cat' => 'content'), + 'f_icons' => array('lang' => 'ACL_F_ICONS', 'cat' => 'content'), + 'f_bbcode' => array('lang' => 'ACL_F_BBCODE', 'cat' => 'content'), + 'f_flash' => array('lang' => 'ACL_F_FLASH', 'cat' => 'content'), + 'f_img' => array('lang' => 'ACL_F_IMG', 'cat' => 'content'), + 'f_sigs' => array('lang' => 'ACL_F_SIGS', 'cat' => 'content'), + 'f_smilies' => array('lang' => 'ACL_F_SMILIES', 'cat' => 'content'), + + 'f_poll' => array('lang' => 'ACL_F_POLL', 'cat' => 'polls'), + 'f_vote' => array('lang' => 'ACL_F_VOTE', 'cat' => 'polls'), + 'f_votechg' => array('lang' => 'ACL_F_VOTECHG', 'cat' => 'polls'), + + // Moderator Permissions + 'm_edit' => array('lang' => 'ACL_M_EDIT', 'cat' => 'post_actions'), + 'm_delete' => array('lang' => 'ACL_M_DELETE', 'cat' => 'post_actions'), + 'm_approve' => array('lang' => 'ACL_M_APPROVE', 'cat' => 'post_actions'), + 'm_report' => array('lang' => 'ACL_M_REPORT', 'cat' => 'post_actions'), + 'm_chgposter' => array('lang' => 'ACL_M_CHGPOSTER', 'cat' => 'post_actions'), + 'm_info' => array('lang' => 'ACL_M_INFO', 'cat' => 'post_actions'), + 'm_softdelete' => array('lang' => 'ACL_M_SOFTDELETE', 'cat' => 'post_actions'), + + 'm_move' => array('lang' => 'ACL_M_MOVE', 'cat' => 'topic_actions'), + 'm_lock' => array('lang' => 'ACL_M_LOCK', 'cat' => 'topic_actions'), + 'm_split' => array('lang' => 'ACL_M_SPLIT', 'cat' => 'topic_actions'), + 'm_merge' => array('lang' => 'ACL_M_MERGE', 'cat' => 'topic_actions'), + + 'm_warn' => array('lang' => 'ACL_M_WARN', 'cat' => 'misc'), + 'm_pm_report' => array('lang' => 'ACL_M_PM_REPORT', 'cat' => 'misc'), + 'm_ban' => array('lang' => 'ACL_M_BAN', 'cat' => 'misc'), + + // Admin Permissions + 'a_board' => array('lang' => 'ACL_A_BOARD', 'cat' => 'settings'), + 'a_server' => array('lang' => 'ACL_A_SERVER', 'cat' => 'settings'), + 'a_jabber' => array('lang' => 'ACL_A_JABBER', 'cat' => 'settings'), + 'a_phpinfo' => array('lang' => 'ACL_A_PHPINFO', 'cat' => 'settings'), + + 'a_forum' => array('lang' => 'ACL_A_FORUM', 'cat' => 'forums'), + 'a_forumadd' => array('lang' => 'ACL_A_FORUMADD', 'cat' => 'forums'), + 'a_forumdel' => array('lang' => 'ACL_A_FORUMDEL', 'cat' => 'forums'), + 'a_prune' => array('lang' => 'ACL_A_PRUNE', 'cat' => 'forums'), + + 'a_icons' => array('lang' => 'ACL_A_ICONS', 'cat' => 'posting'), + 'a_words' => array('lang' => 'ACL_A_WORDS', 'cat' => 'posting'), + 'a_bbcode' => array('lang' => 'ACL_A_BBCODE', 'cat' => 'posting'), + 'a_attach' => array('lang' => 'ACL_A_ATTACH', 'cat' => 'posting'), + + 'a_user' => array('lang' => 'ACL_A_USER', 'cat' => 'user_group'), + 'a_userdel' => array('lang' => 'ACL_A_USERDEL', 'cat' => 'user_group'), + 'a_group' => array('lang' => 'ACL_A_GROUP', 'cat' => 'user_group'), + 'a_groupadd' => array('lang' => 'ACL_A_GROUPADD', 'cat' => 'user_group'), + 'a_groupdel' => array('lang' => 'ACL_A_GROUPDEL', 'cat' => 'user_group'), + 'a_ranks' => array('lang' => 'ACL_A_RANKS', 'cat' => 'user_group'), + 'a_profile' => array('lang' => 'ACL_A_PROFILE', 'cat' => 'user_group'), + 'a_names' => array('lang' => 'ACL_A_NAMES', 'cat' => 'user_group'), + 'a_ban' => array('lang' => 'ACL_A_BAN', 'cat' => 'user_group'), + + 'a_viewauth' => array('lang' => 'ACL_A_VIEWAUTH', 'cat' => 'permissions'), + 'a_authgroups' => array('lang' => 'ACL_A_AUTHGROUPS', 'cat' => 'permissions'), + 'a_authusers' => array('lang' => 'ACL_A_AUTHUSERS', 'cat' => 'permissions'), + 'a_fauth' => array('lang' => 'ACL_A_FAUTH', 'cat' => 'permissions'), + 'a_mauth' => array('lang' => 'ACL_A_MAUTH', 'cat' => 'permissions'), + 'a_aauth' => array('lang' => 'ACL_A_AAUTH', 'cat' => 'permissions'), + 'a_uauth' => array('lang' => 'ACL_A_UAUTH', 'cat' => 'permissions'), + 'a_roles' => array('lang' => 'ACL_A_ROLES', 'cat' => 'permissions'), + 'a_switchperm' => array('lang' => 'ACL_A_SWITCHPERM', 'cat' => 'permissions'), + + 'a_styles' => array('lang' => 'ACL_A_STYLES', 'cat' => 'misc'), + 'a_extensions' => array('lang' => 'ACL_A_EXTENSIONS', 'cat' => 'misc'), + 'a_viewlogs' => array('lang' => 'ACL_A_VIEWLOGS', 'cat' => 'misc'), + 'a_clearlogs' => array('lang' => 'ACL_A_CLEARLOGS', 'cat' => 'misc'), + 'a_modules' => array('lang' => 'ACL_A_MODULES', 'cat' => 'misc'), + 'a_language' => array('lang' => 'ACL_A_LANGUAGE', 'cat' => 'misc'), + 'a_email' => array('lang' => 'ACL_A_EMAIL', 'cat' => 'misc'), + 'a_bots' => array('lang' => 'ACL_A_BOTS', 'cat' => 'misc'), + 'a_reasons' => array('lang' => 'ACL_A_REASONS', 'cat' => 'misc'), + 'a_backup' => array('lang' => 'ACL_A_BACKUP', 'cat' => 'misc'), + 'a_search' => array('lang' => 'ACL_A_SEARCH', 'cat' => 'misc'), + ); +} diff --git a/phpBB/phpbb/php/ini.php b/phpBB/phpbb/php/ini.php new file mode 100644 index 0000000000..73a30659a6 --- /dev/null +++ b/phpBB/phpbb/php/ini.php @@ -0,0 +1,171 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\php; + +/** +* Wrapper class for ini_get function. +* +* Provides easier handling of the different interpretations of ini values. +*/ +class ini +{ + /** + * Simple wrapper for ini_get() + * See http://php.net/manual/en/function.ini-get.php + * + * @param string $varname The configuration option name. + * @return bool|string False if configuration option does not exist, + * the configuration option value (string) otherwise. + */ + public function get($varname) + { + return ini_get($varname); + } + + /** + * Gets the configuration option value as a trimmed string. + * + * @param string $varname The configuration option name. + * @return bool|string False if configuration option does not exist, + * the configuration option value (string) otherwise. + */ + public function get_string($varname) + { + $value = $this->get($varname); + + if ($value === false) + { + return false; + } + + return trim($value); + } + + /** + * Gets configuration option value as a boolean. + * Interprets the string value 'off' as false. + * + * @param string $varname The configuration option name. + * @return bool False if configuration option does not exist. + * False if configuration option is disabled. + * True otherwise. + */ + public function get_bool($varname) + { + $value = $this->get_string($varname); + + if (empty($value) || strtolower($value) == 'off') + { + return false; + } + + return true; + } + + /** + * Gets configuration option value as an integer. + * + * @param string $varname The configuration option name. + * @return bool|int False if configuration option does not exist, + * false if configuration option value is not numeric, + * the configuration option value (integer) otherwise. + */ + public function get_int($varname) + { + $value = $this->get_string($varname); + + if (!is_numeric($value)) + { + return false; + } + + return (int) $value; + } + + /** + * Gets configuration option value as a float. + * + * @param string $varname The configuration option name. + * @return bool|float False if configuration option does not exist, + * false if configuration option value is not numeric, + * the configuration option value (float) otherwise. + */ + public function get_float($varname) + { + $value = $this->get_string($varname); + + if (!is_numeric($value)) + { + return false; + } + + return (float) $value; + } + + /** + * Gets configuration option value in bytes. + * Converts strings like '128M' to bytes (integer or float). + * + * @param string $varname The configuration option name. + * @return bool|int|float False if configuration option does not exist, + * false if configuration option value is not well-formed, + * the configuration option value otherwise. + */ + public function get_bytes($varname) + { + $value = $this->get_string($varname); + + if ($value === false) + { + return false; + } + + if (is_numeric($value)) + { + // Already in bytes. + return phpbb_to_numeric($value); + } + else if (strlen($value) < 2) + { + // Single character. + return false; + } + else if (strlen($value) < 3 && $value[0] === '-') + { + // Two characters but the first one is a minus. + return false; + } + + $value_lower = strtolower($value); + $value_numeric = phpbb_to_numeric($value); + + switch ($value_lower[strlen($value_lower) - 1]) + { + case 'g': + $value_numeric *= 1024; + case 'm': + $value_numeric *= 1024; + case 'k': + $value_numeric *= 1024; + break; + + default: + // It's not already in bytes (and thus numeric) + // and does not carry a unit. + return false; + } + + return $value_numeric; + } +} diff --git a/phpBB/phpbb/plupload/plupload.php b/phpBB/phpbb/plupload/plupload.php new file mode 100644 index 0000000000..04d681cea6 --- /dev/null +++ b/phpBB/phpbb/plupload/plupload.php @@ -0,0 +1,402 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\plupload; + +/** +* This class handles all server-side plupload functions +*/ +class plupload +{ + /** + * @var string + */ + protected $phpbb_root_path; + + /** + * @var \phpbb\config\config + */ + protected $config; + + /** + * @var \phpbb\request\request_interface + */ + protected $request; + + /** + * @var \phpbb\user + */ + protected $user; + + /** + * @var \phpbb\php\ini + */ + protected $php_ini; + + /** + * @var \phpbb\mimetype\guesser + */ + protected $mimetype_guesser; + + /** + * Final destination for uploaded files, i.e. the "files" directory. + * @var string + */ + protected $upload_directory; + + /** + * Temporary upload directory for plupload uploads. + * @var string + */ + protected $temporary_directory; + + /** + * Constructor. + * + * @param string $phpbb_root_path + * @param \phpbb\config\config $config + * @param \phpbb\request\request_interface $request + * @param \phpbb\user $user + * @param \phpbb\php\ini $php_ini + * @param \phpbb\mimetype\guesser $mimetype_guesser + */ + public function __construct($phpbb_root_path, \phpbb\config\config $config, \phpbb\request\request_interface $request, \phpbb\user $user, \phpbb\php\ini $php_ini, \phpbb\mimetype\guesser $mimetype_guesser) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->config = $config; + $this->request = $request; + $this->user = $user; + $this->php_ini = $php_ini; + $this->mimetype_guesser = $mimetype_guesser; + + $this->set_default_directories(); + } + + /** + * Plupload allows for chunking so we must check for that and assemble + * the whole file first before performing any checks on it. + * + * @param string $form_name The name of the file element in the upload form + * + * @return array|null null if there are no chunks to piece together + * otherwise array containing the path to the + * pieced-together file and its size + */ + public function handle_upload($form_name) + { + $chunks_expected = $this->request->variable('chunks', 0); + + // If chunking is disabled or we are not using plupload, just return + // and handle the file as usual + if ($chunks_expected < 2) + { + return; + } + + $file_name = $this->request->variable('name', ''); + $chunk = $this->request->variable('chunk', 0); + + $this->user->add_lang('plupload'); + $this->prepare_temporary_directory(); + + $file_path = $this->temporary_filepath($file_name); + $this->integrate_uploaded_file($form_name, $chunk, $file_path); + + // If we are done with all the chunks, strip the .part suffix and then + // handle the resulting file as normal, otherwise die and await the + // next chunk. + if ($chunk == $chunks_expected - 1) + { + rename("{$file_path}.part", $file_path); + + // Reset upload directories to defaults once completed + $this->set_default_directories(); + + // Need to modify some of the $_FILES values to reflect the new file + return array( + 'tmp_name' => $file_path, + 'name' => $this->request->variable('real_filename', '', true), + 'size' => filesize($file_path), + 'type' => $this->mimetype_guesser->guess($file_path, $file_name), + ); + } + else + { + $json_response = new \phpbb\json_response(); + $json_response->send(array( + 'jsonrpc' => '2.0', + 'id' => 'id', + 'result' => null, + )); + } + } + + /** + * Fill in the plupload configuration options in the template + * + * @param \phpbb\cache\service $cache + * @param \phpbb\template\template $template + * @param string $s_action The URL to submit the POST data to + * @param int $forum_id The ID of the forum + * @param int $max_files Maximum number of files allowed. 0 for unlimited. + * + * @return null + */ + public function configure(\phpbb\cache\service $cache, \phpbb\template\template $template, $s_action, $forum_id, $max_files) + { + $filters = $this->generate_filter_string($cache, $forum_id); + $chunk_size = $this->get_chunk_size(); + $resize = $this->generate_resize_string(); + + $template->assign_vars(array( + 'S_RESIZE' => $resize, + 'S_PLUPLOAD' => true, + 'FILTERS' => $filters, + 'CHUNK_SIZE' => $chunk_size, + 'S_PLUPLOAD_URL' => htmlspecialchars_decode($s_action), + 'MAX_ATTACHMENTS' => $max_files, + 'ATTACH_ORDER' => ($this->config['display_order']) ? 'asc' : 'desc', + 'L_TOO_MANY_ATTACHMENTS' => $this->user->lang('TOO_MANY_ATTACHMENTS', $max_files), + )); + + $this->user->add_lang('plupload'); + } + + /** + * Checks whether the page request was sent by plupload or not + * + * @return bool + */ + public function is_active() + { + return $this->request->header('X-PHPBB-USING-PLUPLOAD', false); + } + + /** + * Returns whether the current HTTP request is a multipart request. + * + * @return bool + */ + public function is_multipart() + { + $content_type = $this->request->server('CONTENT_TYPE'); + + return strpos($content_type, 'multipart') === 0; + } + + /** + * Sends an error message back to the client via JSON response + * + * @param int $code The error code + * @param string $msg The translation string of the message to be sent + * + * @return null + */ + public function emit_error($code, $msg) + { + $json_response = new \phpbb\json_response(); + $json_response->send(array( + 'jsonrpc' => '2.0', + 'id' => 'id', + 'error' => array( + 'code' => $code, + 'message' => $this->user->lang($msg), + ), + )); + } + + /** + * Looks at the list of allowed extensions and generates a string + * appropriate for use in configuring plupload with + * + * @param \phpbb\cache\service $cache + * @param string $forum_id The ID of the forum + * + * @return string + */ + public function generate_filter_string(\phpbb\cache\service $cache, $forum_id) + { + $attach_extensions = $cache->obtain_attach_extensions($forum_id); + unset($attach_extensions['_allowed_']); + $groups = array(); + + // Re-arrange the extension array to $groups[$group_name][] + foreach ($attach_extensions as $extension => $extension_info) + { + if (!isset($groups[$extension_info['group_name']])) + { + $groups[$extension_info['group_name']] = array(); + } + + $groups[$extension_info['group_name']][] = $extension; + } + + $filters = array(); + foreach ($groups as $group => $extensions) + { + $filters[] = sprintf( + "{title: '%s', extensions: '%s'}", + addslashes(ucfirst(strtolower($group))), + addslashes(implode(',', $extensions)) + ); + } + + return implode(',', $filters); + } + + /** + * Generates a string that is used to tell plupload to automatically resize + * files before uploading them. + * + * @return string + */ + public function generate_resize_string() + { + $resize = ''; + if ($this->config['img_max_height'] > 0 && $this->config['img_max_width'] > 0) + { + $resize = sprintf( + 'resize: {width: %d, height: %d, quality: 85},', + (int) $this->config['img_max_width'], + (int) $this->config['img_max_height'] + ); + } + + return $resize; + } + + /** + * Checks various php.ini values and the maximum file size to determine + * the maximum size chunks a file can be split up into for upload + * + * @return int + */ + public function get_chunk_size() + { + $max = min( + $this->php_ini->get_bytes('upload_max_filesize'), + $this->php_ini->get_bytes('post_max_size'), + max(1, $this->php_ini->get_bytes('memory_limit')), + $this->config['max_filesize'] + ); + + // Use half of the maximum possible to leave plenty of room for other + // POST data. + return floor($max / 2); + } + + protected function temporary_filepath($file_name) + { + // Must preserve the extension for plupload to work. + return sprintf( + '%s/%s_%s%s', + $this->temporary_directory, + $this->config['plupload_salt'], + md5($file_name), + \filespec::get_extension($file_name) + ); + } + + /** + * Checks whether the chunk we are about to deal with was actually uploaded + * by PHP and actually exists, if not, it generates an error + * + * @param string $form_name The name of the file in the form data + * + * @return null + */ + protected function integrate_uploaded_file($form_name, $chunk, $file_path) + { + $is_multipart = $this->is_multipart(); + $upload = $this->request->file($form_name); + if ($is_multipart && (!isset($upload['tmp_name']) || !is_uploaded_file($upload['tmp_name']))) + { + $this->emit_error(103, 'PLUPLOAD_ERR_MOVE_UPLOADED'); + } + + $tmp_file = $this->temporary_filepath($upload['tmp_name']); + + if (!phpbb_is_writable($this->temporary_directory) || !move_uploaded_file($upload['tmp_name'], $tmp_file)) + { + $this->emit_error(103, 'PLUPLOAD_ERR_MOVE_UPLOADED'); + } + + $out = fopen("{$file_path}.part", $chunk == 0 ? 'wb' : 'ab'); + if (!$out) + { + $this->emit_error(102, 'PLUPLOAD_ERR_OUTPUT'); + } + + $in = fopen(($is_multipart) ? $tmp_file : 'php://input', 'rb'); + if (!$in) + { + $this->emit_error(101, 'PLUPLOAD_ERR_INPUT'); + } + + while ($buf = fread($in, 4096)) + { + fwrite($out, $buf); + } + + fclose($in); + fclose($out); + + if ($is_multipart) + { + unlink($tmp_file); + } + } + + /** + * Creates the temporary directory if it does not already exist. + * + * @return null + */ + protected function prepare_temporary_directory() + { + if (!file_exists($this->temporary_directory)) + { + mkdir($this->temporary_directory); + + copy( + $this->upload_directory . '/index.htm', + $this->temporary_directory . '/index.htm' + ); + } + } + + /** + * Sets the default directories for uploads + * + * @return null + */ + protected function set_default_directories() + { + $this->upload_directory = $this->phpbb_root_path . $this->config['upload_path']; + $this->temporary_directory = $this->upload_directory . '/plupload'; + } + + /** + * Sets the upload directories to the specified paths + * + * @param string $upload_directory Upload directory + * @param string $temporary_directory Temporary directory + * + * @return null + */ + public function set_upload_directories($upload_directory, $temporary_directory) + { + $this->upload_directory = $upload_directory; + $this->temporary_directory = $temporary_directory; + } +} diff --git a/phpBB/phpbb/profilefields/lang_helper.php b/phpBB/phpbb/profilefields/lang_helper.php new file mode 100644 index 0000000000..2e353722b2 --- /dev/null +++ b/phpBB/phpbb/profilefields/lang_helper.php @@ -0,0 +1,140 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields; + +/** +* Custom Profile Fields +*/ +class lang_helper +{ + /** + * Array with the language option, grouped by field and language + * @var array + */ + protected $options_lang = array(); + + /** + * Database object + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * Table where the language strings are stored + * @var string + */ + protected $language_table; + + /** + * Construct + * + * @param \phpbb\db\driver\driver_interface $db Database object + * @param string $language_table Table where the language strings are stored + */ + public function __construct($db, $language_table) + { + $this->db = $db; + $this->language_table = $language_table; + } + + /** + * Loads preview options into language entries for options + * + * @param int $field_id + * @param int $lang_id + * @param mixed $preview_options + */ + public function load_preview_options($field_id, $lang_id, $preview_options) + { + $lang_options = (!is_array($preview_options)) ? explode("\n", $preview_options) : $preview_options; + + foreach ($lang_options as $num => $var) + { + if (!isset($this->options_lang[$field_id])) + { + $this->options_lang[$field_id] = array(); + } + if (!isset($this->options_lang[$field_id][$lang_id])) + { + $this->options_lang[$field_id][$lang_id] = array(); + } + $this->options_lang[$field_id][$lang_id][($num + 1)] = $var; + } + } + + /** + * Fetches language entries for options from DB + * + * @param int $lang_id + */ + public function load_option_lang($lang_id) + { + $sql = 'SELECT field_id, option_id, lang_value + FROM ' . $this->language_table . ' + WHERE lang_id = ' . (int) $lang_id . " + ORDER BY option_id"; + + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $this->options_lang[$row['field_id']][$lang_id][($row['option_id'] + 1)] = $row['lang_value']; + } + + $this->db->sql_freeresult($result); + } + + /** + * Are language options set for this field? + * + * @param int $field_id Database ID of the field + * @param int $lang_id ID of the language + * @param int $field_value Selected value of the field + * @return boolean + */ + public function is_set($field_id, $lang_id = null, $field_value = null) + { + $is_set = isset($this->options_lang[$field_id]); + + if ($is_set && (!is_null($lang_id) || !is_null($field_value))) + { + $is_set = isset($this->options_lang[$field_id][$lang_id]); + } + + if ($is_set && !is_null($field_value)) + { + $is_set = isset($this->options_lang[$field_id][$lang_id][$field_value]); + } + + return $is_set; + } + + /** + * Get the selected language string + * + * @param int $field_id Database ID of the field + * @param int $lang_id ID of the language + * @param int $field_value Selected value of the field + * @return string + */ + public function get($field_id, $lang_id, $field_value = null) + { + if (is_null($field_value)) + { + return $this->options_lang[$field_id][$lang_id]; + } + + return $this->options_lang[$field_id][$lang_id][$field_value]; + } +} diff --git a/phpBB/phpbb/profilefields/manager.php b/phpBB/phpbb/profilefields/manager.php new file mode 100644 index 0000000000..ea4b24af56 --- /dev/null +++ b/phpBB/phpbb/profilefields/manager.php @@ -0,0 +1,502 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields; + +/** +* Custom Profile Fields +*/ +class manager +{ + /** + * Auth object + * @var \phpbb\auth\auth + */ + protected $auth; + + /** + * Database object + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * Event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $dispatcher; + + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * Service Collection object + * @var \phpbb\di\service_collection + */ + protected $type_collection; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + protected $fields_table; + + protected $fields_language_table; + + protected $fields_data_table; + + protected $profile_cache = array(); + + /** + * Construct + * + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\db\driver\driver_interface $db Database object + * @param \phpbb\event\dispatcher_interface $dispatcher Event dispatcher object + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\di\service_collection $type_collection + * @param \phpbb\user $user User object + * @param string $fields_table + * @param string $fields_language_table + * @param string $fields_data_table + */ + public function __construct(\phpbb\auth\auth $auth, \phpbb\db\driver\driver_interface $db, \phpbb\event\dispatcher_interface $dispatcher, \phpbb\request\request $request, \phpbb\template\template $template, \phpbb\di\service_collection $type_collection, \phpbb\user $user, $fields_table, $fields_language_table, $fields_data_table) + { + $this->auth = $auth; + $this->db = $db; + $this->dispatcher = $dispatcher; + $this->request = $request; + $this->template = $template; + $this->type_collection = $type_collection; + $this->user = $user; + + $this->fields_table = $fields_table; + $this->fields_language_table = $fields_language_table; + $this->fields_data_table = $fields_data_table; + } + + /** + * Assign editable fields to template, mode can be profile (for profile change) or register (for registration) + * Called by ucp_profile and ucp_register + */ + public function generate_profile_fields($mode, $lang_id) + { + $sql_where = ''; + switch ($mode) + { + case 'register': + // If the field is required we show it on the registration page + $sql_where .= ' AND f.field_show_on_reg = 1'; + break; + + case 'profile': + // Show hidden fields to moderators/admins + if (!$this->auth->acl_gets('a_', 'm_') && !$this->auth->acl_getf_global('m_')) + { + $sql_where .= ' AND f.field_show_profile = 1'; + } + break; + + default: + trigger_error('Wrong profile mode specified', E_USER_ERROR); + break; + } + + $sql = 'SELECT l.*, f.* + FROM ' . $this->fields_language_table . ' l, ' . $this->fields_table . " f + WHERE f.field_active = 1 + $sql_where + AND l.lang_id = " . (int) $lang_id . ' + AND l.field_id = f.field_id + ORDER BY f.field_order'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + // Return templated field + $profile_field = $this->type_collection[$row['field_type']]; + $tpl_snippet = $profile_field->process_field_row('change', $row); + + $this->template->assign_block_vars('profile_fields', array( + 'LANG_NAME' => $this->user->lang($row['lang_name']), + 'LANG_EXPLAIN' => $this->user->lang($row['lang_explain']), + 'FIELD' => $tpl_snippet, + 'FIELD_ID' => $profile_field->get_field_ident($row), + 'S_REQUIRED' => ($row['field_required']) ? true : false, + )); + } + $this->db->sql_freeresult($result); + } + + /** + * Build profile cache, used for display + */ + protected function build_cache() + { + $this->profile_cache = array(); + + // Display hidden/no_view fields for admin/moderator + $sql = 'SELECT l.*, f.* + FROM ' . $this->fields_language_table . ' l, ' . $this->fields_table . ' f + WHERE l.lang_id = ' . $this->user->get_iso_lang_id() . ' + AND f.field_active = 1 ' . + ((!$this->auth->acl_gets('a_', 'm_') && !$this->auth->acl_getf_global('m_')) ? ' AND f.field_hide = 0 ' : '') . ' + AND f.field_no_view = 0 + AND l.field_id = f.field_id + ORDER BY f.field_order'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $this->profile_cache[$row['field_ident']] = $row; + } + $this->db->sql_freeresult($result); + } + + /** + * Submit profile field for validation + */ + public function submit_cp_field($mode, $lang_id, &$cp_data, &$cp_error) + { + $sql_where = ''; + switch ($mode) + { + case 'register': + // If the field is required we show it on the registration page + $sql_where .= ' AND f.field_show_on_reg = 1'; + break; + + case 'profile': + // Show hidden fields to moderators/admins + if (!$this->auth->acl_gets('a_', 'm_') && !$this->auth->acl_getf_global('m_')) + { + $sql_where .= ' AND f.field_show_profile = 1'; + } + break; + + default: + trigger_error('Wrong profile mode specified', E_USER_ERROR); + break; + } + + $sql = 'SELECT l.*, f.* + FROM ' . $this->fields_language_table . ' l, ' . $this->fields_table . ' f + WHERE l.lang_id = ' . (int) $lang_id . " + AND f.field_active = 1 + $sql_where + AND l.field_id = f.field_id + ORDER BY f.field_order"; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $profile_field = $this->type_collection[$row['field_type']]; + $cp_data['pf_' . $row['field_ident']] = $profile_field->get_profile_field($row); + $check_value = $cp_data['pf_' . $row['field_ident']]; + + if (($cp_result = $profile_field->validate_profile_field($check_value, $row)) !== false) + { + // If the result is not false, it's an error message + $cp_error[] = $cp_result; + } + } + $this->db->sql_freeresult($result); + } + + /** + * Update profile field data directly + */ + public function update_profile_field_data($user_id, $cp_data) + { + if (!sizeof($cp_data)) + { + return; + } + + $sql = 'UPDATE ' . $this->fields_data_table . ' + SET ' . $this->db->sql_build_array('UPDATE', $cp_data) . ' + WHERE user_id = ' . (int) $user_id; + $this->db->sql_query($sql); + + if (!$this->db->sql_affectedrows()) + { + $cp_data = $this->build_insert_sql_array($cp_data); + $cp_data['user_id'] = (int) $user_id; + + $sql = 'INSERT INTO ' . $this->fields_data_table . ' ' . $this->db->sql_build_array('INSERT', $cp_data); + $this->db->sql_query($sql); + } + } + + /** + * Generate the template arrays in order to display the column names + * + * @param string $restrict_option Restrict the published fields to a certain profile field option + * @return array Returns an array with the template variables type, name and explain for the fields to display + */ + public function generate_profile_fields_template_headlines($restrict_option = '') + { + if (!sizeof($this->profile_cache)) + { + $this->build_cache(); + } + + $tpl_fields = array(); + + // Go through the fields in correct order + foreach ($this->profile_cache as $field_ident => $field_data) + { + if ($restrict_option && !$field_data[$restrict_option]) + { + continue; + } + + $profile_field = $this->type_collection[$field_data['field_type']]; + + $tpl_fields[] = array( + 'PROFILE_FIELD_IDENT' => $field_ident, + 'PROFILE_FIELD_TYPE' => $field_data['field_type'], + 'PROFILE_FIELD_NAME' => $profile_field->get_field_name($field_data['lang_name']), + 'PROFILE_FIELD_EXPLAIN' => $this->user->lang($field_data['lang_explain']), + ); + } + + $profile_cache = $this->profile_cache; + + /** + * Event to modify template headlines of the generated profile fields + * + * @event core.generate_profile_fields_template_headlines + * @var string restrict_option Restrict the published fields to a certain profile field option + * @var array tpl_fields Array with template data fields + * @var array profile_cache A copy of the profile cache to make additional checks + * @since 3.1.6-RC1 + */ + $vars = array( + 'restrict_option', + 'tpl_fields', + 'profile_cache', + ); + extract($this->dispatcher->trigger_event('core.generate_profile_fields_template_headlines', compact($vars))); + unset($profile_cache); + + return $tpl_fields; + } + + /** + * Grab the user specific profile fields data + * + * @param int|array $user_ids Single user id or an array of ids + * @return array Users profile fields data + */ + public function grab_profile_fields_data($user_ids = 0) + { + if (!is_array($user_ids)) + { + $user_ids = array($user_ids); + } + + if (!sizeof($this->profile_cache)) + { + $this->build_cache(); + } + + if (!sizeof($user_ids)) + { + return array(); + } + + $sql = 'SELECT * + FROM ' . $this->fields_data_table . ' + WHERE ' . $this->db->sql_in_set('user_id', array_map('intval', $user_ids)); + $result = $this->db->sql_query($sql); + + $field_data = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $field_data[$row['user_id']] = $row; + } + $this->db->sql_freeresult($result); + + /** + * Event to modify profile fields data retrieved from the database + * + * @event core.grab_profile_fields_data + * @var array user_ids Single user id or an array of ids + * @var array field_data Array with profile fields data + * @since 3.1.0-b3 + */ + $vars = array('user_ids', 'field_data'); + extract($this->dispatcher->trigger_event('core.grab_profile_fields_data', compact($vars))); + + $user_fields = array(); + + // Go through the fields in correct order + foreach (array_keys($this->profile_cache) as $used_ident) + { + foreach ($field_data as $user_id => $row) + { + $user_fields[$user_id][$used_ident]['value'] = $row['pf_' . $used_ident]; + $user_fields[$user_id][$used_ident]['data'] = $this->profile_cache[$used_ident]; + } + + foreach ($user_ids as $user_id) + { + if (!isset($user_fields[$user_id][$used_ident]) && $this->profile_cache[$used_ident]['field_show_novalue']) + { + $user_fields[$user_id][$used_ident]['value'] = ''; + $user_fields[$user_id][$used_ident]['data'] = $this->profile_cache[$used_ident]; + } + } + } + + return $user_fields; + } + + /** + * Assign the user's profile fields data to the template + * + * @param array $profile_row Array with users profile field data + * @param bool $use_contact_fields Should we display contact fields as such? + * This requires special treatments (links should not be parsed in the values, and more) + * @return array + */ + public function generate_profile_fields_template_data($profile_row, $use_contact_fields = true) + { + // $profile_row == $user_fields[$row['user_id']]; + $tpl_fields = array(); + $tpl_fields['row'] = $tpl_fields['blockrow'] = array(); + + /** + * Event to modify data of the generated profile fields, before the template assignment loop + * + * @event core.generate_profile_fields_template_data_before + * @var array profile_row Array with users profile field data + * @var array tpl_fields Array with template data fields + * @var bool use_contact_fields Should we display contact fields as such? + * @since 3.1.0-b3 + */ + $vars = array('profile_row', 'tpl_fields', 'use_contact_fields'); + extract($this->dispatcher->trigger_event('core.generate_profile_fields_template_data_before', compact($vars))); + + foreach ($profile_row as $ident => $ident_ary) + { + $profile_field = $this->type_collection[$ident_ary['data']['field_type']]; + $value = $profile_field->get_profile_value($ident_ary['value'], $ident_ary['data']); + $value_raw = $profile_field->get_profile_value_raw($ident_ary['value'], $ident_ary['data']); + + if ($value === null) + { + continue; + } + + $field_desc = $contact_url = ''; + if ($use_contact_fields && $ident_ary['data']['field_is_contact']) + { + $value = $profile_field->get_profile_contact_value($ident_ary['value'], $ident_ary['data']); + $field_desc = $this->user->lang($ident_ary['data']['field_contact_desc']); + if (strpos($field_desc, '%s') !== false) + { + $field_desc = sprintf($field_desc, $value); + } + $contact_url = ''; + if (strpos($ident_ary['data']['field_contact_url'], '%s') !== false) + { + $contact_url = sprintf($ident_ary['data']['field_contact_url'], $value); + } + } + + $tpl_fields['row'] += array( + 'PROFILE_' . strtoupper($ident) . '_IDENT' => $ident, + 'PROFILE_' . strtoupper($ident) . '_VALUE' => $value, + 'PROFILE_' . strtoupper($ident) . '_VALUE_RAW' => $value_raw, + 'PROFILE_' . strtoupper($ident) . '_CONTACT' => $contact_url, + 'PROFILE_' . strtoupper($ident) . '_DESC' => $field_desc, + 'PROFILE_' . strtoupper($ident) . '_TYPE' => $ident_ary['data']['field_type'], + 'PROFILE_' . strtoupper($ident) . '_NAME' => $this->user->lang($ident_ary['data']['lang_name']), + 'PROFILE_' . strtoupper($ident) . '_EXPLAIN' => $this->user->lang($ident_ary['data']['lang_explain']), + + 'S_PROFILE_' . strtoupper($ident) . '_CONTACT' => $ident_ary['data']['field_is_contact'], + 'S_PROFILE_' . strtoupper($ident) => true, + ); + + $tpl_fields['blockrow'][] = array( + 'PROFILE_FIELD_IDENT' => $ident, + 'PROFILE_FIELD_VALUE' => $value, + 'PROFILE_FIELD_VALUE_RAW' => $value_raw, + 'PROFILE_FIELD_CONTACT' => $contact_url, + 'PROFILE_FIELD_DESC' => $field_desc, + 'PROFILE_FIELD_TYPE' => $ident_ary['data']['field_type'], + 'PROFILE_FIELD_NAME' => $this->user->lang($ident_ary['data']['lang_name']), + 'PROFILE_FIELD_EXPLAIN' => $this->user->lang($ident_ary['data']['lang_explain']), + + 'S_PROFILE_CONTACT' => $ident_ary['data']['field_is_contact'], + 'S_PROFILE_' . strtoupper($ident) => true, + ); + } + + /** + * Event to modify template data of the generated profile fields + * + * @event core.generate_profile_fields_template_data + * @var array profile_row Array with users profile field data + * @var array tpl_fields Array with template data fields + * @var bool use_contact_fields Should we display contact fields as such? + * @since 3.1.0-b3 + */ + $vars = array('profile_row', 'tpl_fields', 'use_contact_fields'); + extract($this->dispatcher->trigger_event('core.generate_profile_fields_template_data', compact($vars))); + + return $tpl_fields; + } + + /** + * Build Array for user insertion into custom profile fields table + */ + public function build_insert_sql_array($cp_data) + { + $sql_not_in = array(); + foreach ($cp_data as $key => $null) + { + $sql_not_in[] = (strncmp($key, 'pf_', 3) === 0) ? substr($key, 3) : $key; + } + + $sql = 'SELECT f.field_type, f.field_ident, f.field_default_value, l.lang_default_value + FROM ' . $this->fields_language_table . ' l, ' . $this->fields_table . ' f + WHERE l.lang_id = ' . $this->user->get_iso_lang_id() . ' + ' . ((sizeof($sql_not_in)) ? ' AND ' . $this->db->sql_in_set('f.field_ident', $sql_not_in, true) : '') . ' + AND l.field_id = f.field_id'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $profile_field = $this->type_collection[$row['field_type']]; + $cp_data['pf_' . $row['field_ident']] = $profile_field->get_default_field_value($row); + } + $this->db->sql_freeresult($result); + + return $cp_data; + } +} diff --git a/phpBB/phpbb/profilefields/type/type_base.php b/phpBB/phpbb/profilefields/type/type_base.php new file mode 100644 index 0000000000..9b4bada26d --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_base.php @@ -0,0 +1,206 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +abstract class type_base implements type_interface +{ + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name() + { + return $this->user->lang('FIELD_' . strtoupper($this->get_name_short())); + } + + /** + * {@inheritDoc} + */ + public function get_service_name() + { + return 'profilefields.type.' . $this->get_name_short(); + } + + /** + * {@inheritDoc} + */ + public function get_template_filename() + { + return 'profilefields/' . $this->get_name_short() . '.html'; + } + + /** + * {@inheritDoc} + */ + public function get_field_ident($field_data) + { + return 'pf_' . $field_data['field_ident']; + } + + /** + * {@inheritDoc} + */ + public function get_field_name($field_name) + { + return isset($this->user->lang[$field_name]) ? $this->user->lang[$field_name] : $field_name; + } + + /** + * {@inheritDoc} + */ + public function get_profile_contact_value($field_value, $field_data) + { + return $this->get_profile_value($field_value, $field_data); + } + + /** + * {@inheritDoc} + */ + public function get_language_options_input($field_data) + { + $field_data['l_lang_name'] = $this->request->variable('l_lang_name', array(0 => ''), true); + $field_data['l_lang_explain'] = $this->request->variable('l_lang_explain', array(0 => ''), true); + $field_data['l_lang_default_value'] = $this->request->variable('l_lang_default_value', array(0 => ''), true); + $field_data['l_lang_options'] = $this->request->variable('l_lang_options', array(0 => ''), true); + + return $field_data; + } + + /** + * {@inheritDoc} + */ + public function prepare_options_form(&$exclude_options, &$visibility_options) + { + return $this->request->variable('lang_options', '', true); + } + + /** + * {@inheritDoc} + */ + public function validate_options_on_submit($error, $field_data) + { + return $error; + } + + /** + * {@inheritDoc} + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step) + { + if ($step == 3 && ($field_data[$key] || $action != 'edit') && $key == 'l_lang_options' && is_array($field_data[$key])) + { + foreach ($field_data[$key] as $lang_id => $options) + { + $field_data[$key][$lang_id] = is_array($options) ? $options : explode("\n", $options); + } + + return $current_value; + } + + return $current_value; + } + + /** + * {@inheritDoc} + */ + public function prepare_hidden_fields($step, $key, $action, &$field_data) + { + if (!$this->request->is_set($key)) + { + // Do not set this variable, we will use the default value + return null; + } + else if ($key == 'field_ident' && isset($field_data[$key])) + { + return $field_data[$key]; + } + else + { + $default_value = ''; + $lang_fields = array( + 'l_lang_name', + 'l_lang_explain', + 'l_lang_default_value', + 'l_lang_options', + ); + + if (in_array($key, $lang_fields)) + { + $default_value = array(0 => ''); + } + return $this->request->variable($key, $default_value, true); + } + } + + /** + * {@inheritDoc} + */ + public function display_options(&$template_vars, &$field_data) + { + return; + } + + /** + * Return templated value/field. Possible values for $mode are: + * change == user is able to set/enter profile values; preview == just show the value + */ + public function process_field_row($mode, $profile_row) + { + $preview_options = ($mode == 'preview') ? $profile_row['lang_options'] : false; + + // set template filename + $this->template->set_filenames(array( + 'cp_body' => $this->get_template_filename(), + )); + + // empty previously filled blockvars + $this->template->destroy_block_vars($this->get_name_short()); + + // Assign template variables + $this->generate_field($profile_row, $preview_options); + + return $this->template->assign_display('cp_body'); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_bool.php b/phpBB/phpbb/profilefields/type/type_bool.php new file mode 100644 index 0000000000..f6f3f17a6c --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_bool.php @@ -0,0 +1,415 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_bool extends type_base +{ + /** + * Profile fields language helper + * @var \phpbb\profilefields\lang_helper + */ + protected $lang_helper; + + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\profilefields\lang_helper $lang_helper Profile fields language helper + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\profilefields\lang_helper $lang_helper, \phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->lang_helper = $lang_helper; + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'bool'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $profile_row = array( + 'var_name' => 'field_default_value', + 'field_id' => 1, + 'lang_name' => $field_data['lang_name'], + 'lang_explain' => $field_data['lang_explain'], + 'lang_id' => $default_lang_id, + 'field_default_value' => $field_data['field_default_value'], + 'field_ident' => 'field_default_value', + 'field_type' => $this->get_service_name(), + 'field_length' => $field_data['field_length'], + 'lang_options' => $field_data['lang_options'], + ); + + $options = array( + 0 => array('TITLE' => $this->user->lang['FIELD_TYPE'], 'EXPLAIN' => $this->user->lang['BOOL_TYPE_EXPLAIN'], 'FIELD' => '<label><input type="radio" class="radio" name="field_length" value="1"' . (($field_data['field_length'] == 1) ? ' checked="checked"' : '') . ' onchange="document.getElementById(\'add_profile_field\').submit();" /> ' . $this->user->lang['RADIO_BUTTONS'] . '</label><label><input type="radio" class="radio" name="field_length" value="2"' . (($field_data['field_length'] == 2) ? ' checked="checked"' : '') . ' onchange="document.getElementById(\'add_profile_field\').submit();" /> ' . $this->user->lang['CHECKBOX'] . '</label>'), + 1 => array('TITLE' => $this->user->lang['DEFAULT_VALUE'], 'FIELD' => $this->process_field_row('preview', $profile_row)), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 1, + 'field_minlen' => 0, + 'field_maxlen' => 0, + 'field_validation' => '', + 'field_novalue' => 0, + 'field_default_value' => 0, + ); + } + + /** + * {@inheritDoc} + */ + public function get_default_field_value($field_data) + { + return $field_data['field_default_value']; + } + + /** + * {@inheritDoc} + */ + public function get_profile_field($profile_row) + { + $var_name = 'pf_' . $profile_row['field_ident']; + + // Checkbox + if ($profile_row['field_length'] == 2) + { + return ($this->request->is_set($var_name)) ? 1 : 0; + } + else + { + return $this->request->variable($var_name, (int) $profile_row['field_default_value']); + } + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + $field_value = (bool) $field_value; + + if (!$field_value && $field_data['field_required']) + { + return $this->user->lang('FIELD_REQUIRED', $this->get_field_name($field_data['lang_name'])); + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value($field_value, $field_data) + { + $field_id = $field_data['field_id']; + $lang_id = $field_data['lang_id']; + + if (!$this->lang_helper->is_set($field_id, $lang_id)) + { + $this->lang_helper->load_option_lang($lang_id); + } + + if (!$field_value && $field_data['field_show_novalue']) + { + $field_value = $field_data['field_default_value']; + } + + if ($field_data['field_length'] == 1) + { + return ($this->lang_helper->is_set($field_id, $lang_id, (int) $field_value)) ? $this->lang_helper->get($field_id, $lang_id, (int) $field_value) : null; + } + else if (!$field_value) + { + return null; + } + else + { + return $this->lang_helper->is_set($field_id, $lang_id, $field_value + 1) ? $this->lang_helper->get($field_id, $lang_id, $field_value + 1) : null; + } + } + + /** + * {@inheritDoc} + */ + public function get_profile_value_raw($field_value, $field_data) + { + if ($field_value == $field_data['field_novalue'] && !$field_data['field_show_novalue']) + { + return null; + } + + if (!$field_value && $field_data['field_show_novalue']) + { + $field_value = $field_data['field_novalue']; + } + + return $field_value; + } + + /** + * {@inheritDoc} + */ + public function generate_field($profile_row, $preview_options = false) + { + $profile_row['field_ident'] = (isset($profile_row['var_name'])) ? $profile_row['var_name'] : 'pf_' . $profile_row['field_ident']; + $field_ident = $profile_row['field_ident']; + $default_value = $profile_row['field_default_value']; + + // checkbox - set the value to "true" if it has been set to 1 + if ($profile_row['field_length'] == 2) + { + $value = ($this->request->is_set($field_ident) && $this->request->variable($field_ident, $default_value) == 1) ? true : ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $default_value : $this->user->profile_fields[$field_ident]); + } + else + { + $value = ($this->request->is_set($field_ident)) ? $this->request->variable($field_ident, $default_value) : ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $default_value : $this->user->profile_fields[$field_ident]); + } + + $profile_row['field_value'] = (int) $value; + $this->template->assign_block_vars('bool', array_change_key_case($profile_row, CASE_UPPER)); + + if ($profile_row['field_length'] == 1) + { + if (!$this->lang_helper->is_set($profile_row['field_id'], $profile_row['lang_id'], 1)) + { + if ($preview_options) + { + $this->lang_helper->load_preview_options($profile_row['field_id'], $profile_row['lang_id'], $preview_options); + } + else + { + $this->lang_helper->load_option_lang($profile_row['lang_id']); + } + } + + $options = $this->lang_helper->get($profile_row['field_id'], $profile_row['lang_id']); + foreach ($options as $option_id => $option_value) + { + $this->template->assign_block_vars('bool.options', array( + 'OPTION_ID' => $option_id, + 'CHECKED' => ($value == $option_id) ? ' checked="checked"' : '', + 'VALUE' => $option_value, + )); + } + } + } + + /** + * {@inheritDoc} + */ + public function get_field_ident($field_data) + { + return ($field_data['field_length'] == '1') ? '' : 'pf_' . $field_data['field_ident']; + } + + /** + * {@inheritDoc} + */ + public function get_database_column_type() + { + return 'TINT:2'; + } + + /** + * {@inheritDoc} + */ + public function get_language_options($field_data) + { + $options = array( + 'lang_name' => 'string', + 'lang_options' => 'two_options', + ); + + if ($field_data['lang_explain']) + { + $options['lang_explain'] = 'text'; + } + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_language_options_input($field_data) + { + $field_data['l_lang_name'] = $this->request->variable('l_lang_name', array(0 => ''), true); + $field_data['l_lang_explain'] = $this->request->variable('l_lang_explain', array(0 => ''), true); + $field_data['l_lang_default_value'] = $this->request->variable('l_lang_default_value', array(0 => ''), true); + + /** + * @todo check if this line is correct... + $field_data['l_lang_default_value'] = $this->request->variable('l_lang_default_value', array(0 => array('')), true); + */ + $field_data['l_lang_options'] = $this->request->variable('l_lang_options', array(0 => array('')), true); + + return $field_data; + } + + /** + * {@inheritDoc} + */ + public function prepare_options_form(&$exclude_options, &$visibility_options) + { + $exclude_options[1][] = 'lang_options'; + + return $this->request->variable('lang_options', array(''), true); + } + + /** + * {@inheritDoc} + */ + public function validate_options_on_submit($error, $field_data) + { + if (empty($field_data['lang_options'][0]) || empty($field_data['lang_options'][1])) + { + $error[] = $this->user->lang['NO_FIELD_ENTRIES']; + } + + return $error; + } + + /** + * {@inheritDoc} + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step) + { + if ($step == 2 && $key == 'field_default_value') + { + // 'field_length' == 1 defines radio buttons. Possible values are 1 or 2 only. + // 'field_length' == 2 defines checkbox. Possible values are 0 or 1 only. + // If we switch the type on step 2, we have to adjust field value. + // 1 is a common value for the checkbox and radio buttons. + + // Adjust unchecked checkbox value. + // If we return or save settings from 2nd/3rd page + // and the checkbox is unchecked, set the value to 0. + if ($this->request->is_set('step') && !$this->request->is_set($key)) + { + return 0; + } + + // If we switch to the checkbox type but former radio buttons value was 2, + // which is not the case for the checkbox, set it to 0 (unchecked). + if ($field_data['field_length'] == 2 && $current_value == 2) + { + return 0; + } + // If we switch to the radio buttons but the former checkbox value was 0, + // which is not the case for the radio buttons, set it to 0. + else if ($field_data['field_length'] == 1 && $current_value == 0) + { + return 2; + } + } + + if ($key == 'l_lang_options' && $this->request->is_set($key)) + { + $field_data[$key] = $this->request->variable($key, array(0 => array('')), true); + + return $current_value; + } + + return parent::get_excluded_options($key, $action, $current_value, $field_data, $step); + } + + /** + * {@inheritDoc} + */ + public function prepare_hidden_fields($step, $key, $action, &$field_data) + { + if ($key == 'field_default_value') + { + $field_length = $this->request->variable('field_length', 0); + + // Do a simple is set check if using checkbox. + if ($field_length == 2) + { + return $this->request->is_set($key); + } + return $this->request->variable($key, $field_data[$key], true); + } + + $default_lang_options = array( + 'l_lang_options' => array(0 => array('')), + 'lang_options' => array(0 => ''), + ); + + if (isset($default_lang_options[$key]) && $this->request->is_set($key)) + { + return $this->request->variable($key, $default_lang_options[$key], true); + } + + return parent::prepare_hidden_fields($step, $key, $action, $field_data); + } + + /** + * {@inheritDoc} + */ + public function display_options(&$template_vars, &$field_data) + { + // Initialize these array elements if we are creating a new field + if (!sizeof($field_data['lang_options'])) + { + // No options have been defined for a boolean field. + $field_data['lang_options'][0] = ''; + $field_data['lang_options'][1] = ''; + } + + $template_vars = array_merge($template_vars, array( + 'S_BOOL' => true, + 'L_LANG_OPTIONS_EXPLAIN' => $this->user->lang['BOOL_ENTRIES_EXPLAIN'], + 'FIRST_LANG_OPTION' => $field_data['lang_options'][0], + 'SECOND_LANG_OPTION' => $field_data['lang_options'][1], + )); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_date.php b/phpBB/phpbb/profilefields/type/type_date.php new file mode 100644 index 0000000000..63a0c79a3d --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_date.php @@ -0,0 +1,374 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_date extends type_base +{ + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'date'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $profile_row = array( + 'var_name' => 'field_default_value', + 'lang_name' => $field_data['lang_name'], + 'lang_explain' => $field_data['lang_explain'], + 'lang_id' => $default_lang_id, + 'field_default_value' => $field_data['field_default_value'], + 'field_ident' => 'field_default_value', + 'field_type' => $this->get_service_name(), + 'field_length' => $field_data['field_length'], + 'lang_options' => $field_data['lang_options'], + ); + + $always_now = request_var('always_now', -1); + if ($always_now == -1) + { + $s_checked = ($field_data['field_default_value'] == 'now') ? true : false; + } + else + { + $s_checked = ($always_now) ? true : false; + } + + $options = array( + 0 => array('TITLE' => $this->user->lang['DEFAULT_VALUE'], 'FIELD' => $this->process_field_row('preview', $profile_row)), + 1 => array('TITLE' => $this->user->lang['ALWAYS_TODAY'], 'FIELD' => '<label><input type="radio" class="radio" name="always_now" value="1"' . (($s_checked) ? ' checked="checked"' : '') . ' onchange="document.getElementById(\'add_profile_field\').submit();" /> ' . $this->user->lang['YES'] . '</label><label><input type="radio" class="radio" name="always_now" value="0"' . ((!$s_checked) ? ' checked="checked"' : '') . ' onchange="document.getElementById(\'add_profile_field\').submit();" /> ' . $this->user->lang['NO'] . '</label>'), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 10, + 'field_minlen' => 10, + 'field_maxlen' => 10, + 'field_validation' => '', + 'field_novalue' => ' 0- 0- 0', + 'field_default_value' => ' 0- 0- 0', + ); + } + + /** + * {@inheritDoc} + */ + public function get_default_field_value($field_data) + { + if ($field_data['field_default_value'] == 'now') + { + $now = getdate(); + $field_data['field_default_value'] = sprintf('%2d-%2d-%4d', $now['mday'], $now['mon'], $now['year']); + } + + return $field_data['field_default_value']; + } + + /** + * {@inheritDoc} + */ + public function get_profile_field($profile_row) + { + $var_name = 'pf_' . $profile_row['field_ident']; + + if (!$this->request->is_set($var_name . '_day')) + { + if ($profile_row['field_default_value'] == 'now') + { + $now = getdate(); + $profile_row['field_default_value'] = sprintf('%2d-%2d-%4d', $now['mday'], $now['mon'], $now['year']); + } + list($day, $month, $year) = explode('-', $profile_row['field_default_value']); + } + else + { + $day = $this->request->variable($var_name . '_day', 0); + $month = $this->request->variable($var_name . '_month', 0); + $year = $this->request->variable($var_name . '_year', 0); + } + + return sprintf('%2d-%2d-%4d', $day, $month, $year); + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + $field_validate = explode('-', $field_value); + + $day = (isset($field_validate[0])) ? (int) $field_validate[0] : 0; + $month = (isset($field_validate[1])) ? (int) $field_validate[1] : 0; + $year = (isset($field_validate[2])) ? (int) $field_validate[2] : 0; + + if ((!$day || !$month || !$year) && !$field_data['field_required']) + { + return false; + } + + if ((!$day || !$month || !$year) && $field_data['field_required']) + { + return $this->user->lang('FIELD_REQUIRED', $this->get_field_name($field_data['lang_name'])); + } + + if ($day < 0 || $day > 31 || $month < 0 || $month > 12 || ($year < 1901 && $year > 0) || $year > gmdate('Y', time()) + 50) + { + return $this->user->lang('FIELD_INVALID_DATE', $this->get_field_name($field_data['lang_name'])); + } + + if (checkdate($month, $day, $year) === false) + { + return $this->user->lang('FIELD_INVALID_DATE', $this->get_field_name($field_data['lang_name'])); + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value($field_value, $field_data) + { + $date = explode('-', $field_value); + $day = (isset($date[0])) ? (int) $date[0] : 0; + $month = (isset($date[1])) ? (int) $date[1] : 0; + $year = (isset($date[2])) ? (int) $date[2] : 0; + + if (!$day && !$month && !$year && !$field_data['field_show_novalue']) + { + return null; + } + else if ($day && $month && $year) + { + // Date should display as the same date for every user regardless of timezone + return $this->user->create_datetime() + ->setDate($year, $month, $day) + ->setTime(0, 0, 0) + ->format($this->user->lang['DATE_FORMAT'], true); + } + + return $field_value; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value_raw($field_value, $field_data) + { + if (($field_value === '' || $field_value === null) && !$field_data['field_show_novalue']) + { + return null; + } + + return $field_value; + } + + /** + * {@inheritDoc} + */ + public function generate_field($profile_row, $preview_options = false) + { + $profile_row['field_ident'] = (isset($profile_row['var_name'])) ? $profile_row['var_name'] : 'pf_' . $profile_row['field_ident']; + $field_ident = $profile_row['field_ident']; + + $now = getdate(); + + if (!$this->request->is_set($profile_row['field_ident'] . '_day')) + { + if ($profile_row['field_default_value'] == 'now') + { + $profile_row['field_default_value'] = sprintf('%2d-%2d-%4d', $now['mday'], $now['mon'], $now['year']); + } + list($day, $month, $year) = explode('-', ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $profile_row['field_default_value'] : $this->user->profile_fields[$field_ident])); + } + else + { + if ($preview_options !== false && $profile_row['field_default_value'] == 'now') + { + $profile_row['field_default_value'] = sprintf('%2d-%2d-%4d', $now['mday'], $now['mon'], $now['year']); + list($day, $month, $year) = explode('-', ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $profile_row['field_default_value'] : $this->user->profile_fields[$field_ident])); + } + else + { + $day = $this->request->variable($profile_row['field_ident'] . '_day', 0); + $month = $this->request->variable($profile_row['field_ident'] . '_month', 0); + $year = $this->request->variable($profile_row['field_ident'] . '_year', 0); + } + } + + $profile_row['s_day_options'] = '<option value="0"' . ((!$day) ? ' selected="selected"' : '') . '>--</option>'; + for ($i = 1; $i < 32; $i++) + { + $profile_row['s_day_options'] .= '<option value="' . $i . '"' . (($i == $day) ? ' selected="selected"' : '') . ">$i</option>"; + } + + $profile_row['s_month_options'] = '<option value="0"' . ((!$month) ? ' selected="selected"' : '') . '>--</option>'; + for ($i = 1; $i < 13; $i++) + { + $profile_row['s_month_options'] .= '<option value="' . $i . '"' . (($i == $month) ? ' selected="selected"' : '') . ">$i</option>"; + } + + $profile_row['s_year_options'] = '<option value="0"' . ((!$year) ? ' selected="selected"' : '') . '>--</option>'; + for ($i = 1901; $i <= $now['year'] + 50; $i++) + { + $profile_row['s_year_options'] .= '<option value="' . $i . '"' . (($i == $year) ? ' selected="selected"' : '') . ">$i</option>"; + } + + $profile_row['field_value'] = 0; + $this->template->assign_block_vars('date', array_change_key_case($profile_row, CASE_UPPER)); + } + + /** + * {@inheritDoc} + */ + public function get_field_ident($field_data) + { + return ''; + } + + /** + * {@inheritDoc} + */ + public function get_database_column_type() + { + return 'VCHAR:10'; + } + + /** + * {@inheritDoc} + */ + public function get_language_options($field_data) + { + $options = array( + 'lang_name' => 'string', + ); + + if ($field_data['lang_explain']) + { + $options['lang_explain'] = 'text'; + } + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step) + { + if ($step == 2 && $key == 'field_default_value') + { + $always_now = $this->request->variable('always_now', -1); + + if ($always_now == 1 || ($always_now === -1 && $current_value == 'now')) + { + $now = getdate(); + + $field_data['field_default_value_day'] = $now['mday']; + $field_data['field_default_value_month'] = $now['mon']; + $field_data['field_default_value_year'] = $now['year']; + $current_value = 'now'; + $this->request->overwrite('field_default_value', $current_value, \phpbb\request\request_interface::POST); + } + else + { + if ($this->request->is_set('field_default_value_day')) + { + $field_data['field_default_value_day'] = $this->request->variable('field_default_value_day', 0); + $field_data['field_default_value_month'] = $this->request->variable('field_default_value_month', 0); + $field_data['field_default_value_year'] = $this->request->variable('field_default_value_year', 0); + $current_value = sprintf('%2d-%2d-%4d', $field_data['field_default_value_day'], $field_data['field_default_value_month'], $field_data['field_default_value_year']); + $this->request->overwrite('field_default_value', $current_value, \phpbb\request\request_interface::POST); + } + else + { + list($field_data['field_default_value_day'], $field_data['field_default_value_month'], $field_data['field_default_value_year']) = explode('-', $current_value); + } + } + + return $current_value; + } + + return parent::get_excluded_options($key, $action, $current_value, $field_data, $step); + } + + /** + * {@inheritDoc} + */ + public function prepare_hidden_fields($step, $key, $action, &$field_data) + { + if ($key == 'field_default_value') + { + $always_now = $this->request->variable('always_now', 0); + + if ($always_now) + { + return 'now'; + } + else if ($this->request->is_set('field_default_value_day')) + { + $field_data['field_default_value_day'] = $this->request->variable('field_default_value_day', 0); + $field_data['field_default_value_month'] = $this->request->variable('field_default_value_month', 0); + $field_data['field_default_value_year'] = $this->request->variable('field_default_value_year', 0); + return sprintf('%2d-%2d-%4d', $field_data['field_default_value_day'], $field_data['field_default_value_month'], $field_data['field_default_value_year']); + } + } + + return parent::prepare_hidden_fields($step, $key, $action, $field_data); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_dropdown.php b/phpBB/phpbb/profilefields/type/type_dropdown.php new file mode 100644 index 0000000000..17ae89e1b2 --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_dropdown.php @@ -0,0 +1,325 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_dropdown extends type_base +{ + /** + * Profile fields language helper + * @var \phpbb\profilefields\lang_helper + */ + protected $lang_helper; + + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\profilefields\lang_helper $lang_helper Profile fields language helper + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\profilefields\lang_helper $lang_helper, \phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->lang_helper = $lang_helper; + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'dropdown'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $profile_row[0] = array( + 'var_name' => 'field_default_value', + 'field_id' => 1, + 'lang_name' => $field_data['lang_name'], + 'lang_explain' => $field_data['lang_explain'], + 'lang_id' => $default_lang_id, + 'field_default_value' => $field_data['field_default_value'], + 'field_ident' => 'field_default_value', + 'field_type' => $this->get_service_name(), + 'lang_options' => $field_data['lang_options'], + ); + + $profile_row[1] = $profile_row[0]; + $profile_row[1]['var_name'] = 'field_novalue'; + $profile_row[1]['field_ident'] = 'field_novalue'; + $profile_row[1]['field_default_value'] = $field_data['field_novalue']; + + $options = array( + 0 => array('TITLE' => $this->user->lang['DEFAULT_VALUE'], 'FIELD' => $this->process_field_row('preview', $profile_row[0])), + 1 => array('TITLE' => $this->user->lang['NO_VALUE_OPTION'], 'EXPLAIN' => $this->user->lang['NO_VALUE_OPTION_EXPLAIN'], 'FIELD' => $this->process_field_row('preview', $profile_row[1])), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 0, + 'field_minlen' => 0, + 'field_maxlen' => 5, + 'field_validation' => '', + 'field_novalue' => 0, + 'field_default_value' => 0, + ); + } + + /** + * {@inheritDoc} + */ + public function get_default_field_value($field_data) + { + return $field_data['field_default_value']; + } + + /** + * {@inheritDoc} + */ + public function get_profile_field($profile_row) + { + $var_name = 'pf_' . $profile_row['field_ident']; + return $this->request->variable($var_name, (int) $profile_row['field_default_value']); + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + $field_value = (int) $field_value; + + // retrieve option lang data if necessary + if (!$this->lang_helper->is_set($field_data['field_id'], $field_data['lang_id'], 1)) + { + $this->lang_helper->load_option_lang($field_data['lang_id']); + } + + if (!$this->lang_helper->is_set($field_data['field_id'], $field_data['lang_id'], $field_value)) + { + return $this->user->lang('FIELD_INVALID_VALUE', $this->get_field_name($field_data['lang_name'])); + } + + if ($field_value == $field_data['field_novalue'] && $field_data['field_required']) + { + return $this->user->lang('FIELD_REQUIRED', $this->get_field_name($field_data['lang_name'])); + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value($field_value, $field_data) + { + $field_id = $field_data['field_id']; + $lang_id = $field_data['lang_id']; + if (!$this->lang_helper->is_set($field_id, $lang_id)) + { + $this->lang_helper->load_option_lang($lang_id); + } + + if ($field_value == $field_data['field_novalue'] && !$field_data['field_show_novalue']) + { + return null; + } + + $field_value = (int) $field_value; + + // User not having a value assigned + if (!$this->lang_helper->is_set($field_id, $lang_id, $field_value)) + { + if ($field_data['field_show_novalue']) + { + $field_value = $field_data['field_novalue']; + } + else + { + return null; + } + } + + return $this->lang_helper->get($field_id, $lang_id, $field_value); + } + + /** + * {@inheritDoc} + */ + public function get_profile_value_raw($field_value, $field_data) + { + if ($field_value == $field_data['field_novalue'] && !$field_data['field_show_novalue']) + { + return null; + } + + if (!$field_value && $field_data['field_show_novalue']) + { + $field_value = $field_data['field_novalue']; + } + + return $field_value; + } + + /** + * {@inheritDoc} + */ + public function generate_field($profile_row, $preview_options = false) + { + $profile_row['field_ident'] = (isset($profile_row['var_name'])) ? $profile_row['var_name'] : 'pf_' . $profile_row['field_ident']; + $field_ident = $profile_row['field_ident']; + $default_value = $profile_row['field_default_value']; + + $value = ($this->request->is_set($field_ident)) ? $this->request->variable($field_ident, $default_value) : ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $default_value : $this->user->profile_fields[$field_ident]); + + if (!$this->lang_helper->is_set($profile_row['field_id'], $profile_row['lang_id'], 1)) + { + if ($preview_options) + { + $this->lang_helper->load_preview_options($profile_row['field_id'], $profile_row['lang_id'], $preview_options); + } + else + { + $this->lang_helper->load_option_lang($profile_row['lang_id']); + } + } + + $profile_row['field_value'] = (int) $value; + $this->template->assign_block_vars('dropdown', array_change_key_case($profile_row, CASE_UPPER)); + + $options = $this->lang_helper->get($profile_row['field_id'], $profile_row['lang_id']); + foreach ($options as $option_id => $option_value) + { + $this->template->assign_block_vars('dropdown.options', array( + 'OPTION_ID' => $option_id, + 'SELECTED' => ($value == $option_id) ? ' selected="selected"' : '', + 'VALUE' => $option_value, + )); + } + } + + /** + * {@inheritDoc} + */ + public function get_database_column_type() + { + return 'UINT'; + } + + /** + * {@inheritDoc} + */ + public function get_language_options($field_data) + { + $options = array( + 'lang_name' => 'string', + 'lang_options' => 'optionfield', + ); + + if ($field_data['lang_explain']) + { + $options['lang_explain'] = 'text'; + } + + return $options; + } + + /** + * {@inheritDoc} + */ + public function prepare_options_form(&$exclude_options, &$visibility_options) + { + $exclude_options[1][] = 'lang_options'; + + return $this->request->variable('lang_options', '', true); + } + + /** + * {@inheritDoc} + */ + public function validate_options_on_submit($error, $field_data) + { + if (!sizeof($field_data['lang_options'])) + { + $error[] = $this->user->lang['NO_FIELD_ENTRIES']; + } + + return $error; + } + + /** + * {@inheritDoc} + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step) + { + if ($step == 2 && $key == 'field_maxlen') + { + // Get the number of options if this key is 'field_maxlen' + return sizeof(explode("\n", $this->request->variable('lang_options', '', true))); + } + + return parent::get_excluded_options($key, $action, $current_value, $field_data, $step); + } + + /** + * {@inheritDoc} + */ + public function display_options(&$template_vars, &$field_data) + { + // Initialize these array elements if we are creating a new field + if (!sizeof($field_data['lang_options'])) + { + // No options have been defined for the dropdown menu + $field_data['lang_options'] = array(); + } + + $template_vars = array_merge($template_vars, array( + 'S_DROPDOWN' => true, + 'L_LANG_OPTIONS_EXPLAIN' => $this->user->lang['DROPDOWN_ENTRIES_EXPLAIN'], + 'LANG_OPTIONS' => implode("\n", $field_data['lang_options']), + )); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_googleplus.php b/phpBB/phpbb/profilefields/type/type_googleplus.php new file mode 100644 index 0000000000..e6729b1935 --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_googleplus.php @@ -0,0 +1,66 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_googleplus extends type_string +{ + /** + * {@inheritDoc} + */ + public function get_name() + { + return $this->user->lang('FIELD_GOOGLEPLUS'); + } + + /** + * {@inheritDoc} + */ + public function get_service_name() + { + return 'profilefields.type.googleplus'; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 20, + 'field_minlen' => 3, + 'field_maxlen' => 255, + 'field_validation' => '(?:(?!\.{2,})([^<>=+]))+', + 'field_novalue' => '', + 'field_default_value' => '', + ); + } + + /** + * {@inheritDoc} + */ + public function get_profile_contact_value($field_value, $field_data) + { + if (!$field_value && !$field_data['field_show_novalue']) + { + return null; + } + + if (!is_numeric($field_value)) + { + $field_value = '+' . $field_value; + } + + return $field_value; + } +} diff --git a/phpBB/phpbb/profilefields/type/type_int.php b/phpBB/phpbb/profilefields/type/type_int.php new file mode 100644 index 0000000000..9dc0181cb8 --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_int.php @@ -0,0 +1,249 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_int extends type_base +{ + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'int'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $options = array( + 0 => array('TITLE' => $this->user->lang['FIELD_LENGTH'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_length" value="' . $field_data['field_length'] . '" />'), + 1 => array('TITLE' => $this->user->lang['MIN_FIELD_NUMBER'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_minlen" value="' . $field_data['field_minlen'] . '" />'), + 2 => array('TITLE' => $this->user->lang['MAX_FIELD_NUMBER'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_maxlen" value="' . $field_data['field_maxlen'] . '" />'), + 3 => array('TITLE' => $this->user->lang['DEFAULT_VALUE'], 'FIELD' => '<input type="number" name="field_default_value" value="' . $field_data['field_default_value'] . '" />'), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 5, + 'field_minlen' => 0, + 'field_maxlen' => 100, + 'field_validation' => '', + 'field_novalue' => 0, + 'field_default_value' => 0, + ); + } + + /** + * {@inheritDoc} + */ + public function get_default_field_value($field_data) + { + if ($field_data['field_default_value'] === '') + { + // We cannot insert an empty string into an integer column. + return null; + } + + return $field_data['field_default_value']; + } + + /** + * {@inheritDoc} + */ + public function get_profile_field($profile_row) + { + $var_name = 'pf_' . $profile_row['field_ident']; + if ($this->request->is_set($var_name) && $this->request->variable($var_name, '') === '') + { + return null; + } + else + { + return $this->request->variable($var_name, (int) $profile_row['field_default_value']); + } + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + if (trim($field_value) === '' && !$field_data['field_required']) + { + return false; + } + + $field_value = (int) $field_value; + + if ($field_value < $field_data['field_minlen']) + { + return $this->user->lang('FIELD_TOO_SMALL', (int) $field_data['field_minlen'], $this->get_field_name($field_data['lang_name'])); + } + else if ($field_value > $field_data['field_maxlen']) + { + return $this->user->lang('FIELD_TOO_LARGE', (int) $field_data['field_maxlen'], $this->get_field_name($field_data['lang_name'])); + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value($field_value, $field_data) + { + if (($field_value === '' || $field_value === null) && !$field_data['field_show_novalue']) + { + return null; + } + return (int) $field_value; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value_raw($field_value, $field_data) + { + if (($field_value === '' || $field_value === null) && !$field_data['field_show_novalue']) + { + return null; + } + return (int) $field_value; + } + + /** + * {@inheritDoc} + */ + public function generate_field($profile_row, $preview_options = false) + { + $profile_row['field_ident'] = (isset($profile_row['var_name'])) ? $profile_row['var_name'] : 'pf_' . $profile_row['field_ident']; + $field_ident = $profile_row['field_ident']; + $default_value = $profile_row['field_default_value']; + + if ($this->request->is_set($field_ident)) + { + $value = ($this->request->variable($field_ident, '') === '') ? null : $this->request->variable($field_ident, $default_value); + } + else + { + if ($preview_options === false && array_key_exists($field_ident, $this->user->profile_fields) && is_null($this->user->profile_fields[$field_ident])) + { + $value = null; + } + else if (!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) + { + $value = $default_value; + } + else + { + $value = $this->user->profile_fields[$field_ident]; + } + } + + $profile_row['field_value'] = (is_null($value) || $value === '') ? '' : (int) $value; + + $this->template->assign_block_vars('int', array_change_key_case($profile_row, CASE_UPPER)); + } + + /** + * {@inheritDoc} + */ + public function get_field_ident($field_data) + { + return 'pf_' . $field_data['field_ident']; + } + + /** + * {@inheritDoc} + */ + public function get_database_column_type() + { + return 'BINT'; + } + + /** + * {@inheritDoc} + */ + public function get_language_options($field_data) + { + $options = array( + 'lang_name' => 'string', + ); + + if ($field_data['lang_explain']) + { + $options['lang_explain'] = 'text'; + } + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step) + { + if ($step == 2 && $key == 'field_default_value') + { + // Permit an empty string + if ($action == 'create' && $this->request->variable('field_default_value', '') === '') + { + return ''; + } + } + + return parent::get_excluded_options($key, $action, $current_value, $field_data, $step); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_interface.php b/phpBB/phpbb/profilefields/type/type_interface.php new file mode 100644 index 0000000000..93b9e4b893 --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_interface.php @@ -0,0 +1,226 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +interface type_interface +{ + /** + * Get the translated name of the type + * + * @return string Translated name of the field type + */ + public function get_name(); + + /** + * Get the short name of the type, used for error messages and template loops + * + * @return string lowercase version of the fields type + */ + public function get_name_short(); + + /** + * Get the name of service representing the type + * + * @return string lowercase version of the fields type + */ + public function get_service_name(); + + /** + * Get the name of template file for this type + * + * @return string Returns the name of the template file + */ + public function get_template_filename(); + + /** + * Get dropdown options for second step in ACP + * + * @param string $default_lang_id ID of the default language + * @param array $field_data Array with data for this field + * @return array with the acp options + */ + public function get_options($default_lang_id, $field_data); + + /** + * Get default values for the options of this type + * + * @return array with values like default field size and more + */ + public function get_default_option_values(); + + /** + * Get default value for this type + * + * @param array $field_data Array with data for this field + * @return mixed default value for new users when no value is given + */ + public function get_default_field_value($field_data); + + /** + * Get profile field value on submit + * + * @param array $profile_row Array with data for this field + * @return mixed Submitted value of the profile field + */ + public function get_profile_field($profile_row); + + /** + * Validate entered profile field data + * + * @param mixed $field_value Field value to validate + * @param array $field_data Array with requirements of the field + * @return mixed String with the error message + */ + public function validate_profile_field(&$field_value, $field_data); + + /** + * Get Profile Value for display + * + * @param mixed $field_value Field value as stored in the database + * @param array $field_data Array with requirements of the field + * @return mixed Field value to display + */ + public function get_profile_value($field_value, $field_data); + + /** + * Get Profile Value ID for display (the raw, unprocessed user data) + * + * @param mixed $field_value Field value as stored in the database + * @param array $field_data Array with requirements of the field + * @return mixed Field value ID to display + */ + public function get_profile_value_raw($field_value, $field_data); + + /** + * Get Profile Value for display + * + * When displaying a contact field, we don't want to have links already parsed and more + * + * @param mixed $field_value Field value as stored in the database + * @param array $field_data Array with requirements of the field + * @return mixed Field value to display + */ + public function get_profile_contact_value($field_value, $field_data); + + /** + * Generate the input field for display + * + * @param array $profile_row Array with data for this field + * @param mixed $preview_options When previewing we use different data + * @return null + */ + public function generate_field($profile_row, $preview_options = false); + + /** + * Get the ident of the field + * + * Some types are multivalue, we can't give them a field_id + * as we would not know which to pick. + * + * @param array $field_data Array with data for this field + * @return string ident of the field + */ + public function get_field_ident($field_data); + + /** + * Get the localized name of the field + * + * @param string $field_name Unlocalized name of this field + * @return string Localized name of the field + */ + public function get_field_name($field_name); + + /** + * Get the column type for the database + * + * @return string Returns the database column type + */ + public function get_database_column_type(); + + /** + * Get the options we need to display for the language input fields in the ACP + * + * @param array $field_data Array with data for this field + * @return array Returns the language options we need to generate + */ + public function get_language_options($field_data); + + /** + * Get the input for the supplied language options + * + * @param array $field_data Array with data for this field + * @return array Returns the language options we need to generate + */ + public function get_language_options_input($field_data); + + /** + * Allows exclusion of options in single steps of the creation process + * + * @param array $exclude_options Array with options that should be excluded in the steps + * @param array $visibility_options Array with options responsible for the fields visibility + * @return mixed Returns the provided language options + */ + public function prepare_options_form(&$exclude_options, &$visibility_options); + + /** + * Allows exclusion of options in single steps of the creation process + * + * @param array $error Array with error messages + * @param array $field_data Array with data for this field + * @return array Array with error messages + */ + public function validate_options_on_submit($error, $field_data); + + /** + * Allows manipulating the intended variables if needed + * + * @param string $key Name of the option + * @param string $action Currently performed action (create|edit) + * @param mixed $current_value Currently value of the option + * @param array $field_data Array with data for this field + * @param int $step Step on which the option is excluded + * @return mixed Final value of the option + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step); + + /** + * Allows manipulating the intended variables if needed + * + * @param int $step Step on which the option is hidden + * @param string $key Name of the option + * @param string $action Currently performed action (create|edit) + * @param array $field_data Array with data for this field + * @return mixed Final value of the option + */ + public function prepare_hidden_fields($step, $key, $action, &$field_data); + + /** + * Allows assigning of additional template variables + * + * @param array $template_vars Template variables we are going to assign + * @param array $field_data Array with data for this field + * @return null + */ + public function display_options(&$template_vars, &$field_data); + + /** + * Return templated value/field. Possible values for $mode are: + * change == user is able to set/enter profile values; preview == just show the value + * + * @param string $mode Mode for displaying the field (preview|change) + * @param array $profile_row Array with data for this field + * @return null + */ + public function process_field_row($mode, $profile_row); +} diff --git a/phpBB/phpbb/profilefields/type/type_string.php b/phpBB/phpbb/profilefields/type/type_string.php new file mode 100644 index 0000000000..8710c8c603 --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_string.php @@ -0,0 +1,159 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_string extends type_string_common +{ + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'string'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $options = array( + 0 => array('TITLE' => $this->user->lang['FIELD_LENGTH'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_length" value="' . $field_data['field_length'] . '" />'), + 1 => array('TITLE' => $this->user->lang['MIN_FIELD_CHARS'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_minlen" value="' . $field_data['field_minlen'] . '" />'), + 2 => array('TITLE' => $this->user->lang['MAX_FIELD_CHARS'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_maxlen" value="' . $field_data['field_maxlen'] . '" />'), + 3 => array('TITLE' => $this->user->lang['FIELD_VALIDATION'], 'FIELD' => '<select name="field_validation">' . $this->validate_options($field_data) . '</select>'), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 10, + 'field_minlen' => 0, + 'field_maxlen' => 20, + 'field_validation' => '.*', + 'field_novalue' => '', + 'field_default_value' => '', + ); + } + + /** + * {@inheritDoc} + */ + public function get_profile_field($profile_row) + { + $var_name = 'pf_' . $profile_row['field_ident']; + return $this->request->variable($var_name, (string) $profile_row['field_default_value'], true); + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + return $this->validate_string_profile_field('string', $field_value, $field_data); + } + + /** + * {@inheritDoc} + */ + public function generate_field($profile_row, $preview_options = false) + { + $profile_row['field_ident'] = (isset($profile_row['var_name'])) ? $profile_row['var_name'] : 'pf_' . $profile_row['field_ident']; + $field_ident = $profile_row['field_ident']; + $default_value = $profile_row['lang_default_value']; + $profile_row['field_value'] = ($this->request->is_set($field_ident)) ? $this->request->variable($field_ident, $default_value, true) : ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $default_value : $this->user->profile_fields[$field_ident]); + + $this->template->assign_block_vars($this->get_name_short(), array_change_key_case($profile_row, CASE_UPPER)); + } + + /** + * {@inheritDoc} + */ + public function get_database_column_type() + { + return 'VCHAR'; + } + + /** + * {@inheritDoc} + */ + public function get_language_options($field_data) + { + $options = array( + 'lang_name' => 'string', + ); + + if ($field_data['lang_explain']) + { + $options['lang_explain'] = 'text'; + } + + if (strlen($field_data['lang_default_value'])) + { + $options['lang_default_value'] = 'string'; + } + + return $options; + } + + /** + * {@inheritDoc} + */ + public function display_options(&$template_vars, &$field_data) + { + $template_vars = array_merge($template_vars, array( + 'S_STRING' => true, + 'L_DEFAULT_VALUE_EXPLAIN' => $this->user->lang['STRING_DEFAULT_VALUE_EXPLAIN'], + 'LANG_DEFAULT_VALUE' => $field_data['lang_default_value'], + )); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_string_common.php b/phpBB/phpbb/profilefields/type/type_string_common.php new file mode 100644 index 0000000000..f5e1992044 --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_string_common.php @@ -0,0 +1,147 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +abstract class type_string_common extends type_base +{ + protected $validation_options = array( + 'CHARS_ANY' => '.*', + 'NUMBERS_ONLY' => '[0-9]+', + 'ALPHA_ONLY' => '[a-zA-Z0-9]+', + 'ALPHA_UNDERSCORE' => '[\w]+', + 'ALPHA_DOTS' => '[a-zA-Z0-9.]+', + 'ALPHA_SPACERS' => '[\w\x20+\-\[\]]+', + 'ALPHA_PUNCTUATION' => '[a-zA-Z][\w\.,\-]+', + 'LETTER_NUM_ONLY' => '[\p{Lu}\p{Ll}0-9]+', + 'LETTER_NUM_UNDERSCORE' => '[\p{Lu}\p{Ll}0-9_]+', + 'LETTER_NUM_DOTS' => '[\p{Lu}\p{Ll}0-9.]+', + 'LETTER_NUM_SPACERS' => '[\p{Lu}\p{Ll}0-9\x20_+\-\[\]]+', + 'LETTER_NUM_PUNCTUATION' => '[\p{Lu}\p{Ll}][\p{Lu}\p{Ll}0-9.,\-_]+', + ); + + /** + * Return possible validation options + */ + public function validate_options($field_data) + { + $validate_options = ''; + foreach ($this->validation_options as $lang => $value) + { + $selected = ($field_data['field_validation'] == $value) ? ' selected="selected"' : ''; + $validate_options .= '<option value="' . $value . '"' . $selected . '>' . $this->user->lang[$lang] . '</option>'; + } + + return $validate_options; + } + + /** + * {@inheritDoc} + */ + public function get_default_field_value($field_data) + { + return $field_data['lang_default_value']; + } + + /** + * Validate entered profile field data + * + * @param string $field_type Field type (string or text) + * @param mixed $field_value Field value to validate + * @param array $field_data Array with requirements of the field + * @return mixed String with key of the error language string, false otherwise + */ + public function validate_string_profile_field($field_type, &$field_value, $field_data) + { + if (trim($field_value) === '' && !$field_data['field_required']) + { + return false; + } + else if (trim($field_value) === '' && $field_data['field_required']) + { + return $this->user->lang('FIELD_REQUIRED', $this->get_field_name($field_data['lang_name'])); + } + + if ($field_data['field_minlen'] && utf8_strlen($field_value) < $field_data['field_minlen']) + { + return $this->user->lang('FIELD_TOO_SHORT', (int) $field_data['field_minlen'], $this->get_field_name($field_data['lang_name'])); + } + else if ($field_data['field_maxlen'] && utf8_strlen(html_entity_decode($field_value)) > $field_data['field_maxlen']) + { + return $this->user->lang('FIELD_TOO_LONG', (int) $field_data['field_maxlen'], $this->get_field_name($field_data['lang_name'])); + } + + if (!empty($field_data['field_validation']) && $field_data['field_validation'] != '.*') + { + $field_validate = ($field_type != 'text') ? $field_value : bbcode_nl2br($field_value); + if (!preg_match('#^' . str_replace('\\\\', '\\', $field_data['field_validation']) . '$#iu', $field_validate)) + { + $validation = array_search($field_data['field_validation'], $this->validation_options); + if ($validation) + { + return $this->user->lang('FIELD_INVALID_CHARS_' . $validation, $this->get_field_name($field_data['lang_name'])); + } + return $this->user->lang('FIELD_INVALID_CHARS_INVALID', $this->get_field_name($field_data['lang_name'])); + } + } + + return false; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value($field_value, $field_data) + { + if (($field_value === null || $field_value === '') && !$field_data['field_show_novalue']) + { + return null; + } + + $field_value = make_clickable($field_value); + $field_value = censor_text($field_value); + $field_value = bbcode_nl2br($field_value); + return $field_value; + } + + /** + * {@inheritDoc} + */ + public function get_profile_value_raw($field_value, $field_data) + { + if (($field_value === null || $field_value === '') && !$field_data['field_show_novalue']) + { + return null; + } + + return $field_value; + } + + /** + * {@inheritDoc} + */ + public function get_profile_contact_value($field_value, $field_data) + { + return $this->get_profile_value_raw($field_value, $field_data); + } + + /** + * {@inheritDoc} + */ + public function prepare_options_form(&$exclude_options, &$visibility_options) + { + $exclude_options[1][] = 'lang_default_value'; + + return $this->request->variable('lang_options', '', true); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_text.php b/phpBB/phpbb/profilefields/type/type_text.php new file mode 100644 index 0000000000..79ee82351a --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_text.php @@ -0,0 +1,204 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_text extends type_string_common +{ + /** + * Request object + * @var \phpbb\request\request + */ + protected $request; + + /** + * Template object + * @var \phpbb\template\template + */ + protected $template; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Construct + * + * @param \phpbb\request\request $request Request object + * @param \phpbb\template\template $template Template object + * @param \phpbb\user $user User object + */ + public function __construct(\phpbb\request\request $request, \phpbb\template\template $template, \phpbb\user $user) + { + $this->request = $request; + $this->template = $template; + $this->user = $user; + } + + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'text'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $options = array( + 0 => array('TITLE' => $this->user->lang['FIELD_LENGTH'], 'FIELD' => '<input type="number" min="0" max="99999" name="rows" value="' . $field_data['rows'] . '" /> ' . $this->user->lang['ROWS'] . '</dd><dd><input type="number" min="0" max="99999" name="columns" value="' . $field_data['columns'] . '" /> ' . $this->user->lang['COLUMNS'] . ' <input type="hidden" name="field_length" value="' . $field_data['field_length'] . '" />'), + 1 => array('TITLE' => $this->user->lang['MIN_FIELD_CHARS'], 'FIELD' => '<input type="number" min="0" max="9999999999" name="field_minlen" value="' . $field_data['field_minlen'] . '" />'), + 2 => array('TITLE' => $this->user->lang['MAX_FIELD_CHARS'], 'FIELD' => '<input type="number" min="0" max="9999999999" name="field_maxlen" value="' . $field_data['field_maxlen'] . '" />'), + 3 => array('TITLE' => $this->user->lang['FIELD_VALIDATION'], 'FIELD' => '<select name="field_validation">' . $this->validate_options($field_data) . '</select>'), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => '5|80', + 'field_minlen' => 0, + 'field_maxlen' => 1000, + 'field_validation' => '.*', + 'field_novalue' => '', + 'field_default_value' => '', + ); + } + + /** + * {@inheritDoc} + */ + public function get_profile_field($profile_row) + { + $var_name = 'pf_' . $profile_row['field_ident']; + return $this->request->variable($var_name, (string) $profile_row['field_default_value'], true); + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + return $this->validate_string_profile_field('text', $field_value, $field_data); + } + + /** + * {@inheritDoc} + */ + public function generate_field($profile_row, $preview_options = false) + { + $field_length = explode('|', $profile_row['field_length']); + $profile_row['field_rows'] = $field_length[0]; + $profile_row['field_cols'] = $field_length[1]; + $profile_row['field_ident'] = (isset($profile_row['var_name'])) ? $profile_row['var_name'] : 'pf_' . $profile_row['field_ident']; + $field_ident = $profile_row['field_ident']; + $default_value = $profile_row['lang_default_value']; + + $profile_row['field_value'] = ($this->request->is_set($field_ident)) ? $this->request->variable($field_ident, $default_value, true) : ((!isset($this->user->profile_fields[$field_ident]) || $preview_options !== false) ? $default_value : $this->user->profile_fields[$field_ident]); + + $this->template->assign_block_vars('text', array_change_key_case($profile_row, CASE_UPPER)); + } + + /** + * {@inheritDoc} + */ + public function get_database_column_type() + { + return 'MTEXT'; + } + + /** + * {@inheritDoc} + */ + public function get_language_options($field_data) + { + $options = array( + 'lang_name' => 'string', + ); + + if ($field_data['lang_explain']) + { + $options['lang_explain'] = 'text'; + } + + if (strlen($field_data['lang_default_value'])) + { + $options['lang_default_value'] = 'text'; + } + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_excluded_options($key, $action, $current_value, &$field_data, $step) + { + if ($step == 2 && $key == 'field_length') + { + if ($this->request->is_set('rows')) + { + $field_data['rows'] = $this->request->variable('rows', 0); + $field_data['columns'] = $this->request->variable('columns', 0); + $current_value = $field_data['rows'] . '|' . $field_data['columns']; + } + else + { + $row_col = explode('|', $current_value); + $field_data['rows'] = $row_col[0]; + $field_data['columns'] = $row_col[1]; + } + + return $current_value; + } + + return parent::get_excluded_options($key, $action, $current_value, $field_data, $step); + } + + /** + * {@inheritDoc} + */ + public function prepare_hidden_fields($step, $key, $action, &$field_data) + { + if ($key == 'field_length' && $this->request->is_set('rows')) + { + $field_data['rows'] = $this->request->variable('rows', 0); + $field_data['columns'] = $this->request->variable('columns', 0); + return $field_data['rows'] . '|' . $field_data['columns']; + } + + return parent::prepare_hidden_fields($step, $key, $action, $field_data); + } + + /** + * {@inheritDoc} + */ + public function display_options(&$template_vars, &$field_data) + { + $template_vars = array_merge($template_vars, array( + 'S_TEXT' => true, + 'L_DEFAULT_VALUE_EXPLAIN' => $this->user->lang['TEXT_DEFAULT_VALUE_EXPLAIN'], + 'LANG_DEFAULT_VALUE' => $field_data['lang_default_value'], + )); + } +} diff --git a/phpBB/phpbb/profilefields/type/type_url.php b/phpBB/phpbb/profilefields/type/type_url.php new file mode 100644 index 0000000000..375cf5b19a --- /dev/null +++ b/phpBB/phpbb/profilefields/type/type_url.php @@ -0,0 +1,74 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\profilefields\type; + +class type_url extends type_string +{ + /** + * {@inheritDoc} + */ + public function get_name_short() + { + return 'url'; + } + + /** + * {@inheritDoc} + */ + public function get_options($default_lang_id, $field_data) + { + $options = array( + 0 => array('TITLE' => $this->user->lang['FIELD_LENGTH'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_length" value="' . $field_data['field_length'] . '" />'), + 1 => array('TITLE' => $this->user->lang['MIN_FIELD_CHARS'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_minlen" value="' . $field_data['field_minlen'] . '" />'), + 2 => array('TITLE' => $this->user->lang['MAX_FIELD_CHARS'], 'FIELD' => '<input type="number" min="0" max="99999" name="field_maxlen" value="' . $field_data['field_maxlen'] . '" />'), + ); + + return $options; + } + + /** + * {@inheritDoc} + */ + public function get_default_option_values() + { + return array( + 'field_length' => 40, + 'field_minlen' => 0, + 'field_maxlen' => 200, + 'field_validation' => '', + 'field_novalue' => '', + 'field_default_value' => '', + ); + } + + /** + * {@inheritDoc} + */ + public function validate_profile_field(&$field_value, $field_data) + { + $field_value = trim($field_value); + + if ($field_value === '' && !$field_data['field_required']) + { + return false; + } + + if (!preg_match('#^' . get_preg_expression('url') . '$#iu', $field_value)) + { + return $this->user->lang('FIELD_INVALID_URL', $this->get_field_name($field_data['lang_name'])); + } + + return false; + } +} diff --git a/phpBB/phpbb/recursive_dot_prefix_filter_iterator.php b/phpBB/phpbb/recursive_dot_prefix_filter_iterator.php new file mode 100644 index 0000000000..1446551b8b --- /dev/null +++ b/phpBB/phpbb/recursive_dot_prefix_filter_iterator.php @@ -0,0 +1,30 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* Class recursive_dot_prefix_filter_iterator +* +* This filter ignores directories starting with a dot. +* When searching for php classes and template files of extensions +* we don't need to look inside these directories. +*/ +class recursive_dot_prefix_filter_iterator extends \RecursiveFilterIterator +{ + public function accept() + { + $filename = $this->current()->getFilename(); + return $filename[0] !== '.' || !$this->current()->isDir(); + } +} diff --git a/phpBB/phpbb/request/deactivated_super_global.php b/phpBB/phpbb/request/deactivated_super_global.php new file mode 100644 index 0000000000..b6cad59be4 --- /dev/null +++ b/phpBB/phpbb/request/deactivated_super_global.php @@ -0,0 +1,116 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\request; + +/** +* Replacement for a superglobal (like $_GET or $_POST) which calls +* trigger_error on all operations but isset, overloads the [] operator with SPL. +*/ +class deactivated_super_global implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * @var string Holds the name of the superglobal this is replacing. + */ + private $name; + + /** + * @var \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE Super global constant. + */ + private $super_global; + + /** + * @var \phpbb\request\request_interface The request class instance holding the actual request data. + */ + private $request; + + /** + * Constructor generates an error message fitting the super global to be used within the other functions. + * + * @param \phpbb\request\request_interface $request A request class instance holding the real super global data. + * @param string $name Name of the super global this is a replacement for - e.g. '_GET'. + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global The variable's super global constant. + */ + public function __construct(\phpbb\request\request_interface $request, $name, $super_global) + { + $this->request = $request; + $this->name = $name; + $this->super_global = $super_global; + } + + /** + * Calls trigger_error with the file and line number the super global was used in. + */ + private function error() + { + $file = ''; + $line = 0; + + $message = 'Illegal use of $' . $this->name . '. You must use the request class or request_var() to access input data. Found in %s on line %d. This error message was generated by deactivated_super_global.'; + + $backtrace = debug_backtrace(); + if (isset($backtrace[1])) + { + $file = $backtrace[1]['file']; + $line = $backtrace[1]['line']; + } + trigger_error(sprintf($message, $file, $line), E_USER_ERROR); + } + + /** + * Redirects isset to the correct request class call. + * + * @param string $offset The key of the super global being accessed. + * + * @return bool Whether the key on the super global exists. + */ + public function offsetExists($offset) + { + return $this->request->is_set($offset, $this->super_global); + } + + /**#@+ + * Part of the \ArrayAccess implementation, will always result in a FATAL error. + */ + public function offsetGet($offset) + { + $this->error(); + } + + public function offsetSet($offset, $value) + { + $this->error(); + } + + public function offsetUnset($offset) + { + $this->error(); + } + /**#@-*/ + + /** + * Part of the \Countable implementation, will always result in a FATAL error + */ + public function count() + { + $this->error(); + } + + /** + * Part of the Traversable/IteratorAggregate implementation, will always result in a FATAL error + */ + public function getIterator() + { + $this->error(); + } +} diff --git a/phpBB/phpbb/request/request.php b/phpBB/phpbb/request/request.php new file mode 100644 index 0000000000..00ff9064cb --- /dev/null +++ b/phpBB/phpbb/request/request.php @@ -0,0 +1,438 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\request; + +/** +* All application input is accessed through this class. +* +* It provides a method to disable access to input data through super globals. +* This should force MOD authors to read about data validation. +*/ +class request implements \phpbb\request\request_interface +{ + /** + * @var array The names of super global variables that this class should protect if super globals are disabled. + */ + protected $super_globals = array( + \phpbb\request\request_interface::POST => '_POST', + \phpbb\request\request_interface::GET => '_GET', + \phpbb\request\request_interface::REQUEST => '_REQUEST', + \phpbb\request\request_interface::COOKIE => '_COOKIE', + \phpbb\request\request_interface::SERVER => '_SERVER', + \phpbb\request\request_interface::FILES => '_FILES', + ); + + /** + * @var array Stores original contents of $_REQUEST array. + */ + protected $original_request = null; + + /** + * @var + */ + protected $super_globals_disabled = false; + + /** + * @var array An associative array that has the value of super global constants as keys and holds their data as values. + */ + protected $input; + + /** + * @var \phpbb\request\type_cast_helper_interface An instance of a type cast helper providing convenience methods for type conversions. + */ + protected $type_cast_helper; + + /** + * Initialises the request class, that means it stores all input data in {@link $input input} + * and then calls {@link \phpbb\request\deactivated_super_global \phpbb\request\deactivated_super_global} + */ + public function __construct(\phpbb\request\type_cast_helper_interface $type_cast_helper = null, $disable_super_globals = true) + { + if ($type_cast_helper) + { + $this->type_cast_helper = $type_cast_helper; + } + else + { + $this->type_cast_helper = new \phpbb\request\type_cast_helper(); + } + + foreach ($this->super_globals as $const => $super_global) + { + $this->input[$const] = isset($GLOBALS[$super_global]) ? $GLOBALS[$super_global] : array(); + } + + // simulate request_order = GP + $this->original_request = $this->input[\phpbb\request\request_interface::REQUEST]; + $this->input[\phpbb\request\request_interface::REQUEST] = $this->input[\phpbb\request\request_interface::POST] + $this->input[\phpbb\request\request_interface::GET]; + + if ($disable_super_globals) + { + $this->disable_super_globals(); + } + } + + /** + * Getter for $super_globals_disabled + * + * @return bool Whether super globals are disabled or not. + */ + public function super_globals_disabled() + { + return $this->super_globals_disabled; + } + + /** + * Disables access of super globals specified in $super_globals. + * This is achieved by overwriting the super globals with instances of {@link \phpbb\request\deactivated_super_global \phpbb\request\deactivated_super_global} + */ + public function disable_super_globals() + { + if (!$this->super_globals_disabled) + { + foreach ($this->super_globals as $const => $super_global) + { + unset($GLOBALS[$super_global]); + $GLOBALS[$super_global] = new \phpbb\request\deactivated_super_global($this, $super_global, $const); + } + + $this->super_globals_disabled = true; + } + } + + /** + * Enables access of super globals specified in $super_globals if they were disabled by {@link disable_super_globals disable_super_globals}. + * This is achieved by making the super globals point to the data stored within this class in {@link $input input}. + */ + public function enable_super_globals() + { + if ($this->super_globals_disabled) + { + foreach ($this->super_globals as $const => $super_global) + { + $GLOBALS[$super_global] = $this->input[$const]; + } + + $GLOBALS['_REQUEST'] = $this->original_request; + + $this->super_globals_disabled = false; + } + } + + /** + * This function allows overwriting or setting a value in one of the super global arrays. + * + * Changes which are performed on the super globals directly will not have any effect on the results of + * other methods this class provides. Using this function should be avoided if possible! It will + * consume twice the the amount of memory of the value + * + * @param string $var_name The name of the variable that shall be overwritten + * @param mixed $value The value which the variable shall contain. + * If this is null the variable will be unset. + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies which super global shall be changed + */ + public function overwrite($var_name, $value, $super_global = \phpbb\request\request_interface::REQUEST) + { + if (!isset($this->super_globals[$super_global])) + { + return; + } + + $this->type_cast_helper->add_magic_quotes($value); + + // setting to null means unsetting + if ($value === null) + { + unset($this->input[$super_global][$var_name]); + if (!$this->super_globals_disabled()) + { + unset($GLOBALS[$this->super_globals[$super_global]][$var_name]); + } + } + else + { + $this->input[$super_global][$var_name] = $value; + if (!$this->super_globals_disabled()) + { + $GLOBALS[$this->super_globals[$super_global]][$var_name] = $value; + } + } + } + + /** + * Central type safe input handling function. + * All variables in GET or POST requests should be retrieved through this function to maximise security. + * + * @param string|array $var_name The form variable's name from which data shall be retrieved. + * If the value is an array this may be an array of indizes which will give + * direct access to a value at any depth. E.g. if the value of "var" is array(1 => "a") + * then specifying array("var", 1) as the name will return "a". + * @param mixed $default A default value that is returned if the variable was not set. + * This function will always return a value of the same type as the default. + * @param bool $multibyte If $default is a string this paramater has to be true if the variable may contain any UTF-8 characters + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies which super global should be used + * + * @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the + * the same as that of $default. If the variable is not set $default is returned. + */ + public function variable($var_name, $default, $multibyte = false, $super_global = \phpbb\request\request_interface::REQUEST) + { + return $this->_variable($var_name, $default, $multibyte, $super_global, true); + } + + /** + * Get a variable, but without trimming strings. + * Same functionality as variable(), except does not run trim() on strings. + * This method should be used when handling passwords. + * + * @param string|array $var_name The form variable's name from which data shall be retrieved. + * If the value is an array this may be an array of indizes which will give + * direct access to a value at any depth. E.g. if the value of "var" is array(1 => "a") + * then specifying array("var", 1) as the name will return "a". + * @param mixed $default A default value that is returned if the variable was not set. + * This function will always return a value of the same type as the default. + * @param bool $multibyte If $default is a string this paramater has to be true if the variable may contain any UTF-8 characters + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies which super global should be used + * + * @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the + * the same as that of $default. If the variable is not set $default is returned. + */ + public function untrimmed_variable($var_name, $default, $multibyte = false, $super_global = \phpbb\request\request_interface::REQUEST) + { + return $this->_variable($var_name, $default, $multibyte, $super_global, false); + } + + /** + * Shortcut method to retrieve SERVER variables. + * + * Also fall back to getenv(), some CGI setups may need it (probably not, but + * whatever). + * + * @param string|array $var_name See \phpbb\request\request_interface::variable + * @param mixed $Default See \phpbb\request\request_interface::variable + * + * @return mixed The server variable value. + */ + public function server($var_name, $default = '') + { + $multibyte = true; + + if ($this->is_set($var_name, \phpbb\request\request_interface::SERVER)) + { + return $this->variable($var_name, $default, $multibyte, \phpbb\request\request_interface::SERVER); + } + else + { + $var = getenv($var_name); + $this->type_cast_helper->recursive_set_var($var, $default, $multibyte); + return $var; + } + } + + /** + * Shortcut method to retrieve the value of client HTTP headers. + * + * @param string|array $header_name The name of the header to retrieve. + * @param mixed $default See \phpbb\request\request_interface::variable + * + * @return mixed The header value. + */ + public function header($header_name, $default = '') + { + $var_name = 'HTTP_' . str_replace('-', '_', strtoupper($header_name)); + return $this->server($var_name, $default); + } + + /** + * Shortcut method to retrieve $_FILES variables + * + * @param string $form_name The name of the file input form element + * + * @return array The uploaded file's information or an empty array if the + * variable does not exist in _FILES. + */ + public function file($form_name) + { + return $this->variable($form_name, array('name' => 'none'), true, \phpbb\request\request_interface::FILES); + } + + /** + * Checks whether a certain variable was sent via POST. + * To make sure that a request was sent using POST you should call this function + * on at least one variable. + * + * @param string $name The name of the form variable which should have a + * _p suffix to indicate the check in the code that creates the form too. + * + * @return bool True if the variable was set in a POST request, false otherwise. + */ + public function is_set_post($name) + { + return $this->is_set($name, \phpbb\request\request_interface::POST); + } + + /** + * Checks whether a certain variable is set in one of the super global + * arrays. + * + * @param string $var Name of the variable + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies the super global which shall be checked + * + * @return bool True if the variable was sent as input + */ + public function is_set($var, $super_global = \phpbb\request\request_interface::REQUEST) + { + return isset($this->input[$super_global][$var]); + } + + /** + * Checks whether the current request is an AJAX request (XMLHttpRequest) + * + * @return bool True if the current request is an ajax request + */ + public function is_ajax() + { + return $this->header('X-Requested-With') == 'XMLHttpRequest'; + } + + /** + * Checks if the current request is happening over HTTPS. + * + * @return bool True if the request is secure. + */ + public function is_secure() + { + $https = $this->server('HTTPS'); + $https = $this->server('HTTP_X_FORWARDED_PROTO') === 'https' ? 'on' : $https; + return !empty($https) && $https !== 'off'; + } + + /** + * Returns all variable names for a given super global + * + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * The super global from which names shall be taken + * + * @return array All variable names that are set for the super global. + * Pay attention when using these, they are unsanitised! + */ + public function variable_names($super_global = \phpbb\request\request_interface::REQUEST) + { + if (!isset($this->input[$super_global])) + { + return array(); + } + + return array_keys($this->input[$super_global]); + } + + /** + * Helper function used by variable() and untrimmed_variable(). + * + * @param string|array $var_name The form variable's name from which data shall be retrieved. + * If the value is an array this may be an array of indizes which will give + * direct access to a value at any depth. E.g. if the value of "var" is array(1 => "a") + * then specifying array("var", 1) as the name will return "a". + * @param mixed $default A default value that is returned if the variable was not set. + * This function will always return a value of the same type as the default. + * @param bool $multibyte If $default is a string this paramater has to be true if the variable may contain any UTF-8 characters + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies which super global should be used + * @param bool $trim Indicates whether trim() should be applied to string values. + * + * @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the + * the same as that of $default. If the variable is not set $default is returned. + */ + protected function _variable($var_name, $default, $multibyte = false, $super_global = \phpbb\request\request_interface::REQUEST, $trim = true) + { + $path = false; + + // deep direct access to multi dimensional arrays + if (is_array($var_name)) + { + $path = $var_name; + // make sure at least the variable name is specified + if (empty($path)) + { + return (is_array($default)) ? array() : $default; + } + // the variable name is the first element on the path + $var_name = array_shift($path); + } + + if (!isset($this->input[$super_global][$var_name])) + { + return (is_array($default)) ? array() : $default; + } + $var = $this->input[$super_global][$var_name]; + + if ($path) + { + // walk through the array structure and find the element we are looking for + foreach ($path as $key) + { + if (is_array($var) && isset($var[$key])) + { + $var = $var[$key]; + } + else + { + return (is_array($default)) ? array() : $default; + } + } + } + + $this->type_cast_helper->recursive_set_var($var, $default, $multibyte, $trim); + + return $var; + } + + /** + * {@inheritdoc} + */ + public function get_super_global($super_global = \phpbb\request\request_interface::REQUEST) + { + return $this->input[$super_global]; + } + + /** + * {@inheritdoc} + */ + public function escape($var, $multibyte) + { + if (is_array($var)) + { + $result = array(); + foreach ($var as $key => $value) + { + $this->type_cast_helper->set_var($key, $key, gettype($key), $multibyte); + $result[$key] = $this->escape($value, $multibyte); + } + $var = $result; + } + else + { + $this->type_cast_helper->set_var($var, $var, 'string', $multibyte); + } + + return $var; + } +} diff --git a/phpBB/phpbb/request/request_interface.php b/phpBB/phpbb/request/request_interface.php new file mode 100644 index 0000000000..47b3b3a4ed --- /dev/null +++ b/phpBB/phpbb/request/request_interface.php @@ -0,0 +1,155 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\request; + +/** +* An interface through which all application input can be accessed. +*/ +interface request_interface +{ + /**#@+ + * Constant identifying the super global with the same name. + */ + const POST = 0; + const GET = 1; + const REQUEST = 2; + const COOKIE = 3; + const SERVER = 4; + const FILES = 5; + /**#@-*/ + + /** + * This function allows overwriting or setting a value in one of the super global arrays. + * + * Changes which are performed on the super globals directly will not have any effect on the results of + * other methods this class provides. Using this function should be avoided if possible! It will + * consume twice the the amount of memory of the value + * + * @param string $var_name The name of the variable that shall be overwritten + * @param mixed $value The value which the variable shall contain. + * If this is null the variable will be unset. + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies which super global shall be changed + */ + public function overwrite($var_name, $value, $super_global = \phpbb\request\request_interface::REQUEST); + + /** + * Central type safe input handling function. + * All variables in GET or POST requests should be retrieved through this function to maximise security. + * + * @param string|array $var_name The form variable's name from which data shall be retrieved. + * If the value is an array this may be an array of indizes which will give + * direct access to a value at any depth. E.g. if the value of "var" is array(1 => "a") + * then specifying array("var", 1) as the name will return "a". + * @param mixed $default A default value that is returned if the variable was not set. + * This function will always return a value of the same type as the default. + * @param bool $multibyte If $default is a string this paramater has to be true if the variable may contain any UTF-8 characters + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies which super global should be used + * + * @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the + * the same as that of $default. If the variable is not set $default is returned. + */ + public function variable($var_name, $default, $multibyte = false, $super_global = \phpbb\request\request_interface::REQUEST); + + /** + * Shortcut method to retrieve SERVER variables. + * + * @param string|array $var_name See \phpbb\request\request_interface::variable + * @param mixed $default See \phpbb\request\request_interface::variable + * + * @return mixed The server variable value. + */ + public function server($var_name, $default = ''); + + /** + * Shortcut method to retrieve the value of client HTTP headers. + * + * @param string|array $header_name The name of the header to retrieve. + * @param mixed $default See \phpbb\request\request_interface::variable + * + * @return mixed The header value. + */ + public function header($var_name, $default = ''); + + /** + * Checks whether a certain variable was sent via POST. + * To make sure that a request was sent using POST you should call this function + * on at least one variable. + * + * @param string $name The name of the form variable which should have a + * _p suffix to indicate the check in the code that creates the form too. + * + * @return bool True if the variable was set in a POST request, false otherwise. + */ + public function is_set_post($name); + + /** + * Checks whether a certain variable is set in one of the super global + * arrays. + * + * @param string $var Name of the variable + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * Specifies the super global which shall be checked + * + * @return bool True if the variable was sent as input + */ + public function is_set($var, $super_global = \phpbb\request\request_interface::REQUEST); + + /** + * Checks whether the current request is an AJAX request (XMLHttpRequest) + * + * @return bool True if the current request is an ajax request + */ + public function is_ajax(); + + /** + * Checks if the current request is happening over HTTPS. + * + * @return bool True if the request is secure. + */ + public function is_secure(); + + /** + * Returns all variable names for a given super global + * + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * The super global from which names shall be taken + * + * @return array All variable names that are set for the super global. + * Pay attention when using these, they are unsanitised! + */ + public function variable_names($super_global = \phpbb\request\request_interface::REQUEST); + + /** + * Returns the original array of the requested super global + * + * @param \phpbb\request\request_interface::POST|GET|REQUEST|COOKIE $super_global + * The super global which will be returned + * + * @return array The original array of the requested super global. + */ + public function get_super_global($super_global = \phpbb\request\request_interface::REQUEST); + + /** + * Escape a string variable. + * + * @param mixed $value The contents to fill with + * @param bool $multibyte Indicates whether string values may contain UTF-8 characters. + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks. + * @return string|array + */ + public function escape($value, $multibyte); +} diff --git a/phpBB/phpbb/request/type_cast_helper.php b/phpBB/phpbb/request/type_cast_helper.php new file mode 100644 index 0000000000..bc654e6182 --- /dev/null +++ b/phpBB/phpbb/request/type_cast_helper.php @@ -0,0 +1,190 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\request; + +/** +* A helper class that provides convenience methods for type casting. +*/ +class type_cast_helper implements \phpbb\request\type_cast_helper_interface +{ + + /** + * @var string Whether slashes need to be stripped from input + */ + protected $strip; + + /** + * Initialises the type cast helper class. + * All it does is find out whether magic quotes are turned on. + */ + public function __construct() + { + if (version_compare(PHP_VERSION, '5.4.0-dev', '>=')) + { + $this->strip = false; + } + else + { + $this->strip = (@get_magic_quotes_gpc()) ? true : false; + } + } + + /** + * Recursively applies addslashes to a variable. + * + * @param mixed &$var Variable passed by reference to which slashes will be added. + */ + public function addslashes_recursively(&$var) + { + if (is_string($var)) + { + $var = addslashes($var); + } + else if (is_array($var)) + { + $var_copy = $var; + $var = array(); + foreach ($var_copy as $key => $value) + { + if (is_string($key)) + { + $key = addslashes($key); + } + $var[$key] = $value; + + $this->addslashes_recursively($var[$key]); + } + } + } + + /** + * Recursively applies addslashes to a variable if magic quotes are turned on. + * + * @param mixed &$var Variable passed by reference to which slashes will be added. + */ + public function add_magic_quotes(&$var) + { + if ($this->strip) + { + $this->addslashes_recursively($var); + } + } + + /** + * Set variable $result to a particular type. + * + * @param mixed &$result The variable to fill + * @param mixed $var The contents to fill with + * @param mixed $type The variable type. Will be used with {@link settype()} + * @param bool $multibyte Indicates whether string values may contain UTF-8 characters. + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks. + * @param bool $trim Indicates whether trim() should be applied to string values. + * Default is true. + */ + public function set_var(&$result, $var, $type, $multibyte = false, $trim = true) + { + settype($var, $type); + $result = $var; + + if ($type == 'string') + { + $result = str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result); + + if ($trim) + { + $result = trim($result); + } + + $result = htmlspecialchars($result, ENT_COMPAT, 'UTF-8'); + + if ($multibyte) + { + $result = utf8_normalize_nfc($result); + } + + if (!empty($result)) + { + // Make sure multibyte characters are wellformed + if ($multibyte) + { + if (!preg_match('/^./u', $result)) + { + $result = ''; + } + } + else + { + // no multibyte, allow only ASCII (0-127) + $result = preg_replace('/[\x80-\xFF]/', '?', $result); + } + } + + $result = ($this->strip) ? stripslashes($result) : $result; + } + } + + /** + * Recursively sets a variable to a given type using {@link set_var set_var} + * + * @param string $var The value which shall be sanitised (passed by reference). + * @param mixed $default Specifies the type $var shall have. + * If it is an array and $var is not one, then an empty array is returned. + * Otherwise var is cast to the same type, and if $default is an array all + * keys and values are cast recursively using this function too. + * @param bool $multibyte Indicates whether string keys and values may contain UTF-8 characters. + * Default is false, causing all bytes outside the ASCII range (0-127) to + * be replaced with question marks. + * @param bool $trim Indicates whether trim() should be applied to string values. + * Default is true. + */ + public function recursive_set_var(&$var, $default, $multibyte, $trim = true) + { + if (is_array($var) !== is_array($default)) + { + $var = (is_array($default)) ? array() : $default; + return; + } + + if (!is_array($default)) + { + $type = gettype($default); + $this->set_var($var, $var, $type, $multibyte, $trim); + } + else + { + // make sure there is at least one key/value pair to use get the + // types from + if (empty($default)) + { + $var = array(); + return; + } + + list($default_key, $default_value) = each($default); + $value_type = gettype($default_value); + $key_type = gettype($default_key); + + $_var = $var; + $var = array(); + + foreach ($_var as $k => $v) + { + $this->set_var($k, $k, $key_type, $multibyte); + + $this->recursive_set_var($v, $default_value, $multibyte, $trim); + $var[$k] = $v; + } + } + } +} diff --git a/phpBB/phpbb/request/type_cast_helper_interface.php b/phpBB/phpbb/request/type_cast_helper_interface.php new file mode 100644 index 0000000000..2cb28d021f --- /dev/null +++ b/phpBB/phpbb/request/type_cast_helper_interface.php @@ -0,0 +1,59 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\request; + +/** +* An interface for type cast operations. +*/ +interface type_cast_helper_interface +{ + /** + * Recursively applies addslashes to a variable. + * + * @param mixed &$var Variable passed by reference to which slashes will be added. + */ + public function addslashes_recursively(&$var); + + /** + * Recursively applies addslashes to a variable if magic quotes are turned on. + * + * @param mixed &$var Variable passed by reference to which slashes will be added. + */ + public function add_magic_quotes(&$var); + + /** + * Set variable $result to a particular type. + * + * @param mixed &$result The variable to fill + * @param mixed $var The contents to fill with + * @param mixed $type The variable type. Will be used with {@link settype()} + * @param bool $multibyte Indicates whether string values may contain UTF-8 characters. + * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks. + */ + public function set_var(&$result, $var, $type, $multibyte = false); + + /** + * Recursively sets a variable to a given type using {@link set_var set_var}. + * + * @param string $var The value which shall be sanitised (passed by reference). + * @param mixed $default Specifies the type $var shall have. + * If it is an array and $var is not one, then an empty array is returned. + * Otherwise var is cast to the same type, and if $default is an array all + * keys and values are cast recursively using this function too. + * @param bool $multibyte Indicates whether string keys and values may contain UTF-8 characters. + * Default is false, causing all bytes outside the ASCII range (0-127) to + * be replaced with question marks. + */ + public function recursive_set_var(&$var, $default, $multibyte); +} diff --git a/phpBB/phpbb/search/base.php b/phpBB/phpbb/search/base.php new file mode 100644 index 0000000000..d9313dddab --- /dev/null +++ b/phpBB/phpbb/search/base.php @@ -0,0 +1,292 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search; + +/** +* @ignore +*/ +define('SEARCH_RESULT_NOT_IN_CACHE', 0); +define('SEARCH_RESULT_IN_CACHE', 1); +define('SEARCH_RESULT_INCOMPLETE', 2); + +/** +* optional base class for search plugins providing simple caching based on ACM +* and functions to retrieve ignore_words and synonyms +*/ +class base +{ + var $ignore_words = array(); + var $match_synonym = array(); + var $replace_synonym = array(); + + function search_backend(&$error) + { + // This class cannot be used as a search plugin + $error = true; + } + + /** + * Retrieves cached search results + * + * @param string $search_key an md5 string generated from all the passed search options to identify the results + * @param int &$result_count will contain the number of all results for the search (not only for the current page) + * @param array &$id_ary is filled with the ids belonging to the requested page that are stored in the cache + * @param int &$start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @param string $sort_dir is either a or d representing ASC and DESC + * + * @return int SEARCH_RESULT_NOT_IN_CACHE or SEARCH_RESULT_IN_CACHE or SEARCH_RESULT_INCOMPLETE + */ + function obtain_ids($search_key, &$result_count, &$id_ary, &$start, $per_page, $sort_dir) + { + global $cache; + + if (!($stored_ids = $cache->get('_search_results_' . $search_key))) + { + // no search results cached for this search_key + return SEARCH_RESULT_NOT_IN_CACHE; + } + else + { + $result_count = $stored_ids[-1]; + $reverse_ids = ($stored_ids[-2] != $sort_dir) ? true : false; + $complete = true; + + // Change start parameter in case out of bounds + if ($result_count) + { + if ($start < 0) + { + $start = 0; + } + else if ($start >= $result_count) + { + $start = floor(($result_count - 1) / $per_page) * $per_page; + } + } + + // change the start to the actual end of the current request if the sort direction differs + // from the dirction in the cache and reverse the ids later + if ($reverse_ids) + { + $start = $result_count - $start - $per_page; + + // the user requested a page past the last index + if ($start < 0) + { + return SEARCH_RESULT_NOT_IN_CACHE; + } + } + + for ($i = $start, $n = $start + $per_page; ($i < $n) && ($i < $result_count); $i++) + { + if (!isset($stored_ids[$i])) + { + $complete = false; + } + else + { + $id_ary[] = $stored_ids[$i]; + } + } + unset($stored_ids); + + if ($reverse_ids) + { + $id_ary = array_reverse($id_ary); + } + + if (!$complete) + { + return SEARCH_RESULT_INCOMPLETE; + } + return SEARCH_RESULT_IN_CACHE; + } + } + + /** + * Caches post/topic ids + * + * @param string $search_key an md5 string generated from all the passed search options to identify the results + * @param string $keywords contains the keywords as entered by the user + * @param array $author_ary an array of author ids, if the author should be ignored during the search the array is empty + * @param int $result_count contains the number of all results for the search (not only for the current page) + * @param array &$id_ary contains a list of post or topic ids that shall be cached, the first element + * must have the absolute index $start in the result set. + * @param int $start indicates the first index of the page + * @param string $sort_dir is either a or d representing ASC and DESC + * + * @return null + */ + function save_ids($search_key, $keywords, $author_ary, $result_count, &$id_ary, $start, $sort_dir) + { + global $cache, $config, $db, $user; + + $length = min(sizeof($id_ary), $config['search_block_size']); + + // nothing to cache so exit + if (!$length) + { + return; + } + + $store_ids = array_slice($id_ary, 0, $length); + + // create a new resultset if there is none for this search_key yet + // or add the ids to the existing resultset + if (!($store = $cache->get('_search_results_' . $search_key))) + { + // add the current keywords to the recent searches in the cache which are listed on the search page + if (!empty($keywords) || sizeof($author_ary)) + { + $sql = 'SELECT search_time + FROM ' . SEARCH_RESULTS_TABLE . ' + WHERE search_key = \'' . $db->sql_escape($search_key) . '\''; + $result = $db->sql_query($sql); + + if (!$db->sql_fetchrow($result)) + { + $sql_ary = array( + 'search_key' => $search_key, + 'search_time' => time(), + 'search_keywords' => $keywords, + 'search_authors' => ' ' . implode(' ', $author_ary) . ' ' + ); + + $sql = 'INSERT INTO ' . SEARCH_RESULTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary); + $db->sql_query($sql); + } + $db->sql_freeresult($result); + } + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_last_search = ' . time() . ' + WHERE user_id = ' . $user->data['user_id']; + $db->sql_query($sql); + + $store = array(-1 => $result_count, -2 => $sort_dir); + $id_range = range($start, $start + $length - 1); + } + else + { + // we use one set of results for both sort directions so we have to calculate the indizes + // for the reversed array and we also have to reverse the ids themselves + if ($store[-2] != $sort_dir) + { + $store_ids = array_reverse($store_ids); + $id_range = range($store[-1] - $start - $length, $store[-1] - $start - 1); + } + else + { + $id_range = range($start, $start + $length - 1); + } + } + + $store_ids = array_combine($id_range, $store_ids); + + // append the ids + if (is_array($store_ids)) + { + $store += $store_ids; + + // if the cache is too big + if (sizeof($store) - 2 > 20 * $config['search_block_size']) + { + // remove everything in front of two blocks in front of the current start index + for ($i = 0, $n = $id_range[0] - 2 * $config['search_block_size']; $i < $n; $i++) + { + if (isset($store[$i])) + { + unset($store[$i]); + } + } + + // remove everything after two blocks after the current stop index + end($id_range); + for ($i = $store[-1] - 1, $n = current($id_range) + 2 * $config['search_block_size']; $i > $n; $i--) + { + if (isset($store[$i])) + { + unset($store[$i]); + } + } + } + $cache->put('_search_results_' . $search_key, $store, $config['search_store_results']); + + $sql = 'UPDATE ' . SEARCH_RESULTS_TABLE . ' + SET search_time = ' . time() . ' + WHERE search_key = \'' . $db->sql_escape($search_key) . '\''; + $db->sql_query($sql); + } + + unset($store); + unset($store_ids); + unset($id_range); + } + + /** + * Removes old entries from the search results table and removes searches with keywords that contain a word in $words. + */ + function destroy_cache($words, $authors = false) + { + global $db, $cache, $config; + + // clear all searches that searched for the specified words + if (sizeof($words)) + { + $sql_where = ''; + foreach ($words as $word) + { + $sql_where .= " OR search_keywords " . $db->sql_like_expression($db->get_any_char() . $word . $db->get_any_char()); + } + + $sql = 'SELECT search_key + FROM ' . SEARCH_RESULTS_TABLE . " + WHERE search_keywords LIKE '%*%' $sql_where"; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $cache->destroy('_search_results_' . $row['search_key']); + } + $db->sql_freeresult($result); + } + + // clear all searches that searched for the specified authors + if (is_array($authors) && sizeof($authors)) + { + $sql_where = ''; + foreach ($authors as $author) + { + $sql_where .= (($sql_where) ? ' OR ' : '') . 'search_authors ' . $db->sql_like_expression($db->get_any_char() . ' ' . (int) $author . ' ' . $db->get_any_char()); + } + + $sql = 'SELECT search_key + FROM ' . SEARCH_RESULTS_TABLE . " + WHERE $sql_where"; + $result = $db->sql_query($sql); + + while ($row = $db->sql_fetchrow($result)) + { + $cache->destroy('_search_results_' . $row['search_key']); + } + $db->sql_freeresult($result); + } + + $sql = 'DELETE + FROM ' . SEARCH_RESULTS_TABLE . ' + WHERE search_time < ' . (time() - $config['search_store_results']); + $db->sql_query($sql); + } +} diff --git a/phpBB/phpbb/search/fulltext_mysql.php b/phpBB/phpbb/search/fulltext_mysql.php new file mode 100644 index 0000000000..64a63e83e0 --- /dev/null +++ b/phpBB/phpbb/search/fulltext_mysql.php @@ -0,0 +1,1141 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search; + +/** +* Fulltext search for MySQL +*/ +class fulltext_mysql extends \phpbb\search\base +{ + /** + * Associative array holding index stats + * @var array + */ + protected $stats = array(); + + /** + * Holds the words entered by user, obtained by splitting the entered query on whitespace + * @var array + */ + protected $split_words = array(); + + /** + * Config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Database connection + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * phpBB event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $phpbb_dispatcher; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Associative array stores the min and max word length to be searched + * @var array + */ + protected $word_length = array(); + + /** + * Contains tidied search query. + * Operators are prefixed in search query and common words excluded + * @var string + */ + protected $search_query; + + /** + * Contains common words. + * Common words are words with length less/more than min/max length + * @var array + */ + protected $common_words = array(); + + /** + * Constructor + * Creates a new \phpbb\search\fulltext_mysql, which is used as a search backend + * + * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $phpEx PHP file extension + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\config\config $config Config object + * @param \phpbb\db\driver\driver_interface Database object + * @param \phpbb\user $user User object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object + */ + public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher) + { + $this->config = $config; + $this->db = $db; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->user = $user; + + $this->word_length = array('min' => $this->config['fulltext_mysql_min_word_len'], 'max' => $this->config['fulltext_mysql_max_word_len']); + + /** + * Load the UTF tools + */ + if (!function_exists('utf8_strlen')) + { + include($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx); + } + + $error = false; + } + + /** + * Returns the name of this search backend to be displayed to administrators + * + * @return string Name + */ + public function get_name() + { + return 'MySQL Fulltext'; + } + + /** + * Returns the search_query + * + * @return string search query + */ + public function get_search_query() + { + return $this->search_query; + } + + /** + * Returns the common_words array + * + * @return array common words that are ignored by search backend + */ + public function get_common_words() + { + return $this->common_words; + } + + /** + * Returns the word_length array + * + * @return array min and max word length for searching + */ + public function get_word_length() + { + return $this->word_length; + } + + /** + * Checks for correct MySQL version and stores min/max word length in the config + * + * @return string|bool Language key of the error/incompatiblity occurred + */ + public function init() + { + if ($this->db->get_sql_layer() != 'mysql4' && $this->db->get_sql_layer() != 'mysqli') + { + return $this->user->lang['FULLTEXT_MYSQL_INCOMPATIBLE_DATABASE']; + } + + $result = $this->db->sql_query('SHOW TABLE STATUS LIKE \'' . POSTS_TABLE . '\''); + $info = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $engine = ''; + if (isset($info['Engine'])) + { + $engine = $info['Engine']; + } + else if (isset($info['Type'])) + { + $engine = $info['Type']; + } + + $fulltext_supported = + $engine === 'MyISAM' || + // FULLTEXT is supported on InnoDB since MySQL 5.6.4 according to + // http://dev.mysql.com/doc/refman/5.6/en/innodb-storage-engine.html + // We also require https://bugs.mysql.com/bug.php?id=67004 to be + // fixed for proper overall operation. Hence we require 5.6.8. + $engine === 'InnoDB' && + phpbb_version_compare($this->db->sql_server_info(true), '5.6.8', '>='); + + if (!$fulltext_supported) + { + return $this->user->lang['FULLTEXT_MYSQL_NOT_SUPPORTED']; + } + + $sql = 'SHOW VARIABLES + LIKE \'ft\_%\''; + $result = $this->db->sql_query($sql); + + $mysql_info = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $mysql_info[$row['Variable_name']] = $row['Value']; + } + $this->db->sql_freeresult($result); + + set_config('fulltext_mysql_max_word_len', $mysql_info['ft_max_word_len']); + set_config('fulltext_mysql_min_word_len', $mysql_info['ft_min_word_len']); + + return false; + } + + /** + * Splits keywords entered by a user into an array of words stored in $this->split_words + * Stores the tidied search query in $this->search_query + * + * @param string &$keywords Contains the keyword as entered by the user + * @param string $terms is either 'all' or 'any' + * @return bool false if no valid keywords were found and otherwise true + */ + public function split_keywords(&$keywords, $terms) + { + if ($terms == 'all') + { + $match = array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#(^|\s)\+#', '#(^|\s)-#', '#(^|\s)\|#'); + $replace = array(' +', ' |', ' -', ' +', ' -', ' |'); + + $keywords = preg_replace($match, $replace, $keywords); + } + + // Filter out as above + $split_keywords = preg_replace("#[\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords))); + + // Split words + $split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords))); + $matches = array(); + preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches); + $this->split_words = $matches[1]; + + // We limit the number of allowed keywords to minimize load on the database + if ($this->config['max_num_search_keywords'] && sizeof($this->split_words) > $this->config['max_num_search_keywords']) + { + trigger_error($this->user->lang('MAX_NUM_SEARCH_KEYWORDS_REFINE', (int) $this->config['max_num_search_keywords'], sizeof($this->split_words))); + } + + // to allow phrase search, we need to concatenate quoted words + $tmp_split_words = array(); + $phrase = ''; + foreach ($this->split_words as $word) + { + if ($phrase) + { + $phrase .= ' ' . $word; + if (strpos($word, '"') !== false && substr_count($word, '"') % 2 == 1) + { + $tmp_split_words[] = $phrase; + $phrase = ''; + } + } + else if (strpos($word, '"') !== false && substr_count($word, '"') % 2 == 1) + { + $phrase = $word; + } + else + { + $tmp_split_words[] = $word; + } + } + if ($phrase) + { + $tmp_split_words[] = $phrase; + } + + $this->split_words = $tmp_split_words; + + unset($tmp_split_words); + unset($phrase); + + foreach ($this->split_words as $i => $word) + { + // Check for not allowed search queries for InnoDB. + // We assume similar restrictions for MyISAM, which is usually even + // slower but not as restrictive as InnoDB. + // InnoDB full-text search does not support the use of a leading + // plus sign with wildcard ('+*'), a plus and minus sign + // combination ('+-'), or leading a plus and minus sign combination. + // InnoDB full-text search only supports leading plus or minus signs. + // For example, InnoDB supports '+apple' but does not support 'apple+'. + // Specifying a trailing plus or minus sign causes InnoDB to report + // a syntax error. InnoDB full-text search does not support the use + // of multiple operators on a single search word, as in this example: + // '++apple'. Use of multiple operators on a single search word + // returns a syntax error to standard out. + // Also, ensure that the wildcard character is only used at the + // end of the line as it's intended by MySQL. + if (preg_match('#^(\+[+-]|\+\*|.+[+-]$|.+\*(?!$))#', $word)) + { + unset($this->split_words[$i]); + continue; + } + + $clean_word = preg_replace('#^[+\-|"]#', '', $word); + + // check word length + $clean_len = utf8_strlen(str_replace('*', '', $clean_word)); + if (($clean_len < $this->config['fulltext_mysql_min_word_len']) || ($clean_len > $this->config['fulltext_mysql_max_word_len'])) + { + $this->common_words[] = $word; + unset($this->split_words[$i]); + } + } + + if ($terms == 'any') + { + $this->search_query = ''; + foreach ($this->split_words as $word) + { + if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0)) + { + $word = substr($word, 1); + } + $this->search_query .= $word . ' '; + } + } + else + { + $this->search_query = ''; + foreach ($this->split_words as $word) + { + if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0)) + { + $this->search_query .= $word . ' '; + } + else if (strpos($word, '|') === 0) + { + $this->search_query .= substr($word, 1) . ' '; + } + else + { + $this->search_query .= '+' . $word . ' '; + } + } + } + + $this->search_query = utf8_htmlspecialchars($this->search_query); + + if ($this->search_query) + { + $this->split_words = array_values($this->split_words); + sort($this->split_words); + return true; + } + return false; + } + + /** + * Turns text into an array of words + * @param string $text contains post text/subject + */ + public function split_message($text) + { + // Split words + $text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text))); + $matches = array(); + preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches); + $text = $matches[1]; + + // remove too short or too long words + $text = array_values($text); + for ($i = 0, $n = sizeof($text); $i < $n; $i++) + { + $text[$i] = trim($text[$i]); + if (utf8_strlen($text[$i]) < $this->config['fulltext_mysql_min_word_len'] || utf8_strlen($text[$i]) > $this->config['fulltext_mysql_max_word_len']) + { + unset($text[$i]); + } + } + + return array_values($text); + } + + /** + * Performs a search on keywords depending on display specific params. You have to run split_keywords() first + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched) + * @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words) + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No keywords? No posts + if (!$this->search_query) + { + return false; + } + + // generate a search_key from all the options to identify the results + $search_key_array = array( + implode(', ', $this->split_words), + $type, + $fields, + $terms, + $sort_days, + $sort_key, + $topic_id, + implode(',', $ex_fid_ary), + $post_visibility, + implode(',', $author_ary) + ); + + /** + * Allow changing the search_key for cached results + * + * @event core.search_mysql_by_keyword_modify_search_key + * @var array search_key_array Array with search parameters to generate the search_key + * @var string type Searching type ('posts', 'topics') + * @var string fields Searching fields ('titleonly', 'msgonly', 'firstpost', 'all') + * @var string terms Searching terms ('all', 'any') + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @since 3.1.7-RC1 + */ + $vars = array( + 'search_key_array', + 'type', + 'fields', + 'terms', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_by_keyword_modify_search_key', compact($vars))); + + $search_key = md5(implode('#', $search_key_array)); + + if ($start < 0) + { + $start = 0; + } + + // try reading the results from cache + $result_count = 0; + if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE) + { + return $result_count; + } + + $id_ary = array(); + + $join_topic = ($type == 'posts') ? false : true; + + // Build sql strings for sorting + $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC'); + $sql_sort_table = $sql_sort_join = ''; + + switch ($sql_sort[0]) + { + case 'u': + $sql_sort_table = USERS_TABLE . ' u, '; + $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster '; + break; + + case 't': + $join_topic = true; + break; + + case 'f': + $sql_sort_table = FORUMS_TABLE . ' f, '; + $sql_sort_join = ' AND f.forum_id = p.forum_id '; + break; + } + + // Build some display specific sql strings + switch ($fields) + { + case 'titleonly': + $sql_match = 'p.post_subject'; + $sql_match_where = ' AND p.post_id = t.topic_first_post_id'; + $join_topic = true; + break; + + case 'msgonly': + $sql_match = 'p.post_text'; + $sql_match_where = ''; + break; + + case 'firstpost': + $sql_match = 'p.post_subject, p.post_text'; + $sql_match_where = ' AND p.post_id = t.topic_first_post_id'; + $join_topic = true; + break; + + default: + $sql_match = 'p.post_subject, p.post_text'; + $sql_match_where = ''; + break; + } + + $search_query = $this->search_query; + + /** + * Allow changing the query used to search for posts using fulltext_mysql + * + * @event core.search_mysql_keywords_main_query_before + * @var string search_query The parsed keywords used for this search + * @var int result_count The previous result count for the format of the query. + * Set to 0 to force a re-count + * @var bool join_topic Weather or not TOPICS_TABLE should be CROSS JOIN'ED + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name An extra username to search on (!empty(author_ary) must be true, to be relevant) + * @var array ex_fid_ary Which forums not to search on + * @var int topic_id Limit the search to this topic_id only + * @var string sql_sort_table Extra tables to include in the SQL query. + * Used in conjunction with sql_sort_join + * @var string sql_sort_join SQL conditions to join all the tables used together. + * Used in conjunction with sql_sort_table + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sql_match Which columns to do the search on. + * @var string sql_match_where Extra conditions to use to properly filter the matching process + * @var string sort_by_sql The possible predefined sort types + * @var string sort_key The sort type used from the possible sort types + * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used + * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir + * @var int start How many posts to skip in the search results (used for pagination) + * @since 3.1.5-RC1 + */ + $vars = array( + 'search_query', + 'result_count', + 'join_topic', + 'author_ary', + 'author_name', + 'ex_fid_ary', + 'topic_id', + 'sql_sort_table', + 'sql_sort_join', + 'sort_days', + 'sql_match', + 'sql_match_where', + 'sort_by_sql', + 'sort_key', + 'sort_dir', + 'sql_sort', + 'start', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_keywords_main_query_before', compact($vars))); + + $sql_select = (!$result_count) ? 'SQL_CALC_FOUND_ROWS ' : ''; + $sql_select = ($type == 'posts') ? $sql_select . 'p.post_id' : 'DISTINCT ' . $sql_select . 't.topic_id'; + $sql_from = ($join_topic) ? TOPICS_TABLE . ' t, ' : ''; + $field = ($type == 'posts') ? 'post_id' : 'topic_id'; + if (sizeof($author_ary) && $author_name) + { + // first one matches post of registered users, second one guests and deleted users + $sql_author = ' AND (' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')'; + } + else if (sizeof($author_ary)) + { + $sql_author = ' AND ' . $this->db->sql_in_set('p.poster_id', $author_ary); + } + else + { + $sql_author = ''; + } + + $sql_where_options = $sql_sort_join; + $sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : ''; + $sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : ''; + $sql_where_options .= (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : ''; + $sql_where_options .= ' AND ' . $post_visibility; + $sql_where_options .= $sql_author; + $sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : ''; + $sql_where_options .= $sql_match_where; + + $sql = "SELECT $sql_select + FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p + WHERE MATCH ($sql_match) AGAINST ('" . $this->db->sql_escape(htmlspecialchars_decode($this->search_query)) . "' IN BOOLEAN MODE) + $sql_where_options + ORDER BY $sql_sort"; + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + + $id_ary = array_unique($id_ary); + + // if the total result count is not cached yet, retrieve it from the db + if (!$result_count) + { + $sql_found_rows = 'SELECT FOUND_ROWS() as result_count'; + $result = $this->db->sql_query($sql_found_rows); + $result_count = (int) $this->db->sql_fetchfield('result_count'); + $this->db->sql_freeresult($result); + + if (!$result_count) + { + return false; + } + } + + if ($start >= $result_count) + { + $start = floor(($result_count - 1) / $per_page) * $per_page; + + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + + $id_ary = array_unique($id_ary); + } + + // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page + $this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir); + $id_ary = array_slice($id_ary, 0, (int) $per_page); + + return $result_count; + } + + /** + * Performs a search on an author's posts without caring about message contents. Depends on display specific params + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param boolean $firstpost_only if true, only topic starting posts will be considered + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No author? No posts + if (!sizeof($author_ary)) + { + return 0; + } + + // generate a search_key from all the options to identify the results + $search_key_array = array( + '', + $type, + ($firstpost_only) ? 'firstpost' : '', + '', + '', + $sort_days, + $sort_key, + $topic_id, + implode(',', $ex_fid_ary), + $post_visibility, + implode(',', $author_ary), + $author_name, + ); + + /** + * Allow changing the search_key for cached results + * + * @event core.search_mysql_by_author_modify_search_key + * @var array search_key_array Array with search parameters to generate the search_key + * @var string type Searching type ('posts', 'topics') + * @var boolean firstpost_only Flag indicating if only topic starting posts are considered + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name The username to search on + * @since 3.1.7-RC1 + */ + $vars = array( + 'search_key_array', + 'type', + 'firstpost_only', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + 'author_name', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_by_author_modify_search_key', compact($vars))); + + $search_key = md5(implode('#', $search_key_array)); + + if ($start < 0) + { + $start = 0; + } + + // try reading the results from cache + $result_count = 0; + if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE) + { + return $result_count; + } + + $id_ary = array(); + + // Create some display specific sql strings + if ($author_name) + { + // first one matches post of registered users, second one guests and deleted users + $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')'; + } + else + { + $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary); + } + $sql_fora = (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : ''; + $sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : ''; + $sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : ''; + $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : ''; + + // Build sql strings for sorting + $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC'); + $sql_sort_table = $sql_sort_join = ''; + switch ($sql_sort[0]) + { + case 'u': + $sql_sort_table = USERS_TABLE . ' u, '; + $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster '; + break; + + case 't': + $sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : ''; + $sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : ''; + break; + + case 'f': + $sql_sort_table = FORUMS_TABLE . ' f, '; + $sql_sort_join = ' AND f.forum_id = p.forum_id '; + break; + } + + $m_approve_fid_sql = ' AND ' . $post_visibility; + + /** + * Allow changing the query used to search for posts by author in fulltext_mysql + * + * @event core.search_mysql_author_query_before + * @var int result_count The previous result count for the format of the query. + * Set to 0 to force a re-count + * @var string sql_sort_table CROSS JOIN'ed table to allow doing the sort chosen + * @var string sql_sort_join Condition to define how to join the CROSS JOIN'ed table specifyed in sql_sort_table + * @var string type Either "posts" or "topics" specifying the type of search being made + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name An extra username to search on + * @var string sql_author SQL WHERE condition for the post author ids + * @var int topic_id Limit the search to this topic_id only + * @var string sql_topic_id SQL of topic_id + * @var string sort_by_sql The possible predefined sort types + * @var string sort_key The sort type used from the possible sort types + * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used + * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir + * @var string sort_days Time, in days, that the oldest post showing can have + * @var string sql_time The SQL to search on the time specifyed by sort_days + * @var bool firstpost_only Wether or not to search only on the first post of the topics + * @var string sql_firstpost The SQL with the conditions to join the tables when using firstpost_only + * @var array ex_fid_ary Forum ids that must not be searched on + * @var array sql_fora SQL query for ex_fid_ary + * @var string m_approve_fid_sql WHERE clause condition on post_visibility restrictions + * @var int start How many posts to skip in the search results (used for pagination) + * @since 3.1.5-RC1 + */ + $vars = array( + 'result_count', + 'sql_sort_table', + 'sql_sort_join', + 'type', + 'author_ary', + 'author_name', + 'sql_author', + 'topic_id', + 'sql_topic_id', + 'sort_by_sql', + 'sort_key', + 'sort_dir', + 'sql_sort', + 'sort_days', + 'sql_time', + 'firstpost_only', + 'sql_firstpost', + 'ex_fid_ary', + 'sql_fora', + 'm_approve_fid_sql', + 'start', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_mysql_author_query_before', compact($vars))); + + // If the cache was completely empty count the results + $calc_results = ($result_count) ? '' : 'SQL_CALC_FOUND_ROWS '; + + // Build the query for really selecting the post_ids + if ($type == 'posts') + { + $sql = "SELECT {$calc_results}p.post_id + FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . " + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $m_approve_fid_sql + $sql_fora + $sql_sort_join + $sql_time + ORDER BY $sql_sort"; + $field = 'post_id'; + } + else + { + $sql = "SELECT {$calc_results}t.topic_id + FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $m_approve_fid_sql + $sql_fora + AND t.topic_id = p.topic_id + $sql_sort_join + $sql_time + GROUP BY t.topic_id + ORDER BY $sql_sort"; + $field = 'topic_id'; + } + + // Only read one block of posts from the db and then cache it + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + + // retrieve the total result count if needed + if (!$result_count) + { + $sql_found_rows = 'SELECT FOUND_ROWS() as result_count'; + $result = $this->db->sql_query($sql_found_rows); + $result_count = (int) $this->db->sql_fetchfield('result_count'); + $this->db->sql_freeresult($result); + + if (!$result_count) + { + return false; + } + } + + if ($start >= $result_count) + { + $start = floor(($result_count - 1) / $per_page) * $per_page; + + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + + $id_ary = array_unique($id_ary); + } + + if (sizeof($id_ary)) + { + $this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir); + $id_ary = array_slice($id_ary, 0, $per_page); + + return $result_count; + } + return false; + } + + /** + * Destroys cached search results, that contained one of the new words in a post so the results won't be outdated + * + * @param string $mode contains the post mode: edit, post, reply, quote ... + * @param int $post_id contains the post id of the post to index + * @param string $message contains the post text of the post + * @param string $subject contains the subject of the post to index + * @param int $poster_id contains the user id of the poster + * @param int $forum_id contains the forum id of parent forum of the post + */ + public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id) + { + // Split old and new post/subject to obtain array of words + $split_text = $this->split_message($message); + $split_title = ($subject) ? $this->split_message($subject) : array(); + + $words = array_unique(array_merge($split_text, $split_title)); + + unset($split_text); + unset($split_title); + + // destroy cached search results containing any of the words removed or added + $this->destroy_cache($words, array($poster_id)); + + unset($words); + } + + /** + * Destroy cached results, that might be outdated after deleting a post + */ + public function index_remove($post_ids, $author_ids, $forum_ids) + { + $this->destroy_cache(array(), array_unique($author_ids)); + } + + /** + * Destroy old cache entries + */ + public function tidy() + { + // destroy too old cached search results + $this->destroy_cache(array()); + + set_config('search_last_gc', time(), true); + } + + /** + * Create fulltext index + * + * @return string|bool error string is returned incase of errors otherwise false + */ + public function create_index($acp_module, $u_action) + { + // Make sure we can actually use MySQL with fulltext indexes + if ($error = $this->init()) + { + return $error; + } + + if (empty($this->stats)) + { + $this->get_stats(); + } + + $alter_list = array(); + + if (!isset($this->stats['post_subject'])) + { + $alter_entry = array(); + if ($this->db->get_sql_layer() == 'mysqli' || version_compare($this->db->sql_server_info(true), '4.1.3', '>=')) + { + $alter_entry[] = 'MODIFY post_subject varchar(255) COLLATE utf8_unicode_ci DEFAULT \'\' NOT NULL'; + } + else + { + $alter_entry[] = 'MODIFY post_subject text NOT NULL'; + } + $alter_entry[] = 'ADD FULLTEXT (post_subject)'; + $alter_list[] = $alter_entry; + } + + if (!isset($this->stats['post_content'])) + { + $alter_entry = array(); + if ($this->db->get_sql_layer() == 'mysqli' || version_compare($this->db->sql_server_info(true), '4.1.3', '>=')) + { + $alter_entry[] = 'MODIFY post_text mediumtext COLLATE utf8_unicode_ci NOT NULL'; + } + else + { + $alter_entry[] = 'MODIFY post_text mediumtext NOT NULL'; + } + + $alter_entry[] = 'ADD FULLTEXT post_content (post_text, post_subject)'; + $alter_list[] = $alter_entry; + } + + if (sizeof($alter_list)) + { + foreach ($alter_list as $alter) + { + $this->db->sql_query('ALTER TABLE ' . POSTS_TABLE . ' ' . implode(', ', $alter)); + } + } + + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE); + + return false; + } + + /** + * Drop fulltext index + * + * @return string|bool error string is returned incase of errors otherwise false + */ + public function delete_index($acp_module, $u_action) + { + // Make sure we can actually use MySQL with fulltext indexes + if ($error = $this->init()) + { + return $error; + } + + if (empty($this->stats)) + { + $this->get_stats(); + } + + $alter = array(); + + if (isset($this->stats['post_subject'])) + { + $alter[] = 'DROP INDEX post_subject'; + } + + if (isset($this->stats['post_content'])) + { + $alter[] = 'DROP INDEX post_content'; + } + + if (sizeof($alter)) + { + $this->db->sql_query('ALTER TABLE ' . POSTS_TABLE . ' ' . implode(', ', $alter)); + } + + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE); + + return false; + } + + /** + * Returns true if both FULLTEXT indexes exist + */ + public function index_created() + { + if (empty($this->stats)) + { + $this->get_stats(); + } + + return isset($this->stats['post_subject']) && isset($this->stats['post_content']); + } + + /** + * Returns an associative array containing information about the indexes + */ + public function index_stats() + { + if (empty($this->stats)) + { + $this->get_stats(); + } + + return array( + $this->user->lang['FULLTEXT_MYSQL_TOTAL_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] : 0, + ); + } + + /** + * Computes the stats and store them in the $this->stats associative array + */ + protected function get_stats() + { + if (strpos($this->db->get_sql_layer(), 'mysql') === false) + { + $this->stats = array(); + return; + } + + $sql = 'SHOW INDEX + FROM ' . POSTS_TABLE; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + // deal with older MySQL versions which didn't use Index_type + $index_type = (isset($row['Index_type'])) ? $row['Index_type'] : $row['Comment']; + + if ($index_type == 'FULLTEXT') + { + if ($row['Key_name'] == 'post_subject') + { + $this->stats['post_subject'] = $row; + } + else if ($row['Key_name'] == 'post_content') + { + $this->stats['post_content'] = $row; + } + } + } + $this->db->sql_freeresult($result); + + $this->stats['total_posts'] = empty($this->stats) ? 0 : $this->db->get_estimated_row_count(POSTS_TABLE); + } + + /** + * Display a note, that UTF-8 support is not available with certain versions of PHP + * + * @return associative array containing template and config variables + */ + public function acp() + { + $tpl = ' + <dl> + <dt><label>' . $this->user->lang['MIN_SEARCH_CHARS'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_MYSQL_MIN_SEARCH_CHARS_EXPLAIN'] . '</span></dt> + <dd>' . $this->config['fulltext_mysql_min_word_len'] . '</dd> + </dl> + <dl> + <dt><label>' . $this->user->lang['MAX_SEARCH_CHARS'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_MYSQL_MAX_SEARCH_CHARS_EXPLAIN'] . '</span></dt> + <dd>' . $this->config['fulltext_mysql_max_word_len'] . '</dd> + </dl> + '; + + // These are fields required in the config table + return array( + 'tpl' => $tpl, + 'config' => array() + ); + } +} diff --git a/phpBB/phpbb/search/fulltext_native.php b/phpBB/phpbb/search/fulltext_native.php new file mode 100644 index 0000000000..63b0b24edf --- /dev/null +++ b/phpBB/phpbb/search/fulltext_native.php @@ -0,0 +1,1996 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search; + +/** +* phpBB's own db driven fulltext search, version 2 +*/ +class fulltext_native extends \phpbb\search\base +{ + /** + * Associative array holding index stats + * @var array + */ + protected $stats = array(); + + /** + * Associative array stores the min and max word length to be searched + * @var array + */ + protected $word_length = array(); + + /** + * Contains tidied search query. + * Operators are prefixed in search query and common words excluded + * @var string + */ + protected $search_query; + + /** + * Contains common words. + * Common words are words with length less/more than min/max length + * @var array + */ + protected $common_words = array(); + + /** + * Post ids of posts containing words that are to be included + * @var array + */ + protected $must_contain_ids = array(); + + /** + * Post ids of posts containing words that should not be included + * @var array + */ + protected $must_not_contain_ids = array(); + + /** + * Post ids of posts containing at least one word that needs to be excluded + * @var array + */ + protected $must_exclude_one_ids = array(); + + /** + * Relative path to board root + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP Extension + * @var string + */ + protected $php_ext; + + /** + * Config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Database connection + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * phpBB event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $phpbb_dispatcher; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Initialises the fulltext_native search backend with min/max word length and makes sure the UTF-8 normalizer is loaded + * + * @param boolean|string &$error is passed by reference and should either be set to false on success or an error message on failure + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object + */ + public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $phpEx; + $this->config = $config; + $this->db = $db; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->user = $user; + + $this->word_length = array('min' => $this->config['fulltext_native_min_chars'], 'max' => $this->config['fulltext_native_max_chars']); + + /** + * Load the UTF tools + */ + if (!class_exists('utf_normalizer')) + { + include($this->phpbb_root_path . 'includes/utf/utf_normalizer.' . $this->php_ext); + } + if (!function_exists('utf8_decode_ncr')) + { + include($this->phpbb_root_path . 'includes/utf/utf_tools.' . $this->php_ext); + } + + $error = false; + } + + /** + * Returns the name of this search backend to be displayed to administrators + * + * @return string Name + */ + public function get_name() + { + return 'phpBB Native Fulltext'; + } + + /** + * Returns the search_query + * + * @return string search query + */ + public function get_search_query() + { + return $this->search_query; + } + + /** + * Returns the common_words array + * + * @return array common words that are ignored by search backend + */ + public function get_common_words() + { + return $this->common_words; + } + + /** + * Returns the word_length array + * + * @return array min and max word length for searching + */ + public function get_word_length() + { + return $this->word_length; + } + + /** + * This function fills $this->search_query with the cleaned user search query + * + * If $terms is 'any' then the words will be extracted from the search query + * and combined with | inside brackets. They will afterwards be treated like + * an standard search query. + * + * Then it analyses the query and fills the internal arrays $must_not_contain_ids, + * $must_contain_ids and $must_exclude_one_ids which are later used by keyword_search() + * + * @param string $keywords contains the search query string as entered by the user + * @param string $terms is either 'all' (use search query as entered, default words to 'must be contained in post') + * or 'any' (find all posts containing at least one of the given words) + * @return boolean false if no valid keywords were found and otherwise true + */ + public function split_keywords($keywords, $terms) + { + $tokens = '+-|()*'; + + $keywords = trim($this->cleanup($keywords, $tokens)); + + // allow word|word|word without brackets + if ((strpos($keywords, ' ') === false) && (strpos($keywords, '|') !== false) && (strpos($keywords, '(') === false)) + { + $keywords = '(' . $keywords . ')'; + } + + $open_bracket = $space = false; + for ($i = 0, $n = strlen($keywords); $i < $n; $i++) + { + if ($open_bracket !== false) + { + switch ($keywords[$i]) + { + case ')': + if ($open_bracket + 1 == $i) + { + $keywords[$i - 1] = '|'; + $keywords[$i] = '|'; + } + $open_bracket = false; + break; + case '(': + $keywords[$i] = '|'; + break; + case '+': + case '-': + case ' ': + $keywords[$i] = '|'; + break; + case '*': + if ($i === 0 || ($keywords[$i - 1] !== '*' && strcspn($keywords[$i - 1], $tokens) === 0)) + { + if ($i === $n - 1 || ($keywords[$i + 1] !== '*' && strcspn($keywords[$i + 1], $tokens) === 0)) + { + $keywords = substr($keywords, 0, $i) . substr($keywords, $i + 1); + } + } + break; + } + } + else + { + switch ($keywords[$i]) + { + case ')': + $keywords[$i] = ' '; + break; + case '(': + $open_bracket = $i; + $space = false; + break; + case '|': + $keywords[$i] = ' '; + break; + case '-': + case '+': + $space = $keywords[$i]; + break; + case ' ': + if ($space !== false) + { + $keywords[$i] = $space; + } + break; + default: + $space = false; + } + } + } + + if ($open_bracket) + { + $keywords .= ')'; + } + + $match = array( + '# +#', + '#\|\|+#', + '#(\+|\-)(?:\+|\-)+#', + '#\(\|#', + '#\|\)#', + ); + $replace = array( + ' ', + '|', + '$1', + '(', + ')', + ); + + $keywords = preg_replace($match, $replace, $keywords); + $num_keywords = sizeof(explode(' ', $keywords)); + + // We limit the number of allowed keywords to minimize load on the database + if ($this->config['max_num_search_keywords'] && $num_keywords > $this->config['max_num_search_keywords']) + { + trigger_error($this->user->lang('MAX_NUM_SEARCH_KEYWORDS_REFINE', (int) $this->config['max_num_search_keywords'], $num_keywords)); + } + + // $keywords input format: each word separated by a space, words in a bracket are not separated + + // the user wants to search for any word, convert the search query + if ($terms == 'any') + { + $words = array(); + + preg_match_all('#([^\\s+\\-|()]+)(?:$|[\\s+\\-|()])#u', $keywords, $words); + if (sizeof($words[1])) + { + $keywords = '(' . implode('|', $words[1]) . ')'; + } + } + + // set the search_query which is shown to the user + $this->search_query = $keywords; + + $exact_words = array(); + preg_match_all('#([^\\s+\\-|()]+)(?:$|[\\s+\\-|()])#u', $keywords, $exact_words); + $exact_words = $exact_words[1]; + + $common_ids = $words = array(); + + if (sizeof($exact_words)) + { + $sql = 'SELECT word_id, word_text, word_common + FROM ' . SEARCH_WORDLIST_TABLE . ' + WHERE ' . $this->db->sql_in_set('word_text', $exact_words) . ' + ORDER BY word_count ASC'; + $result = $this->db->sql_query($sql); + + // store an array of words and ids, remove common words + while ($row = $this->db->sql_fetchrow($result)) + { + if ($row['word_common']) + { + $this->common_words[] = $row['word_text']; + $common_ids[$row['word_text']] = (int) $row['word_id']; + continue; + } + + $words[$row['word_text']] = (int) $row['word_id']; + } + $this->db->sql_freeresult($result); + } + + // Handle +, - without preceeding whitespace character + $match = array('#(\S)\+#', '#(\S)-#'); + $replace = array('$1 +', '$1 +'); + + $keywords = preg_replace($match, $replace, $keywords); + + // now analyse the search query, first split it using the spaces + $query = explode(' ', $keywords); + + $this->must_contain_ids = array(); + $this->must_not_contain_ids = array(); + $this->must_exclude_one_ids = array(); + + $mode = ''; + $ignore_no_id = true; + + foreach ($query as $word) + { + if (empty($word)) + { + continue; + } + + // words which should not be included + if ($word[0] == '-') + { + $word = substr($word, 1); + + // a group of which at least one may not be in the resulting posts + if ($word[0] == '(') + { + $word = array_unique(explode('|', substr($word, 1, -1))); + $mode = 'must_exclude_one'; + } + // one word which should not be in the resulting posts + else + { + $mode = 'must_not_contain'; + } + $ignore_no_id = true; + } + // words which have to be included + else + { + // no prefix is the same as a +prefix + if ($word[0] == '+') + { + $word = substr($word, 1); + } + + // a group of words of which at least one word should be in every resulting post + if ($word[0] == '(') + { + $word = array_unique(explode('|', substr($word, 1, -1))); + } + $ignore_no_id = false; + $mode = 'must_contain'; + } + + if (empty($word)) + { + continue; + } + + // if this is an array of words then retrieve an id for each + if (is_array($word)) + { + $non_common_words = array(); + $id_words = array(); + foreach ($word as $i => $word_part) + { + if (strpos($word_part, '*') !== false) + { + $id_words[] = '\'' . $this->db->sql_escape(str_replace('*', '%', $word_part)) . '\''; + $non_common_words[] = $word_part; + } + else if (isset($words[$word_part])) + { + $id_words[] = $words[$word_part]; + $non_common_words[] = $word_part; + } + else + { + $len = utf8_strlen($word_part); + if ($len < $this->word_length['min'] || $len > $this->word_length['max']) + { + $this->common_words[] = $word_part; + } + } + } + if (sizeof($id_words)) + { + sort($id_words); + if (sizeof($id_words) > 1) + { + $this->{$mode . '_ids'}[] = $id_words; + } + else + { + $mode = ($mode == 'must_exclude_one') ? 'must_not_contain' : $mode; + $this->{$mode . '_ids'}[] = $id_words[0]; + } + } + // throw an error if we shall not ignore unexistant words + else if (!$ignore_no_id && sizeof($non_common_words)) + { + trigger_error(sprintf($this->user->lang['WORDS_IN_NO_POST'], implode($this->user->lang['COMMA_SEPARATOR'], $non_common_words))); + } + unset($non_common_words); + } + // else we only need one id + else if (($wildcard = strpos($word, '*') !== false) || isset($words[$word])) + { + if ($wildcard) + { + $len = utf8_strlen(str_replace('*', '', $word)); + if ($len >= $this->word_length['min'] && $len <= $this->word_length['max']) + { + $this->{$mode . '_ids'}[] = '\'' . $this->db->sql_escape(str_replace('*', '%', $word)) . '\''; + } + else + { + $this->common_words[] = $word; + } + } + else + { + $this->{$mode . '_ids'}[] = $words[$word]; + } + } + else + { + if (!isset($common_ids[$word])) + { + $len = utf8_strlen($word); + if ($len < $this->word_length['min'] || $len > $this->word_length['max']) + { + $this->common_words[] = $word; + } + } + } + } + + // Return true if all words are not common words + if (sizeof($exact_words) - sizeof($this->common_words) > 0) + { + return true; + } + return false; + } + + /** + * Performs a search on keywords depending on display specific params. You have to run split_keywords() first + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched) + * @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words) + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No keywords? No posts. + if (empty($this->search_query)) + { + return false; + } + + // we can't search for negatives only + if (empty($this->must_contain_ids)) + { + return false; + } + + $must_contain_ids = $this->must_contain_ids; + $must_not_contain_ids = $this->must_not_contain_ids; + $must_exclude_one_ids = $this->must_exclude_one_ids; + + sort($must_contain_ids); + sort($must_not_contain_ids); + sort($must_exclude_one_ids); + + // generate a search_key from all the options to identify the results + $search_key_array = array( + serialize($must_contain_ids), + serialize($must_not_contain_ids), + serialize($must_exclude_one_ids), + $type, + $fields, + $terms, + $sort_days, + $sort_key, + $topic_id, + implode(',', $ex_fid_ary), + $post_visibility, + implode(',', $author_ary), + $author_name, + ); + + /** + * Allow changing the search_key for cached results + * + * @event core.search_native_by_keyword_modify_search_key + * @var array search_key_array Array with search parameters to generate the search_key + * @var array must_contain_ids Array with post ids of posts containing words that are to be included + * @var array must_not_contain_ids Array with post ids of posts containing words that should not be included + * @var array must_exclude_one_ids Array with post ids of posts containing at least one word that needs to be excluded + * @var string type Searching type ('posts', 'topics') + * @var string fields Searching fields ('titleonly', 'msgonly', 'firstpost', 'all') + * @var string terms Searching terms ('all', 'any') + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @since 3.1.7-RC1 + */ + $vars = array( + 'search_key_array', + 'must_contain_ids', + 'must_not_contain_ids', + 'must_exclude_one_ids', + 'type', + 'fields', + 'terms', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_native_by_keyword_modify_search_key', compact($vars))); + + $search_key = md5(implode('#', $search_key_array)); + + // try reading the results from cache + $total_results = 0; + if ($this->obtain_ids($search_key, $total_results, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE) + { + return $total_results; + } + + $id_ary = array(); + + $sql_where = array(); + $group_by = false; + $m_num = 0; + $w_num = 0; + + $sql_array = array( + 'SELECT' => ($type == 'posts') ? 'p.post_id' : 'p.topic_id', + 'FROM' => array( + SEARCH_WORDMATCH_TABLE => array(), + SEARCH_WORDLIST_TABLE => array(), + ), + 'LEFT_JOIN' => array(array( + 'FROM' => array(POSTS_TABLE => 'p'), + 'ON' => 'm0.post_id = p.post_id', + )), + ); + + $title_match = ''; + $left_join_topics = false; + $group_by = true; + // Build some display specific sql strings + switch ($fields) + { + case 'titleonly': + $title_match = 'title_match = 1'; + $group_by = false; + // no break + case 'firstpost': + $left_join_topics = true; + $sql_where[] = 'p.post_id = t.topic_first_post_id'; + break; + + case 'msgonly': + $title_match = 'title_match = 0'; + $group_by = false; + break; + } + + if ($type == 'topics') + { + $left_join_topics = true; + $group_by = true; + } + + /** + * @todo Add a query optimizer (handle stuff like "+(4|3) +4") + */ + + foreach ($this->must_contain_ids as $subquery) + { + if (is_array($subquery)) + { + $group_by = true; + + $word_id_sql = array(); + $word_ids = array(); + foreach ($subquery as $id) + { + if (is_string($id)) + { + $sql_array['LEFT_JOIN'][] = array( + 'FROM' => array(SEARCH_WORDLIST_TABLE => 'w' . $w_num), + 'ON' => "w$w_num.word_text LIKE $id" + ); + $word_ids[] = "w$w_num.word_id"; + + $w_num++; + } + else + { + $word_ids[] = $id; + } + } + + $sql_where[] = $this->db->sql_in_set("m$m_num.word_id", $word_ids); + + unset($word_id_sql); + unset($word_ids); + } + else if (is_string($subquery)) + { + $sql_array['FROM'][SEARCH_WORDLIST_TABLE][] = 'w' . $w_num; + + $sql_where[] = "w$w_num.word_text LIKE $subquery"; + $sql_where[] = "m$m_num.word_id = w$w_num.word_id"; + + $group_by = true; + $w_num++; + } + else + { + $sql_where[] = "m$m_num.word_id = $subquery"; + } + + $sql_array['FROM'][SEARCH_WORDMATCH_TABLE][] = 'm' . $m_num; + + if ($title_match) + { + $sql_where[] = "m$m_num.$title_match"; + } + + if ($m_num != 0) + { + $sql_where[] = "m$m_num.post_id = m0.post_id"; + } + $m_num++; + } + + foreach ($this->must_not_contain_ids as $key => $subquery) + { + if (is_string($subquery)) + { + $sql_array['LEFT_JOIN'][] = array( + 'FROM' => array(SEARCH_WORDLIST_TABLE => 'w' . $w_num), + 'ON' => "w$w_num.word_text LIKE $subquery" + ); + + $this->must_not_contain_ids[$key] = "w$w_num.word_id"; + + $group_by = true; + $w_num++; + } + } + + if (sizeof($this->must_not_contain_ids)) + { + $sql_array['LEFT_JOIN'][] = array( + 'FROM' => array(SEARCH_WORDMATCH_TABLE => 'm' . $m_num), + 'ON' => $this->db->sql_in_set("m$m_num.word_id", $this->must_not_contain_ids) . (($title_match) ? " AND m$m_num.$title_match" : '') . " AND m$m_num.post_id = m0.post_id" + ); + + $sql_where[] = "m$m_num.word_id IS NULL"; + $m_num++; + } + + foreach ($this->must_exclude_one_ids as $ids) + { + $is_null_joins = array(); + foreach ($ids as $id) + { + if (is_string($id)) + { + $sql_array['LEFT_JOIN'][] = array( + 'FROM' => array(SEARCH_WORDLIST_TABLE => 'w' . $w_num), + 'ON' => "w$w_num.word_text LIKE $id" + ); + $id = "w$w_num.word_id"; + + $group_by = true; + $w_num++; + } + + $sql_array['LEFT_JOIN'][] = array( + 'FROM' => array(SEARCH_WORDMATCH_TABLE => 'm' . $m_num), + 'ON' => "m$m_num.word_id = $id AND m$m_num.post_id = m0.post_id" . (($title_match) ? " AND m$m_num.$title_match" : '') + ); + $is_null_joins[] = "m$m_num.word_id IS NULL"; + + $m_num++; + } + $sql_where[] = '(' . implode(' OR ', $is_null_joins) . ')'; + } + + $sql_where[] = $post_visibility; + + $search_query = $this->search_query; + $must_exclude_one_ids = $this->must_exclude_one_ids; + $must_not_contain_ids = $this->must_not_contain_ids; + $must_contain_ids = $this->must_contain_ids; + + /** + * Allow changing the query used for counting for posts using fulltext_native + * + * @event core.search_native_keywords_count_query_before + * @var string search_query The parsed keywords used for this search + * @var array must_not_contain_ids Ids that cannot be taken into account for the results + * @var array must_exclude_one_ids Ids that cannot be on the results + * @var array must_contain_ids Ids that must be on the results + * @var int total_results The previous result count for the format of the query + * Set to 0 to force a re-count + * @var array sql_array The data on how to search in the DB at this point + * @var bool left_join_topics Whether or not TOPICS_TABLE should be CROSS JOIN'ED + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name An extra username to search on (!empty(author_ary) must be true, to be relevant) + * @var array ex_fid_ary Which forums not to search on + * @var int topic_id Limit the search to this topic_id only + * @var string sql_sort_table Extra tables to include in the SQL query. + * Used in conjunction with sql_sort_join + * @var string sql_sort_join SQL conditions to join all the tables used together. + * Used in conjunction with sql_sort_table + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sql_where An array of the current WHERE clause conditions + * @var string sql_match Which columns to do the search on + * @var string sql_match_where Extra conditions to use to properly filter the matching process + * @var bool group_by Whether or not the SQL query requires a GROUP BY for the elements in the SELECT clause + * @var string sort_by_sql The possible predefined sort types + * @var string sort_key The sort type used from the possible sort types + * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used + * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir + * @var int start How many posts to skip in the search results (used for pagination) + * @since 3.1.5-RC1 + */ + $vars = array( + 'search_query', + 'must_not_contain_ids', + 'must_exclude_one_ids', + 'must_contain_ids', + 'total_results', + 'sql_array', + 'left_join_topics', + 'author_ary', + 'author_name', + 'ex_fid_ary', + 'topic_id', + 'sql_sort_table', + 'sql_sort_join', + 'sort_days', + 'sql_where', + 'sql_match', + 'sql_match_where', + 'group_by', + 'sort_by_sql', + 'sort_key', + 'sort_dir', + 'sql_sort', + 'start', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_native_keywords_count_query_before', compact($vars))); + + if ($topic_id) + { + $sql_where[] = 'p.topic_id = ' . $topic_id; + } + + if (sizeof($author_ary)) + { + if ($author_name) + { + // first one matches post of registered users, second one guests and deleted users + $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')'; + } + else + { + $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary); + } + $sql_where[] = $sql_author; + } + + if (sizeof($ex_fid_ary)) + { + $sql_where[] = $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true); + } + + if ($sort_days) + { + $sql_where[] = 'p.post_time >= ' . (time() - ($sort_days * 86400)); + } + + $sql_array['WHERE'] = implode(' AND ', $sql_where); + + $is_mysql = false; + // if the total result count is not cached yet, retrieve it from the db + if (!$total_results) + { + $sql = ''; + $sql_array_count = $sql_array; + + if ($left_join_topics) + { + $sql_array_count['LEFT_JOIN'][] = array( + 'FROM' => array(TOPICS_TABLE => 't'), + 'ON' => 'p.topic_id = t.topic_id' + ); + } + + switch ($this->db->get_sql_layer()) + { + case 'mysql4': + case 'mysqli': + + // 3.x does not support SQL_CALC_FOUND_ROWS + // $sql_array['SELECT'] = 'SQL_CALC_FOUND_ROWS ' . $sql_array['SELECT']; + $is_mysql = true; + + break; + + case 'sqlite': + case 'sqlite3': + $sql_array_count['SELECT'] = ($type == 'posts') ? 'DISTINCT p.post_id' : 'DISTINCT p.topic_id'; + $sql = 'SELECT COUNT(' . (($type == 'posts') ? 'post_id' : 'topic_id') . ') as total_results + FROM (' . $this->db->sql_build_query('SELECT', $sql_array_count) . ')'; + + // no break + + default: + $sql_array_count['SELECT'] = ($type == 'posts') ? 'COUNT(DISTINCT p.post_id) AS total_results' : 'COUNT(DISTINCT p.topic_id) AS total_results'; + $sql = (!$sql) ? $this->db->sql_build_query('SELECT', $sql_array_count) : $sql; + + $result = $this->db->sql_query($sql); + $total_results = (int) $this->db->sql_fetchfield('total_results'); + $this->db->sql_freeresult($result); + + if (!$total_results) + { + return false; + } + break; + } + + unset($sql_array_count, $sql); + } + + // Build sql strings for sorting + $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC'); + + switch ($sql_sort[0]) + { + case 'u': + $sql_array['FROM'][USERS_TABLE] = 'u'; + $sql_where[] = 'u.user_id = p.poster_id '; + break; + + case 't': + $left_join_topics = true; + break; + + case 'f': + $sql_array['FROM'][FORUMS_TABLE] = 'f'; + $sql_where[] = 'f.forum_id = p.forum_id'; + break; + } + + if ($left_join_topics) + { + $sql_array['LEFT_JOIN'][] = array( + 'FROM' => array(TOPICS_TABLE => 't'), + 'ON' => 'p.topic_id = t.topic_id' + ); + } + + // if using mysql and the total result count is not calculated yet, get it from the db + if (!$total_results && $is_mysql) + { + // Also count rows for the query as if there was not LIMIT. Add SQL_CALC_FOUND_ROWS to SQL + $sql_array['SELECT'] = 'SQL_CALC_FOUND_ROWS ' . $sql_array['SELECT']; + } + + $sql_array['WHERE'] = implode(' AND ', $sql_where); + $sql_array['GROUP_BY'] = ($group_by) ? (($type == 'posts') ? 'p.post_id' : 'p.topic_id') . ', ' . $sort_by_sql[$sort_key] : ''; + $sql_array['ORDER_BY'] = $sql_sort; + + unset($sql_where, $sql_sort, $group_by); + + $sql = $this->db->sql_build_query('SELECT', $sql_array); + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[(($type == 'posts') ? 'post_id' : 'topic_id')]; + } + $this->db->sql_freeresult($result); + + if (!$total_results && $is_mysql) + { + // Get the number of results as calculated by MySQL + $sql_count = 'SELECT FOUND_ROWS() as total_results'; + $result = $this->db->sql_query($sql_count); + $total_results = (int) $this->db->sql_fetchfield('total_results'); + $this->db->sql_freeresult($result); + + if (!$total_results) + { + return false; + } + } + + if ($start >= $total_results) + { + $start = floor(($total_results - 1) / $per_page) * $per_page; + + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[(($type == 'posts') ? 'post_id' : 'topic_id')]; + } + $this->db->sql_freeresult($result); + + } + + // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page + $this->save_ids($search_key, $this->search_query, $author_ary, $total_results, $id_ary, $start, $sort_dir); + $id_ary = array_slice($id_ary, 0, (int) $per_page); + + return $total_results; + } + + /** + * Performs a search on an author's posts without caring about message contents. Depends on display specific params + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param boolean $firstpost_only if true, only topic starting posts will be considered + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No author? No posts + if (!sizeof($author_ary)) + { + return 0; + } + + // generate a search_key from all the options to identify the results + $search_key_array = array( + '', + $type, + ($firstpost_only) ? 'firstpost' : '', + '', + '', + $sort_days, + $sort_key, + $topic_id, + implode(',', $ex_fid_ary), + $post_visibility, + implode(',', $author_ary), + $author_name, + ); + + /** + * Allow changing the search_key for cached results + * + * @event core.search_native_by_author_modify_search_key + * @var array search_key_array Array with search parameters to generate the search_key + * @var string type Searching type ('posts', 'topics') + * @var boolean firstpost_only Flag indicating if only topic starting posts are considered + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name The username to search on + * @since 3.1.7-RC1 + */ + $vars = array( + 'search_key_array', + 'type', + 'firstpost_only', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + 'author_name', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_native_by_author_modify_search_key', compact($vars))); + + $search_key = md5(implode('#', $search_key_array)); + + // try reading the results from cache + $total_results = 0; + if ($this->obtain_ids($search_key, $total_results, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE) + { + return $total_results; + } + + $id_ary = array(); + + // Create some display specific sql strings + if ($author_name) + { + // first one matches post of registered users, second one guests and deleted users + $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')'; + } + else + { + $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary); + } + $sql_fora = (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : ''; + $sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : ''; + $sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : ''; + $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : ''; + $post_visibility = ($post_visibility) ? ' AND ' . $post_visibility : ''; + + // Build sql strings for sorting + $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC'); + $sql_sort_table = $sql_sort_join = ''; + switch ($sql_sort[0]) + { + case 'u': + $sql_sort_table = USERS_TABLE . ' u, '; + $sql_sort_join = ' AND u.user_id = p.poster_id '; + break; + + case 't': + $sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : ''; + $sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : ''; + break; + + case 'f': + $sql_sort_table = FORUMS_TABLE . ' f, '; + $sql_sort_join = ' AND f.forum_id = p.forum_id '; + break; + } + + $select = ($type == 'posts') ? 'p.post_id' : 't.topic_id'; + $is_mysql = false; + + /** + * Allow changing the query used to search for posts by author in fulltext_native + * + * @event core.search_native_author_count_query_before + * @var int total_results The previous result count for the format of the query. + * Set to 0 to force a re-count + * @var string type The type of search being made + * @var string select SQL SELECT clause for what to get + * @var string sql_sort_table CROSS JOIN'ed table to allow doing the sort chosen + * @var string sql_sort_join Condition to define how to join the CROSS JOIN'ed table specifyed in sql_sort_table + * @var array sql_author SQL WHERE condition for the post author ids + * @var int topic_id Limit the search to this topic_id only + * @var string sort_by_sql The possible predefined sort types + * @var string sort_key The sort type used from the possible sort types + * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used + * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir + * @var string sort_days Time, in days, that the oldest post showing can have + * @var string sql_time The SQL to search on the time specifyed by sort_days + * @var bool firstpost_only Wether or not to search only on the first post of the topics + * @var string sql_firstpost The SQL used in the WHERE claused to filter by firstpost. + * @var array ex_fid_ary Forum ids that must not be searched on + * @var array sql_fora SQL query for ex_fid_ary + * @var int start How many posts to skip in the search results (used for pagination) + * @since 3.1.5-RC1 + */ + $vars = array( + 'total_results', + 'type', + 'select', + 'sql_sort_table', + 'sql_sort_join', + 'sql_author', + 'topic_id', + 'sort_by_sql', + 'sort_key', + 'sort_dir', + 'sql_sort', + 'sort_days', + 'sql_time', + 'firstpost_only', + 'sql_firstpost', + 'ex_fid_ary', + 'sql_fora', + 'start', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_native_author_count_query_before', compact($vars))); + + // If the cache was completely empty count the results + if (!$total_results) + { + switch ($this->db->get_sql_layer()) + { + case 'mysql4': + case 'mysqli': +// $select = 'SQL_CALC_FOUND_ROWS ' . $select; + $is_mysql = true; + break; + + default: + if ($type == 'posts') + { + $sql = 'SELECT COUNT(p.post_id) as total_results + FROM ' . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . " + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $post_visibility + $sql_fora + $sql_time"; + } + else + { + if ($this->db->get_sql_layer() == 'sqlite' || $this->db->get_sql_layer() == 'sqlite3') + { + $sql = 'SELECT COUNT(topic_id) as total_results + FROM (SELECT DISTINCT t.topic_id'; + } + else + { + $sql = 'SELECT COUNT(DISTINCT t.topic_id) as total_results'; + } + + $sql .= ' FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $post_visibility + $sql_fora + AND t.topic_id = p.topic_id + $sql_time" . (($this->db->get_sql_layer() == 'sqlite' || $this->db->get_sql_layer() == 'sqlite3') ? ')' : ''); + } + $result = $this->db->sql_query($sql); + + $total_results = (int) $this->db->sql_fetchfield('total_results'); + $this->db->sql_freeresult($result); + + if (!$total_results) + { + return false; + } + break; + } + } + + // Build the query for really selecting the post_ids + if ($type == 'posts') + { + $sql = "SELECT $select + FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t' : '') . " + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $post_visibility + $sql_fora + $sql_sort_join + $sql_time + ORDER BY $sql_sort"; + $field = 'post_id'; + } + else + { + $sql = "SELECT $select + FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $post_visibility + $sql_fora + AND t.topic_id = p.topic_id + $sql_sort_join + $sql_time + GROUP BY t.topic_id, " . $sort_by_sql[$sort_key] . ' + ORDER BY ' . $sql_sort; + $field = 'topic_id'; + } + + // Only read one block of posts from the db and then cache it + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + + if (!$total_results && $is_mysql) + { + // Count rows for the executed queries. Replace $select within $sql with SQL_CALC_FOUND_ROWS, and run it. + $sql_calc = str_replace('SELECT ' . $select, 'SELECT SQL_CALC_FOUND_ROWS ' . $select, $sql); + + $result = $this->db->sql_query($sql_calc); + $this->db->sql_freeresult($result); + + $sql_count = 'SELECT FOUND_ROWS() as total_results'; + $result = $this->db->sql_query($sql_count); + $total_results = (int) $this->db->sql_fetchfield('total_results'); + $this->db->sql_freeresult($result); + + if (!$total_results) + { + return false; + } + } + + if ($start >= $total_results) + { + $start = floor(($total_results - 1) / $per_page) * $per_page; + + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + } + + if (sizeof($id_ary)) + { + $this->save_ids($search_key, '', $author_ary, $total_results, $id_ary, $start, $sort_dir); + $id_ary = array_slice($id_ary, 0, $per_page); + + return $total_results; + } + return false; + } + + /** + * Split a text into words of a given length + * + * The text is converted to UTF-8, cleaned up, and split. Then, words that + * conform to the defined length range are returned in an array. + * + * NOTE: duplicates are NOT removed from the return array + * + * @param string $text Text to split, encoded in UTF-8 + * @return array Array of UTF-8 words + */ + public function split_message($text) + { + $match = $words = array(); + + /** + * Taken from the original code + */ + // Do not index code + $match[] = '#\[code(?:=.*?)?(\:?[0-9a-z]{5,})\].*?\[\/code(\:?[0-9a-z]{5,})\]#is'; + // BBcode + $match[] = '#\[\/?[a-z0-9\*\+\-]+(?:=.*?)?(?::[a-z])?(\:?[0-9a-z]{5,})\]#'; + + $min = $this->word_length['min']; + $max = $this->word_length['max']; + + $isset_min = $min - 1; + + /** + * Clean up the string, remove HTML tags, remove BBCodes + */ + $word = strtok($this->cleanup(preg_replace($match, ' ', strip_tags($text)), -1), ' '); + + while (strlen($word)) + { + if (strlen($word) > 255 || strlen($word) <= $isset_min) + { + /** + * Words longer than 255 bytes are ignored. This will have to be + * changed whenever we change the length of search_wordlist.word_text + * + * Words shorter than $isset_min bytes are ignored, too + */ + $word = strtok(' '); + continue; + } + + $len = utf8_strlen($word); + + /** + * Test whether the word is too short to be indexed. + * + * Note that this limit does NOT apply to CJK and Hangul + */ + if ($len < $min) + { + /** + * Note: this could be optimized. If the codepoint is lower than Hangul's range + * we know that it will also be lower than CJK ranges + */ + if ((strncmp($word, UTF8_HANGUL_FIRST, 3) < 0 || strncmp($word, UTF8_HANGUL_LAST, 3) > 0) + && (strncmp($word, UTF8_CJK_FIRST, 3) < 0 || strncmp($word, UTF8_CJK_LAST, 3) > 0) + && (strncmp($word, UTF8_CJK_B_FIRST, 4) < 0 || strncmp($word, UTF8_CJK_B_LAST, 4) > 0)) + { + $word = strtok(' '); + continue; + } + } + + $words[] = $word; + $word = strtok(' '); + } + + return $words; + } + + /** + * Updates wordlist and wordmatch tables when a message is posted or changed + * + * @param string $mode Contains the post mode: edit, post, reply, quote + * @param int $post_id The id of the post which is modified/created + * @param string &$message New or updated post content + * @param string &$subject New or updated post subject + * @param int $poster_id Post author's user id + * @param int $forum_id The id of the forum in which the post is located + */ + public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id) + { + if (!$this->config['fulltext_native_load_upd']) + { + /** + * The search indexer is disabled, return + */ + return; + } + + // Split old and new post/subject to obtain array of 'words' + $split_text = $this->split_message($message); + $split_title = $this->split_message($subject); + + $cur_words = array('post' => array(), 'title' => array()); + + $words = array(); + if ($mode == 'edit') + { + $words['add']['post'] = array(); + $words['add']['title'] = array(); + $words['del']['post'] = array(); + $words['del']['title'] = array(); + + $sql = 'SELECT w.word_id, w.word_text, m.title_match + FROM ' . SEARCH_WORDLIST_TABLE . ' w, ' . SEARCH_WORDMATCH_TABLE . " m + WHERE m.post_id = $post_id + AND w.word_id = m.word_id"; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $which = ($row['title_match']) ? 'title' : 'post'; + $cur_words[$which][$row['word_text']] = $row['word_id']; + } + $this->db->sql_freeresult($result); + + $words['add']['post'] = array_diff($split_text, array_keys($cur_words['post'])); + $words['add']['title'] = array_diff($split_title, array_keys($cur_words['title'])); + $words['del']['post'] = array_diff(array_keys($cur_words['post']), $split_text); + $words['del']['title'] = array_diff(array_keys($cur_words['title']), $split_title); + } + else + { + $words['add']['post'] = $split_text; + $words['add']['title'] = $split_title; + $words['del']['post'] = array(); + $words['del']['title'] = array(); + } + unset($split_text); + unset($split_title); + + // Get unique words from the above arrays + $unique_add_words = array_unique(array_merge($words['add']['post'], $words['add']['title'])); + + // We now have unique arrays of all words to be added and removed and + // individual arrays of added and removed words for text and title. What + // we need to do now is add the new words (if they don't already exist) + // and then add (or remove) matches between the words and this post + if (sizeof($unique_add_words)) + { + $sql = 'SELECT word_id, word_text + FROM ' . SEARCH_WORDLIST_TABLE . ' + WHERE ' . $this->db->sql_in_set('word_text', $unique_add_words); + $result = $this->db->sql_query($sql); + + $word_ids = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $word_ids[$row['word_text']] = $row['word_id']; + } + $this->db->sql_freeresult($result); + $new_words = array_diff($unique_add_words, array_keys($word_ids)); + + $this->db->sql_transaction('begin'); + if (sizeof($new_words)) + { + $sql_ary = array(); + + foreach ($new_words as $word) + { + $sql_ary[] = array('word_text' => (string) $word, 'word_count' => 0); + } + $this->db->sql_return_on_error(true); + $this->db->sql_multi_insert(SEARCH_WORDLIST_TABLE, $sql_ary); + $this->db->sql_return_on_error(false); + } + unset($new_words, $sql_ary); + } + else + { + $this->db->sql_transaction('begin'); + } + + // now update the search match table, remove links to removed words and add links to new words + foreach ($words['del'] as $word_in => $word_ary) + { + $title_match = ($word_in == 'title') ? 1 : 0; + + if (sizeof($word_ary)) + { + $sql_in = array(); + foreach ($word_ary as $word) + { + $sql_in[] = $cur_words[$word_in][$word]; + } + + $sql = 'DELETE FROM ' . SEARCH_WORDMATCH_TABLE . ' + WHERE ' . $this->db->sql_in_set('word_id', $sql_in) . ' + AND post_id = ' . intval($post_id) . " + AND title_match = $title_match"; + $this->db->sql_query($sql); + + $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . ' + SET word_count = word_count - 1 + WHERE ' . $this->db->sql_in_set('word_id', $sql_in) . ' + AND word_count > 0'; + $this->db->sql_query($sql); + + unset($sql_in); + } + } + + $this->db->sql_return_on_error(true); + foreach ($words['add'] as $word_in => $word_ary) + { + $title_match = ($word_in == 'title') ? 1 : 0; + + if (sizeof($word_ary)) + { + $sql = 'INSERT INTO ' . SEARCH_WORDMATCH_TABLE . ' (post_id, word_id, title_match) + SELECT ' . (int) $post_id . ', word_id, ' . (int) $title_match . ' + FROM ' . SEARCH_WORDLIST_TABLE . ' + WHERE ' . $this->db->sql_in_set('word_text', $word_ary); + $this->db->sql_query($sql); + + $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . ' + SET word_count = word_count + 1 + WHERE ' . $this->db->sql_in_set('word_text', $word_ary); + $this->db->sql_query($sql); + } + } + $this->db->sql_return_on_error(false); + + $this->db->sql_transaction('commit'); + + // destroy cached search results containing any of the words removed or added + $this->destroy_cache(array_unique(array_merge($words['add']['post'], $words['add']['title'], $words['del']['post'], $words['del']['title'])), array($poster_id)); + + unset($unique_add_words); + unset($words); + unset($cur_words); + } + + /** + * Removes entries from the wordmatch table for the specified post_ids + */ + public function index_remove($post_ids, $author_ids, $forum_ids) + { + if (sizeof($post_ids)) + { + $sql = 'SELECT w.word_id, w.word_text, m.title_match + FROM ' . SEARCH_WORDMATCH_TABLE . ' m, ' . SEARCH_WORDLIST_TABLE . ' w + WHERE ' . $this->db->sql_in_set('m.post_id', $post_ids) . ' + AND w.word_id = m.word_id'; + $result = $this->db->sql_query($sql); + + $message_word_ids = $title_word_ids = $word_texts = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + if ($row['title_match']) + { + $title_word_ids[] = $row['word_id']; + } + else + { + $message_word_ids[] = $row['word_id']; + } + $word_texts[] = $row['word_text']; + } + $this->db->sql_freeresult($result); + + if (sizeof($title_word_ids)) + { + $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . ' + SET word_count = word_count - 1 + WHERE ' . $this->db->sql_in_set('word_id', $title_word_ids) . ' + AND word_count > 0'; + $this->db->sql_query($sql); + } + + if (sizeof($message_word_ids)) + { + $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . ' + SET word_count = word_count - 1 + WHERE ' . $this->db->sql_in_set('word_id', $message_word_ids) . ' + AND word_count > 0'; + $this->db->sql_query($sql); + } + + unset($title_word_ids); + unset($message_word_ids); + + $sql = 'DELETE FROM ' . SEARCH_WORDMATCH_TABLE . ' + WHERE ' . $this->db->sql_in_set('post_id', $post_ids); + $this->db->sql_query($sql); + } + + $this->destroy_cache(array_unique($word_texts), array_unique($author_ids)); + } + + /** + * Tidy up indexes: Tag 'common words' and remove + * words no longer referenced in the match table + */ + public function tidy() + { + // Is the fulltext indexer disabled? If yes then we need not + // carry on ... it's okay ... I know when I'm not wanted boo hoo + if (!$this->config['fulltext_native_load_upd']) + { + set_config('search_last_gc', time(), true); + return; + } + + $destroy_cache_words = array(); + + // Remove common words + if ($this->config['num_posts'] >= 100 && $this->config['fulltext_native_common_thres']) + { + $common_threshold = ((double) $this->config['fulltext_native_common_thres']) / 100.0; + // First, get the IDs of common words + $sql = 'SELECT word_id, word_text + FROM ' . SEARCH_WORDLIST_TABLE . ' + WHERE word_count > ' . floor($this->config['num_posts'] * $common_threshold) . ' + OR word_common = 1'; + $result = $this->db->sql_query($sql); + + $sql_in = array(); + while ($row = $this->db->sql_fetchrow($result)) + { + $sql_in[] = $row['word_id']; + $destroy_cache_words[] = $row['word_text']; + } + $this->db->sql_freeresult($result); + + if (sizeof($sql_in)) + { + // Flag the words + $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . ' + SET word_common = 1 + WHERE ' . $this->db->sql_in_set('word_id', $sql_in); + $this->db->sql_query($sql); + + // by setting search_last_gc to the new time here we make sure that if a user reloads because the + // following query takes too long, he won't run into it again + set_config('search_last_gc', time(), true); + + // Delete the matches + $sql = 'DELETE FROM ' . SEARCH_WORDMATCH_TABLE . ' + WHERE ' . $this->db->sql_in_set('word_id', $sql_in); + $this->db->sql_query($sql); + } + unset($sql_in); + } + + if (sizeof($destroy_cache_words)) + { + // destroy cached search results containing any of the words that are now common or were removed + $this->destroy_cache(array_unique($destroy_cache_words)); + } + + set_config('search_last_gc', time(), true); + } + + /** + * Deletes all words from the index + */ + public function delete_index($acp_module, $u_action) + { + switch ($this->db->get_sql_layer()) + { + case 'sqlite': + case 'sqlite3': + $this->db->sql_query('DELETE FROM ' . SEARCH_WORDLIST_TABLE); + $this->db->sql_query('DELETE FROM ' . SEARCH_WORDMATCH_TABLE); + $this->db->sql_query('DELETE FROM ' . SEARCH_RESULTS_TABLE); + break; + + default: + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_WORDLIST_TABLE); + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_WORDMATCH_TABLE); + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE); + break; + } + } + + /** + * Returns true if both FULLTEXT indexes exist + */ + public function index_created() + { + if (!sizeof($this->stats)) + { + $this->get_stats(); + } + + return ($this->stats['total_words'] && $this->stats['total_matches']) ? true : false; + } + + /** + * Returns an associative array containing information about the indexes + */ + public function index_stats() + { + if (!sizeof($this->stats)) + { + $this->get_stats(); + } + + return array( + $this->user->lang['TOTAL_WORDS'] => $this->stats['total_words'], + $this->user->lang['TOTAL_MATCHES'] => $this->stats['total_matches']); + } + + protected function get_stats() + { + $this->stats['total_words'] = $this->db->get_estimated_row_count(SEARCH_WORDLIST_TABLE); + $this->stats['total_matches'] = $this->db->get_estimated_row_count(SEARCH_WORDMATCH_TABLE); + } + + /** + * Clean up a text to remove non-alphanumeric characters + * + * This method receives a UTF-8 string, normalizes and validates it, replaces all + * non-alphanumeric characters with strings then returns the result. + * + * Any number of "allowed chars" can be passed as a UTF-8 string in NFC. + * + * @param string $text Text to split, in UTF-8 (not normalized or sanitized) + * @param string $allowed_chars String of special chars to allow + * @param string $encoding Text encoding + * @return string Cleaned up text, only alphanumeric chars are left + * + * @todo \normalizer::cleanup being able to be used? + */ + protected function cleanup($text, $allowed_chars = null, $encoding = 'utf-8') + { + static $conv = array(), $conv_loaded = array(); + $words = $allow = array(); + + // Convert the text to UTF-8 + $encoding = strtolower($encoding); + if ($encoding != 'utf-8') + { + $text = utf8_recode($text, $encoding); + } + + $utf_len_mask = array( + "\xC0" => 2, + "\xD0" => 2, + "\xE0" => 3, + "\xF0" => 4 + ); + + /** + * Replace HTML entities and NCRs + */ + $text = htmlspecialchars_decode(utf8_decode_ncr($text), ENT_QUOTES); + + /** + * Load the UTF-8 normalizer + * + * If we use it more widely, an instance of that class should be held in a + * a global variable instead + */ + \utf_normalizer::nfc($text); + + /** + * The first thing we do is: + * + * - convert ASCII-7 letters to lowercase + * - remove the ASCII-7 non-alpha characters + * - remove the bytes that should not appear in a valid UTF-8 string: 0xC0, + * 0xC1 and 0xF5-0xFF + * + * @todo in theory, the third one is already taken care of during normalization and those chars should have been replaced by Unicode replacement chars + */ + $sb_match = "ISTCPAMELRDOJBNHFGVWUQKYXZ\r\n\t!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\xC0\xC1\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"; + $sb_replace = 'istcpamelrdojbnhfgvwuqkyxz '; + + /** + * This is the list of legal ASCII chars, it is automatically extended + * with ASCII chars from $allowed_chars + */ + $legal_ascii = ' eaisntroludcpmghbfvq10xy2j9kw354867z'; + + /** + * Prepare an array containing the extra chars to allow + */ + if (isset($allowed_chars[0])) + { + $pos = 0; + $len = strlen($allowed_chars); + do + { + $c = $allowed_chars[$pos]; + + if ($c < "\x80") + { + /** + * ASCII char + */ + $sb_pos = strpos($sb_match, $c); + if (is_int($sb_pos)) + { + /** + * Remove the char from $sb_match and its corresponding + * replacement in $sb_replace + */ + $sb_match = substr($sb_match, 0, $sb_pos) . substr($sb_match, $sb_pos + 1); + $sb_replace = substr($sb_replace, 0, $sb_pos) . substr($sb_replace, $sb_pos + 1); + $legal_ascii .= $c; + } + + ++$pos; + } + else + { + /** + * UTF-8 char + */ + $utf_len = $utf_len_mask[$c & "\xF0"]; + $allow[substr($allowed_chars, $pos, $utf_len)] = 1; + $pos += $utf_len; + } + } + while ($pos < $len); + } + + $text = strtr($text, $sb_match, $sb_replace); + $ret = ''; + + $pos = 0; + $len = strlen($text); + + do + { + /** + * Do all consecutive ASCII chars at once + */ + if ($spn = strspn($text, $legal_ascii, $pos)) + { + $ret .= substr($text, $pos, $spn); + $pos += $spn; + } + + if ($pos >= $len) + { + return $ret; + } + + /** + * Capture the UTF char + */ + $utf_len = $utf_len_mask[$text[$pos] & "\xF0"]; + $utf_char = substr($text, $pos, $utf_len); + $pos += $utf_len; + + if (($utf_char >= UTF8_HANGUL_FIRST && $utf_char <= UTF8_HANGUL_LAST) + || ($utf_char >= UTF8_CJK_FIRST && $utf_char <= UTF8_CJK_LAST) + || ($utf_char >= UTF8_CJK_B_FIRST && $utf_char <= UTF8_CJK_B_LAST)) + { + /** + * All characters within these ranges are valid + * + * We separate them with a space in order to index each character + * individually + */ + $ret .= ' ' . $utf_char . ' '; + continue; + } + + if (isset($allow[$utf_char])) + { + /** + * The char is explicitly allowed + */ + $ret .= $utf_char; + continue; + } + + if (isset($conv[$utf_char])) + { + /** + * The char is mapped to something, maybe to itself actually + */ + $ret .= $conv[$utf_char]; + continue; + } + + /** + * The char isn't mapped, but did we load its conversion table? + * + * The search indexer table is split into blocks. The block number of + * each char is equal to its codepoint right-shifted for 11 bits. It + * means that out of the 11, 16 or 21 meaningful bits of a 2-, 3- or + * 4- byte sequence we only keep the leftmost 0, 5 or 10 bits. Thus, + * all UTF chars encoded in 2 bytes are in the same first block. + */ + if (isset($utf_char[2])) + { + if (isset($utf_char[3])) + { + /** + * 1111 0nnn 10nn nnnn 10nx xxxx 10xx xxxx + * 0000 0111 0011 1111 0010 0000 + */ + $idx = ((ord($utf_char[0]) & 0x07) << 7) | ((ord($utf_char[1]) & 0x3F) << 1) | ((ord($utf_char[2]) & 0x20) >> 5); + } + else + { + /** + * 1110 nnnn 10nx xxxx 10xx xxxx + * 0000 0111 0010 0000 + */ + $idx = ((ord($utf_char[0]) & 0x07) << 1) | ((ord($utf_char[1]) & 0x20) >> 5); + } + } + else + { + /** + * 110x xxxx 10xx xxxx + * 0000 0000 0000 0000 + */ + $idx = 0; + } + + /** + * Check if the required conv table has been loaded already + */ + if (!isset($conv_loaded[$idx])) + { + $conv_loaded[$idx] = 1; + $file = $this->phpbb_root_path . 'includes/utf/data/search_indexer_' . $idx . '.' . $this->php_ext; + + if (file_exists($file)) + { + $conv += include($file); + } + } + + if (isset($conv[$utf_char])) + { + $ret .= $conv[$utf_char]; + } + else + { + /** + * We add an entry to the conversion table so that we + * don't have to convert to codepoint and perform the checks + * that are above this block + */ + $conv[$utf_char] = ' '; + $ret .= ' '; + } + } + while (1); + + return $ret; + } + + /** + * Returns a list of options for the ACP to display + */ + public function acp() + { + /** + * if we need any options, copied from fulltext_native for now, will have to be adjusted or removed + */ + + $tpl = ' + <dl> + <dt><label for="fulltext_native_load_upd">' . $this->user->lang['YES_SEARCH_UPDATE'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['YES_SEARCH_UPDATE_EXPLAIN'] . '</span></dt> + <dd><label><input type="radio" id="fulltext_native_load_upd" name="config[fulltext_native_load_upd]" value="1"' . (($this->config['fulltext_native_load_upd']) ? ' checked="checked"' : '') . ' class="radio" /> ' . $this->user->lang['YES'] . '</label><label><input type="radio" name="config[fulltext_native_load_upd]" value="0"' . ((!$this->config['fulltext_native_load_upd']) ? ' checked="checked"' : '') . ' class="radio" /> ' . $this->user->lang['NO'] . '</label></dd> + </dl> + <dl> + <dt><label for="fulltext_native_min_chars">' . $this->user->lang['MIN_SEARCH_CHARS'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['MIN_SEARCH_CHARS_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_native_min_chars" type="number" min="0" max="255" name="config[fulltext_native_min_chars]" value="' . (int) $this->config['fulltext_native_min_chars'] . '" /></dd> + </dl> + <dl> + <dt><label for="fulltext_native_max_chars">' . $this->user->lang['MAX_SEARCH_CHARS'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['MAX_SEARCH_CHARS_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_native_max_chars" type="number" min="0" max="255" name="config[fulltext_native_max_chars]" value="' . (int) $this->config['fulltext_native_max_chars'] . '" /></dd> + </dl> + <dl> + <dt><label for="fulltext_native_common_thres">' . $this->user->lang['COMMON_WORD_THRESHOLD'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['COMMON_WORD_THRESHOLD_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_native_common_thres" type="text" name="config[fulltext_native_common_thres]" value="' . (double) $this->config['fulltext_native_common_thres'] . '" /> %</dd> + </dl> + '; + + // These are fields required in the config table + return array( + 'tpl' => $tpl, + 'config' => array('fulltext_native_load_upd' => 'bool', 'fulltext_native_min_chars' => 'integer:0:255', 'fulltext_native_max_chars' => 'integer:0:255', 'fulltext_native_common_thres' => 'double:0:100') + ); + } +} diff --git a/phpBB/phpbb/search/fulltext_postgres.php b/phpBB/phpbb/search/fulltext_postgres.php new file mode 100644 index 0000000000..04441e6226 --- /dev/null +++ b/phpBB/phpbb/search/fulltext_postgres.php @@ -0,0 +1,1106 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search; + +/** +* Fulltext search for PostgreSQL +*/ +class fulltext_postgres extends \phpbb\search\base +{ + /** + * Associative array holding index stats + * @var array + */ + protected $stats = array(); + + /** + * Holds the words entered by user, obtained by splitting the entered query on whitespace + * @var array + */ + protected $split_words = array(); + + /** + * Stores the tsearch query + * @var string + */ + protected $tsearch_query; + + /** + * True if phrase search is supported. + * PostgreSQL fulltext currently doesn't support it + * @var boolean + */ + protected $phrase_search = false; + + /** + * Config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Database connection + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * phpBB event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $phpbb_dispatcher; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Contains tidied search query. + * Operators are prefixed in search query and common words excluded + * @var string + */ + protected $search_query; + + /** + * Contains common words. + * Common words are words with length less/more than min/max length + * @var array + */ + protected $common_words = array(); + + /** + * Associative array stores the min and max word length to be searched + * @var array + */ + protected $word_length = array(); + + /** + * Constructor + * Creates a new \phpbb\search\fulltext_postgres, which is used as a search backend + * + * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $phpEx PHP file extension + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\config\config $config Config object + * @param \phpbb\db\driver\driver_interface Database object + * @param \phpbb\user $user User object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object + */ + public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher) + { + $this->config = $config; + $this->db = $db; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->user = $user; + + $this->word_length = array('min' => $this->config['fulltext_postgres_min_word_len'], 'max' => $this->config['fulltext_postgres_max_word_len']); + + /** + * Load the UTF tools + */ + if (!function_exists('utf8_strlen')) + { + include($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx); + } + + $error = false; + } + + /** + * Returns the name of this search backend to be displayed to administrators + * + * @return string Name + */ + public function get_name() + { + return 'PostgreSQL Fulltext'; + } + + /** + * Returns the search_query + * + * @return string search query + */ + public function get_search_query() + { + return $this->search_query; + } + + /** + * Returns the common_words array + * + * @return array common words that are ignored by search backend + */ + public function get_common_words() + { + return $this->common_words; + } + + /** + * Returns the word_length array + * + * @return array min and max word length for searching + */ + public function get_word_length() + { + return $this->word_length; + } + + /** + * Returns if phrase search is supported or not + * + * @return bool + */ + public function supports_phrase_search() + { + return $this->phrase_search; + } + + /** + * Checks for correct PostgreSQL version and stores min/max word length in the config + * + * @return string|bool Language key of the error/incompatiblity occurred + */ + public function init() + { + if ($this->db->get_sql_layer() != 'postgres') + { + return $this->user->lang['FULLTEXT_POSTGRES_INCOMPATIBLE_DATABASE']; + } + + return false; + } + + /** + * Splits keywords entered by a user into an array of words stored in $this->split_words + * Stores the tidied search query in $this->search_query + * + * @param string &$keywords Contains the keyword as entered by the user + * @param string $terms is either 'all' or 'any' + * @return bool false if no valid keywords were found and otherwise true + */ + public function split_keywords(&$keywords, $terms) + { + if ($terms == 'all') + { + $match = array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#(^|\s)\+#', '#(^|\s)-#', '#(^|\s)\|#'); + $replace = array(' +', ' |', ' -', ' +', ' -', ' |'); + + $keywords = preg_replace($match, $replace, $keywords); + } + + // Filter out as above + $split_keywords = preg_replace("#[\"\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords))); + + // Split words + $split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords))); + $matches = array(); + preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches); + $this->split_words = $matches[1]; + + foreach ($this->split_words as $i => $word) + { + $clean_word = preg_replace('#^[+\-|"]#', '', $word); + + // check word length + $clean_len = utf8_strlen(str_replace('*', '', $clean_word)); + if (($clean_len < $this->config['fulltext_postgres_min_word_len']) || ($clean_len > $this->config['fulltext_postgres_max_word_len'])) + { + $this->common_words[] = $word; + unset($this->split_words[$i]); + } + } + + if ($terms == 'any') + { + $this->search_query = ''; + $this->tsearch_query = ''; + foreach ($this->split_words as $word) + { + if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0)) + { + $word = substr($word, 1); + } + $this->search_query .= $word . ' '; + $this->tsearch_query .= '|' . $word . ' '; + } + } + else + { + $this->search_query = ''; + $this->tsearch_query = ''; + foreach ($this->split_words as $word) + { + if (strpos($word, '+') === 0) + { + $this->search_query .= $word . ' '; + $this->tsearch_query .= '&' . substr($word, 1) . ' '; + } + else if (strpos($word, '-') === 0) + { + $this->search_query .= $word . ' '; + $this->tsearch_query .= '&!' . substr($word, 1) . ' '; + } + else if (strpos($word, '|') === 0) + { + $this->search_query .= $word . ' '; + $this->tsearch_query .= '|' . substr($word, 1) . ' '; + } + else + { + $this->search_query .= '+' . $word . ' '; + $this->tsearch_query .= '&' . $word . ' '; + } + } + } + + $this->tsearch_query = substr($this->tsearch_query, 1); + $this->search_query = utf8_htmlspecialchars($this->search_query); + + if ($this->search_query) + { + $this->split_words = array_values($this->split_words); + sort($this->split_words); + return true; + } + return false; + } + + /** + * Turns text into an array of words + * @param string $text contains post text/subject + */ + public function split_message($text) + { + // Split words + $text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text))); + $matches = array(); + preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches); + $text = $matches[1]; + + // remove too short or too long words + $text = array_values($text); + for ($i = 0, $n = sizeof($text); $i < $n; $i++) + { + $text[$i] = trim($text[$i]); + if (utf8_strlen($text[$i]) < $this->config['fulltext_postgres_min_word_len'] || utf8_strlen($text[$i]) > $this->config['fulltext_postgres_max_word_len']) + { + unset($text[$i]); + } + } + + return array_values($text); + } + + /** + * Performs a search on keywords depending on display specific params. You have to run split_keywords() first + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched) + * @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words) + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No keywords? No posts + if (!$this->search_query) + { + return false; + } + + // When search query contains queries like -foo + if (strpos($this->search_query, '+') === false) + { + return false; + } + + // generate a search_key from all the options to identify the results + $search_key_array = array( + implode(', ', $this->split_words), + $type, + $fields, + $terms, + $sort_days, + $sort_key, + $topic_id, + implode(',', $ex_fid_ary), + $post_visibility, + implode(',', $author_ary) + ); + + /** + * Allow changing the search_key for cached results + * + * @event core.search_postgres_by_keyword_modify_search_key + * @var array search_key_array Array with search parameters to generate the search_key + * @var string type Searching type ('posts', 'topics') + * @var string fields Searching fields ('titleonly', 'msgonly', 'firstpost', 'all') + * @var string terms Searching terms ('all', 'any') + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @since 3.1.7-RC1 + */ + $vars = array( + 'search_key_array', + 'type', + 'fields', + 'terms', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_by_keyword_modify_search_key', compact($vars))); + + $search_key = md5(implode('#', $search_key_array)); + + if ($start < 0) + { + $start = 0; + } + + // try reading the results from cache + $result_count = 0; + if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE) + { + return $result_count; + } + + $id_ary = array(); + + $join_topic = ($type == 'posts') ? false : true; + + // Build sql strings for sorting + $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC'); + $sql_sort_table = $sql_sort_join = ''; + + switch ($sql_sort[0]) + { + case 'u': + $sql_sort_table = USERS_TABLE . ' u, '; + $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster '; + break; + + case 't': + $join_topic = true; + break; + + case 'f': + $sql_sort_table = FORUMS_TABLE . ' f, '; + $sql_sort_join = ' AND f.forum_id = p.forum_id '; + break; + } + + // Build some display specific sql strings + switch ($fields) + { + case 'titleonly': + $sql_match = 'p.post_subject'; + $sql_match_where = ' AND p.post_id = t.topic_first_post_id'; + $join_topic = true; + break; + + case 'msgonly': + $sql_match = 'p.post_text'; + $sql_match_where = ''; + break; + + case 'firstpost': + $sql_match = 'p.post_subject, p.post_text'; + $sql_match_where = ' AND p.post_id = t.topic_first_post_id'; + $join_topic = true; + break; + + default: + $sql_match = 'p.post_subject, p.post_text'; + $sql_match_where = ''; + break; + } + + $tsearch_query = $this->tsearch_query; + + /** + * Allow changing the query used to search for posts using fulltext_postgres + * + * @event core.search_postgres_keywords_main_query_before + * @var string tsearch_query The parsed keywords used for this search + * @var int result_count The previous result count for the format of the query. + * Set to 0 to force a re-count + * @var bool join_topic Weather or not TOPICS_TABLE should be CROSS JOIN'ED + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name An extra username to search on (!empty(author_ary) must be true, to be relevant) + * @var array ex_fid_ary Which forums not to search on + * @var int topic_id Limit the search to this topic_id only + * @var string sql_sort_table Extra tables to include in the SQL query. + * Used in conjunction with sql_sort_join + * @var string sql_sort_join SQL conditions to join all the tables used together. + * Used in conjunction with sql_sort_table + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sql_match Which columns to do the search on. + * @var string sql_match_where Extra conditions to use to properly filter the matching process + * @var string sort_by_sql The possible predefined sort types + * @var string sort_key The sort type used from the possible sort types + * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used + * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir + * @var int start How many posts to skip in the search results (used for pagination) + * @since 3.1.5-RC1 + */ + $vars = array( + 'tsearch_query', + 'result_count', + 'join_topic', + 'author_ary', + 'author_name', + 'ex_fid_ary', + 'topic_id', + 'sql_sort_table', + 'sql_sort_join', + 'sort_days', + 'sql_match', + 'sql_match_where', + 'sort_by_sql', + 'sort_key', + 'sort_dir', + 'sql_sort', + 'start', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_keywords_main_query_before', compact($vars))); + + $sql_select = ($type == 'posts') ? 'p.post_id' : 'DISTINCT t.topic_id'; + $sql_from = ($join_topic) ? TOPICS_TABLE . ' t, ' : ''; + $field = ($type == 'posts') ? 'post_id' : 'topic_id'; + $sql_author = (sizeof($author_ary) == 1) ? ' = ' . $author_ary[0] : 'IN (' . implode(', ', $author_ary) . ')'; + + if (sizeof($author_ary) && $author_name) + { + // first one matches post of registered users, second one guests and deleted users + $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')'; + } + else if (sizeof($author_ary)) + { + $sql_author = ' AND ' . $this->db->sql_in_set('p.poster_id', $author_ary); + } + else + { + $sql_author = ''; + } + + $sql_where_options = $sql_sort_join; + $sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : ''; + $sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : ''; + $sql_where_options .= (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : ''; + $sql_where_options .= ' AND ' . $post_visibility; + $sql_where_options .= $sql_author; + $sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : ''; + $sql_where_options .= $sql_match_where; + + $tmp_sql_match = array(); + $sql_match = str_replace(',', " || ' ' ||", $sql_match); + $tmp_sql_match = "to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', " . $sql_match . ") @@ to_tsquery ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', '" . $this->db->sql_escape($this->tsearch_query) . "')"; + + $this->db->sql_transaction('begin'); + + $sql_from = "FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p"; + $sql_where = "WHERE (" . $tmp_sql_match . ") + $sql_where_options"; + $sql = "SELECT $sql_select + $sql_from + $sql_where + ORDER BY $sql_sort"; + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = $row[$field]; + } + $this->db->sql_freeresult($result); + + $id_ary = array_unique($id_ary); + + // if the total result count is not cached yet, retrieve it from the db + if (!$result_count) + { + $sql_count = "SELECT COUNT(*) as result_count + $sql_from + $sql_where"; + $result = $this->db->sql_query($sql_count); + $result_count = (int) $this->db->sql_fetchfield('result_count'); + $this->db->sql_freeresult($result); + + if (!$result_count) + { + return false; + } + } + + $this->db->sql_transaction('commit'); + + if ($start >= $result_count) + { + $start = floor(($result_count - 1) / $per_page) * $per_page; + + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = $row[$field]; + } + $this->db->sql_freeresult($result); + + $id_ary = array_unique($id_ary); + } + + // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page + $this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir); + $id_ary = array_slice($id_ary, 0, (int) $per_page); + + return $result_count; + } + + /** + * Performs a search on an author's posts without caring about message contents. Depends on display specific params + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param boolean $firstpost_only if true, only topic starting posts will be considered + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No author? No posts + if (!sizeof($author_ary)) + { + return 0; + } + + // generate a search_key from all the options to identify the results + $search_key_array = array( + '', + $type, + ($firstpost_only) ? 'firstpost' : '', + '', + '', + $sort_days, + $sort_key, + $topic_id, + implode(',', $ex_fid_ary), + $post_visibility, + implode(',', $author_ary), + $author_name, + ); + + /** + * Allow changing the search_key for cached results + * + * @event core.search_postgres_by_author_modify_search_key + * @var array search_key_array Array with search parameters to generate the search_key + * @var string type Searching type ('posts', 'topics') + * @var boolean firstpost_only Flag indicating if only topic starting posts are considered + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name The username to search on + * @since 3.1.7-RC1 + */ + $vars = array( + 'search_key_array', + 'type', + 'firstpost_only', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + 'author_name', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_by_author_modify_search_key', compact($vars))); + + $search_key = md5(implode('#', $search_key_array)); + + if ($start < 0) + { + $start = 0; + } + + // try reading the results from cache + $result_count = 0; + if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE) + { + return $result_count; + } + + $id_ary = array(); + + // Create some display specific sql strings + if ($author_name) + { + // first one matches post of registered users, second one guests and deleted users + $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')'; + } + else + { + $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary); + } + $sql_fora = (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : ''; + $sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : ''; + $sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : ''; + $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : ''; + + // Build sql strings for sorting + $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC'); + $sql_sort_table = $sql_sort_join = ''; + switch ($sql_sort[0]) + { + case 'u': + $sql_sort_table = USERS_TABLE . ' u, '; + $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster '; + break; + + case 't': + $sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : ''; + $sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : ''; + break; + + case 'f': + $sql_sort_table = FORUMS_TABLE . ' f, '; + $sql_sort_join = ' AND f.forum_id = p.forum_id '; + break; + } + + $m_approve_fid_sql = ' AND ' . $post_visibility; + + /** + * Allow changing the query used to search for posts by author in fulltext_postgres + * + * @event core.search_postgres_author_count_query_before + * @var int result_count The previous result count for the format of the query. + * Set to 0 to force a re-count + * @var string sql_sort_table CROSS JOIN'ed table to allow doing the sort chosen + * @var string sql_sort_join Condition to define how to join the CROSS JOIN'ed table specifyed in sql_sort_table + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name An extra username to search on + * @var string sql_author SQL WHERE condition for the post author ids + * @var int topic_id Limit the search to this topic_id only + * @var string sql_topic_id SQL of topic_id + * @var string sort_by_sql The possible predefined sort types + * @var string sort_key The sort type used from the possible sort types + * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used + * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir + * @var string sort_days Time, in days, that the oldest post showing can have + * @var string sql_time The SQL to search on the time specifyed by sort_days + * @var bool firstpost_only Wether or not to search only on the first post of the topics + * @var array ex_fid_ary Forum ids that must not be searched on + * @var array sql_fora SQL query for ex_fid_ary + * @var string m_approve_fid_sql WHERE clause condition on post_visibility restrictions + * @var int start How many posts to skip in the search results (used for pagination) + * @since 3.1.5-RC1 + */ + $vars = array( + 'result_count', + 'sql_sort_table', + 'sql_sort_join', + 'author_ary', + 'author_name', + 'sql_author', + 'topic_id', + 'sql_topic_id', + 'sort_by_sql', + 'sort_key', + 'sort_dir', + 'sql_sort', + 'sort_days', + 'sql_time', + 'firstpost_only', + 'ex_fid_ary', + 'sql_fora', + 'm_approve_fid_sql', + 'start', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_author_count_query_before', compact($vars))); + + // Build the query for really selecting the post_ids + if ($type == 'posts') + { + $sql = "SELECT p.post_id + FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . " + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $m_approve_fid_sql + $sql_fora + $sql_sort_join + $sql_time + ORDER BY $sql_sort"; + $field = 'post_id'; + } + else + { + $sql = "SELECT t.topic_id + FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $m_approve_fid_sql + $sql_fora + AND t.topic_id = p.topic_id + $sql_sort_join + $sql_time + GROUP BY t.topic_id, $sort_by_sql[$sort_key] + ORDER BY $sql_sort"; + $field = 'topic_id'; + } + + $this->db->sql_transaction('begin'); + + // Only read one block of posts from the db and then cache it + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = $row[$field]; + } + $this->db->sql_freeresult($result); + + // retrieve the total result count if needed + if (!$result_count) + { + if ($type == 'posts') + { + $sql_count = "SELECT COUNT(*) as result_count + FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . " + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $m_approve_fid_sql + $sql_fora + $sql_sort_join + $sql_time"; + } + else + { + $sql_count = "SELECT COUNT(*) as result_count + FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p + WHERE $sql_author + $sql_topic_id + $sql_firstpost + $m_approve_fid_sql + $sql_fora + AND t.topic_id = p.topic_id + $sql_sort_join + $sql_time + GROUP BY t.topic_id, $sort_by_sql[$sort_key]"; + } + + $result = $this->db->sql_query($sql_count); + $result_count = (int) $this->db->sql_fetchfield('result_count'); + + if (!$result_count) + { + return false; + } + } + + $this->db->sql_transaction('commit'); + + if ($start >= $result_count) + { + $start = floor(($result_count - 1) / $per_page) * $per_page; + + $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start); + while ($row = $this->db->sql_fetchrow($result)) + { + $id_ary[] = (int) $row[$field]; + } + $this->db->sql_freeresult($result); + + $id_ary = array_unique($id_ary); + } + + if (sizeof($id_ary)) + { + $this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir); + $id_ary = array_slice($id_ary, 0, $per_page); + + return $result_count; + } + return false; + } + + /** + * Destroys cached search results, that contained one of the new words in a post so the results won't be outdated + * + * @param string $mode contains the post mode: edit, post, reply, quote ... + * @param int $post_id contains the post id of the post to index + * @param string $message contains the post text of the post + * @param string $subject contains the subject of the post to index + * @param int $poster_id contains the user id of the poster + * @param int $forum_id contains the forum id of parent forum of the post + */ + public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id) + { + // Split old and new post/subject to obtain array of words + $split_text = $this->split_message($message); + $split_title = ($subject) ? $this->split_message($subject) : array(); + + $words = array_unique(array_merge($split_text, $split_title)); + + unset($split_text); + unset($split_title); + + // destroy cached search results containing any of the words removed or added + $this->destroy_cache($words, array($poster_id)); + + unset($words); + } + + /** + * Destroy cached results, that might be outdated after deleting a post + */ + public function index_remove($post_ids, $author_ids, $forum_ids) + { + $this->destroy_cache(array(), $author_ids); + } + + /** + * Destroy old cache entries + */ + public function tidy() + { + // destroy too old cached search results + $this->destroy_cache(array()); + + set_config('search_last_gc', time(), true); + } + + /** + * Create fulltext index + * + * @return string|bool error string is returned incase of errors otherwise false + */ + public function create_index($acp_module, $u_action) + { + // Make sure we can actually use PostgreSQL with fulltext indexes + if ($error = $this->init()) + { + return $error; + } + + if (empty($this->stats)) + { + $this->get_stats(); + } + + if (!isset($this->stats['post_subject'])) + { + $this->db->sql_query("CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_subject ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_subject))"); + } + + if (!isset($this->stats['post_content'])) + { + $this->db->sql_query("CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_content ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_text || ' ' || post_subject))"); + } + + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE); + + return false; + } + + /** + * Drop fulltext index + * + * @return string|bool error string is returned incase of errors otherwise false + */ + public function delete_index($acp_module, $u_action) + { + // Make sure we can actually use PostgreSQL with fulltext indexes + if ($error = $this->init()) + { + return $error; + } + + if (empty($this->stats)) + { + $this->get_stats(); + } + + if (isset($this->stats['post_subject'])) + { + $this->db->sql_query('DROP INDEX ' . $this->stats['post_subject']['relname']); + } + + if (isset($this->stats['post_content'])) + { + $this->db->sql_query('DROP INDEX ' . $this->stats['post_content']['relname']); + } + + $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE); + + return false; + } + + /** + * Returns true if both FULLTEXT indexes exist + */ + public function index_created() + { + if (empty($this->stats)) + { + $this->get_stats(); + } + + return (isset($this->stats['post_subject']) && isset($this->stats['post_content'])) ? true : false; + } + + /** + * Returns an associative array containing information about the indexes + */ + public function index_stats() + { + if (empty($this->stats)) + { + $this->get_stats(); + } + + return array( + $this->user->lang['FULLTEXT_POSTGRES_TOTAL_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] : 0, + ); + } + + /** + * Computes the stats and store them in the $this->stats associative array + */ + protected function get_stats() + { + if ($this->db->get_sql_layer() != 'postgres') + { + $this->stats = array(); + return; + } + + $sql = "SELECT c2.relname, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS indexdef + FROM pg_catalog.pg_class c1, pg_catalog.pg_index i, pg_catalog.pg_class c2 + WHERE c1.relname = '" . POSTS_TABLE . "' + AND pg_catalog.pg_table_is_visible(c1.oid) + AND c1.oid = i.indrelid + AND i.indexrelid = c2.oid"; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + // deal with older PostgreSQL versions which didn't use Index_type + if (strpos($row['indexdef'], 'to_tsvector') !== false) + { + if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_subject' || $row['relname'] == POSTS_TABLE . '_post_subject') + { + $this->stats['post_subject'] = $row; + } + else if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_content' || $row['relname'] == POSTS_TABLE . '_post_content') + { + $this->stats['post_content'] = $row; + } + } + } + $this->db->sql_freeresult($result); + + $this->stats['total_posts'] = $this->config['num_posts']; + } + + /** + * Display various options that can be configured for the backend from the acp + * + * @return associative array containing template and config variables + */ + public function acp() + { + $tpl = ' + <dl> + <dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK_EXPLAIN'] . '</span></dt> + <dd>' . (($this->db->get_sql_layer() == 'postgres') ? $this->user->lang['YES'] : $this->user->lang['NO']) . '</dd> + </dl> + <dl> + <dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME_EXPLAIN'] . '</span></dt> + <dd><select name="config[fulltext_postgres_ts_name]">'; + + if ($this->db->get_sql_layer() == 'postgres') + { + $sql = 'SELECT cfgname AS ts_name + FROM pg_ts_config'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $tpl .= '<option value="' . $row['ts_name'] . '"' . ($row['ts_name'] === $this->config['fulltext_postgres_ts_name'] ? ' selected="selected"' : '') . '>' . $row['ts_name'] . '</option>'; + } + $this->db->sql_freeresult($result); + } + else + { + $tpl .= '<option value="' . $this->config['fulltext_postgres_ts_name'] . '" selected="selected">' . $this->config['fulltext_postgres_ts_name'] . '</option>'; + } + + $tpl .= '</select></dd> + </dl> + <dl> + <dt><label for="fulltext_postgres_min_word_len">' . $this->user->lang['FULLTEXT_POSTGRES_MIN_WORD_LEN'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_MIN_WORD_LEN_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_postgres_min_word_len" type="number" min="0" max="255" name="config[fulltext_postgres_min_word_len]" value="' . (int) $this->config['fulltext_postgres_min_word_len'] . '" /></dd> + </dl> + <dl> + <dt><label for="fulltext_postgres_max_word_len">' . $this->user->lang['FULLTEXT_POSTGRES_MAX_WORD_LEN'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_MAX_WORD_LEN_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_postgres_max_word_len" type="number" min="0" max="255" name="config[fulltext_postgres_max_word_len]" value="' . (int) $this->config['fulltext_postgres_max_word_len'] . '" /></dd> + </dl> + '; + + // These are fields required in the config table + return array( + 'tpl' => $tpl, + 'config' => array('fulltext_postgres_ts_name' => 'string', 'fulltext_postgres_min_word_len' => 'integer:0:255', 'fulltext_postgres_max_word_len' => 'integer:0:255') + ); + } +} diff --git a/phpBB/phpbb/search/fulltext_sphinx.php b/phpBB/phpbb/search/fulltext_sphinx.php new file mode 100644 index 0000000000..0dbc6e33df --- /dev/null +++ b/phpBB/phpbb/search/fulltext_sphinx.php @@ -0,0 +1,973 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search; + +define('SPHINX_MAX_MATCHES', 20000); +define('SPHINX_CONNECT_RETRIES', 3); +define('SPHINX_CONNECT_WAIT_TIME', 300); + +/** +* Fulltext search based on the sphinx search deamon +*/ +class fulltext_sphinx +{ + /** + * Associative array holding index stats + * @var array + */ + protected $stats = array(); + + /** + * Holds the words entered by user, obtained by splitting the entered query on whitespace + * @var array + */ + protected $split_words = array(); + + /** + * Holds unique sphinx id + * @var string + */ + protected $id; + + /** + * Stores the names of both main and delta sphinx indexes + * separated by a semicolon + * @var string + */ + protected $indexes; + + /** + * Sphinx searchd client object + * @var SphinxClient + */ + protected $sphinx; + + /** + * Relative path to board root + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP Extension + * @var string + */ + protected $php_ext; + + /** + * Auth object + * @var \phpbb\auth\auth + */ + protected $auth; + + /** + * Config object + * @var \phpbb\config\config + */ + protected $config; + + /** + * Database connection + * @var \phpbb\db\driver\driver_interface + */ + protected $db; + + /** + * Database Tools object + * @var \phpbb\db\tools + */ + protected $db_tools; + + /** + * Stores the database type if supported by sphinx + * @var string + */ + protected $dbtype; + + /** + * phpBB event dispatcher object + * @var \phpbb\event\dispatcher_interface + */ + protected $phpbb_dispatcher; + + /** + * User object + * @var \phpbb\user + */ + protected $user; + + /** + * Stores the generated content of the sphinx config file + * @var string + */ + protected $config_file_data = ''; + + /** + * Contains tidied search query. + * Operators are prefixed in search query and common words excluded + * @var string + */ + protected $search_query; + + /** + * Constructor + * Creates a new \phpbb\search\fulltext_postgres, which is used as a search backend + * + * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false + * @param string $phpbb_root_path Relative path to phpBB root + * @param string $phpEx PHP file extension + * @param \phpbb\auth\auth $auth Auth object + * @param \phpbb\config\config $config Config object + * @param \phpbb\db\driver\driver_interface Database object + * @param \phpbb\user $user User object + * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object + */ + public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher) + { + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $phpEx; + $this->config = $config; + $this->phpbb_dispatcher = $phpbb_dispatcher; + $this->user = $user; + $this->db = $db; + $this->auth = $auth; + + // Initialize \phpbb\db\tools object + $this->db_tools = new \phpbb\db\tools($this->db); + + if (!$this->config['fulltext_sphinx_id']) + { + set_config('fulltext_sphinx_id', unique_id()); + } + $this->id = $this->config['fulltext_sphinx_id']; + $this->indexes = 'index_phpbb_' . $this->id . '_delta;index_phpbb_' . $this->id . '_main'; + + if (!class_exists('SphinxClient')) + { + require($this->phpbb_root_path . 'includes/sphinxapi.' . $this->php_ext); + } + + // Initialize sphinx client + $this->sphinx = new \SphinxClient(); + + $this->sphinx->SetServer(($this->config['fulltext_sphinx_host'] ? $this->config['fulltext_sphinx_host'] : 'localhost'), ($this->config['fulltext_sphinx_port'] ? (int) $this->config['fulltext_sphinx_port'] : 9312)); + + $error = false; + } + + /** + * Returns the name of this search backend to be displayed to administrators + * + * @return string Name + */ + public function get_name() + { + return 'Sphinx Fulltext'; + } + + /** + * Returns the search_query + * + * @return string search query + */ + public function get_search_query() + { + return $this->search_query; + } + + /** + * Returns false as there is no word_len array + * + * @return false + */ + public function get_word_length() + { + return false; + } + + /** + * Returns an empty array as there are no common_words + * + * @return array common words that are ignored by search backend + */ + public function get_common_words() + { + return array(); + } + + /** + * Checks permissions and paths, if everything is correct it generates the config file + * + * @return string|bool Language key of the error/incompatiblity encountered, or false if successful + */ + public function init() + { + if ($this->db->get_sql_layer() != 'mysql' && $this->db->get_sql_layer() != 'mysql4' && $this->db->get_sql_layer() != 'mysqli' && $this->db->get_sql_layer() != 'postgres') + { + return $this->user->lang['FULLTEXT_SPHINX_WRONG_DATABASE']; + } + + // Move delta to main index each hour + set_config('search_gc', 3600); + + return false; + } + + /** + * Generates content of sphinx.conf + * + * @return bool True if sphinx.conf content is correctly generated, false otherwise + */ + protected function config_generate() + { + // Check if Database is supported by Sphinx + if ($this->db->get_sql_layer() =='mysql' || $this->db->get_sql_layer() == 'mysql4' || $this->db->get_sql_layer() == 'mysqli') + { + $this->dbtype = 'mysql'; + } + else if ($this->db->get_sql_layer() == 'postgres') + { + $this->dbtype = 'pgsql'; + } + else + { + $this->config_file_data = $this->user->lang('FULLTEXT_SPHINX_WRONG_DATABASE'); + return false; + } + + // Check if directory paths have been filled + if (!$this->config['fulltext_sphinx_data_path']) + { + $this->config_file_data = $this->user->lang('FULLTEXT_SPHINX_NO_CONFIG_DATA'); + return false; + } + + include($this->phpbb_root_path . 'config.' . $this->php_ext); + + /* Now that we're sure everything was entered correctly, + generate a config for the index. We use a config value + fulltext_sphinx_id for this, as it should be unique. */ + $config_object = new \phpbb\search\sphinx\config($this->config_file_data); + $config_data = array( + 'source source_phpbb_' . $this->id . '_main' => array( + array('type', $this->dbtype . ' # mysql or pgsql'), + // This config value sql_host needs to be changed incase sphinx and sql are on different servers + array('sql_host', $dbhost . ' # SQL server host sphinx connects to'), + array('sql_user', '[dbuser]'), + array('sql_pass', '[dbpassword]'), + array('sql_db', $dbname), + array('sql_port', $dbport . ' # optional, default is 3306 for mysql and 5432 for pgsql'), + array('sql_query_pre', 'SET NAMES \'utf8\''), + array('sql_query_pre', 'UPDATE ' . SPHINX_TABLE . ' SET max_doc_id = (SELECT MAX(post_id) FROM ' . POSTS_TABLE . ') WHERE counter_id = 1'), + array('sql_query_range', 'SELECT MIN(post_id), MAX(post_id) FROM ' . POSTS_TABLE . ''), + array('sql_range_step', '5000'), + array('sql_query', 'SELECT + p.post_id AS id, + p.forum_id, + p.topic_id, + p.poster_id, + p.post_visibility, + CASE WHEN p.post_id = t.topic_first_post_id THEN 1 ELSE 0 END as topic_first_post, + p.post_time, + p.post_subject, + p.post_subject as title, + p.post_text as data, + t.topic_last_post_time, + 0 as deleted + FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t + WHERE + p.topic_id = t.topic_id + AND p.post_id >= $start AND p.post_id <= $end'), + array('sql_query_post', ''), + array('sql_query_post_index', 'UPDATE ' . SPHINX_TABLE . ' SET max_doc_id = $maxid WHERE counter_id = 1'), + array('sql_query_info', 'SELECT * FROM ' . POSTS_TABLE . ' WHERE post_id = $id'), + array('sql_attr_uint', 'forum_id'), + array('sql_attr_uint', 'topic_id'), + array('sql_attr_uint', 'poster_id'), + array('sql_attr_uint', 'post_visibility'), + array('sql_attr_bool', 'topic_first_post'), + array('sql_attr_bool', 'deleted'), + array('sql_attr_timestamp', 'post_time'), + array('sql_attr_timestamp', 'topic_last_post_time'), + array('sql_attr_string', 'post_subject'), + ), + 'source source_phpbb_' . $this->id . '_delta : source_phpbb_' . $this->id . '_main' => array( + array('sql_query_pre', ''), + array('sql_query_range', ''), + array('sql_range_step', ''), + array('sql_query', 'SELECT + p.post_id AS id, + p.forum_id, + p.topic_id, + p.poster_id, + p.post_visibility, + CASE WHEN p.post_id = t.topic_first_post_id THEN 1 ELSE 0 END as topic_first_post, + p.post_time, + p.post_subject, + p.post_subject as title, + p.post_text as data, + t.topic_last_post_time, + 0 as deleted + FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t + WHERE + p.topic_id = t.topic_id + AND p.post_id >= ( SELECT max_doc_id FROM ' . SPHINX_TABLE . ' WHERE counter_id=1 )'), + ), + 'index index_phpbb_' . $this->id . '_main' => array( + array('path', $this->config['fulltext_sphinx_data_path'] . 'index_phpbb_' . $this->id . '_main'), + array('source', 'source_phpbb_' . $this->id . '_main'), + array('docinfo', 'extern'), + array('morphology', 'none'), + array('stopwords', ''), + array('min_word_len', '2'), + array('charset_type', 'utf-8'), + array('charset_table', 'U+FF10..U+FF19->0..9, 0..9, U+FF41..U+FF5A->a..z, U+FF21..U+FF3A->a..z, A..Z->a..z, a..z, U+0149, U+017F, U+0138, U+00DF, U+00FF, U+00C0..U+00D6->U+00E0..U+00F6, U+00E0..U+00F6, U+00D8..U+00DE->U+00F8..U+00FE, U+00F8..U+00FE, U+0100->U+0101, U+0101, U+0102->U+0103, U+0103, U+0104->U+0105, U+0105, U+0106->U+0107, U+0107, U+0108->U+0109, U+0109, U+010A->U+010B, U+010B, U+010C->U+010D, U+010D, U+010E->U+010F, U+010F, U+0110->U+0111, U+0111, U+0112->U+0113, U+0113, U+0114->U+0115, U+0115, U+0116->U+0117, U+0117, U+0118->U+0119, U+0119, U+011A->U+011B, U+011B, U+011C->U+011D, U+011D, U+011E->U+011F, U+011F, U+0130->U+0131, U+0131, U+0132->U+0133, U+0133, U+0134->U+0135, U+0135, U+0136->U+0137, U+0137, U+0139->U+013A, U+013A, U+013B->U+013C, U+013C, U+013D->U+013E, U+013E, U+013F->U+0140, U+0140, U+0141->U+0142, U+0142, U+0143->U+0144, U+0144, U+0145->U+0146, U+0146, U+0147->U+0148, U+0148, U+014A->U+014B, U+014B, U+014C->U+014D, U+014D, U+014E->U+014F, U+014F, U+0150->U+0151, U+0151, U+0152->U+0153, U+0153, U+0154->U+0155, U+0155, U+0156->U+0157, U+0157, U+0158->U+0159, U+0159, U+015A->U+015B, U+015B, U+015C->U+015D, U+015D, U+015E->U+015F, U+015F, U+0160->U+0161, U+0161, U+0162->U+0163, U+0163, U+0164->U+0165, U+0165, U+0166->U+0167, U+0167, U+0168->U+0169, U+0169, U+016A->U+016B, U+016B, U+016C->U+016D, U+016D, U+016E->U+016F, U+016F, U+0170->U+0171, U+0171, U+0172->U+0173, U+0173, U+0174->U+0175, U+0175, U+0176->U+0177, U+0177, U+0178->U+00FF, U+00FF, U+0179->U+017A, U+017A, U+017B->U+017C, U+017C, U+017D->U+017E, U+017E, U+0410..U+042F->U+0430..U+044F, U+0430..U+044F, U+4E00..U+9FFF'), + array('min_prefix_len', '0'), + array('min_infix_len', '0'), + ), + 'index index_phpbb_' . $this->id . '_delta : index_phpbb_' . $this->id . '_main' => array( + array('path', $this->config['fulltext_sphinx_data_path'] . 'index_phpbb_' . $this->id . '_delta'), + array('source', 'source_phpbb_' . $this->id . '_delta'), + ), + 'indexer' => array( + array('mem_limit', $this->config['fulltext_sphinx_indexer_mem_limit'] . 'M'), + ), + 'searchd' => array( + array('compat_sphinxql_magics' , '0'), + array('listen' , ($this->config['fulltext_sphinx_host'] ? $this->config['fulltext_sphinx_host'] : 'localhost') . ':' . ($this->config['fulltext_sphinx_port'] ? $this->config['fulltext_sphinx_port'] : '9312')), + array('log', $this->config['fulltext_sphinx_data_path'] . 'log/searchd.log'), + array('query_log', $this->config['fulltext_sphinx_data_path'] . 'log/sphinx-query.log'), + array('read_timeout', '5'), + array('max_children', '30'), + array('pid_file', $this->config['fulltext_sphinx_data_path'] . 'searchd.pid'), + array('max_matches', (string) SPHINX_MAX_MATCHES), + array('binlog_path', $this->config['fulltext_sphinx_data_path']), + ), + ); + + $non_unique = array('sql_query_pre' => true, 'sql_attr_uint' => true, 'sql_attr_timestamp' => true, 'sql_attr_str2ordinal' => true, 'sql_attr_bool' => true); + $delete = array('sql_group_column' => true, 'sql_date_column' => true, 'sql_str2ordinal_column' => true); + + /** + * Allow adding/changing the Sphinx configuration data + * + * @event core.search_sphinx_modify_config_data + * @var array config_data Array with the Sphinx configuration data + * @var array non_unique Array with the Sphinx non-unique variables to delete + * @var array delete Array with the Sphinx variables to delete + * @since 3.1.7-RC1 + */ + $vars = array( + 'config_data', + 'non_unique', + 'delete', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_sphinx_modify_config_data', compact($vars))); + + foreach ($config_data as $section_name => $section_data) + { + $section = $config_object->get_section_by_name($section_name); + if (!$section) + { + $section = $config_object->add_section($section_name); + } + + foreach ($delete as $key => $void) + { + $section->delete_variables_by_name($key); + } + + foreach ($non_unique as $key => $void) + { + $section->delete_variables_by_name($key); + } + + foreach ($section_data as $entry) + { + $key = $entry[0]; + $value = $entry[1]; + + if (!isset($non_unique[$key])) + { + $variable = $section->get_variable_by_name($key); + if (!$variable) + { + $variable = $section->create_variable($key, $value); + } + else + { + $variable->set_value($value); + } + } + else + { + $variable = $section->create_variable($key, $value); + } + } + } + $this->config_file_data = $config_object->get_data(); + + return true; + } + + /** + * Splits keywords entered by a user into an array of words stored in $this->split_words + * Stores the tidied search query in $this->search_query + * + * @param string $keywords Contains the keyword as entered by the user + * @param string $terms is either 'all' or 'any' + * @return false if no valid keywords were found and otherwise true + */ + public function split_keywords(&$keywords, $terms) + { + if ($terms == 'all') + { + $match = array('#\sand\s#i', '#\sor\s#i', '#\snot\s#i', '#\+#', '#-#', '#\|#', '#@#'); + $replace = array(' & ', ' | ', ' - ', ' +', ' -', ' |', ''); + + $replacements = 0; + $keywords = preg_replace($match, $replace, $keywords); + $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED); + } + else + { + $this->sphinx->SetMatchMode(SPH_MATCH_ANY); + } + + // Keep quotes and new lines + $keywords = str_replace(array('"', "\n"), array('"', ' '), trim($keywords)); + + if (strlen($keywords) > 0) + { + $this->search_query = str_replace('"', '"', $keywords); + return true; + } + + return false; + } + + /** + * Performs a search on keywords depending on display specific params. You have to run split_keywords() first + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched) + * @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words) + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page) + { + // No keywords? No posts. + if (!strlen($this->search_query) && !sizeof($author_ary)) + { + return false; + } + + $id_ary = array(); + + $join_topic = ($type != 'posts'); + + // Sorting + + if ($type == 'topics') + { + switch ($sort_key) + { + case 'a': + $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'poster_id ' . (($sort_dir == 'a') ? 'ASC' : 'DESC')); + break; + + case 'f': + $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'forum_id ' . (($sort_dir == 'a') ? 'ASC' : 'DESC')); + break; + + case 'i': + + case 's': + $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'post_subject ' . (($sort_dir == 'a') ? 'ASC' : 'DESC')); + break; + + case 't': + + default: + $this->sphinx->SetGroupBy('topic_id', SPH_GROUPBY_ATTR, 'topic_last_post_time ' . (($sort_dir == 'a') ? 'ASC' : 'DESC')); + break; + } + } + else + { + switch ($sort_key) + { + case 'a': + $this->sphinx->SetSortMode(($sort_dir == 'a') ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'poster_id'); + break; + + case 'f': + $this->sphinx->SetSortMode(($sort_dir == 'a') ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'forum_id'); + break; + + case 'i': + + case 's': + $this->sphinx->SetSortMode(($sort_dir == 'a') ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'post_subject'); + break; + + case 't': + + default: + $this->sphinx->SetSortMode(($sort_dir == 'a') ? SPH_SORT_ATTR_ASC : SPH_SORT_ATTR_DESC, 'post_time'); + break; + } + } + + // Most narrow filters first + if ($topic_id) + { + $this->sphinx->SetFilter('topic_id', array($topic_id)); + } + + /** + * Allow modifying the Sphinx search options + * + * @event core.search_sphinx_keywords_modify_options + * @var string type Searching type ('posts', 'topics') + * @var string fields Searching fields ('titleonly', 'msgonly', 'firstpost', 'all') + * @var string terms Searching terms ('all', 'any') + * @var int sort_days Time, in days, of the oldest possible post to list + * @var string sort_key The sort type used from the possible sort types + * @var int topic_id Limit the search to this topic_id only + * @var array ex_fid_ary Which forums not to search on + * @var string post_visibility Post visibility data + * @var array author_ary Array of user_id containing the users to filter the results to + * @var string author_name The username to search on + * @var object sphinx The Sphinx searchd client object + * @since 3.1.7-RC1 + */ + $sphinx = $this->sphinx; + $vars = array( + 'type', + 'fields', + 'terms', + 'sort_days', + 'sort_key', + 'topic_id', + 'ex_fid_ary', + 'post_visibility', + 'author_ary', + 'author_name', + 'sphinx', + ); + extract($this->phpbb_dispatcher->trigger_event('core.search_sphinx_keywords_modify_options', compact($vars))); + $this->sphinx = $sphinx; + unset($sphinx); + + $search_query_prefix = ''; + + switch ($fields) + { + case 'titleonly': + // Only search the title + if ($terms == 'all') + { + $search_query_prefix = '@title '; + } + // Weight for the title + $this->sphinx->SetFieldWeights(array("title" => 5, "data" => 1)); + // 1 is first_post, 0 is not first post + $this->sphinx->SetFilter('topic_first_post', array(1)); + break; + + case 'msgonly': + // Only search the body + if ($terms == 'all') + { + $search_query_prefix = '@data '; + } + // Weight for the body + $this->sphinx->SetFieldWeights(array("title" => 1, "data" => 5)); + break; + + case 'firstpost': + // More relative weight for the title, also search the body + $this->sphinx->SetFieldWeights(array("title" => 5, "data" => 1)); + // 1 is first_post, 0 is not first post + $this->sphinx->SetFilter('topic_first_post', array(1)); + break; + + default: + // More relative weight for the title, also search the body + $this->sphinx->SetFieldWeights(array("title" => 5, "data" => 1)); + break; + } + + if (sizeof($author_ary)) + { + $this->sphinx->SetFilter('poster_id', $author_ary); + } + + // As this is not simply possible at the moment, we limit the result to approved posts. + // This will make it impossible for moderators to search unapproved and softdeleted posts, + // but at least it will also cause the same for normal users. + $this->sphinx->SetFilter('post_visibility', array(ITEM_APPROVED)); + + if (sizeof($ex_fid_ary)) + { + // All forums that a user is allowed to access + $fid_ary = array_unique(array_intersect(array_keys($this->auth->acl_getf('f_read', true)), array_keys($this->auth->acl_getf('f_search', true)))); + // All forums that the user wants to and can search in + $search_forums = array_diff($fid_ary, $ex_fid_ary); + + if (sizeof($search_forums)) + { + $this->sphinx->SetFilter('forum_id', $search_forums); + } + } + + $this->sphinx->SetFilter('deleted', array(0)); + + $this->sphinx->SetLimits($start, (int) $per_page, SPHINX_MAX_MATCHES); + $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); + + // Could be connection to localhost:9312 failed (errno=111, + // msg=Connection refused) during rotate, retry if so + $retries = SPHINX_CONNECT_RETRIES; + while (!$result && (strpos($this->sphinx->GetLastError(), "errno=111,") !== false) && $retries--) + { + usleep(SPHINX_CONNECT_WAIT_TIME); + $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); + } + + if ($this->sphinx->GetLastError()) + { + add_log('critical', 'LOG_SPHINX_ERROR', $this->sphinx->GetLastError()); + if ($this->auth->acl_get('a_')) + { + trigger_error($this->user->lang('SPHINX_SEARCH_FAILED', $this->sphinx->GetLastError())); + } + else + { + trigger_error($this->user->lang('SPHINX_SEARCH_FAILED_LOG')); + } + } + + $result_count = $result['total_found']; + + if ($result_count && $start >= $result_count) + { + $start = floor(($result_count - 1) / $per_page) * $per_page; + + $this->sphinx->SetLimits((int) $start, (int) $per_page, SPHINX_MAX_MATCHES); + $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); + + // Could be connection to localhost:9312 failed (errno=111, + // msg=Connection refused) during rotate, retry if so + $retries = SPHINX_CONNECT_RETRIES; + while (!$result && (strpos($this->sphinx->GetLastError(), "errno=111,") !== false) && $retries--) + { + usleep(SPHINX_CONNECT_WAIT_TIME); + $result = $this->sphinx->Query($search_query_prefix . str_replace('"', '"', $this->search_query), $this->indexes); + } + } + + $id_ary = array(); + if (isset($result['matches'])) + { + if ($type == 'posts') + { + $id_ary = array_keys($result['matches']); + } + else + { + foreach ($result['matches'] as $key => $value) + { + $id_ary[] = $value['attrs']['topic_id']; + } + } + } + else + { + return false; + } + + $id_ary = array_slice($id_ary, 0, (int) $per_page); + + return $result_count; + } + + /** + * Performs a search on an author's posts without caring about message contents. Depends on display specific params + * + * @param string $type contains either posts or topics depending on what should be searched for + * @param boolean $firstpost_only if true, only topic starting posts will be considered + * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query + * @param string $sort_key is the key of $sort_by_sql for the selected sorting + * @param string $sort_dir is either a or d representing ASC and DESC + * @param string $sort_days specifies the maximum amount of days a post may be old + * @param array $ex_fid_ary specifies an array of forum ids which should not be searched + * @param string $post_visibility specifies which types of posts the user can view in which forums + * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched + * @param array $author_ary an array of author ids + * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match + * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered + * @param int $start indicates the first index of the page + * @param int $per_page number of ids each page is supposed to contain + * @return boolean|int total number of results + */ + public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, $start, $per_page) + { + $this->search_query = ''; + + $this->sphinx->SetMatchMode(SPH_MATCH_FULLSCAN); + $fields = ($firstpost_only) ? 'firstpost' : 'all'; + $terms = 'all'; + return $this->keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, $id_ary, $start, $per_page); + } + + /** + * Updates wordlist and wordmatch tables when a message is posted or changed + * + * @param string $mode Contains the post mode: edit, post, reply, quote + * @param int $post_id The id of the post which is modified/created + * @param string &$message New or updated post content + * @param string &$subject New or updated post subject + * @param int $poster_id Post author's user id + * @param int $forum_id The id of the forum in which the post is located + */ + public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id) + { + if ($mode == 'edit') + { + $this->sphinx->UpdateAttributes($this->indexes, array('forum_id', 'poster_id'), array((int) $post_id => array((int) $forum_id, (int) $poster_id))); + } + else if ($mode != 'post' && $post_id) + { + // Update topic_last_post_time for full topic + $sql_array = array( + 'SELECT' => 'p1.post_id', + 'FROM' => array( + POSTS_TABLE => 'p1', + ), + 'LEFT_JOIN' => array(array( + 'FROM' => array( + POSTS_TABLE => 'p2' + ), + 'ON' => 'p1.topic_id = p2.topic_id', + )), + 'WHERE' => 'p2.post_id = ' . ((int) $post_id), + ); + + $sql = $this->db->sql_build_query('SELECT', $sql_array); + $result = $this->db->sql_query($sql); + + $post_updates = array(); + $post_time = time(); + while ($row = $this->db->sql_fetchrow($result)) + { + $post_updates[(int) $row['post_id']] = array($post_time); + } + $this->db->sql_freeresult($result); + + if (sizeof($post_updates)) + { + $this->sphinx->UpdateAttributes($this->indexes, array('topic_last_post_time'), $post_updates); + } + } + } + + /** + * Delete a post from the index after it was deleted + */ + public function index_remove($post_ids, $author_ids, $forum_ids) + { + $values = array(); + foreach ($post_ids as $post_id) + { + $values[$post_id] = array(1); + } + + $this->sphinx->UpdateAttributes($this->indexes, array('deleted'), $values); + } + + /** + * Nothing needs to be destroyed + */ + public function tidy($create = false) + { + set_config('search_last_gc', time(), true); + } + + /** + * Create sphinx table + * + * @return string|bool error string is returned incase of errors otherwise false + */ + public function create_index($acp_module, $u_action) + { + if (!$this->index_created()) + { + $table_data = array( + 'COLUMNS' => array( + 'counter_id' => array('UINT', 0), + 'max_doc_id' => array('UINT', 0), + ), + 'PRIMARY_KEY' => 'counter_id', + ); + $this->db_tools->sql_create_table(SPHINX_TABLE, $table_data); + + $sql = 'TRUNCATE TABLE ' . SPHINX_TABLE; + $this->db->sql_query($sql); + + $data = array( + 'counter_id' => '1', + 'max_doc_id' => '0', + ); + $sql = 'INSERT INTO ' . SPHINX_TABLE . ' ' . $this->db->sql_build_array('INSERT', $data); + $this->db->sql_query($sql); + } + + return false; + } + + /** + * Drop sphinx table + * + * @return string|bool error string is returned incase of errors otherwise false + */ + public function delete_index($acp_module, $u_action) + { + if (!$this->index_created()) + { + return false; + } + + $this->db_tools->sql_table_drop(SPHINX_TABLE); + + return false; + } + + /** + * Returns true if the sphinx table was created + * + * @return bool true if sphinx table was created + */ + public function index_created($allow_new_files = true) + { + $created = false; + + if ($this->db_tools->sql_table_exists(SPHINX_TABLE)) + { + $created = true; + } + + return $created; + } + + /** + * Returns an associative array containing information about the indexes + * + * @return string|bool Language string of error false otherwise + */ + public function index_stats() + { + if (empty($this->stats)) + { + $this->get_stats(); + } + + return array( + $this->user->lang['FULLTEXT_SPHINX_MAIN_POSTS'] => ($this->index_created()) ? $this->stats['main_posts'] : 0, + $this->user->lang['FULLTEXT_SPHINX_DELTA_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] - $this->stats['main_posts'] : 0, + $this->user->lang['FULLTEXT_MYSQL_TOTAL_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] : 0, + ); + } + + /** + * Collects stats that can be displayed on the index maintenance page + */ + protected function get_stats() + { + if ($this->index_created()) + { + $sql = 'SELECT COUNT(post_id) as total_posts + FROM ' . POSTS_TABLE; + $result = $this->db->sql_query($sql); + $this->stats['total_posts'] = (int) $this->db->sql_fetchfield('total_posts'); + $this->db->sql_freeresult($result); + + $sql = 'SELECT COUNT(p.post_id) as main_posts + FROM ' . POSTS_TABLE . ' p, ' . SPHINX_TABLE . ' m + WHERE p.post_id <= m.max_doc_id + AND m.counter_id = 1'; + $result = $this->db->sql_query($sql); + $this->stats['main_posts'] = (int) $this->db->sql_fetchfield('main_posts'); + $this->db->sql_freeresult($result); + } + } + + /** + * Returns a list of options for the ACP to display + * + * @return associative array containing template and config variables + */ + public function acp() + { + $config_vars = array( + 'fulltext_sphinx_data_path' => 'string', + 'fulltext_sphinx_host' => 'string', + 'fulltext_sphinx_port' => 'string', + 'fulltext_sphinx_indexer_mem_limit' => 'int', + ); + + $tpl = ' + <span class="error">' . $this->user->lang['FULLTEXT_SPHINX_CONFIGURE']. '</span> + <dl> + <dt><label for="fulltext_sphinx_data_path">' . $this->user->lang['FULLTEXT_SPHINX_DATA_PATH'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_SPHINX_DATA_PATH_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_sphinx_data_path" type="text" size="40" maxlength="255" name="config[fulltext_sphinx_data_path]" value="' . $this->config['fulltext_sphinx_data_path'] . '" /></dd> + </dl> + <dl> + <dt><label for="fulltext_sphinx_host">' . $this->user->lang['FULLTEXT_SPHINX_HOST'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_SPHINX_HOST_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_sphinx_host" type="text" size="40" maxlength="255" name="config[fulltext_sphinx_host]" value="' . $this->config['fulltext_sphinx_host'] . '" /></dd> + </dl> + <dl> + <dt><label for="fulltext_sphinx_port">' . $this->user->lang['FULLTEXT_SPHINX_PORT'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_SPHINX_PORT_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_sphinx_port" type="number" min="0" max="9999999999" name="config[fulltext_sphinx_port]" value="' . $this->config['fulltext_sphinx_port'] . '" /></dd> + </dl> + <dl> + <dt><label for="fulltext_sphinx_indexer_mem_limit">' . $this->user->lang['FULLTEXT_SPHINX_INDEXER_MEM_LIMIT'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_SPHINX_INDEXER_MEM_LIMIT_EXPLAIN'] . '</span></dt> + <dd><input id="fulltext_sphinx_indexer_mem_limit" type="number" min="0" max="9999999999" name="config[fulltext_sphinx_indexer_mem_limit]" value="' . $this->config['fulltext_sphinx_indexer_mem_limit'] . '" /> ' . $this->user->lang['MIB'] . '</dd> + </dl> + <dl> + <dt><label for="fulltext_sphinx_config_file">' . $this->user->lang['FULLTEXT_SPHINX_CONFIG_FILE'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_SPHINX_CONFIG_FILE_EXPLAIN'] . '</span></dt> + <dd>' . (($this->config_generate()) ? '<textarea readonly="readonly" rows="6" id="sphinx_config_data">' . htmlspecialchars($this->config_file_data) . '</textarea>' : $this->config_file_data) . '</dd> + <dl> + '; + + // These are fields required in the config table + return array( + 'tpl' => $tpl, + 'config' => $config_vars + ); + } +} diff --git a/phpBB/phpbb/search/index.htm b/phpBB/phpbb/search/index.htm new file mode 100644 index 0000000000..ee1f723a7d --- /dev/null +++ b/phpBB/phpbb/search/index.htm @@ -0,0 +1,10 @@ +<html> +<head> +<title></title> +<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> +</head> + +<body bgcolor="#FFFFFF" text="#000000"> + +</body> +</html> diff --git a/phpBB/phpbb/search/sphinx/config.php b/phpBB/phpbb/search/sphinx/config.php new file mode 100644 index 0000000000..675649b460 --- /dev/null +++ b/phpBB/phpbb/search/sphinx/config.php @@ -0,0 +1,284 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search\sphinx; + +/** +* An object representing the sphinx configuration +* Can read it from file and write it back out after modification +*/ +class config +{ + private $sections = array(); + + /** + * Constructor which optionally loads data from a variable + * + * @param string $config_data Variable containing the sphinx configuration data + * + * @access public + */ + function __construct($config_data) + { + if ($config_data != '') + { + $this->read($config_data); + } + } + + /** + * Get a section object by its name + * + * @param string $name The name of the section that shall be returned + * @return \phpbb\search\sphinx\config_section The section object or null if none was found + * + * @access public + */ + function get_section_by_name($name) + { + for ($i = 0, $size = sizeof($this->sections); $i < $size; $i++) + { + // Make sure this is really a section object and not a comment + if (($this->sections[$i] instanceof \phpbb\search\sphinx\config_section) && $this->sections[$i]->get_name() == $name) + { + return $this->sections[$i]; + } + } + } + + /** + * Appends a new empty section to the end of the config + * + * @param string $name The name for the new section + * @return \phpbb\search\sphinx\config_section The newly created section object + * + * @access public + */ + function add_section($name) + { + $this->sections[] = new \phpbb\search\sphinx\config_section($name, ''); + return $this->sections[sizeof($this->sections) - 1]; + } + + /** + * Reads the config file data + * + * @param string $config_data The config file data + * + * @access private + */ + function read($config_data) + { + $this->sections = array(); + + $section = null; + $found_opening_bracket = false; + $in_value = false; + + foreach ($config_data as $i => $line) + { + // If the value of a variable continues to the next line because the line + // break was escaped then we don't trim leading space but treat it as a part of the value + if ($in_value) + { + $line = rtrim($line); + } + else + { + $line = trim($line); + } + + // If we're not inside a section look for one + if (!$section) + { + // Add empty lines and comments as comment objects to the section list + // that way they're not deleted when reassembling the file from the sections + if (!$line || $line[0] == '#') + { + $this->sections[] = new \phpbb\search\sphinx\config_comment($config_file[$i]); + continue; + } + else + { + // Otherwise we scan the line reading the section name until we find + // an opening curly bracket or a comment + $section_name = ''; + $section_name_comment = ''; + $found_opening_bracket = false; + for ($j = 0, $length = strlen($line); $j < $length; $j++) + { + if ($line[$j] == '#') + { + $section_name_comment = substr($line, $j); + break; + } + + if ($found_opening_bracket) + { + continue; + } + + if ($line[$j] == '{') + { + $found_opening_bracket = true; + continue; + } + + $section_name .= $line[$j]; + } + + // And then we create the new section object + $section_name = trim($section_name); + $section = new \phpbb\search\sphinx\config_section($section_name, $section_name_comment); + } + } + else + { + // If we're looking for variables inside a section + $skip_first = false; + + // If we're not in a value continuing over the line feed + if (!$in_value) + { + // Then add empty lines and comments as comment objects to the variable list + // of this section so they're not deleted on reassembly + if (!$line || $line[0] == '#') + { + $section->add_variable(new \phpbb\search\sphinx\config_comment($config_file[$i])); + continue; + } + + // As long as we haven't yet actually found an opening bracket for this section + // we treat everything as comments so it's not deleted either + if (!$found_opening_bracket) + { + if ($line[0] == '{') + { + $skip_first = true; + $line = substr($line, 1); + $found_opening_bracket = true; + } + else + { + $section->add_variable(new \phpbb\search\sphinx\config_comment($config_file[$i])); + continue; + } + } + } + + // If we did not find a comment in this line or still add to the previous + // line's value ... + if ($line || $in_value) + { + if (!$in_value) + { + $name = ''; + $value = ''; + $comment = ''; + $found_assignment = false; + } + $in_value = false; + $end_section = false; + + /* ... then we should prase this line char by char: + - first there's the variable name + - then an equal sign + - the variable value + - possibly a backslash before the linefeed in this case we need to continue + parsing the value in the next line + - a # indicating that the rest of the line is a comment + - a closing curly bracket indicating the end of this section*/ + for ($j = 0, $length = strlen($line); $j < $length; $j++) + { + if ($line[$j] == '#') + { + $comment = substr($line, $j); + break; + } + else if ($line[$j] == '}') + { + $comment = substr($line, $j + 1); + $end_section = true; + break; + } + else if (!$found_assignment) + { + if ($line[$j] == '=') + { + $found_assignment = true; + } + else + { + $name .= $line[$j]; + } + } + else + { + if ($line[$j] == '\\' && $j == $length - 1) + { + $value .= "\n"; + $in_value = true; + // Go to the next line and keep processing the value in there + continue 2; + } + $value .= $line[$j]; + } + } + + // If a name and an equal sign were found then we have append a + // new variable object to the section + if ($name && $found_assignment) + { + $section->add_variable(new \phpbb\search\sphinx\config_variable(trim($name), trim($value), ($end_section) ? '' : $comment)); + continue; + } + + /* If we found a closing curly bracket this section has been completed + and we can append it to the section list and continue with looking for + the next section */ + if ($end_section) + { + $section->set_end_comment($comment); + $this->sections[] = $section; + $section = null; + continue; + } + } + + // If we did not find anything meaningful up to here, then just treat it + // as a comment + $comment = ($skip_first) ? "\t" . substr(ltrim($config_file[$i]), 1) : $config_file[$i]; + $section->add_variable(new \phpbb\search\sphinx\config_comment($comment)); + } + } + + } + + /** + * Returns the config data + * + * @return string $data The config data that is generated + * + * @access public + */ + function get_data() + { + $data = ""; + foreach ($this->sections as $section) + { + $data .= $section->to_string(); + } + + return $data; + } +} diff --git a/phpBB/phpbb/search/sphinx/config_comment.php b/phpBB/phpbb/search/sphinx/config_comment.php new file mode 100644 index 0000000000..b5cd0a3db5 --- /dev/null +++ b/phpBB/phpbb/search/sphinx/config_comment.php @@ -0,0 +1,47 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search\sphinx; + +/** +* \phpbb\search\sphinx\config_comment +* Represents a comment inside the sphinx configuration +*/ +class config_comment +{ + private $exact_string; + + /** + * Create a new comment + * + * @param string $exact_string The content of the comment including newlines, leading whitespace, etc. + * + * @access public + */ + function __construct($exact_string) + { + $this->exact_string = $exact_string; + } + + /** + * Simply returns the comment as it was created + * + * @return string The exact string that was specified in the constructor + * + * @access public + */ + function to_string() + { + return $this->exact_string; + } +} diff --git a/phpBB/phpbb/search/sphinx/config_section.php b/phpBB/phpbb/search/sphinx/config_section.php new file mode 100644 index 0000000000..14ab3a752c --- /dev/null +++ b/phpBB/phpbb/search/sphinx/config_section.php @@ -0,0 +1,160 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search\sphinx; + +/** +* \phpbb\search\sphinx\config_section +* Represents a single section inside the sphinx configuration +*/ +class config_section +{ + private $name; + private $comment; + private $end_comment; + private $variables = array(); + + /** + * Construct a new section + * + * @param string $name Name of the section + * @param string $comment Comment that should be appended after the name in the + * textual format. + * + * @access public + */ + function __construct($name, $comment) + { + $this->name = $name; + $this->comment = $comment; + $this->end_comment = ''; + } + + /** + * Add a variable object to the list of variables in this section + * + * @param \phpbb\search\sphinx\config_variable $variable The variable object + * + * @access public + */ + function add_variable($variable) + { + $this->variables[] = $variable; + } + + /** + * Adds a comment after the closing bracket in the textual representation + * + * @param string $end_comment + * + * @access public + */ + function set_end_comment($end_comment) + { + $this->end_comment = $end_comment; + } + + /** + * Getter for the name of this section + * + * @return string Section's name + * + * @access public + */ + function get_name() + { + return $this->name; + } + + /** + * Get a variable object by its name + * + * @param string $name The name of the variable that shall be returned + * @return \phpbb\search\sphinx\config_section The first variable object from this section with the + * given name or null if none was found + * + * @access public + */ + function get_variable_by_name($name) + { + for ($i = 0, $size = sizeof($this->variables); $i < $size; $i++) + { + // Make sure this is a variable object and not a comment + if (($this->variables[$i] instanceof \phpbb\search\sphinx\config_variable) && $this->variables[$i]->get_name() == $name) + { + return $this->variables[$i]; + } + } + } + + /** + * Deletes all variables with the given name + * + * @param string $name The name of the variable objects that are supposed to be removed + * + * @access public + */ + function delete_variables_by_name($name) + { + for ($i = 0, $size = sizeof($this->variables); $i < $size; $i++) + { + // Make sure this is a variable object and not a comment + if (($this->variables[$i] instanceof \phpbb\search\sphinx\config_variable) && $this->variables[$i]->get_name() == $name) + { + array_splice($this->variables, $i, 1); + $i--; + } + } + } + + /** + * Create a new variable object and append it to the variable list of this section + * + * @param string $name The name for the new variable + * @param string $value The value for the new variable + * @return \phpbb\search\sphinx\config_variable Variable object that was created + * + * @access public + */ + function create_variable($name, $value) + { + $this->variables[] = new \phpbb\search\sphinx\config_variable($name, $value, ''); + return $this->variables[sizeof($this->variables) - 1]; + } + + /** + * Turns this object into a string which can be written to a config file + * + * @return string Config data in textual form, parsable for sphinx + * + * @access public + */ + function to_string() + { + $content = $this->name . ' ' . $this->comment . "\n{\n"; + + // Make sure we don't get too many newlines after the opening bracket + while (trim($this->variables[0]->to_string()) == '') + { + array_shift($this->variables); + } + + foreach ($this->variables as $variable) + { + $content .= $variable->to_string(); + } + $content .= '}' . $this->end_comment . "\n"; + + return $content; + } +} diff --git a/phpBB/phpbb/search/sphinx/config_variable.php b/phpBB/phpbb/search/sphinx/config_variable.php new file mode 100644 index 0000000000..85cee20b62 --- /dev/null +++ b/phpBB/phpbb/search/sphinx/config_variable.php @@ -0,0 +1,78 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\search\sphinx; + +/** +* \phpbb\search\sphinx\config_variable +* Represents a single variable inside the sphinx configuration +*/ +class config_variable +{ + private $name; + private $value; + private $comment; + + /** + * Constructs a new variable object + * + * @param string $name Name of the variable + * @param string $value Value of the variable + * @param string $comment Optional comment after the variable in the + * config file + * + * @access public + */ + function __construct($name, $value, $comment) + { + $this->name = $name; + $this->value = $value; + $this->comment = $comment; + } + + /** + * Getter for the variable's name + * + * @return string The variable object's name + * + * @access public + */ + function get_name() + { + return $this->name; + } + + /** + * Allows changing the variable's value + * + * @param string $value New value for this variable + * + * @access public + */ + function set_value($value) + { + $this->value = $value; + } + + /** + * Turns this object into a string readable by sphinx + * + * @return string Config data in textual form + * + * @access public + */ + function to_string() + { + return "\t" . $this->name . ' = ' . str_replace("\n", " \\\n", $this->value) . ' ' . $this->comment . "\n"; + } +} diff --git a/phpBB/phpbb/session.php b/phpBB/phpbb/session.php new file mode 100644 index 0000000000..45e82df591 --- /dev/null +++ b/phpBB/phpbb/session.php @@ -0,0 +1,1617 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* Session class +*/ +class session +{ + var $cookie_data = array(); + var $page = array(); + var $data = array(); + var $browser = ''; + var $forwarded_for = ''; + var $host = ''; + var $session_id = ''; + var $ip = ''; + var $load = 0; + var $time_now = 0; + var $update_session_page = true; + + /** + * Extract current session page + * + * @param string $root_path current root path (phpbb_root_path) + * @return array + */ + static function extract_current_page($root_path) + { + global $request, $symfony_request, $phpbb_filesystem; + + $page_array = array(); + + // First of all, get the request uri... + $script_name = $request->escape($symfony_request->getScriptName(), true); + $args = $request->escape(explode('&', $symfony_request->getQueryString()), true); + + // If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support... + if (!$script_name) + { + $script_name = htmlspecialchars_decode($request->server('REQUEST_URI')); + $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name; + $page_array['failover'] = 1; + } + + // Replace backslashes and doubled slashes (could happen on some proxy setups) + $script_name = str_replace(array('\\', '//'), '/', $script_name); + + // Now, remove the sid and let us get a clean query string... + $use_args = array(); + + // Since some browser do not encode correctly we need to do this with some "special" characters... + // " -> %22, ' => %27, < -> %3C, > -> %3E + $find = array('"', "'", '<', '>', '"', '<', '>'); + $replace = array('%22', '%27', '%3C', '%3E', '%22', '%3C', '%3E'); + + foreach ($args as $key => $argument) + { + if (strpos($argument, 'sid=') === 0) + { + continue; + } + + $use_args[] = str_replace($find, $replace, $argument); + } + unset($args); + + // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2 + + // The current query string + $query_string = trim(implode('&', $use_args)); + + // basenamed page name (for example: index.php) + $page_name = (substr($script_name, -1, 1) == '/') ? '' : basename($script_name); + $page_name = urlencode(htmlspecialchars($page_name)); + + $symfony_request_path = $phpbb_filesystem->clean_path($symfony_request->getPathInfo()); + if ($symfony_request_path !== '/') + { + $page_name .= str_replace('%2F', '/', urlencode($symfony_request_path)); + } + + // current directory within the phpBB root (for example: adm) + $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path))); + $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./'))); + $intersection = array_intersect_assoc($root_dirs, $page_dirs); + + $root_dirs = array_diff_assoc($root_dirs, $intersection); + $page_dirs = array_diff_assoc($page_dirs, $intersection); + + $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs); + + if ($page_dir && substr($page_dir, -1, 1) == '/') + { + $page_dir = substr($page_dir, 0, -1); + } + + // Current page from phpBB root (for example: adm/index.php?i=10&b=2) + $page = (($page_dir) ? $page_dir . '/' : '') . $page_name; + if ($query_string) + { + $page .= '?' . $query_string; + } + + // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in / + $script_path = $symfony_request->getBasePath(); + + // The script path from the webroot to the phpBB root (for example: /phpBB3/) + $script_dirs = explode('/', $script_path); + array_splice($script_dirs, -sizeof($page_dirs)); + $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : ''); + + // We are on the base level (phpBB root == webroot), lets adjust the variables a bit... + if (!$root_script_path) + { + $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path; + } + + $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/'; + $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/'; + + $forum_id = $request->variable('f', 0); + // maximum forum id value is maximum value of mediumint unsigned column + $forum_id = ($forum_id > 0 && $forum_id < 16777215) ? $forum_id : 0; + + $page_array += array( + 'page_name' => $page_name, + 'page_dir' => $page_dir, + + 'query_string' => $query_string, + 'script_path' => str_replace(' ', '%20', htmlspecialchars($script_path)), + 'root_script_path' => str_replace(' ', '%20', htmlspecialchars($root_script_path)), + + 'page' => $page, + 'forum' => $forum_id, + ); + + return $page_array; + } + + /** + * Get valid hostname/port. HTTP_HOST is used, SERVER_NAME if HTTP_HOST not present. + */ + function extract_current_hostname() + { + global $config, $request; + + // Get hostname + $host = htmlspecialchars_decode($request->header('Host', $request->server('SERVER_NAME'))); + + // Should be a string and lowered + $host = (string) strtolower($host); + + // If host is equal the cookie domain or the server name (if config is set), then we assume it is valid + if ((isset($config['cookie_domain']) && $host === $config['cookie_domain']) || (isset($config['server_name']) && $host === $config['server_name'])) + { + return $host; + } + + // Is the host actually a IP? If so, we use the IP... (IPv4) + if (long2ip(ip2long($host)) === $host) + { + return $host; + } + + // Now return the hostname (this also removes any port definition). The http:// is prepended to construct a valid URL, hosts never have a scheme assigned + $host = @parse_url('http://' . $host); + $host = (!empty($host['host'])) ? $host['host'] : ''; + + // Remove any portions not removed by parse_url (#) + $host = str_replace('#', '', $host); + + // If, by any means, the host is now empty, we will use a "best approach" way to guess one + if (empty($host)) + { + if (!empty($config['server_name'])) + { + $host = $config['server_name']; + } + else if (!empty($config['cookie_domain'])) + { + $host = (strpos($config['cookie_domain'], '.') === 0) ? substr($config['cookie_domain'], 1) : $config['cookie_domain']; + } + else + { + // Set to OS hostname or localhost + $host = (function_exists('php_uname')) ? php_uname('n') : 'localhost'; + } + } + + // It may be still no valid host, but for sure only a hostname (we may further expand on the cookie domain... if set) + return $host; + } + + /** + * Start session management + * + * This is where all session activity begins. We gather various pieces of + * information from the client and server. We test to see if a session already + * exists. If it does, fine and dandy. If it doesn't we'll go on to create a + * new one ... pretty logical heh? We also examine the system load (if we're + * running on a system which makes such information readily available) and + * halt if it's above an admin definable limit. + * + * @param bool $update_session_page if true the session page gets updated. + * This can be set to circumvent certain scripts to update the users last visited page. + */ + function session_begin($update_session_page = true) + { + global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path; + global $request, $phpbb_container, $phpbb_dispatcher; + + // Give us some basic information + $this->time_now = time(); + $this->cookie_data = array('u' => 0, 'k' => ''); + $this->update_session_page = $update_session_page; + $this->browser = $request->header('User-Agent'); + $this->referer = $request->header('Referer'); + $this->forwarded_for = $request->header('X-Forwarded-For'); + + $this->host = $this->extract_current_hostname(); + $this->page = $this->extract_current_page($phpbb_root_path); + + // if the forwarded for header shall be checked we have to validate its contents + if ($config['forwarded_for_check']) + { + $this->forwarded_for = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->forwarded_for)); + + // split the list of IPs + $ips = explode(' ', $this->forwarded_for); + foreach ($ips as $ip) + { + // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly + if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip)) + { + // contains invalid data, don't use the forwarded for header + $this->forwarded_for = ''; + break; + } + } + } + else + { + $this->forwarded_for = ''; + } + + if ($request->is_set($config['cookie_name'] . '_sid', \phpbb\request\request_interface::COOKIE) || $request->is_set($config['cookie_name'] . '_u', \phpbb\request\request_interface::COOKIE)) + { + $this->cookie_data['u'] = request_var($config['cookie_name'] . '_u', 0, false, true); + $this->cookie_data['k'] = request_var($config['cookie_name'] . '_k', '', false, true); + $this->session_id = request_var($config['cookie_name'] . '_sid', '', false, true); + + $SID = (defined('NEED_SID')) ? '?sid=' . $this->session_id : '?sid='; + $_SID = (defined('NEED_SID')) ? $this->session_id : ''; + + if (empty($this->session_id)) + { + $this->session_id = $_SID = request_var('sid', ''); + $SID = '?sid=' . $this->session_id; + $this->cookie_data = array('u' => 0, 'k' => ''); + } + } + else + { + $this->session_id = $_SID = request_var('sid', ''); + $SID = '?sid=' . $this->session_id; + } + + $_EXTRA_URL = array(); + + // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests + // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip. + $ip = htmlspecialchars_decode($request->server('REMOTE_ADDR')); + $ip = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $ip)); + + /** + * Event to alter user IP address + * + * @event core.session_ip_after + * @var string ip REMOTE_ADDR + * @since 3.1.10-RC1 + */ + $vars = array('ip'); + extract($phpbb_dispatcher->trigger_event('core.session_ip_after', compact($vars))); + + // split the list of IPs + $ips = explode(' ', trim($ip)); + + // Default IP if REMOTE_ADDR is invalid + $this->ip = '127.0.0.1'; + + foreach ($ips as $ip) + { + if (function_exists('phpbb_ip_normalise')) + { + // Normalise IP address + $ip = phpbb_ip_normalise($ip); + + if (empty($ip)) + { + // IP address is invalid. + break; + } + + // IP address is valid. + $this->ip = $ip; + + // Skip legacy code. + continue; + } + + if (preg_match(get_preg_expression('ipv4'), $ip)) + { + $this->ip = $ip; + } + else if (preg_match(get_preg_expression('ipv6'), $ip)) + { + // Quick check for IPv4-mapped address in IPv6 + if (stripos($ip, '::ffff:') === 0) + { + $ipv4 = substr($ip, 7); + + if (preg_match(get_preg_expression('ipv4'), $ipv4)) + { + $ip = $ipv4; + } + } + + $this->ip = $ip; + } + else + { + // We want to use the last valid address in the chain + // Leave foreach loop when address is invalid + break; + } + } + + $this->load = false; + + // Load limit check (if applicable) + if ($config['limit_load'] || $config['limit_search_load']) + { + if ((function_exists('sys_getloadavg') && $load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg')))) + { + $this->load = array_slice($load, 0, 1); + $this->load = floatval($this->load[0]); + } + else + { + set_config('limit_load', '0'); + set_config('limit_search_load', '0'); + } + } + + // if no session id is set, redirect to index.php + $session_id = $request->variable('sid', ''); + if (defined('NEED_SID') && (empty($session_id) || $this->session_id !== $session_id)) + { + send_status_line(401, 'Unauthorized'); + redirect(append_sid("{$phpbb_root_path}index.$phpEx")); + } + + // if session id is set + if (!empty($this->session_id)) + { + $sql = 'SELECT u.*, s.* + FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u + WHERE s.session_id = '" . $db->sql_escape($this->session_id) . "' + AND u.user_id = s.session_user_id"; + $result = $db->sql_query($sql); + $this->data = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + // Did the session exist in the DB? + if (isset($this->data['user_id'])) + { + // Validate IP length according to admin ... enforces an IP + // check on bots if admin requires this +// $quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check']; + + if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false) + { + $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']); + $u_ip = short_ipv6($this->ip, $config['ip_check']); + } + else + { + $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check'])); + $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check'])); + } + + $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : ''; + $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : ''; + + $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : ''; + $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : ''; + + // referer checks + // The @ before $config['referer_validation'] suppresses notices present while running the updater + $check_referer_path = (@$config['referer_validation'] == REFERER_VALIDATE_PATH); + $referer_valid = true; + + // we assume HEAD and TRACE to be foul play and thus only whitelist GET + if (@$config['referer_validation'] && strtolower($request->server('REQUEST_METHOD')) !== 'get') + { + $referer_valid = $this->validate_referer($check_referer_path); + } + + if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid) + { + $session_expired = false; + + // Check whether the session is still valid if we have one + $provider_collection = $phpbb_container->get('auth.provider_collection'); + $provider = $provider_collection->get_provider(); + + if (!($provider instanceof \phpbb\auth\provider\provider_interface)) + { + throw new \RuntimeException($provider . ' must implement \phpbb\auth\provider\provider_interface'); + } + + $ret = $provider->validate_session($this->data); + if ($ret !== null && !$ret) + { + $session_expired = true; + } + + if (!$session_expired) + { + // Check the session length timeframe if autologin is not enabled. + // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide. + if (!$this->data['session_autologin']) + { + if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60)) + { + $session_expired = true; + } + } + else if (!$config['allow_autologin'] || ($config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - (86400 * (int) $config['max_autologin_time']) + 60)) + { + $session_expired = true; + } + } + + if (!$session_expired) + { + $this->data['is_registered'] = ($this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false; + $this->data['is_bot'] = (!$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS) ? true : false; + $this->data['user_lang'] = basename($this->data['user_lang']); + + // Is user banned? Are they excluded? Won't return on ban, exists within method + $this->check_ban_for_current_session($config); + + return true; + } + } + else + { + // Added logging temporarly to help debug bugs... + if (defined('DEBUG') && $this->data['user_id'] != ANONYMOUS) + { + if ($referer_valid) + { + add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for)); + } + else + { + add_log('critical', 'LOG_REFERER_INVALID', $this->referer); + } + } + } + } + } + + // If we reach here then no (valid) session exists. So we'll create a new one + return $this->session_create(); + } + + /** + * Create a new session + * + * If upon trying to start a session we discover there is nothing existing we + * jump here. Additionally this method is called directly during login to regenerate + * the session for the specific user. In this method we carry out a number of tasks; + * garbage collection, (search)bot checking, banned user comparison. Basically + * though this method will result in a new session for a specific user. + */ + function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true) + { + global $SID, $_SID, $db, $config, $cache, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher; + + $this->data = array(); + + /* Garbage collection ... remove old sessions updating user information + // if necessary. It means (potentially) 11 queries but only infrequently + if ($this->time_now > $config['session_last_gc'] + $config['session_gc']) + { + $this->session_gc(); + }*/ + + // Do we allow autologin on this board? No? Then override anything + // that may be requested here + if (!$config['allow_autologin']) + { + $this->cookie_data['k'] = $persist_login = false; + } + + /** + * Here we do a bot check, oh er saucy! No, not that kind of bot + * check. We loop through the list of bots defined by the admin and + * see if we have any useragent and/or IP matches. If we do, this is a + * bot, act accordingly + */ + $bot = false; + $active_bots = $cache->obtain_bots(); + + foreach ($active_bots as $row) + { + if ($row['bot_agent'] && preg_match('#' . str_replace('\*', '.*?', preg_quote($row['bot_agent'], '#')) . '#i', $this->browser)) + { + $bot = $row['user_id']; + } + + // If ip is supplied, we will make sure the ip is matching too... + if ($row['bot_ip'] && ($bot || !$row['bot_agent'])) + { + // Set bot to false, then we only have to set it to true if it is matching + $bot = false; + + foreach (explode(',', $row['bot_ip']) as $bot_ip) + { + $bot_ip = trim($bot_ip); + + if (!$bot_ip) + { + continue; + } + + if (strpos($this->ip, $bot_ip) === 0) + { + $bot = (int) $row['user_id']; + break; + } + } + } + + if ($bot) + { + break; + } + } + + $provider_collection = $phpbb_container->get('auth.provider_collection'); + $provider = $provider_collection->get_provider(); + $this->data = $provider->autologin(); + + if ($user_id !== false && sizeof($this->data) && $this->data['user_id'] != $user_id) + { + $this->data = array(); + } + + if (sizeof($this->data)) + { + $this->cookie_data['k'] = ''; + $this->cookie_data['u'] = $this->data['user_id']; + } + + // If we're presented with an autologin key we'll join against it. + // Else if we've been passed a user_id we'll grab data based on that + if (isset($this->cookie_data['k']) && $this->cookie_data['k'] && $this->cookie_data['u'] && !sizeof($this->data)) + { + $sql = 'SELECT u.* + FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k + WHERE u.user_id = ' . (int) $this->cookie_data['u'] . ' + AND u.user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ") + AND k.user_id = u.user_id + AND k.key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'"; + $result = $db->sql_query($sql); + $user_data = $db->sql_fetchrow($result); + + if ($user_id === false || (isset($user_data['user_id']) && $user_id == $user_data['user_id'])) + { + $this->data = $user_data; + $bot = false; + } + + $db->sql_freeresult($result); + } + + if ($user_id !== false && !sizeof($this->data)) + { + $this->cookie_data['k'] = ''; + $this->cookie_data['u'] = $user_id; + + $sql = 'SELECT * + FROM ' . USERS_TABLE . ' + WHERE user_id = ' . (int) $this->cookie_data['u'] . ' + AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')'; + $result = $db->sql_query($sql); + $this->data = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + $bot = false; + } + + // Bot user, if they have a SID in the Request URI we need to get rid of it + // otherwise they'll index this page with the SID, duplicate content oh my! + if ($bot && isset($_GET['sid'])) + { + send_status_line(301, 'Moved Permanently'); + redirect(build_url(array('sid'))); + } + + // If no data was returned one or more of the following occurred: + // Key didn't match one in the DB + // User does not exist + // User is inactive + // User is bot + if (!sizeof($this->data) || !is_array($this->data)) + { + $this->cookie_data['k'] = ''; + $this->cookie_data['u'] = ($bot) ? $bot : ANONYMOUS; + + if (!$bot) + { + $sql = 'SELECT * + FROM ' . USERS_TABLE . ' + WHERE user_id = ' . (int) $this->cookie_data['u']; + } + else + { + // We give bots always the same session if it is not yet expired. + $sql = 'SELECT u.*, s.* + FROM ' . USERS_TABLE . ' u + LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id) + WHERE u.user_id = ' . (int) $bot; + } + + $result = $db->sql_query($sql); + $this->data = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + } + + if ($this->data['user_id'] != ANONYMOUS && !$bot) + { + $this->data['session_last_visit'] = (isset($this->data['session_time']) && $this->data['session_time']) ? $this->data['session_time'] : (($this->data['user_lastvisit']) ? $this->data['user_lastvisit'] : time()); + } + else + { + $this->data['session_last_visit'] = $this->time_now; + } + + // Force user id to be integer... + $this->data['user_id'] = (int) $this->data['user_id']; + + // At this stage we should have a filled data array, defined cookie u and k data. + // data array should contain recent session info if we're a real user and a recent + // session exists in which case session_id will also be set + + // Is user banned? Are they excluded? Won't return on ban, exists within method + $this->check_ban_for_current_session($config); + + $this->data['is_registered'] = (!$bot && $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false; + $this->data['is_bot'] = ($bot) ? true : false; + + // If our friend is a bot, we re-assign a previously assigned session + if ($this->data['is_bot'] && $bot == $this->data['user_id'] && $this->data['session_id']) + { + // Only assign the current session if the ip, browser and forwarded_for match... + if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false) + { + $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']); + $u_ip = short_ipv6($this->ip, $config['ip_check']); + } + else + { + $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check'])); + $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check'])); + } + + $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : ''; + $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : ''; + + $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : ''; + $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : ''; + + if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for) + { + $this->session_id = $this->data['session_id']; + + // Only update session DB a minute or so after last update or if page changes + if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page'])) + { + // Update the last visit time + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_lastvisit = ' . (int) $this->data['session_time'] . ' + WHERE user_id = ' . (int) $this->data['user_id']; + $db->sql_query($sql); + } + + $SID = '?sid='; + $_SID = ''; + return true; + } + else + { + // If the ip and browser does not match make sure we only have one bot assigned to one session + $db->sql_query('DELETE FROM ' . SESSIONS_TABLE . ' WHERE session_user_id = ' . $this->data['user_id']); + } + } + + $session_autologin = (($this->cookie_data['k'] || $persist_login) && $this->data['is_registered']) ? true : false; + $set_admin = ($set_admin && $this->data['is_registered']) ? true : false; + + // Create or update the session + $sql_ary = array( + 'session_user_id' => (int) $this->data['user_id'], + 'session_start' => (int) $this->time_now, + 'session_last_visit' => (int) $this->data['session_last_visit'], + 'session_time' => (int) $this->time_now, + 'session_browser' => (string) trim(substr($this->browser, 0, 149)), + 'session_forwarded_for' => (string) $this->forwarded_for, + 'session_ip' => (string) $this->ip, + 'session_autologin' => ($session_autologin) ? 1 : 0, + 'session_admin' => ($set_admin) ? 1 : 0, + 'session_viewonline' => ($viewonline) ? 1 : 0, + ); + + if ($this->update_session_page) + { + $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199); + $sql_ary['session_forum_id'] = $this->page['forum']; + } + + $db->sql_return_on_error(true); + + $sql = 'DELETE + FROM ' . SESSIONS_TABLE . ' + WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\' + AND session_user_id = ' . ANONYMOUS; + + if (!defined('IN_ERROR_HANDLER') && (!$this->session_id || !$db->sql_query($sql) || !$db->sql_affectedrows())) + { + // Limit new sessions in 1 minute period (if required) + if (empty($this->data['session_time']) && $config['active_sessions']) + { +// $db->sql_return_on_error(false); + + $sql = 'SELECT COUNT(session_id) AS sessions + FROM ' . SESSIONS_TABLE . ' + WHERE session_time >= ' . ($this->time_now - 60); + $result = $db->sql_query($sql); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if ((int) $row['sessions'] > (int) $config['active_sessions']) + { + send_status_line(503, 'Service Unavailable'); + trigger_error('BOARD_UNAVAILABLE'); + } + } + } + + // Since we re-create the session id here, the inserted row must be unique. Therefore, we display potential errors. + // Commented out because it will not allow forums to update correctly +// $db->sql_return_on_error(false); + + // Something quite important: session_page always holds the *last* page visited, except for the *first* visit. + // We are not able to simply have an empty session_page btw, therefore we need to tell phpBB how to detect this special case. + // If the session id is empty, we have a completely new one and will set an "identifier" here. This identifier is able to be checked later. + if (empty($this->data['session_id'])) + { + // This is a temporary variable, only set for the very first visit + $this->data['session_created'] = true; + } + + $this->session_id = $this->data['session_id'] = md5(unique_id()); + + $sql_ary['session_id'] = (string) $this->session_id; + $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199); + $sql_ary['session_forum_id'] = $this->page['forum']; + + $sql = 'INSERT INTO ' . SESSIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary); + $db->sql_query($sql); + + $db->sql_return_on_error(false); + + // Regenerate autologin/persistent login key + if ($session_autologin) + { + $this->set_login_key(); + } + + // refresh data + $SID = '?sid=' . $this->session_id; + $_SID = $this->session_id; + $this->data = array_merge($this->data, $sql_ary); + + if (!$bot) + { + $cookie_expire = $this->time_now + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000); + + $this->set_cookie('u', $this->cookie_data['u'], $cookie_expire); + $this->set_cookie('k', $this->cookie_data['k'], $cookie_expire); + $this->set_cookie('sid', $this->session_id, $cookie_expire); + + unset($cookie_expire); + + $sql = 'SELECT COUNT(session_id) AS sessions + FROM ' . SESSIONS_TABLE . ' + WHERE session_user_id = ' . (int) $this->data['user_id'] . ' + AND session_time >= ' . (int) ($this->time_now - (max($config['session_length'], $config['form_token_lifetime']))); + $result = $db->sql_query($sql); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if ((int) $row['sessions'] <= 1 || empty($this->data['user_form_salt'])) + { + $this->data['user_form_salt'] = unique_id(); + // Update the form key + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_form_salt = \'' . $db->sql_escape($this->data['user_form_salt']) . '\' + WHERE user_id = ' . (int) $this->data['user_id']; + $db->sql_query($sql); + } + } + else + { + $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now; + + // Update the last visit time + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_lastvisit = ' . (int) $this->data['session_time'] . ' + WHERE user_id = ' . (int) $this->data['user_id']; + $db->sql_query($sql); + + $SID = '?sid='; + $_SID = ''; + } + + $session_data = $sql_ary; + /** + * Event to send new session data to extension + * Read-only event + * + * @event core.session_create_after + * @var array session_data Associative array of session keys to be updated + * @since 3.1.6-RC1 + */ + $vars = array('session_data'); + extract($phpbb_dispatcher->trigger_event('core.session_create_after', compact($vars))); + unset($session_data); + + return true; + } + + /** + * Kills a session + * + * This method does what it says on the tin. It will delete a pre-existing session. + * It resets cookie information (destroying any autologin key within that cookie data) + * and update the users information from the relevant session data. It will then + * grab guest user information. + */ + function session_kill($new_session = true) + { + global $SID, $_SID, $db, $config, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher; + + $sql = 'DELETE FROM ' . SESSIONS_TABLE . " + WHERE session_id = '" . $db->sql_escape($this->session_id) . "' + AND session_user_id = " . (int) $this->data['user_id']; + $db->sql_query($sql); + + $user_id = (int) $this->data['user_id']; + $session_id = $this->session_id; + /** + * Event to send session kill information to extension + * Read-only event + * + * @event core.session_kill_after + * @var int user_id user_id of the session user. + * @var string session_id current user's session_id + * @var bool new_session should we create new session for user + * @since 3.1.6-RC1 + */ + $vars = array('user_id', 'session_id', 'new_session'); + extract($phpbb_dispatcher->trigger_event('core.session_kill_after', compact($vars))); + unset($user_id); + unset($session_id); + + // Allow connecting logout with external auth method logout + $provider_collection = $phpbb_container->get('auth.provider_collection'); + $provider = $provider_collection->get_provider(); + $provider->logout($this->data, $new_session); + + if ($this->data['user_id'] != ANONYMOUS) + { + // Delete existing session, update last visit info first! + if (!isset($this->data['session_time'])) + { + $this->data['session_time'] = time(); + } + + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_lastvisit = ' . (int) $this->data['session_time'] . ' + WHERE user_id = ' . (int) $this->data['user_id']; + $db->sql_query($sql); + + if ($this->cookie_data['k']) + { + $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' + WHERE user_id = ' . (int) $this->data['user_id'] . " + AND key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'"; + $db->sql_query($sql); + } + + // Reset the data array + $this->data = array(); + + $sql = 'SELECT * + FROM ' . USERS_TABLE . ' + WHERE user_id = ' . ANONYMOUS; + $result = $db->sql_query($sql); + $this->data = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + } + + $cookie_expire = $this->time_now - 31536000; + $this->set_cookie('u', '', $cookie_expire); + $this->set_cookie('k', '', $cookie_expire); + $this->set_cookie('sid', '', $cookie_expire); + unset($cookie_expire); + + $SID = '?sid='; + $this->session_id = $_SID = ''; + + // To make sure a valid session is created we create one for the anonymous user + if ($new_session) + { + $this->session_create(ANONYMOUS); + } + + return true; + } + + /** + * Session garbage collection + * + * This looks a lot more complex than it really is. Effectively we are + * deleting any sessions older than an admin definable limit. Due to the + * way in which we maintain session data we have to ensure we update user + * data before those sessions are destroyed. In addition this method + * removes autologin key information that is older than an admin defined + * limit. + */ + function session_gc() + { + global $db, $config, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher; + + $batch_size = 10; + + if (!$this->time_now) + { + $this->time_now = time(); + } + + // Firstly, delete guest sessions + $sql = 'DELETE FROM ' . SESSIONS_TABLE . ' + WHERE session_user_id = ' . ANONYMOUS . ' + AND session_time < ' . (int) ($this->time_now - $config['session_length']); + $db->sql_query($sql); + + // Get expired sessions, only most recent for each user + $sql = 'SELECT session_user_id, session_page, MAX(session_time) AS recent_time + FROM ' . SESSIONS_TABLE . ' + WHERE session_time < ' . ($this->time_now - $config['session_length']) . ' + GROUP BY session_user_id, session_page'; + $result = $db->sql_query_limit($sql, $batch_size); + + $del_user_id = array(); + $del_sessions = 0; + + while ($row = $db->sql_fetchrow($result)) + { + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_lastvisit = ' . (int) $row['recent_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "' + WHERE user_id = " . (int) $row['session_user_id']; + $db->sql_query($sql); + + $del_user_id[] = (int) $row['session_user_id']; + $del_sessions++; + } + $db->sql_freeresult($result); + + if (sizeof($del_user_id)) + { + // Delete expired sessions + $sql = 'DELETE FROM ' . SESSIONS_TABLE . ' + WHERE ' . $db->sql_in_set('session_user_id', $del_user_id) . ' + AND session_time < ' . ($this->time_now - $config['session_length']); + $db->sql_query($sql); + } + + if ($del_sessions < $batch_size) + { + // Less than 10 users, update gc timer ... else we want gc + // called again to delete other sessions + set_config('session_last_gc', $this->time_now, true); + + if ($config['max_autologin_time']) + { + $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' + WHERE last_login < ' . (time() - (86400 * (int) $config['max_autologin_time'])); + $db->sql_query($sql); + } + + // only called from CRON; should be a safe workaround until the infrastructure gets going + $captcha_factory = $phpbb_container->get('captcha.factory'); + $captcha_factory->garbage_collect($config['captcha_plugin']); + + $sql = 'DELETE FROM ' . LOGIN_ATTEMPT_TABLE . ' + WHERE attempt_time < ' . (time() - (int) $config['ip_login_limit_time']); + $db->sql_query($sql); + } + + /** + * Event to trigger extension on session_gc + * + * @event core.session_gc_after + * @since 3.1.6-RC1 + */ + $phpbb_dispatcher->dispatch('core.session_gc_after'); + + return; + } + + /** + * Sets a cookie + * + * Sets a cookie of the given name with the specified data for the given length of time. If no time is specified, a session cookie will be set. + * + * @param string $name Name of the cookie, will be automatically prefixed with the phpBB cookie name. track becomes [cookie_name]_track then. + * @param string $cookiedata The data to hold within the cookie + * @param int $cookietime The expiration time as UNIX timestamp. If 0 is provided, a session cookie is set. + * @param bool $httponly Use HttpOnly. Defaults to true. Use false to make cookie accessible by client-side scripts. + */ + function set_cookie($name, $cookiedata, $cookietime, $httponly = true) + { + global $config; + + $name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata); + $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime); + $domain = (!$config['cookie_domain'] || $config['cookie_domain'] == '127.0.0.1' || strpos($config['cookie_domain'], '.') === false) ? '' : '; domain=' . $config['cookie_domain']; + + header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . ';' . (($httponly) ? ' HttpOnly' : ''), false); + } + + /** + * Check for banned user + * + * Checks whether the supplied user is banned by id, ip or email. If no parameters + * are passed to the method pre-existing session data is used. + * + * @param int|false $user_id The user id + * @param mixed $user_ips Can contain a string with one IP or an array of multiple IPs + * @param string|false $user_email The user email + * @param bool $return If $return is false this routine does not return on finding a banned user, + * it outputs a relevant message and stops execution. + */ + function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false) + { + global $config, $db, $phpbb_dispatcher; + + if (defined('IN_CHECK_BAN') || defined('SKIP_CHECK_BAN')) + { + return; + } + + $banned = false; + $cache_ttl = 3600; + $where_sql = array(); + + $sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end + FROM ' . BANLIST_TABLE . ' + WHERE '; + + // Determine which entries to check, only return those + if ($user_email === false) + { + $where_sql[] = "ban_email = ''"; + } + + if ($user_ips === false) + { + $where_sql[] = "(ban_ip = '' OR ban_exclude = 1)"; + } + + if ($user_id === false) + { + $where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)'; + } + else + { + $cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0; + $_sql = '(ban_userid = ' . $user_id; + + if ($user_email !== false) + { + $_sql .= " OR ban_email <> ''"; + } + + if ($user_ips !== false) + { + $_sql .= " OR ban_ip <> ''"; + } + + $_sql .= ')'; + + $where_sql[] = $_sql; + } + + $sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : ''; + $result = $db->sql_query($sql, $cache_ttl); + + $ban_triggered_by = 'user'; + while ($row = $db->sql_fetchrow($result)) + { + if ($row['ban_end'] && $row['ban_end'] < time()) + { + continue; + } + + $ip_banned = false; + if (!empty($row['ban_ip'])) + { + if (!is_array($user_ips)) + { + $ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips); + } + else + { + foreach ($user_ips as $user_ip) + { + if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip)) + { + $ip_banned = true; + break; + } + } + } + } + + if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) || + $ip_banned || + (!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email))) + { + if (!empty($row['ban_exclude'])) + { + $banned = false; + break; + } + else + { + $banned = true; + $ban_row = $row; + + if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) + { + $ban_triggered_by = 'user'; + } + else if ($ip_banned) + { + $ban_triggered_by = 'ip'; + } + else + { + $ban_triggered_by = 'email'; + } + + // Don't break. Check if there is an exclude rule for this user + } + } + } + $db->sql_freeresult($result); + + /** + * Event to set custom ban type + * + * @event core.session_set_custom_ban + * @var bool return If $return is false this routine does not return on finding a banned user, it outputs a relevant message and stops execution + * @var bool banned Check if user already banned + * @var array|false ban_row Ban data + * @var string ban_triggered_by Method that caused ban, can be your custom method + * @since 3.1.3-RC1 + */ + $ban_row = isset($ban_row) ? $ban_row : false; + $vars = array('return', 'banned', 'ban_row', 'ban_triggered_by'); + extract($phpbb_dispatcher->trigger_event('core.session_set_custom_ban', compact($vars))); + + if ($banned && !$return) + { + global $template, $phpbb_root_path, $phpEx; + + // If the session is empty we need to create a valid one... + if (empty($this->session_id)) + { + // This seems to be no longer needed? - #14971 +// $this->session_create(ANONYMOUS); + } + + // Initiate environment ... since it won't be set at this stage + $this->setup(); + + // Logout the user, banned users are unable to use the normal 'logout' link + if ($this->data['user_id'] != ANONYMOUS) + { + $this->session_kill(); + } + + // We show a login box here to allow founders accessing the board if banned by IP + if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS) + { + $this->setup('ucp'); + $this->data['is_registered'] = $this->data['is_bot'] = false; + + // Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again. + define('IN_CHECK_BAN', 1); + + login_box("index.$phpEx"); + + // The false here is needed, else the user is able to circumvent the ban. + $this->session_kill(false); + } + + // Ok, we catch the case of an empty session id for the anonymous user... + // This can happen if the user is logging in, banned by username and the login_box() being called "again". + if (empty($this->session_id) && defined('IN_CHECK_BAN')) + { + $this->session_create(ANONYMOUS); + } + + // Determine which message to output + $till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : ''; + $message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM'; + + $contact_link = phpbb_get_board_contact_link($config, $phpbb_root_path, $phpEx); + $message = sprintf($this->lang[$message], $till_date, '<a href="' . $contact_link . '">', '</a>'); + $message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : ''; + $message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>'; + + // A very special case... we are within the cron script which is not supposed to print out the ban message... show blank page + if (defined('IN_CRON')) + { + garbage_collection(); + exit_handler(); + exit; + } + + // To circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again + $this->session_kill(false); + + trigger_error($message); + } + + return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned; + } + + /** + * Check the current session for bans + * + * @return true if session user is banned. + */ + protected function check_ban_for_current_session($config) + { + if (!defined('SKIP_CHECK_BAN') && $this->data['user_type'] != USER_FOUNDER) + { + if (!$config['forwarded_for_check']) + { + $this->check_ban($this->data['user_id'], $this->ip); + } + else + { + $ips = explode(' ', $this->forwarded_for); + $ips[] = $this->ip; + $this->check_ban($this->data['user_id'], $ips); + } + } + } + + /** + * Check if ip is blacklisted + * This should be called only where absolutely necessary + * + * Only IPv4 (rbldns does not support AAAA records/IPv6 lookups) + * + * @author satmd (from the php manual) + * @param string $mode register/post - spamcop for example is ommitted for posting + * @param string|false $ip the IPv4 address to check + * + * @return false if ip is not blacklisted, else an array([checked server], [lookup]) + */ + function check_dnsbl($mode, $ip = false) + { + if ($ip === false) + { + $ip = $this->ip; + } + + // Neither Spamhaus nor Spamcop supports IPv6 addresses. + if (strpos($ip, ':') !== false) + { + return false; + } + + $dnsbl_check = array( + 'sbl.spamhaus.org' => 'http://www.spamhaus.org/query/bl?ip=', + ); + + if ($mode == 'register') + { + $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?'; + } + + if ($ip) + { + $quads = explode('.', $ip); + $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0]; + + // Need to be listed on all servers... + $listed = true; + $info = array(); + + foreach ($dnsbl_check as $dnsbl => $lookup) + { + if (phpbb_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true) + { + $info = array($dnsbl, $lookup . $ip); + } + else + { + $listed = false; + } + } + + if ($listed) + { + return $info; + } + } + + return false; + } + + /** + * Check if URI is blacklisted + * This should be called only where absolutly necessary, for example on the submitted website field + * This function is not in use at the moment and is only included for testing purposes, it may not work at all! + * This means it is untested at the moment and therefore commented out + * + * @param string $uri URI to check + * @return true if uri is on blacklist, else false. Only blacklist is checked (~zero FP), no grey lists + function check_uribl($uri) + { + // Normally parse_url() is not intended to parse uris + // We need to get the top-level domain name anyway... change. + $uri = parse_url($uri); + + if ($uri === false || empty($uri['host'])) + { + return false; + } + + $uri = trim($uri['host']); + + if ($uri) + { + // One problem here... the return parameter for the "windows" method is different from what + // we expect... this may render this check useless... + if (phpbb_checkdnsrr($uri . '.multi.uribl.com.', 'A') === true) + { + return true; + } + } + + return false; + } + */ + + /** + * Set/Update a persistent login key + * + * This method creates or updates a persistent session key. When a user makes + * use of persistent (formerly auto-) logins a key is generated and stored in the + * DB. When they revisit with the same key it's automatically updated in both the + * DB and cookie. Multiple keys may exist for each user representing different + * browsers or locations. As with _any_ non-secure-socket no passphrase login this + * remains vulnerable to exploit. + */ + function set_login_key($user_id = false, $key = false, $user_ip = false) + { + global $config, $db; + + $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id; + $user_ip = ($user_ip === false) ? $this->ip : $user_ip; + $key = ($key === false) ? (($this->cookie_data['k']) ? $this->cookie_data['k'] : false) : $key; + + $key_id = unique_id(hexdec(substr($this->session_id, 0, 8))); + + $sql_ary = array( + 'key_id' => (string) md5($key_id), + 'last_ip' => (string) $this->ip, + 'last_login' => (int) time() + ); + + if (!$key) + { + $sql_ary += array( + 'user_id' => (int) $user_id + ); + } + + if ($key) + { + $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . ' + SET ' . $db->sql_build_array('UPDATE', $sql_ary) . ' + WHERE user_id = ' . (int) $user_id . " + AND key_id = '" . $db->sql_escape(md5($key)) . "'"; + } + else + { + $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary); + } + $db->sql_query($sql); + + $this->cookie_data['k'] = $key_id; + + return false; + } + + /** + * Reset all login keys for the specified user + * + * This method removes all current login keys for a specified (or the current) + * user. It will be called on password change to render old keys unusable + */ + function reset_login_keys($user_id = false) + { + global $config, $db; + + $user_id = ($user_id === false) ? (int) $this->data['user_id'] : (int) $user_id; + + $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' + WHERE user_id = ' . (int) $user_id; + $db->sql_query($sql); + + // If the user is logged in, update last visit info first before deleting sessions + $sql = 'SELECT session_time, session_page + FROM ' . SESSIONS_TABLE . ' + WHERE session_user_id = ' . (int) $user_id . ' + ORDER BY session_time DESC'; + $result = $db->sql_query_limit($sql, 1); + $row = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + if ($row) + { + $sql = 'UPDATE ' . USERS_TABLE . ' + SET user_lastvisit = ' . (int) $row['session_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "' + WHERE user_id = " . (int) $user_id; + $db->sql_query($sql); + } + + // Let's also clear any current sessions for the specified user_id + // If it's the current user then we'll leave this session intact + $sql_where = 'session_user_id = ' . (int) $user_id; + $sql_where .= ($user_id === (int) $this->data['user_id']) ? " AND session_id <> '" . $db->sql_escape($this->session_id) . "'" : ''; + + $sql = 'DELETE FROM ' . SESSIONS_TABLE . " + WHERE $sql_where"; + $db->sql_query($sql); + + // We're changing the password of the current user and they have a key + // Lets regenerate it to be safe + if ($user_id === (int) $this->data['user_id'] && $this->cookie_data['k']) + { + $this->set_login_key($user_id); + } + } + + + /** + * Check if the request originated from the same page. + * @param bool $check_script_path If true, the path will be checked as well + */ + function validate_referer($check_script_path = false) + { + global $config, $request; + + // no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason) + if (empty($this->referer) || empty($this->host)) + { + return true; + } + + $host = htmlspecialchars($this->host); + $ref = substr($this->referer, strpos($this->referer, '://') + 3); + + if (!(stripos($ref, $host) === 0) && (!$config['force_server_vars'] || !(stripos($ref, $config['server_name']) === 0))) + { + return false; + } + else if ($check_script_path && rtrim($this->page['root_script_path'], '/') !== '') + { + $ref = substr($ref, strlen($host)); + $server_port = $request->server('SERVER_PORT', 0); + + if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0) + { + $ref = substr($ref, strlen(":$server_port")); + } + + if (!(stripos(rtrim($ref, '/'), rtrim($this->page['root_script_path'], '/')) === 0)) + { + return false; + } + } + + return true; + } + + + function unset_admin() + { + global $db; + $sql = 'UPDATE ' . SESSIONS_TABLE . ' + SET session_admin = 0 + WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\''; + $db->sql_query($sql); + } + + /** + * Update the session data + * + * @param array $session_data associative array of session keys to be updated + * @param string $session_id optional session_id, defaults to current user's session_id + */ + public function update_session($session_data, $session_id = null) + { + global $db, $phpbb_dispatcher; + + $session_id = ($session_id) ? $session_id : $this->session_id; + + $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $session_data) . " + WHERE session_id = '" . $db->sql_escape($session_id) . "'"; + $db->sql_query($sql); + + /** + * Event to send update session information to extension + * Read-only event + * + * @event core.update_session_after + * @var array session_data Associative array of session keys to be updated + * @var string session_id current user's session_id + * @since 3.1.6-RC1 + */ + $vars = array('session_data', 'session_id'); + extract($phpbb_dispatcher->trigger_event('core.update_session_after', compact($vars))); + } + + public function update_session_infos() + { + global $config, $db, $request; + + // No need to update if it's a new session. Informations are already inserted by session_create() + if (isset($this->data['session_created']) && $this->data['session_created']) + { + return; + } + + // Only update session DB a minute or so after last update or if page changes + if ($this->time_now - ((isset($this->data['session_time'])) ? $this->data['session_time'] : 0) > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page'])) + { + $sql_ary = array('session_time' => $this->time_now); + + // Do not update the session page for ajax requests, so the view online still works as intended + if ($this->update_session_page && !$request->is_ajax()) + { + $sql_ary['session_page'] = substr($this->page['page'], 0, 199); + $sql_ary['session_forum_id'] = $this->page['forum']; + } + + $db->sql_return_on_error(true); + + $this->update_session($sql_ary); + + $db->sql_return_on_error(false); + + $this->data = array_merge($this->data, $sql_ary); + + if ($this->data['user_id'] != ANONYMOUS && isset($config['new_member_post_limit']) && $this->data['user_new'] && $config['new_member_post_limit'] <= $this->data['user_posts']) + { + $this->leave_newly_registered(); + } + } + } +} diff --git a/phpBB/phpbb/symfony_request.php b/phpBB/phpbb/symfony_request.php new file mode 100644 index 0000000000..2931cae3cc --- /dev/null +++ b/phpBB/phpbb/symfony_request.php @@ -0,0 +1,39 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +use Symfony\Component\HttpFoundation\Request; + +/** + * WARNING: The Symfony request does not escape the input and should be used very carefully + * prefer the phpbb request as possible + */ +class symfony_request extends Request +{ + /** + * Constructor + * + * @param \phpbb\request\request_interface $phpbb_request + */ + public function __construct(\phpbb\request\request_interface $phpbb_request) + { + $get_parameters = $phpbb_request->get_super_global(\phpbb\request\request_interface::GET); + $post_parameters = $phpbb_request->get_super_global(\phpbb\request\request_interface::POST); + $server_parameters = $phpbb_request->get_super_global(\phpbb\request\request_interface::SERVER); + $files_parameters = $phpbb_request->get_super_global(\phpbb\request\request_interface::FILES); + $cookie_parameters = $phpbb_request->get_super_global(\phpbb\request\request_interface::COOKIE); + + parent::__construct($get_parameters, $post_parameters, array(), $cookie_parameters, $files_parameters, $server_parameters); + } +} diff --git a/phpBB/phpbb/template/asset.php b/phpBB/phpbb/template/asset.php new file mode 100644 index 0000000000..ff9366af4a --- /dev/null +++ b/phpBB/phpbb/template/asset.php @@ -0,0 +1,205 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template; + +class asset +{ + protected $components = array(); + + /** @var \phpbb\path_helper **/ + protected $path_helper; + + /** + * Constructor + * + * @param string $url URL + * @param \phpbb\path_helper $path_helper Path helper object + */ + public function __construct($url, \phpbb\path_helper $path_helper) + { + $this->path_helper = $path_helper; + + $this->set_url($url); + } + + /** + * Set URL + * + * @param string $url URL + */ + public function set_url($url) + { + if (version_compare(PHP_VERSION, '5.4.7') < 0 && substr($url, 0, 2) === '//') + { + // Workaround for PHP 5.4.6 and older bug #62844 - add fake scheme and then remove it + $this->components = parse_url('http:' . $url); + $this->components['scheme'] = ''; + return; + } + $this->components = parse_url($url); + } + + /** + * Convert URL components into string + * + * @param array $components URL components + * @return string URL + */ + protected function join_url($components) + { + $path = ''; + if (isset($components['scheme'])) + { + $path = $components['scheme'] === '' ? '//' : $components['scheme'] . '://'; + } + + if (isset($components['user']) || isset($components['pass'])) + { + if ($path === '' && !isset($components['port'])) + { + $path = '//'; + } + $path .= $components['user']; + if (isset($components['pass'])) + { + $path .= ':' . $components['pass']; + } + $path .= '@'; + } + + if (isset($components['host'])) + { + if ($path === '' && !isset($components['port'])) + { + $path = '//'; + } + $path .= $components['host']; + if (isset($components['port'])) + { + $path .= ':' . $components['port']; + } + } + + if (isset($components['path'])) + { + $path .= $components['path']; + } + + if (isset($components['query'])) + { + $path .= '?' . $components['query']; + } + + if (isset($components['fragment'])) + { + $path .= '#' . $components['fragment']; + } + + return $path; + } + + /** + * Get URL + * + * @return string URL + */ + public function get_url() + { + return $this->path_helper->update_web_root_path($this->join_url($this->components)); + } + + /** + * Checks if URL is local and relative + * + * @return boolean True if URL is local and relative + */ + public function is_relative() + { + if (empty($this->components) || !isset($this->components['path'])) + { + // Invalid URL + return false; + } + return !isset($this->components['scheme']) && !isset($this->components['host']) && substr($this->components['path'], 0, 1) !== '/'; + } + + /** + * Get path component of current URL + * + * @return string Path + */ + public function get_path() + { + return isset($this->components['path']) ? $this->components['path'] : ''; + } + + /** + * Set path component + * + * @param string $path Path component + * @param boolean $urlencode If true, parts of path should be encoded with rawurlencode() + */ + public function set_path($path, $urlencode = false) + { + // Since 1.7.0 Twig returns the real path of the file. We need it to be relative to the working directory. + $real_root_path = realpath($this->path_helper->get_phpbb_root_path()) . DIRECTORY_SEPARATOR; + + // If the asset is under the phpBB root path we need to remove its path and then prepend $phpbb_root_path + if (substr($path . DIRECTORY_SEPARATOR, 0, strlen($real_root_path)) === $real_root_path) + { + $path = $this->path_helper->get_phpbb_root_path() . str_replace('\\', '/', substr($path, strlen($real_root_path))); + } + else + { + // Else we make the path relative to the current working directory + $real_root_path = realpath('.') . DIRECTORY_SEPARATOR; + if ($real_root_path && substr($path . DIRECTORY_SEPARATOR, 0, strlen($real_root_path)) === $real_root_path) + { + $path = str_replace('\\', '/', substr($path, strlen($real_root_path))); + } + } + + if ($urlencode) + { + $paths = explode('/', $path); + foreach ($paths as &$dir) + { + $dir = rawurlencode($dir); + } + $path = implode('/', $paths); + } + + $this->components['path'] = $path; + } + + /** + * Add assets_version parameter to URL. + * Parameter will not be added if assets_version already exists in URL + * + * @param string $version Version + */ + public function add_assets_version($version) + { + if (!isset($this->components['query'])) + { + $this->components['query'] = 'assets_version=' . $version; + return; + } + $query = $this->components['query']; + if (!preg_match('/(^|[&;])assets_version=/', $query)) + { + $this->components['query'] = $query . '&assets_version=' . $version; + } + } +} diff --git a/phpBB/phpbb/template/base.php b/phpBB/phpbb/template/base.php new file mode 100644 index 0000000000..41c0a01ba8 --- /dev/null +++ b/phpBB/phpbb/template/base.php @@ -0,0 +1,164 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template; + +abstract class base implements template +{ + /** + * Template context. + * Stores template data used during template rendering. + * + * @var \phpbb\template\context + */ + protected $context; + + /** + * Array of filenames assigned to set_filenames + * + * @var array + */ + protected $filenames = array(); + + /** + * {@inheritdoc} + */ + public function set_filenames(array $filename_array) + { + $this->filenames = array_merge($this->filenames, $filename_array); + + return $this; + } + + /** + * Get a filename from the handle + * + * @param string $handle + * @return string + */ + protected function get_filename_from_handle($handle) + { + return (isset($this->filenames[$handle])) ? $this->filenames[$handle] : $handle; + } + + /** + * {@inheritdoc} + */ + public function destroy() + { + $this->context->clear(); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function destroy_block_vars($blockname) + { + $this->context->destroy_block_vars($blockname); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function assign_vars(array $vararray) + { + foreach ($vararray as $key => $val) + { + $this->assign_var($key, $val); + } + + return $this; + } + + /** + * {@inheritdoc} + */ + public function assign_var($varname, $varval) + { + $this->context->assign_var($varname, $varval); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function append_var($varname, $varval) + { + $this->context->append_var($varname, $varval); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function assign_block_vars($blockname, array $vararray) + { + $this->context->assign_block_vars($blockname, $vararray); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function assign_block_vars_array($blockname, array $block_vars_array) + { + $this->context->assign_block_vars_array($blockname, $block_vars_array); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function alter_block_array($blockname, array $vararray, $key = false, $mode = 'insert') + { + return $this->context->alter_block_array($blockname, $vararray, $key, $mode); + } + + /** + * {@inheritdoc} + */ + public function find_key_index($blockname, $key) + { + return $this->context->find_key_index($blockname, $key); + } + + /** + * Calls hook if any is defined. + * + * @param string $handle Template handle being displayed. + * @param string $method Method name of the caller. + */ + protected function call_hook($handle, $method) + { + global $phpbb_hook; + + if (!empty($phpbb_hook) && $phpbb_hook->call_hook(array('template', $method), $handle, $this)) + { + if ($phpbb_hook->hook_return(array('template', $method))) + { + $result = $phpbb_hook->hook_return_result(array('template', $method)); + return array($result); + } + } + + return false; + } +} diff --git a/phpBB/phpbb/template/context.php b/phpBB/phpbb/template/context.php new file mode 100644 index 0000000000..5d04a09865 --- /dev/null +++ b/phpBB/phpbb/template/context.php @@ -0,0 +1,540 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template; + +/** +* Stores variables assigned to template. +*/ +class context +{ + /** + * variable that holds all the data we'll be substituting into + * the compiled templates. Takes form: + * --> $this->tpldata[block][iteration#][child][iteration#][child2][iteration#][variablename] == value + * if it's a root-level variable, it'll be like this: + * --> $this->tpldata[.][0][varname] == value + * + * @var array + */ + private $tpldata = array('.' => array(0 => array())); + + /** + * @var array Reference to template->tpldata['.'][0] + */ + private $rootref; + + /** + * @var bool + */ + private $num_rows_is_set; + + public function __construct() + { + $this->clear(); + } + + /** + * Clears template data set. + */ + public function clear() + { + $this->tpldata = array('.' => array(0 => array())); + $this->rootref = &$this->tpldata['.'][0]; + $this->num_rows_is_set = false; + } + + /** + * Assign a single scalar value to a single key. + * + * Value can be a string, an integer or a boolean. + * + * @param string $varname Variable name + * @param string $varval Value to assign to variable + * @return true + */ + public function assign_var($varname, $varval) + { + $this->rootref[$varname] = $varval; + + return true; + } + + /** + * Append text to the string value stored in a key. + * + * Text is appended using the string concatenation operator (.). + * + * @param string $varname Variable name + * @param string $varval Value to append to variable + * @return true + */ + public function append_var($varname, $varval) + { + $this->rootref[$varname] = (isset($this->rootref[$varname]) ? $this->rootref[$varname] : '') . $varval; + + return true; + } + + /** + * Returns a reference to template data array. + * + * This function is public so that template renderer may invoke it. + * Users should alter template variables via functions in \phpbb\template\template. + * + * Note: modifying returned array will affect data stored in the context. + * + * @return array template data + */ + public function &get_data_ref() + { + // returning a reference directly is not + // something php is capable of doing + $ref = &$this->tpldata; + + if (!$this->num_rows_is_set) + { + /* + * We do not set S_NUM_ROWS while adding a row, to reduce the complexity + * If we would set it on adding, each subsequent adding would cause + * n modifications, resulting in a O(n!) complexity, rather then O(n) + */ + foreach ($ref as $loop_name => &$loop_data) + { + if ($loop_name === '.') + { + continue; + } + + $this->set_num_rows($loop_data); + } + $this->num_rows_is_set = true; + } + + return $ref; + } + + /** + * Set S_NUM_ROWS for each row in this template block + * + * @param array $loop_data + */ + protected function set_num_rows(&$loop_data) + { + $s_num_rows = sizeof($loop_data); + foreach ($loop_data as &$mod_block) + { + foreach ($mod_block as $sub_block_name => &$sub_block) + { + // If the key name is lowercase and the data is an array, + // it could be a template loop. So we set the S_NUM_ROWS there + // aswell. + if ($sub_block_name === strtolower($sub_block_name) && is_array($sub_block)) + { + $this->set_num_rows($sub_block); + } + } + + // Check whether we are inside a block before setting the variable + if (isset($mod_block['S_BLOCK_NAME'])) + { + $mod_block['S_NUM_ROWS'] = $s_num_rows; + } + } + } + + /** + * Returns a reference to template root scope. + * + * This function is public so that template renderer may invoke it. + * Users should not need to invoke this function. + * + * Note: modifying returned array will affect data stored in the context. + * + * @return array template data + */ + public function &get_root_ref() + { + // rootref is already a reference + return $this->rootref; + } + + /** + * Assign key variable pairs from an array to a specified block + * + * @param string $blockname Name of block to assign $vararray to + * @param array $vararray A hash of variable name => value pairs + * @return true + */ + public function assign_block_vars($blockname, array $vararray) + { + $this->num_rows_is_set = false; + if (strpos($blockname, '.') !== false) + { + // Nested block. + $blocks = explode('.', $blockname); + $blockcount = sizeof($blocks) - 1; + + $str = &$this->tpldata; + for ($i = 0; $i < $blockcount; $i++) + { + $str = &$str[$blocks[$i]]; + $str = &$str[sizeof($str) - 1]; + } + + $s_row_count = isset($str[$blocks[$blockcount]]) ? sizeof($str[$blocks[$blockcount]]) : 0; + $vararray['S_ROW_COUNT'] = $vararray['S_ROW_NUM'] = $s_row_count; + + // Assign S_FIRST_ROW + if (!$s_row_count) + { + $vararray['S_FIRST_ROW'] = true; + } + + // Assign S_BLOCK_NAME + $vararray['S_BLOCK_NAME'] = $blocks[$blockcount]; + + // Now the tricky part, we always assign S_LAST_ROW and remove the entry before + // This is much more clever than going through the complete template data on display (phew) + $vararray['S_LAST_ROW'] = true; + if ($s_row_count > 0) + { + unset($str[$blocks[$blockcount]][($s_row_count - 1)]['S_LAST_ROW']); + } + + // Now we add the block that we're actually assigning to. + // We're adding a new iteration to this block with the given + // variable assignments. + $str[$blocks[$blockcount]][] = $vararray; + } + else + { + // Top-level block. + $s_row_count = (isset($this->tpldata[$blockname])) ? sizeof($this->tpldata[$blockname]) : 0; + $vararray['S_ROW_COUNT'] = $vararray['S_ROW_NUM'] = $s_row_count; + + // Assign S_FIRST_ROW + if (!$s_row_count) + { + $vararray['S_FIRST_ROW'] = true; + } + + // Assign S_BLOCK_NAME + $vararray['S_BLOCK_NAME'] = $blockname; + + // We always assign S_LAST_ROW and remove the entry before + $vararray['S_LAST_ROW'] = true; + if ($s_row_count > 0) + { + unset($this->tpldata[$blockname][($s_row_count - 1)]['S_LAST_ROW']); + } + + // Add a new iteration to this block with the variable assignments we were given. + $this->tpldata[$blockname][] = $vararray; + } + + return true; + } + + /** + * Assign key variable pairs from an array to a whole specified block loop + * + * @param string $blockname Name of block to assign $block_vars_array to + * @param array $block_vars_array An array of hashes of variable name => value pairs + * @return true + */ + public function assign_block_vars_array($blockname, array $block_vars_array) + { + foreach ($block_vars_array as $vararray) + { + $this->assign_block_vars($blockname, $vararray); + } + + return true; + } + + /** + * Find the index for a specified key in the innermost specified block + * + * @param string $blockname the blockname, for example 'loop' + * @param mixed $key Key to search for + * + * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position] + * + * int: Position [the position to search for] + * + * If key is false the position is set to 0 + * If key is true the position is set to the last entry + * + * @return mixed false if not found, index position otherwise; be sure to test with === + */ + public function find_key_index($blockname, $key) + { + // For nested block, $blockcount > 0, for top-level block, $blockcount == 0 + $blocks = explode('.', $blockname); + $blockcount = sizeof($blocks) - 1; + + $block = $this->tpldata; + for ($i = 0; $i < $blockcount; $i++) + { + if (($pos = strpos($blocks[$i], '[')) !== false) + { + $name = substr($blocks[$i], 0, $pos); + + if (strpos($blocks[$i], '[]') === $pos) + { + $index = sizeof($block[$name]) - 1; + } + else + { + $index = min((int) substr($blocks[$i], $pos + 1, -1), sizeof($block[$name]) - 1); + } + } + else + { + $name = $blocks[$i]; + $index = sizeof($block[$name]) - 1; + } + if (!isset($block[$name])) + { + return false; + } + $block = $block[$name]; + if (!isset($block[$index])) + { + return false; + } + $block = $block[$index]; + } + + if (!isset($block[$blocks[$i]])) + { + return false; + } + $block = $block[$blocks[$i]]; // Traverse the last block + + // Change key to zero (change first position) if false and to last position if true + if ($key === false || $key === true) + { + return ($key === false) ? 0 : sizeof($block) - 1; + } + + // Get correct position if array given + if (is_array($key)) + { + // Search array to get correct position + list($search_key, $search_value) = @each($key); + foreach ($block as $i => $val_ary) + { + if ($val_ary[$search_key] === $search_value) + { + return $i; + } + } + } + + return (is_int($key) && ((0 <= $key) && ($key < sizeof($block)))) ? $key : false; + } + + /** + * Change already assigned key variable pair (one-dimensional - single loop entry) + * + * An example of how to use this function: + * {@example alter_block_array.php} + * + * @param string $blockname the blockname, for example 'loop' + * @param array $vararray the var array to insert/add or merge + * @param mixed $key Key to search for + * + * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position] + * + * int: Position [the position to change or insert at directly given] + * + * If key is false the position is set to 0 + * If key is true the position is set to the last entry + * + * @param string $mode Mode to execute (valid modes are 'insert' and 'change') + * + * If insert, the vararray is inserted at the given position (position counting from zero). + * If change, the current block gets merged with the vararray (resulting in new key/value pairs be added and existing keys be replaced by the new \value). + * + * Since counting begins by zero, inserting at the last position will result in this array: array(vararray, last positioned array) + * and inserting at position 1 will result in this array: array(first positioned array, vararray, following vars) + * + * @return bool false on error, true on success + */ + public function alter_block_array($blockname, array $vararray, $key = false, $mode = 'insert') + { + $this->num_rows_is_set = false; + + // For nested block, $blockcount > 0, for top-level block, $blockcount == 0 + $blocks = explode('.', $blockname); + $blockcount = sizeof($blocks) - 1; + + $block = &$this->tpldata; + for ($i = 0; $i < $blockcount; $i++) + { + if (($pos = strpos($blocks[$i], '[')) !== false) + { + $name = substr($blocks[$i], 0, $pos); + + if (strpos($blocks[$i], '[]') === $pos) + { + $index = sizeof($block[$name]) - 1; + } + else + { + $index = min((int) substr($blocks[$i], $pos + 1, -1), sizeof($block[$name]) - 1); + } + } + else + { + $name = $blocks[$i]; + $index = sizeof($block[$name]) - 1; + } + $block = &$block[$name]; + $block = &$block[$index]; + } + $name = $blocks[$i]; + + // If last block does not exist and we are inserting, and not searching for key, we create it empty; otherwise, nothing to do + if (!isset($block[$name])) + { + if ($mode != 'insert' || is_array($key)) + { + return false; + } + $block[$name] = array(); + } + + $block = &$block[$name]; // Now we can traverse the last block + + // Change key to zero (change first position) if false and to last position if true + if ($key === false || $key === true) + { + $key = ($key === false) ? 0 : sizeof($block); + } + + // Get correct position if array given + if (is_array($key)) + { + // Search array to get correct position + list($search_key, $search_value) = @each($key); + + $key = null; + foreach ($block as $i => $val_ary) + { + if ($val_ary[$search_key] === $search_value) + { + $key = $i; + break; + } + } + + // key/value pair not found + if ($key === null) + { + return false; + } + } + + // Insert Block + if ($mode == 'insert') + { + // Make sure we are not exceeding the last iteration + if ($key >= sizeof($block)) + { + $key = sizeof($block); + unset($block[($key - 1)]['S_LAST_ROW']); + $vararray['S_LAST_ROW'] = true; + } + if ($key <= 0) + { + $key = 0; + unset($block[0]['S_FIRST_ROW']); + $vararray['S_FIRST_ROW'] = true; + } + + // Assign S_BLOCK_NAME + $vararray['S_BLOCK_NAME'] = $name; + + // Re-position template blocks + for ($i = sizeof($block); $i > $key; $i--) + { + $block[$i] = $block[$i-1]; + + $block[$i]['S_ROW_COUNT'] = $block[$i]['S_ROW_NUM'] = $i; + } + + // Insert vararray at given position + $block[$key] = $vararray; + $block[$key]['S_ROW_COUNT'] = $block[$key]['S_ROW_NUM'] = $key; + + return true; + } + + // Which block to change? + if ($mode == 'change') + { + // If key is out of bounds, do not change anything + if ($key > sizeof($block) || $key < 0) + { + return false; + } + + if ($key == sizeof($block)) + { + $key--; + } + + $block[$key] = array_merge($block[$key], $vararray); + + return true; + } + + return false; + } + + /** + * Reset/empty complete block + * + * @param string $blockname Name of block to destroy + * @return true + */ + public function destroy_block_vars($blockname) + { + $this->num_rows_is_set = false; + if (strpos($blockname, '.') !== false) + { + // Nested block. + $blocks = explode('.', $blockname); + $blockcount = sizeof($blocks) - 1; + + $str = &$this->tpldata; + for ($i = 0; $i < $blockcount; $i++) + { + $str = &$str[$blocks[$i]]; + $str = &$str[sizeof($str) - 1]; + } + + unset($str[$blocks[$blockcount]]); + } + else + { + // Top-level block. + unset($this->tpldata[$blockname]); + } + + return true; + } +} diff --git a/phpBB/phpbb/template/template.php b/phpBB/phpbb/template/template.php new file mode 100644 index 0000000000..9e3d658ca8 --- /dev/null +++ b/phpBB/phpbb/template/template.php @@ -0,0 +1,199 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template; + +interface template +{ + + /** + * Clear the cache + * + * @return \phpbb\template\template + */ + public function clear_cache(); + + /** + * Sets the template filenames for handles. + * + * @param array $filename_array Should be a hash of handle => filename pairs. + * @return \phpbb\template\template $this + */ + public function set_filenames(array $filename_array); + + /** + * Get the style tree of the style preferred by the current user + * + * @return array Style tree, most specific first + */ + public function get_user_style(); + + /** + * Set style location based on (current) user's chosen style. + * + * @param array $style_directories The directories to add style paths for + * E.g. array('ext/foo/bar/styles', 'styles') + * Default: array('styles') (phpBB's style directory) + * @return \phpbb\template\template $this + */ + public function set_style($style_directories = array('styles')); + + /** + * Set custom style location (able to use directory outside of phpBB). + * + * Note: Templates are still compiled to phpBB's cache directory. + * + * @param string|array $names Array of names or string of name of template(s) in inheritance tree order, used by extensions. + * @param string|array or string $paths Array of style paths, relative to current root directory + * @return \phpbb\template\template $this + */ + public function set_custom_style($names, $paths); + + /** + * Clears all variables and blocks assigned to this template. + * + * @return \phpbb\template\template $this + */ + public function destroy(); + + /** + * Reset/empty complete block + * + * @param string $blockname Name of block to destroy + * @return \phpbb\template\template $this + */ + public function destroy_block_vars($blockname); + + /** + * Display a template for provided handle. + * + * The template will be loaded and compiled, if necessary, first. + * + * This function calls hooks. + * + * @param string $handle Handle to display + * @return \phpbb\template\template $this + */ + public function display($handle); + + /** + * Display the handle and assign the output to a template variable + * or return the compiled result. + * + * @param string $handle Handle to operate on + * @param string $template_var Template variable to assign compiled handle to + * @param bool $return_content If true return compiled handle, otherwise assign to $template_var + * @return \phpbb\template\template|string if $return_content is true return string of the compiled handle, otherwise return $this + */ + public function assign_display($handle, $template_var = '', $return_content = true); + + /** + * Assign key variable pairs from an array + * + * @param array $vararray A hash of variable name => value pairs + * @return \phpbb\template\template $this + */ + public function assign_vars(array $vararray); + + /** + * Assign a single scalar value to a single key. + * + * Value can be a string, an integer or a boolean. + * + * @param string $varname Variable name + * @param string $varval Value to assign to variable + * @return \phpbb\template\template $this + */ + public function assign_var($varname, $varval); + + /** + * Append text to the string value stored in a key. + * + * Text is appended using the string concatenation operator (.). + * + * @param string $varname Variable name + * @param string $varval Value to append to variable + * @return \phpbb\template\template $this + */ + public function append_var($varname, $varval); + + /** + * Assign key variable pairs from an array to a specified block + * @param string $blockname Name of block to assign $vararray to + * @param array $vararray A hash of variable name => value pairs + * @return \phpbb\template\template $this + */ + public function assign_block_vars($blockname, array $vararray); + + /** + * Assign key variable pairs from an array to a whole specified block loop + * @param string $blockname Name of block to assign $block_vars_array to + * @param array $block_vars_array An array of hashes of variable name => value pairs + * @return \phpbb\template\template $this + */ + public function assign_block_vars_array($blockname, array $block_vars_array); + + /** + * Change already assigned key variable pair (one-dimensional - single loop entry) + * + * An example of how to use this function: + * {@example alter_block_array.php} + * + * @param string $blockname the blockname, for example 'loop' + * @param array $vararray the var array to insert/add or merge + * @param mixed $key Key to search for + * + * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position] + * + * int: Position [the position to change or insert at directly given] + * + * If key is false the position is set to 0 + * If key is true the position is set to the last entry + * + * @param string $mode Mode to execute (valid modes are 'insert' and 'change') + * + * If insert, the vararray is inserted at the given position (position counting from zero). + * If change, the current block gets merged with the vararray (resulting in new \key/value pairs be added and existing keys be replaced by the new \value). + * + * Since counting begins by zero, inserting at the last position will result in this array: array(vararray, last positioned array) + * and inserting at position 1 will result in this array: array(first positioned array, vararray, following vars) + * + * @return bool false on error, true on success + */ + public function alter_block_array($blockname, array $vararray, $key = false, $mode = 'insert'); + + /** + * Find the index for a specified key in the innermost specified block + * + * @param string $blockname the blockname, for example 'loop' + * @param mixed $key Key to search for + * + * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position] + * + * int: Position [the position to search for] + * + * If key is false the position is set to 0 + * If key is true the position is set to the last entry + * + * @return mixed false if not found, index position otherwise; be sure to test with === + */ + public function find_key_index($blockname, $key); + + /** + * Get path to template for handle (required for BBCode parser) + * + * @param string $handle Handle to retrieve the source file + * @return string + */ + public function get_source_file_for_handle($handle); +} diff --git a/phpBB/phpbb/template/twig/definition.php b/phpBB/phpbb/template/twig/definition.php new file mode 100644 index 0000000000..cb3c953692 --- /dev/null +++ b/phpBB/phpbb/template/twig/definition.php @@ -0,0 +1,69 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig; + +/** +* This class holds all DEFINE variables from the current page load +*/ +class definition +{ + /** @var array **/ + protected $definitions = array(); + + /** + * Get a DEFINE'd variable + * + * @param string $name + * @param array $arguments + * + * @return mixed Null if not found + */ + public function __call($name, $arguments) + { + return (isset($this->definitions[$name])) ? $this->definitions[$name] : null; + } + + /** + * DEFINE a variable + * + * @param string $name + * @param mixed $value + * @return \phpbb\template\twig\definition + */ + public function set($name, $value) + { + $this->definitions[$name] = $value; + + return $this; + } + + /** + * Append to a variable + * + * @param string $name + * @param string $value + * @return \phpbb\template\twig\definition + */ + public function append($name, $value) + { + if (!isset($this->definitions[$name])) + { + $this->definitions[$name] = ''; + } + + $this->definitions[$name] .= $value; + + return $this; + } +} diff --git a/phpBB/phpbb/template/twig/environment.php b/phpBB/phpbb/template/twig/environment.php new file mode 100644 index 0000000000..476ffd935e --- /dev/null +++ b/phpBB/phpbb/template/twig/environment.php @@ -0,0 +1,205 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig; + +class environment extends \Twig_Environment +{ + /** @var \phpbb\config\config */ + protected $phpbb_config; + + /** @var \phpbb\path_helper */ + protected $phpbb_path_helper; + + /** @var \phpbb\extension\manager */ + protected $extension_manager; + + /** @var string */ + protected $phpbb_root_path; + + /** @var string */ + protected $web_root_path; + + /** @var array **/ + protected $namespace_look_up_order = array('__main__'); + + /** + * Constructor + * + * @param \phpbb\config\config $phpbb_config The phpBB configuration + * @param \phpbb\path_helper $path_helper phpBB path helper + * @param \phpbb\extension\manager $extension_manager phpBB extension manager + * @param \Twig_LoaderInterface $loader Twig loader interface + * @param array $options Array of options to pass to Twig + */ + public function __construct($phpbb_config, \phpbb\path_helper $path_helper, \phpbb\extension\manager $extension_manager = null, \Twig_LoaderInterface $loader = null, $options = array()) + { + $this->phpbb_config = $phpbb_config; + + $this->phpbb_path_helper = $path_helper; + $this->extension_manager = $extension_manager; + + $this->phpbb_root_path = $this->phpbb_path_helper->get_phpbb_root_path(); + $this->web_root_path = $this->phpbb_path_helper->get_web_root_path(); + + return parent::__construct($loader, $options); + } + + /** + * Get the list of enabled phpBB extensions + * + * Used in EVENT node + * + * @return array + */ + public function get_phpbb_extensions() + { + return ($this->extension_manager) ? $this->extension_manager->all_enabled() : array(); + } + + /** + * Get phpBB config + * + * @return \phpbb\config\config + */ + public function get_phpbb_config() + { + return $this->phpbb_config; + } + + /** + * Get the phpBB root path + * + * @return string + */ + public function get_phpbb_root_path() + { + return $this->phpbb_root_path; + } + + /** + * Get the web root path + * + * @return string + */ + public function get_web_root_path() + { + return $this->web_root_path; + } + + /** + * Get the phpbb path helper object + * + * @return \phpbb\path_helper + */ + public function get_path_helper() + { + return $this->phpbb_path_helper; + } + + /** + * Get the namespace look up order + * + * @return array + */ + public function getNamespaceLookUpOrder() + { + return $this->namespace_look_up_order; + } + + /** + * Set the namespace look up order to load templates from + * + * @param array $namespace + * @return \Twig_Environment + */ + public function setNamespaceLookUpOrder($namespace) + { + $this->namespace_look_up_order = $namespace; + + return $this; + } + + /** + * Loads a template by name. + * + * @param string $name The template name + * @param integer $index The index if it is an embedded template + * @return \Twig_TemplateInterface A template instance representing the given template name + * @throws \Twig_Error_Loader + */ + public function loadTemplate($name, $index = null) + { + if (strpos($name, '@') === false) + { + foreach ($this->getNamespaceLookUpOrder() as $namespace) + { + try + { + if ($namespace === '__main__') + { + return parent::loadTemplate($name, $index); + } + + return parent::loadTemplate('@' . $namespace . '/' . $name, $index); + } + catch (\Twig_Error_Loader $e) + { + } + } + + // We were unable to load any templates + throw $e; + } + else + { + return parent::loadTemplate($name, $index); + } + } + + /** + * Finds a template by name. + * + * @param string $name The template name + * @return string + * @throws \Twig_Error_Loader + */ + public function findTemplate($name) + { + if (strpos($name, '@') === false) + { + foreach ($this->getNamespaceLookUpOrder() as $namespace) + { + try + { + if ($namespace === '__main__') + { + return parent::getLoader()->getCacheKey($name); + } + + return parent::getLoader()->getCacheKey('@' . $namespace . '/' . $name); + } + catch (\Twig_Error_Loader $e) + { + } + } + + // We were unable to load any templates + throw $e; + } + else + { + return parent::getLoader()->getCacheKey($name); + } + } +} diff --git a/phpBB/phpbb/template/twig/extension.php b/phpBB/phpbb/template/twig/extension.php new file mode 100644 index 0000000000..d5b14129b5 --- /dev/null +++ b/phpBB/phpbb/template/twig/extension.php @@ -0,0 +1,184 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig; + +class extension extends \Twig_Extension +{ + /** @var \phpbb\template\context */ + protected $context; + + /** @var \phpbb\user */ + protected $user; + + /** + * Constructor + * + * @param \phpbb\template\context $context + * @param \phpbb\user $user + * @return \phpbb\template\twig\extension + */ + public function __construct(\phpbb\template\context $context, $user) + { + $this->context = $context; + $this->user = $user; + } + + /** + * Get the name of this extension + * + * @return string + */ + public function getName() + { + return 'phpbb'; + } + + /** + * Returns the token parser instance to add to the existing list. + * + * @return array An array of Twig_TokenParser instances + */ + public function getTokenParsers() + { + return array( + new \phpbb\template\twig\tokenparser\defineparser, + new \phpbb\template\twig\tokenparser\includeparser, + new \phpbb\template\twig\tokenparser\includejs, + new \phpbb\template\twig\tokenparser\includecss, + new \phpbb\template\twig\tokenparser\event, + new \phpbb\template\twig\tokenparser\includephp, + new \phpbb\template\twig\tokenparser\php, + ); + } + + /** + * Returns a list of filters to add to the existing list. + * + * @return array An array of filters + */ + public function getFilters() + { + return array( + new \Twig_SimpleFilter('subset', array($this, 'loop_subset'), array('needs_environment' => true)), + new \Twig_SimpleFilter('addslashes', 'addslashes'), + ); + } + + /** + * Returns a list of global functions to add to the existing list. + * + * @return array An array of global functions + */ + public function getFunctions() + { + return array( + new \Twig_SimpleFunction('lang', array($this, 'lang')), + ); + } + + /** + * Returns a list of operators to add to the existing list. + * + * @return array An array of operators + */ + public function getOperators() + { + return array( + array( + '!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'), + ), + array( + // precedence settings are copied from similar operators in Twig core extension + '||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + '&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + + 'eq' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Equal', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + + 'ne' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + 'neq' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + '<>' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + + '===' => array('precedence' => 20, 'class' => '\phpbb\template\twig\node\expression\binary\equalequal', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + '!==' => array('precedence' => 20, 'class' => '\phpbb\template\twig\node\expression\binary\notequalequal', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + + 'gt' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Greater', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + 'gte' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_GreaterEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + 'ge' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_GreaterEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + 'lt' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Less', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + 'lte' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_LessEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + 'le' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_LessEqual', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + + 'mod' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mod', 'associativity' => \Twig_ExpressionParser::OPERATOR_LEFT), + ), + ); + } + + /** + * Grabs a subset of a loop + * + * @param \Twig_Environment $env A Twig_Environment instance + * @param mixed $item A variable + * @param integer $start Start of the subset + * @param integer $end End of the subset + * @param Boolean $preserveKeys Whether to preserve key or not (when the input is an array) + * + * @return mixed The sliced variable + */ + function loop_subset(\Twig_Environment $env, $item, $start, $end = null, $preserveKeys = false) + { + // We do almost the same thing as Twig's slice (array_slice), except when $end is positive + if ($end >= 1) + { + // When end is > 1, subset will end on the last item in an array with the specified $end + // This is different from slice in that it is the number we end on rather than the number + // of items to grab (length) + + // Start must always be the actual starting number for this calculation (not negative) + $start = ($start < 0) ? sizeof($item) + $start : $start; + $end = $end - $start; + } + + // We always include the last element (this was the past design) + $end = ($end == -1 || $end === null) ? null : $end + 1; + + return twig_slice($env, $item, $start, $end, $preserveKeys); + } + + /** + * Get output for a language variable (L_FOO, LA_FOO) + * + * This function checks to see if the language var was outputted to $context + * (e.g. in the ACP, L_TITLE) + * If not, we return the result of $user->lang() + * + * @return string + */ + function lang() + { + $args = func_get_args(); + $key = $args[0]; + + $context_vars = $this->context->get_root_ref(); + + if (isset($context_vars['L_' . $key])) + { + return $context_vars['L_' . $key]; + } + + // LA_ is transformed into lang(\'$1\')|addslashes, so we should not + // need to check for it + + return call_user_func_array(array($this->user, 'lang'), $args); + } +} diff --git a/phpBB/phpbb/template/twig/lexer.php b/phpBB/phpbb/template/twig/lexer.php new file mode 100644 index 0000000000..c5dc7273ba --- /dev/null +++ b/phpBB/phpbb/template/twig/lexer.php @@ -0,0 +1,354 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig; + +class lexer extends \Twig_Lexer +{ + public function tokenize($code, $filename = null) + { + // Our phpBB tags + // Commented out tokens are handled separately from the main replace + $phpbb_tags = array( + /*'BEGIN', + 'BEGINELSE', + 'END', + 'IF', + 'ELSE', + 'ELSEIF', + 'ENDIF', + 'DEFINE', + 'UNDEFINE',*/ + 'ENDDEFINE', + 'INCLUDE', + 'INCLUDEPHP', + 'INCLUDEJS', + 'INCLUDECSS', + 'PHP', + 'ENDPHP', + 'EVENT', + ); + + // Twig tag masks + $twig_tags = array( + 'autoescape', + 'endautoescape', + 'if', + 'elseif', + 'else', + 'endif', + 'block', + 'endblock', + 'use', + 'extends', + 'embed', + 'filter', + 'endfilter', + 'flush', + 'for', + 'endfor', + 'macro', + 'endmacro', + 'import', + 'from', + 'sandbox', + 'endsandbox', + 'set', + 'endset', + 'spaceless', + 'endspaceless', + 'verbatim', + 'endverbatim', + ); + + // Fix tokens that may have inline variables (e.g. <!-- DEFINE $TEST = '{FOO}') + $code = $this->strip_surrounding_quotes(array( + 'INCLUDE', + 'INCLUDEPHP', + 'INCLUDEJS', + 'INCLUDECSS', + ), $code); + $code = $this->fix_inline_variable_tokens(array( + 'DEFINE \$[a-zA-Z0-9_]+ =', + 'INCLUDE', + 'INCLUDEPHP', + 'INCLUDEJS', + 'INCLUDECSS', + ), $code); + $code = $this->add_surrounding_quotes(array( + 'INCLUDE', + 'INCLUDEPHP', + 'INCLUDEJS', + 'INCLUDECSS', + ), $code); + + // Fix our BEGIN statements + $code = $this->fix_begin_tokens($code); + + // Fix our IF tokens + $code = $this->fix_if_tokens($code); + + // Fix our DEFINE tokens + $code = $this->fix_define_tokens($code); + + // Replace all of our starting tokens, <!-- TOKEN --> with Twig style, {% TOKEN %} + // This also strips outer parenthesis, <!-- IF (blah) --> becomes <!-- IF blah --> + $code = preg_replace('#<!-- (' . implode('|', $phpbb_tags) . ')(?: (.*?) ?)?-->#', '{% $1 $2 %}', $code); + + // Replace all of our twig masks with Twig code (e.g. <!-- BLOCK .+ --> with {% block $1 %}) + $code = $this->replace_twig_tag_masks($code, $twig_tags); + + // Replace all of our language variables, {L_VARNAME}, with Twig style, {{ lang('NAME') }} + // Appends any filters after lang() + $code = preg_replace('#{L_([a-zA-Z0-9_\.]+)(\|[^}]+?)?}#', '{{ lang(\'$1\')$2 }}', $code); + + // Replace all of our escaped language variables, {LA_VARNAME}, with Twig style, {{ lang('NAME')|addslashes }} + // Appends any filters after lang(), but before addslashes + $code = preg_replace('#{LA_([a-zA-Z0-9_\.]+)(\|[^}]+?)?}#', '{{ lang(\'$1\')$2|addslashes }}', $code); + + // Replace all of our variables, {VARNAME}, with Twig style, {{ VARNAME }} + // Appends any filters + $code = preg_replace('#{([a-zA-Z0-9_\.]+)(\|[^}]+?)?}#', '{{ $1$2 }}', $code); + + return parent::tokenize($code, $filename); + } + + /** + * Strip surrounding quotes + * + * First step to fix tokens that may have inline variables + * E.g. <!-- INCLUDE '{TEST}.html' to <!-- INCLUDE {TEST}.html + * + * @param array $tokens array of tokens to search for (imploded to a regular expression) + * @param string $code + * @return string + */ + protected function strip_surrounding_quotes($tokens, $code) + { + // Remove matching quotes at the beginning/end if a statement; + // E.g. 'asdf'"' -> asdf'" + // E.g. "asdf'"" -> asdf'" + // E.g. 'asdf'" -> 'asdf'" + return preg_replace('#<!-- (' . implode('|', $tokens) . ') (([\'"])?(.*?)\1) -->#', '<!-- $1 $2 -->', $code); + } + + /** + * Fix tokens that may have inline variables + * + * Second step to fix tokens that may have inline variables + * E.g. <!-- INCLUDE '{TEST}.html' to <!-- INCLUDE ' ~ {TEST} ~ '.html + * + * @param array $tokens array of tokens to search for (imploded to a regular expression) + * @param string $code + * @return string + */ + protected function fix_inline_variable_tokens($tokens, $code) + { + $callback = function($matches) + { + // Replace template variables with start/end to parse variables (' ~ TEST ~ '.html) + $matches[2] = preg_replace('#{([a-zA-Z0-9_\.$]+)}#', "'~ \$1 ~'", $matches[2]); + + return "<!-- {$matches[1]} {$matches[2]} -->"; + }; + + return preg_replace_callback('#<!-- (' . implode('|', $tokens) . ') (.+?) -->#', $callback, $code); + } + + /** + * Add surrounding quotes + * + * Last step to fix tokens that may have inline variables + * E.g. <!-- INCLUDE '{TEST}.html' to <!-- INCLUDE '' ~ {TEST} ~ '.html' + * + * @param array $tokens array of tokens to search for (imploded to a regular expression) + * @param string $code + * @return string + */ + protected function add_surrounding_quotes($tokens, $code) + { + return preg_replace('#<!-- (' . implode('|', $tokens) . ') (.+?) -->#', '<!-- $1 \'$2\' -->', $code); + } + + /** + * Fix begin tokens (convert our BEGIN to Twig for) + * + * Not meant to be used outside of this context, public because the anonymous function calls this + * + * @param string $code + * @param array $parent_nodes (used in recursion) + * @return string + */ + public function fix_begin_tokens($code, $parent_nodes = array()) + { + // PHP 5.3 cannot use $this in an anonymous function, so use this as a work-around + $parent_class = $this; + $callback = function ($matches) use ($parent_class, $parent_nodes) + { + $hard_parents = explode('.', $matches[1]); + array_pop($hard_parents); // ends with . + if ($hard_parents) + { + $parent_nodes = array_merge($hard_parents, $parent_nodes); + } + + $name = $matches[2]; + $subset = trim(substr($matches[3], 1, -1)); // Remove parenthesis + $body = $matches[4]; + + // Replace <!-- BEGINELSE --> + $body = str_replace('<!-- BEGINELSE -->', '{% else %}', $body); + + // Is the designer wanting to call another loop in a loop? + // <!-- BEGIN loop --> + // <!-- BEGIN !loop2 --> + // <!-- END !loop2 --> + // <!-- END loop --> + // 'loop2' is actually on the same nesting level as 'loop' you assign + // variables to it with template->assign_block_vars('loop2', array(...)) + if (strpos($name, '!') === 0) + { + // Count the number if ! occurrences + $count = substr_count($name, '!'); + for ($i = 0; $i < $count; $i++) + { + array_pop($parent_nodes); + $name = substr($name, 1); + } + } + + // Remove all parent nodes, e.g. foo, bar from foo.bar.foobar.VAR + foreach ($parent_nodes as $node) + { + $body = preg_replace('#([^a-zA-Z0-9_])' . $node . '\.([a-zA-Z0-9_]+)\.#', '$1$2.', $body); + } + + // Add current node to list of parent nodes for child nodes + $parent_nodes[] = $name; + + // Recursive...fix any child nodes + $body = $parent_class->fix_begin_tokens($body, $parent_nodes); + + // Need the parent variable name + array_pop($parent_nodes); + $parent = (!empty($parent_nodes)) ? end($parent_nodes) . '.' : ''; + + if ($subset !== '') + { + $subset = '|subset(' . $subset . ')'; + } + + $parent = ($parent) ?: 'loops.'; + // Turn into a Twig for loop + return "{% for {$name} in {$parent}{$name}{$subset} %}{$body}{% endfor %}"; + }; + + return preg_replace_callback('#<!-- BEGIN ((?:[a-zA-Z0-9_]+\.)*)([!a-zA-Z0-9_]+)(\([0-9,\-]+\))? -->(.+?)<!-- END \1\2 -->#s', $callback, $code); + } + + /** + * Fix IF statements + * + * @param string $code + * @return string + */ + protected function fix_if_tokens($code) + { + // Replace ELSE IF with ELSEIF + $code = preg_replace('#<!-- ELSE IF (.+?) -->#', '<!-- ELSEIF $1 -->', $code); + + // Replace our "div by" with Twig's divisibleby (Twig does not like test names with spaces) + $code = preg_replace('# div by ([0-9]+)#', ' divisibleby($1)', $code); + + $callback = function($matches) + { + $inner = $matches[2]; + // Replace $TEST with definition.TEST + $inner = preg_replace('#(\s\(*!?)\$([a-zA-Z_0-9]+)#', '$1definition.$2', $inner); + + // Replace .foo with loops.foo|length + $inner = preg_replace('#(\s\(*!?)\.([a-zA-Z_0-9]+)([^a-zA-Z_0-9\.])#', '$1loops.$2|length$3', $inner); + + // Replace .foo.bar with foo.bar|length + $inner = preg_replace('#(\s\(*!?)\.([a-zA-Z_0-9\.]+)([^a-zA-Z_0-9\.])#', '$1$2|length$3', $inner); + + return "<!-- {$matches[1]}IF{$inner}-->"; + }; + + return preg_replace_callback('#<!-- (ELSE)?IF((.*?) (?:\(*!?[\$|\.]([^\s]+)(.*?))?)-->#', $callback, $code); + } + + /** + * Fix DEFINE statements and {$VARNAME} variables + * + * @param string $code + * @return string + */ + protected function fix_define_tokens($code) + { + /** + * Changing $VARNAME to definition.varname because set is only local + * context (e.g. DEFINE $TEST will only make $TEST available in current + * template and any child templates, but not any parent templates). + * + * DEFINE handles setting it properly to definition in its node, but the + * variables reading FROM it need to be altered to definition.VARNAME + * + * Setting up definition as a class in the array passed to Twig + * ($context) makes set definition.TEST available in the global context + */ + + // Replace <!-- DEFINE $NAME with {% DEFINE definition.NAME + $code = preg_replace('#<!-- DEFINE \$(.*?) -->#', '{% DEFINE $1 %}', $code); + + // Changing UNDEFINE NAME to DEFINE NAME = null to save from creating an extra token parser/node + $code = preg_replace('#<!-- UNDEFINE \$(.*?)-->#', '{% DEFINE $1= null %}', $code); + + // Replace all of our variables, {$VARNAME}, with Twig style, {{ definition.VARNAME }} + $code = preg_replace('#{\$([a-zA-Z0-9_\.]+)}#', '{{ definition.$1 }}', $code); + + // Replace all of our variables, ~ $VARNAME ~, with Twig style, ~ definition.VARNAME ~ + $code = preg_replace('#~ \$([a-zA-Z0-9_\.]+) ~#', '~ definition.$1 ~', $code); + + return $code; + } + + /** + * Replace Twig tag masks with Twig tag calls + * + * E.g. <!-- BLOCK foo --> with {% block foo %} + * + * @param string $code + * @param array $twig_tags All tags we want to create a mask for + * @return string + */ + protected function replace_twig_tag_masks($code, $twig_tags) + { + $callback = function ($matches) + { + $matches[1] = strtolower($matches[1]); + + return "{% {$matches[1]}{$matches[2]}%}"; + }; + + foreach ($twig_tags as &$tag) + { + $tag = strtoupper($tag); + } + + // twig_tags is an array of the twig tags, which are all lowercase, but we use all uppercase tags + $code = preg_replace_callback('#<!-- (' . implode('|', $twig_tags) . ')(.*?)-->#',$callback, $code); + + return $code; + } +} diff --git a/phpBB/phpbb/template/twig/loader.php b/phpBB/phpbb/template/twig/loader.php new file mode 100644 index 0000000000..139a413b70 --- /dev/null +++ b/phpBB/phpbb/template/twig/loader.php @@ -0,0 +1,148 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig; + +/** +* Twig Template loader +*/ +class loader extends \Twig_Loader_Filesystem +{ + protected $safe_directories = array(); + + /** + * Set safe directories + * + * @param array $directories Array of directories that are safe (empty to clear) + * @return \Twig_Loader_Filesystem + */ + public function setSafeDirectories($directories = array()) + { + $this->safe_directories = array(); + + if (!empty($directories)) + { + foreach ($directories as $directory) + { + $this->addSafeDirectory($directory); + } + } + + return $this; + } + + /** + * Add safe directory + * + * @param string $directory Directory that should be added + * @return \Twig_Loader_Filesystem + */ + public function addSafeDirectory($directory) + { + $directory = phpbb_realpath($directory); + + if ($directory !== false) + { + $this->safe_directories[] = $directory; + } + + return $this; + } + + /** + * Get current safe directories + * + * @return array + */ + public function getSafeDirectories() + { + return $this->safe_directories; + } + + /** + * Override for parent::validateName() + * + * This is done because we added support for safe directories, and when Twig + * findTemplate() is called, validateName() is called first, which would + * always throw an exception if the file is outside of the configured + * template directories. + */ + protected function validateName($name) + { + return; + } + + /** + * Find the template + * + * Override for Twig_Loader_Filesystem::findTemplate to add support + * for loading from safe directories. + */ + protected function findTemplate($name) + { + $name = (string) $name; + + // normalize name + $name = preg_replace('#/{2,}#', '/', strtr($name, '\\', '/')); + + // If this is in the cache we can skip the entire process below + // as it should have already been validated + if (isset($this->cache[$name])) + { + return $this->cache[$name]; + } + + // First, find the template name. The override above of validateName + // causes the validateName process to be skipped for this call + $file = parent::findTemplate($name); + + try + { + // Try validating the name (which may throw an exception) + parent::validateName($name); + } + catch (\Twig_Error_Loader $e) + { + if (strpos($e->getRawMessage(), 'Looks like you try to load a template outside configured directories') === 0) + { + // Ok, so outside of the configured template directories, we + // can now check if we're within a "safe" directory + + // Find the real path of the directory the file is in + $directory = phpbb_realpath(dirname($file)); + + if ($directory === false) + { + // Some sort of error finding the actual path, must throw the exception + throw $e; + } + + foreach ($this->safe_directories as $safe_directory) + { + if (strpos($directory, $safe_directory) === 0) + { + // The directory being loaded is below a directory + // that is "safe". We're good to load it! + return $file; + } + } + } + + // Not within any safe directories + throw $e; + } + + // No exception from validateName, safe to load. + return $file; + } +} diff --git a/phpBB/phpbb/template/twig/node/definenode.php b/phpBB/phpbb/template/twig/node/definenode.php new file mode 100644 index 0000000000..ddbd151d20 --- /dev/null +++ b/phpBB/phpbb/template/twig/node/definenode.php @@ -0,0 +1,57 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @copyright Portions (c) 2009 Fabien Potencier, Armin Ronacher +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class definenode extends \Twig_Node +{ + public function __construct($capture, \Twig_NodeInterface $name, \Twig_NodeInterface $value, $lineno, $tag = null) + { + parent::__construct(array('name' => $name, 'value' => $value), array('capture' => $capture, 'safe' => false), $lineno, $tag); + } + + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + if ($this->getAttribute('capture')) + { + $compiler + ->write("ob_start();\n") + ->subcompile($this->getNode('value')) + ; + + $compiler->write("\$value = ('' === \$value = ob_get_clean()) ? '' : new \Twig_Markup(\$value, \$this->env->getCharset());\n"); + } + else + { + $compiler + ->write("\$value = ") + ->subcompile($this->getNode('value')) + ->raw(";\n") + ; + } + + $compiler + ->write("\$context['definition']->set('") + ->raw($this->getNode('name')->getAttribute('name')) + ->raw("', \$value);\n") + ; + } +} diff --git a/phpBB/phpbb/template/twig/node/event.php b/phpBB/phpbb/template/twig/node/event.php new file mode 100644 index 0000000000..b765bde98d --- /dev/null +++ b/phpBB/phpbb/template/twig/node/event.php @@ -0,0 +1,82 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class event extends \Twig_Node +{ + /** + * The subdirectory in which all template listener files must be placed + * @var string + */ + protected $listener_directory = 'event/'; + + /** @var \Twig_Environment */ + protected $environment; + + public function __construct(\Twig_Node_Expression $expr, \phpbb\template\twig\environment $environment, $lineno, $tag = null) + { + $this->environment = $environment; + + parent::__construct(array('expr' => $expr), array(), $lineno, $tag); + } + + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $location = $this->listener_directory . $this->getNode('expr')->getAttribute('name'); + + foreach ($this->environment->get_phpbb_extensions() as $ext_namespace => $ext_path) + { + $ext_namespace = str_replace('/', '_', $ext_namespace); + + if (defined('DEBUG')) + { + // If debug mode is enabled, lets check for new/removed EVENT + // templates on page load rather than at compile. This is + // slower, but makes developing extensions easier (no need to + // purge the cache when a new event template file is added) + $compiler + ->write("if (\$this->env->getLoader()->exists('@{$ext_namespace}/{$location}.html')) {\n") + ->indent() + ; + } + + if (defined('DEBUG') || $this->environment->getLoader()->exists('@' . $ext_namespace . '/' . $location . '.html')) + { + $compiler + ->write("\$previous_look_up_order = \$this->env->getNamespaceLookUpOrder();\n") + + // We set the namespace lookup order to be this extension first, then the main path + ->write("\$this->env->setNamespaceLookUpOrder(array('{$ext_namespace}', '__main__'));\n") + ->write("\$this->env->loadTemplate('@{$ext_namespace}/{$location}.html')->display(\$context);\n") + ->write("\$this->env->setNamespaceLookUpOrder(\$previous_look_up_order);\n") + ; + } + + if (defined('DEBUG')) + { + $compiler + ->outdent() + ->write("}\n\n") + ; + } + } + } +} diff --git a/phpBB/phpbb/template/twig/node/expression/binary/equalequal.php b/phpBB/phpbb/template/twig/node/expression/binary/equalequal.php new file mode 100644 index 0000000000..2cd15d59da --- /dev/null +++ b/phpBB/phpbb/template/twig/node/expression/binary/equalequal.php @@ -0,0 +1,22 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node\expression\binary; + +class equalequal extends \Twig_Node_Expression_Binary +{ + public function operator(\Twig_Compiler $compiler) + { + return $compiler->raw('==='); + } +} diff --git a/phpBB/phpbb/template/twig/node/expression/binary/notequalequal.php b/phpBB/phpbb/template/twig/node/expression/binary/notequalequal.php new file mode 100644 index 0000000000..5f2908fb9b --- /dev/null +++ b/phpBB/phpbb/template/twig/node/expression/binary/notequalequal.php @@ -0,0 +1,22 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node\expression\binary; + +class notequalequal extends \Twig_Node_Expression_Binary +{ + public function operator(\Twig_Compiler $compiler) + { + return $compiler->raw('!=='); + } +} diff --git a/phpBB/phpbb/template/twig/node/includeasset.php b/phpBB/phpbb/template/twig/node/includeasset.php new file mode 100644 index 0000000000..15195a226b --- /dev/null +++ b/phpBB/phpbb/template/twig/node/includeasset.php @@ -0,0 +1,81 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +abstract class includeasset extends \Twig_Node +{ + /** @var \Twig_Environment */ + protected $environment; + + public function __construct(\Twig_Node_Expression $expr, \phpbb\template\twig\environment $environment, $lineno, $tag = null) + { + $this->environment = $environment; + + parent::__construct(array('expr' => $expr), array(), $lineno, $tag); + } + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $config = $this->environment->get_phpbb_config(); + + $compiler + ->write("\$asset_file = ") + ->subcompile($this->getNode('expr')) + ->raw(";\n") + ->write("\$asset = new \phpbb\\template\\asset(\$asset_file, \$this->getEnvironment()->get_path_helper());\n") + ->write("if (substr(\$asset_file, 0, 2) !== './' && \$asset->is_relative()) {\n") + ->indent() + ->write("\$asset_path = \$asset->get_path();") + ->write("\$local_file = \$this->getEnvironment()->get_phpbb_root_path() . \$asset_path;\n") + ->write("if (!file_exists(\$local_file)) {\n") + ->indent() + ->write("\$local_file = \$this->getEnvironment()->findTemplate(\$asset_path);\n") + ->write("\$asset->set_path(\$local_file, true);\n") + ->outdent() + ->write("\$asset->add_assets_version('{$config['assets_version']}');\n") + ->write("\$asset_file = \$asset->get_url();\n") + ->write("}\n") + ->outdent() + ->write("}\n") + ->write("\$context['definition']->append('{$this->get_definition_name()}', '") + ; + + $this->append_asset($compiler); + + $compiler + ->raw("\n');\n") + ; + } + + /** + * Get the definition name + * + * @return string (e.g. 'SCRIPTS') + */ + abstract public function get_definition_name(); + + /** + * Append the output code for the asset + * + * @param \Twig_Compiler A Twig_Compiler instance + * @return null + */ + abstract protected function append_asset(\Twig_Compiler $compiler); +} diff --git a/phpBB/phpbb/template/twig/node/includecss.php b/phpBB/phpbb/template/twig/node/includecss.php new file mode 100644 index 0000000000..2dac154036 --- /dev/null +++ b/phpBB/phpbb/template/twig/node/includecss.php @@ -0,0 +1,37 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class includecss extends \phpbb\template\twig\node\includeasset +{ + /** + * {@inheritdoc} + */ + public function get_definition_name() + { + return 'STYLESHEETS'; + } + + /** + * {@inheritdoc} + */ + public function append_asset(\Twig_Compiler $compiler) + { + $compiler + ->raw("<link href=\"' . ") + ->raw("\$asset_file . '\"") + ->raw(' rel="stylesheet" type="text/css" media="screen" />') + ; + } +} diff --git a/phpBB/phpbb/template/twig/node/includejs.php b/phpBB/phpbb/template/twig/node/includejs.php new file mode 100644 index 0000000000..0f67f9ff60 --- /dev/null +++ b/phpBB/phpbb/template/twig/node/includejs.php @@ -0,0 +1,39 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class includejs extends \phpbb\template\twig\node\includeasset +{ + /** + * {@inheritdoc} + */ + public function get_definition_name() + { + return 'SCRIPTS'; + } + + /** + * {@inheritdoc} + */ + protected function append_asset(\Twig_Compiler $compiler) + { + $config = $this->environment->get_phpbb_config(); + + $compiler + ->raw("<script type=\"text/javascript\" src=\"' . ") + ->raw("\$asset_file") + ->raw(". '\"></script>\n") + ; + } +} diff --git a/phpBB/phpbb/template/twig/node/includenode.php b/phpBB/phpbb/template/twig/node/includenode.php new file mode 100644 index 0000000000..c36ac3c324 --- /dev/null +++ b/phpBB/phpbb/template/twig/node/includenode.php @@ -0,0 +1,53 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class includenode extends \Twig_Node_Include +{ + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $compiler + ->write("\$location = ") + ->subcompile($this->getNode('expr')) + ->raw(";\n") + ->write("\$namespace = false;\n") + ->write("if (strpos(\$location, '@') === 0) {\n") + ->indent() + ->write("\$namespace = substr(\$location, 1, strpos(\$location, '/') - 1);\n") + ->write("\$previous_look_up_order = \$this->env->getNamespaceLookUpOrder();\n") + + // We set the namespace lookup order to be this namespace first, then the main path + ->write("\$this->env->setNamespaceLookUpOrder(array(\$namespace, '__main__'));\n") + ->outdent() + ->write("}\n") + ; + + parent::compile($compiler); + + $compiler + ->write("if (\$namespace) {\n") + ->indent() + ->write("\$this->env->setNamespaceLookUpOrder(\$previous_look_up_order);\n") + ->outdent() + ->write("}\n") + ; + } +} diff --git a/phpBB/phpbb/template/twig/node/includephp.php b/phpBB/phpbb/template/twig/node/includephp.php new file mode 100644 index 0000000000..76182c2f84 --- /dev/null +++ b/phpBB/phpbb/template/twig/node/includephp.php @@ -0,0 +1,91 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* Sections (c) 2009 Fabien Potencier, Armin Ronacher +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class includephp extends \Twig_Node +{ + /** @var \Twig_Environment */ + protected $environment; + + public function __construct(\Twig_Node_Expression $expr, \phpbb\template\twig\environment $environment, $lineno, $ignoreMissing = false, $tag = null) + { + $this->environment = $environment; + + parent::__construct(array('expr' => $expr), array('ignore_missing' => (Boolean) $ignoreMissing), $lineno, $tag); + } + + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $config = $this->environment->get_phpbb_config(); + + if (!$config['tpl_allow_php']) + { + $compiler + ->write("// INCLUDEPHP Disabled\n") + ; + + return; + } + + if ($this->getAttribute('ignore_missing')) + { + $compiler + ->write("try {\n") + ->indent() + ; + } + + $compiler + ->write("\$location = ") + ->subcompile($this->getNode('expr')) + ->raw(";\n") + ->write("if (phpbb_is_absolute(\$location)) {\n") + ->indent() + // Absolute path specified + ->write("require(\$location);\n") + ->outdent() + ->write("} else if (file_exists(\$this->getEnvironment()->get_phpbb_root_path() . \$location)) {\n") + ->indent() + // PHP file relative to phpbb_root_path + ->write("require(\$this->getEnvironment()->get_phpbb_root_path() . \$location);\n") + ->outdent() + ->write("} else {\n") + ->indent() + // Local path (behaves like INCLUDE) + ->write("require(\$this->getEnvironment()->getLoader()->getCacheKey(\$location));\n") + ->outdent() + ->write("}\n") + ; + + if ($this->getAttribute('ignore_missing')) + { + $compiler + ->outdent() + ->write("} catch (\Twig_Error_Loader \$e) {\n") + ->indent() + ->write("// ignore missing template\n") + ->outdent() + ->write("}\n\n") + ; + } + } +} diff --git a/phpBB/phpbb/template/twig/node/php.php b/phpBB/phpbb/template/twig/node/php.php new file mode 100644 index 0000000000..4ee415e446 --- /dev/null +++ b/phpBB/phpbb/template/twig/node/php.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\node; + +class php extends \Twig_Node +{ + /** @var \Twig_Environment */ + protected $environment; + + public function __construct(\Twig_Node_Text $text, \phpbb\template\twig\environment $environment, $lineno, $tag = null) + { + $this->environment = $environment; + + parent::__construct(array('text' => $text), array(), $lineno, $tag); + } + + /** + * Compiles the node to PHP. + * + * @param \Twig_Compiler A Twig_Compiler instance + */ + public function compile(\Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $config = $this->environment->get_phpbb_config(); + + if (!$config['tpl_allow_php']) + { + $compiler + ->write("// PHP Disabled\n") + ; + + return; + } + + $compiler + ->raw($this->getNode('text')->getAttribute('data')) + ; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/defineparser.php b/phpBB/phpbb/template/twig/tokenparser/defineparser.php new file mode 100644 index 0000000000..b755836ccd --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/defineparser.php @@ -0,0 +1,76 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @copyright Portions (c) 2009 Fabien Potencier, Armin Ronacher +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class defineparser extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + * @throws \Twig_Error_Syntax + * @throws \phpbb\template\twig\node\definenode + */ + public function parse(\Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + $name = $this->parser->getExpressionParser()->parseExpression(); + + $capture = false; + if ($stream->test(\Twig_Token::OPERATOR_TYPE, '=')) + { + $stream->next(); + $value = $this->parser->getExpressionParser()->parseExpression(); + + if ($value instanceof \Twig_Node_Expression_Name) + { + // This would happen if someone improperly formed their DEFINE syntax + // e.g. <!-- DEFINE $VAR = foo --> + throw new \Twig_Error_Syntax('Invalid DEFINE', $token->getLine(), $this->parser->getFilename()); + } + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + } + else + { + $capture = true; + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + $value = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + } + + return new \phpbb\template\twig\node\definenode($capture, $name, $value, $lineno, $this->getTag()); + } + + public function decideBlockEnd(\Twig_Token $token) + { + return $token->test('ENDDEFINE'); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'DEFINE'; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/event.php b/phpBB/phpbb/template/twig/tokenparser/event.php new file mode 100644 index 0000000000..f73ef4ae25 --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/event.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class event extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + $stream = $this->parser->getStream(); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new \phpbb\template\twig\node\event($expr, $this->parser->getEnvironment(), $token->getLine(), $this->getTag()); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'EVENT'; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/includecss.php b/phpBB/phpbb/template/twig/tokenparser/includecss.php new file mode 100644 index 0000000000..1f30811754 --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/includecss.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class includecss extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + $stream = $this->parser->getStream(); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new \phpbb\template\twig\node\includecss($expr, $this->parser->getEnvironment(), $token->getLine(), $this->getTag()); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'INCLUDECSS'; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/includejs.php b/phpBB/phpbb/template/twig/tokenparser/includejs.php new file mode 100644 index 0000000000..4b67d2c468 --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/includejs.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class includejs extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + $stream = $this->parser->getStream(); + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new \phpbb\template\twig\node\includejs($expr, $this->parser->getEnvironment(), $token->getLine(), $this->getTag()); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'INCLUDEJS'; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/includeparser.php b/phpBB/phpbb/template/twig/tokenparser/includeparser.php new file mode 100644 index 0000000000..aa7236aaa6 --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/includeparser.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @copyright Portions (c) 2009 Fabien Potencier, Armin Ronacher +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class includeparser extends \Twig_TokenParser_Include +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + list($variables, $only, $ignoreMissing) = $this->parseArguments(); + + return new \phpbb\template\twig\node\includenode($expr, $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'INCLUDE'; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/includephp.php b/phpBB/phpbb/template/twig/tokenparser/includephp.php new file mode 100644 index 0000000000..3992636f8c --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/includephp.php @@ -0,0 +1,55 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @copyright Portions (c) 2009 Fabien Potencier, Armin Ronacher +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class includephp extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + $stream = $this->parser->getStream(); + + $ignoreMissing = false; + if ($stream->test(\Twig_Token::NAME_TYPE, 'ignore')) + { + $stream->next(); + $stream->expect(\Twig_Token::NAME_TYPE, 'missing'); + + $ignoreMissing = true; + } + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new \phpbb\template\twig\node\includephp($expr, $this->parser->getEnvironment(), $token->getLine(), $ignoreMissing, $this->getTag()); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'INCLUDEPHP'; + } +} diff --git a/phpBB/phpbb/template/twig/tokenparser/php.php b/phpBB/phpbb/template/twig/tokenparser/php.php new file mode 100644 index 0000000000..f11ce35896 --- /dev/null +++ b/phpBB/phpbb/template/twig/tokenparser/php.php @@ -0,0 +1,52 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig\tokenparser; + +class php extends \Twig_TokenParser +{ + /** + * Parses a token and returns a node. + * + * @param \Twig_Token $token A Twig_Token instance + * + * @return \Twig_NodeInterface A Twig_NodeInterface instance + */ + public function parse(\Twig_Token $token) + { + $stream = $this->parser->getStream(); + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + $body = $this->parser->subparse(array($this, 'decideEnd'), true); + + $stream->expect(\Twig_Token::BLOCK_END_TYPE); + + return new \phpbb\template\twig\node\php($body, $this->parser->getEnvironment(), $token->getLine(), $this->getTag()); + } + + public function decideEnd(\Twig_Token $token) + { + return $token->test('ENDPHP'); + } + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag() + { + return 'PHP'; + } +} diff --git a/phpBB/phpbb/template/twig/twig.php b/phpBB/phpbb/template/twig/twig.php new file mode 100644 index 0000000000..d1bbb2b55a --- /dev/null +++ b/phpBB/phpbb/template/twig/twig.php @@ -0,0 +1,389 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\template\twig; + +/** +* Twig Template class. +*/ +class twig extends \phpbb\template\base +{ + /** + * Path of the cache directory for the template + * + * Cannot be changed during runtime. + * + * @var string + */ + private $cachepath = ''; + + /** + * phpBB path helper + * @var \phpbb\path_helper + */ + protected $path_helper; + + /** + * phpBB root path + * @var string + */ + protected $phpbb_root_path; + + /** + * PHP file extension + * @var string + */ + protected $php_ext; + + /** + * phpBB config instance + * @var \phpbb\config\config + */ + protected $config; + + /** + * Current user + * @var \phpbb\user + */ + protected $user; + + /** + * Extension manager. + * + * @var \phpbb\extension\manager + */ + protected $extension_manager; + + /** + * Twig Environment + * + * @var \Twig_Environment + */ + protected $twig; + + /** + * Constructor. + * + * @param \phpbb\path_helper $path_helper + * @param \phpbb\config\config $config + * @param \phpbb\user $user + * @param \phpbb\template\context $context template context + * @param \phpbb\extension\manager $extension_manager extension manager, if null then template events will not be invoked + */ + public function __construct(\phpbb\path_helper $path_helper, $config, $user, \phpbb\template\context $context, \phpbb\extension\manager $extension_manager = null) + { + $this->path_helper = $path_helper; + $this->phpbb_root_path = $path_helper->get_phpbb_root_path(); + $this->php_ext = $path_helper->get_php_ext(); + $this->config = $config; + $this->user = $user; + $this->context = $context; + $this->extension_manager = $extension_manager; + + $this->cachepath = $this->phpbb_root_path . 'cache/twig/'; + + // Initiate the loader, __main__ namespace paths will be setup later in set_style_names() + $loader = new \phpbb\template\twig\loader(''); + + $this->twig = new \phpbb\template\twig\environment( + $this->config, + $this->path_helper, + $this->extension_manager, + $loader, + array( + 'cache' => (defined('IN_INSTALL')) ? false : $this->cachepath, + 'debug' => defined('DEBUG'), + 'auto_reload' => (bool) $this->config['load_tplcompile'], + 'autoescape' => false, + ) + ); + + $this->twig->addExtension( + new \phpbb\template\twig\extension( + $this->context, + $this->user + ) + ); + + if (defined('DEBUG')) + { + $this->twig->addExtension(new \Twig_Extension_Debug()); + } + + $lexer = new \phpbb\template\twig\lexer($this->twig); + + $this->twig->setLexer($lexer); + + // Add admin namespace + if ($this->path_helper->get_adm_relative_path() !== null && is_dir($this->phpbb_root_path . $this->path_helper->get_adm_relative_path() . 'style/')) + { + $this->twig->getLoader()->setPaths($this->phpbb_root_path . $this->path_helper->get_adm_relative_path() . 'style/', 'admin'); + } + } + + /** + * Clear the cache + * + * @return \phpbb\template\template + */ + public function clear_cache() + { + if (is_dir($this->cachepath)) + { + $this->twig->clearCacheFiles(); + } + + return $this; + } + + /** + * Get the style tree of the style preferred by the current user + * + * @return array Style tree, most specific first + */ + public function get_user_style() + { + $style_list = array( + $this->user->style['style_path'], + ); + + if ($this->user->style['style_parent_id']) + { + $style_list = array_merge($style_list, array_reverse(explode('/', $this->user->style['style_parent_tree']))); + } + + return $style_list; + } + + /** + * Set style location based on (current) user's chosen style. + * + * @param array $style_directories The directories to add style paths for + * E.g. array('ext/foo/bar/styles', 'styles') + * Default: array('styles') (phpBB's style directory) + * @return \phpbb\template\template $this + */ + public function set_style($style_directories = array('styles')) + { + if ($style_directories !== array('styles') && $this->twig->getLoader()->getPaths('core') === array()) + { + // We should set up the core styles path since not already setup + $this->set_style(); + } + + $names = $this->get_user_style(); + // Add 'all' folder to $names array + // It allows extensions to load a template file from 'all' folder, + // if a style doesn't include it. + $names[] = 'all'; + + $paths = array(); + foreach ($style_directories as $directory) + { + foreach ($names as $name) + { + $path = $this->phpbb_root_path . trim($directory, '/') . "/{$name}/"; + $template_path = $path . 'template/'; + $theme_path = $path . 'theme/'; + + $is_valid_dir = false; + if (is_dir($template_path)) + { + $is_valid_dir = true; + $paths[] = $template_path; + } + if (is_dir($theme_path)) + { + $is_valid_dir = true; + $paths[] = $theme_path; + } + + if ($is_valid_dir) + { + // Add the base style directory as a safe directory + $this->twig->getLoader()->addSafeDirectory($path); + } + } + } + + // If we're setting up the main phpBB styles directory and the core + // namespace isn't setup yet, we will set it up now + if ($style_directories === array('styles') && $this->twig->getLoader()->getPaths('core') === array()) + { + // Set up the core style paths namespace + $this->twig->getLoader()->setPaths($paths, 'core'); + } + + $this->set_custom_style($names, $paths); + + return $this; + } + + /** + * Set custom style location (able to use directory outside of phpBB). + * + * Note: Templates are still compiled to phpBB's cache directory. + * + * @param string|array $names Array of names (or detailed names) or string of name of template(s) in inheritance tree order, used by extensions. + * E.g. array( + * 'name' => 'adm', + * 'ext_path' => 'adm/style/', + * ) + * @param string|array of string $paths Array of style paths, relative to current root directory + * @return \phpbb\template\template $this + */ + public function set_custom_style($names, $paths) + { + $paths = (is_string($paths)) ? array($paths) : $paths; + $names = (is_string($names)) ? array($names) : $names; + + // Set as __main__ namespace + $this->twig->getLoader()->setPaths($paths); + + // Add all namespaces for all extensions + if ($this->extension_manager instanceof \phpbb\extension\manager) + { + $names[] = 'all'; + + foreach ($this->extension_manager->all_enabled() as $ext_namespace => $ext_path) + { + // namespaces cannot contain / + $namespace = str_replace('/', '_', $ext_namespace); + $paths = array(); + + foreach ($names as $template_dir) + { + if (is_array($template_dir)) + { + if (isset($template_dir['ext_path'])) + { + $ext_style_template_path = $ext_path . $template_dir['ext_path']; + $ext_style_path = dirname($ext_style_template_path); + $ext_style_theme_path = $ext_style_path . 'theme/'; + } + else + { + $ext_style_path = $ext_path . 'styles/' . $template_dir['name'] . '/'; + $ext_style_template_path = $ext_style_path . 'template/'; + $ext_style_theme_path = $ext_style_path . 'theme/'; + } + } + else + { + $ext_style_path = $ext_path . 'styles/' . $template_dir . '/'; + $ext_style_template_path = $ext_style_path . 'template/'; + $ext_style_theme_path = $ext_style_path . 'theme/'; + } + + $is_valid_dir = false; + if (is_dir($ext_style_template_path)) + { + $is_valid_dir = true; + $paths[] = $ext_style_template_path; + } + if (is_dir($ext_style_theme_path)) + { + $is_valid_dir = true; + $paths[] = $ext_style_theme_path; + } + + if ($is_valid_dir) + { + // Add the base style directory as a safe directory + $this->twig->getLoader()->addSafeDirectory($ext_style_path); + } + } + + $this->twig->getLoader()->setPaths($paths, $namespace); + } + } + + return $this; + } + + /** + * Display a template for provided handle. + * + * The template will be loaded and compiled, if necessary, first. + * + * This function calls hooks. + * + * @param string $handle Handle to display + * @return \phpbb\template\template $this + */ + public function display($handle) + { + $result = $this->call_hook($handle, __FUNCTION__); + if ($result !== false) + { + return $result[0]; + } + + $this->twig->display($this->get_filename_from_handle($handle), $this->get_template_vars()); + + return $this; + } + + /** + * Display the handle and assign the output to a template variable + * or return the compiled result. + * + * @param string $handle Handle to operate on + * @param string $template_var Template variable to assign compiled handle to + * @param bool $return_content If true return compiled handle, otherwise assign to $template_var + * @return \phpbb\template\template|string if $return_content is true return string of the compiled handle, otherwise return $this + */ + public function assign_display($handle, $template_var = '', $return_content = true) + { + if ($return_content) + { + return $this->twig->render($this->get_filename_from_handle($handle), $this->get_template_vars()); + } + + $this->assign_var($template_var, $this->twig->render($this->get_filename_from_handle($handle), $this->get_template_vars())); + + return $this; + } + + /** + * Get template vars in a format Twig will use (from the context) + * + * @return array + */ + protected function get_template_vars() + { + $context_vars = $this->context->get_data_ref(); + + $vars = array_merge( + $context_vars['.'][0], // To get normal vars + array( + 'definition' => new \phpbb\template\twig\definition(), + 'user' => $this->user, + 'loops' => $context_vars, // To get loops + ) + ); + + // cleanup + unset($vars['loops']['.']); + + return $vars; + } + + /** + * {@inheritdoc} + */ + public function get_source_file_for_handle($handle) + { + return $this->twig->getLoader()->getCacheKey($this->get_filename_from_handle($handle)); + } +} diff --git a/phpBB/phpbb/tree/nestedset.php b/phpBB/phpbb/tree/nestedset.php new file mode 100644 index 0000000000..8490c7c299 --- /dev/null +++ b/phpBB/phpbb/tree/nestedset.php @@ -0,0 +1,877 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\tree; + +abstract class nestedset implements \phpbb\tree\tree_interface +{ + /** @var \phpbb\db\driver\driver_interface */ + protected $db; + + /** @var \phpbb\lock\db */ + protected $lock; + + /** @var string */ + protected $table_name; + + /** + * Prefix for the language keys returned by exceptions + * @var string + */ + protected $message_prefix = ''; + + /** + * Column names in the table + * @var string + */ + protected $column_item_id = 'item_id'; + protected $column_left_id = 'left_id'; + protected $column_right_id = 'right_id'; + protected $column_parent_id = 'parent_id'; + protected $column_item_parents = 'item_parents'; + + /** + * Additional SQL restrictions + * Allows to have multiple nested sets in one table + * @var string + */ + protected $sql_where = ''; + + /** + * List of item properties to be cached in the item_parents column + * @var array + */ + protected $item_basic_data = array('*'); + + /** + * Construct + * + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param \phpbb\lock\db $lock Lock class used to lock the table when moving forums around + * @param string $table_name Table name + * @param string $message_prefix Prefix for the messages thrown by exceptions + * @param string $sql_where Additional SQL restrictions for the queries + * @param array $item_basic_data Array with basic item data that is stored in item_parents + * @param array $columns Array with column names to overwrite + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\lock\db $lock, $table_name, $message_prefix = '', $sql_where = '', $item_basic_data = array(), $columns = array()) + { + $this->db = $db; + $this->lock = $lock; + + $this->table_name = $table_name; + $this->message_prefix = $message_prefix; + $this->sql_where = $sql_where; + $this->item_basic_data = (!empty($item_basic_data)) ? $item_basic_data : array('*'); + + if (!empty($columns)) + { + foreach ($columns as $column => $name) + { + $column_name = 'column_' . $column; + $this->$column_name = $name; + } + } + } + + /** + * Returns additional sql where restrictions + * + * @param string $operator SQL operator that needs to be prepended to sql_where, + * if it is not empty. + * @param string $column_prefix Prefix that needs to be prepended to column names + * @return string Returns additional where statements to narrow down the tree, + * prefixed with operator and prepended column_prefix to column names + */ + public function get_sql_where($operator = 'AND', $column_prefix = '') + { + return (!$this->sql_where) ? '' : $operator . ' ' . sprintf($this->sql_where, $column_prefix); + } + + /** + * Acquires a lock on the item table + * + * @return bool True if the lock was acquired, false if it has been acquired previously + * + * @throws \RuntimeException If the lock could not be acquired + */ + protected function acquire_lock() + { + if ($this->lock->owns_lock()) + { + return false; + } + + if (!$this->lock->acquire()) + { + throw new \RuntimeException($this->message_prefix . 'LOCK_FAILED_ACQUIRE'); + } + + return true; + } + + /** + * {@inheritdoc} + */ + public function insert(array $additional_data) + { + $item_data = $this->reset_nestedset_values($additional_data); + + $sql = 'INSERT INTO ' . $this->table_name . ' ' . $this->db->sql_build_array('INSERT', $item_data); + $this->db->sql_query($sql); + + $item_data[$this->column_item_id] = (int) $this->db->sql_nextid(); + + return array_merge($item_data, $this->add_item_to_nestedset($item_data[$this->column_item_id])); + } + + /** + * Add an item which already has a database row at the end of the tree + * + * @param int $item_id The item to be added + * @return array Array with updated data, if the item was added successfully + * Empty array otherwise + */ + protected function add_item_to_nestedset($item_id) + { + $sql = 'SELECT MAX(' . $this->column_right_id . ') AS ' . $this->column_right_id . ' + FROM ' . $this->table_name . ' + ' . $this->get_sql_where('WHERE'); + $result = $this->db->sql_query($sql); + $current_max_right_id = (int) $this->db->sql_fetchfield($this->column_right_id); + $this->db->sql_freeresult($result); + + $update_item_data = array( + $this->column_parent_id => 0, + $this->column_left_id => $current_max_right_id + 1, + $this->column_right_id => $current_max_right_id + 2, + $this->column_item_parents => '', + ); + + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->db->sql_build_array('UPDATE', $update_item_data) . ' + WHERE ' . $this->column_item_id . ' = ' . (int) $item_id . ' + AND ' . $this->column_parent_id . ' = 0 + AND ' . $this->column_left_id . ' = 0 + AND ' . $this->column_right_id . ' = 0'; + $this->db->sql_query($sql); + + return ($this->db->sql_affectedrows() == 1) ? $update_item_data : array(); + } + + /** + * Remove an item from the tree without deleting it from the database + * + * Also removes all subitems from the tree without deleting them from the database either + * + * @param int $item_id The item to be deleted + * @return array Item ids that have been removed + * @throws \OutOfBoundsException + */ + protected function remove_item_from_nestedset($item_id) + { + $item_id = (int) $item_id; + if (!$item_id) + { + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + $items = $this->get_subtree_data($item_id); + $item_ids = array_keys($items); + + if (empty($items) || !isset($items[$item_id])) + { + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + $this->remove_subset($item_ids, $items[$item_id]); + + return $item_ids; + } + + /** + * {@inheritdoc} + */ + public function delete($item_id) + { + $removed_items = $this->remove_item_from_nestedset($item_id); + + $sql = 'DELETE FROM ' . $this->table_name . ' + WHERE ' . $this->db->sql_in_set($this->column_item_id, $removed_items) . ' + ' . $this->get_sql_where('AND'); + $this->db->sql_query($sql); + + return $removed_items; + } + + /** + * {@inheritdoc} + */ + public function move($item_id, $delta) + { + if ($delta == 0) + { + return false; + } + + $this->acquire_lock(); + + $action = ($delta > 0) ? 'move_up' : 'move_down'; + $delta = abs($delta); + + // Keep $this->get_sql_where() here, to ensure we are in the right tree. + $sql = 'SELECT * + FROM ' . $this->table_name . ' + WHERE ' . $this->column_item_id . ' = ' . (int) $item_id . ' + ' . $this->get_sql_where(); + $result = $this->db->sql_query_limit($sql, $delta); + $item = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$item) + { + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + /** + * Fetch all the siblings between the item's current spot + * and where we want to move it to. If there are less than $delta + * siblings between the current spot and the target then the + * item will move as far as possible + */ + $sql = "SELECT {$this->column_item_id}, {$this->column_parent_id}, {$this->column_left_id}, {$this->column_right_id}, {$this->column_item_parents} + FROM " . $this->table_name . ' + WHERE ' . $this->column_parent_id . ' = ' . (int) $item[$this->column_parent_id] . ' + ' . $this->get_sql_where() . ' + AND '; + + if ($action == 'move_up') + { + $sql .= $this->column_right_id . ' < ' . (int) $item[$this->column_right_id] . ' ORDER BY ' . $this->column_right_id . ' DESC'; + } + else + { + $sql .= $this->column_left_id . ' > ' . (int) $item[$this->column_left_id] . ' ORDER BY ' . $this->column_left_id . ' ASC'; + } + + $result = $this->db->sql_query_limit($sql, $delta); + + $target = false; + while ($row = $this->db->sql_fetchrow($result)) + { + $target = $row; + } + $this->db->sql_freeresult($result); + + if (!$target) + { + $this->lock->release(); + // The item is already on top or bottom + return false; + } + + /** + * $left_id and $right_id define the scope of the items that are affected by the move. + * $diff_up and $diff_down are the values to substract or add to each item's left_id + * and right_id in order to move them up or down. + * $move_up_left and $move_up_right define the scope of the items that are moving + * up. Other items in the scope of ($left_id, $right_id) are considered to move down. + */ + if ($action == 'move_up') + { + $left_id = (int) $target[$this->column_left_id]; + $right_id = (int) $item[$this->column_right_id]; + + $diff_up = (int) $item[$this->column_left_id] - (int) $target[$this->column_left_id]; + $diff_down = (int) $item[$this->column_right_id] + 1 - (int) $item[$this->column_left_id]; + + $move_up_left = (int) $item[$this->column_left_id]; + $move_up_right = (int) $item[$this->column_right_id]; + } + else + { + $left_id = (int) $item[$this->column_left_id]; + $right_id = (int) $target[$this->column_right_id]; + + $diff_up = (int) $item[$this->column_right_id] + 1 - (int) $item[$this->column_left_id]; + $diff_down = (int) $target[$this->column_right_id] - (int) $item[$this->column_right_id]; + + $move_up_left = (int) $item[$this->column_right_id] + 1; + $move_up_right = (int) $target[$this->column_right_id]; + } + + // Now do the dirty job + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->column_left_id . ' = ' . $this->column_left_id . ' + CASE + WHEN ' . $this->column_left_id . " BETWEEN {$move_up_left} AND {$move_up_right} THEN -{$diff_up} + ELSE {$diff_down} + END, + " . $this->column_right_id . ' = ' . $this->column_right_id . ' + CASE + WHEN ' . $this->column_right_id . " BETWEEN {$move_up_left} AND {$move_up_right} THEN -{$diff_up} + ELSE {$diff_down} + END + WHERE + " . $this->column_left_id . " BETWEEN {$left_id} AND {$right_id} + AND " . $this->column_right_id . " BETWEEN {$left_id} AND {$right_id} + " . $this->get_sql_where(); + $this->db->sql_query($sql); + + $this->lock->release(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function move_down($item_id) + { + return $this->move($item_id, -1); + } + + /** + * {@inheritdoc} + */ + public function move_up($item_id) + { + return $this->move($item_id, 1); + } + + /** + * {@inheritdoc} + */ + public function move_children($current_parent_id, $new_parent_id) + { + $current_parent_id = (int) $current_parent_id; + $new_parent_id = (int) $new_parent_id; + + if ($current_parent_id == $new_parent_id) + { + return false; + } + + if (!$current_parent_id) + { + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + $this->acquire_lock(); + + $item_data = $this->get_subtree_data($current_parent_id); + if (!isset($item_data[$current_parent_id])) + { + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + $current_parent = $item_data[$current_parent_id]; + unset($item_data[$current_parent_id]); + $move_items = array_keys($item_data); + + if (($current_parent[$this->column_right_id] - $current_parent[$this->column_left_id]) <= 1) + { + $this->lock->release(); + return false; + } + + if (in_array($new_parent_id, $move_items)) + { + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_PARENT'); + } + + $diff = sizeof($move_items) * 2; + $sql_exclude_moved_items = $this->db->sql_in_set($this->column_item_id, $move_items, true); + + $this->db->sql_transaction('begin'); + + $this->remove_subset($move_items, $current_parent, false, true); + + if ($new_parent_id) + { + // Retrieve new-parent again, it may have been changed... + $sql = 'SELECT * + FROM ' . $this->table_name . ' + WHERE ' . $this->column_item_id . ' = ' . $new_parent_id; + $result = $this->db->sql_query($sql); + $new_parent = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$new_parent) + { + $this->db->sql_transaction('rollback'); + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_PARENT'); + } + + $new_right_id = $this->prepare_adding_subset($move_items, $new_parent, true); + + if ($new_right_id > $current_parent[$this->column_right_id]) + { + $diff = ' + ' . ($new_right_id - $current_parent[$this->column_right_id]); + } + else + { + $diff = ' - ' . abs($new_right_id - $current_parent[$this->column_right_id]); + } + } + else + { + $sql = 'SELECT MAX(' . $this->column_right_id . ') AS ' . $this->column_right_id . ' + FROM ' . $this->table_name . ' + WHERE ' . $sql_exclude_moved_items . ' + ' . $this->get_sql_where('AND'); + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $diff = ' + ' . ($row[$this->column_right_id] - $current_parent[$this->column_left_id]); + } + + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->column_left_id . ' = ' . $this->column_left_id . $diff . ', + ' . $this->column_right_id . ' = ' . $this->column_right_id . $diff . ', + ' . $this->column_parent_id . ' = ' . $this->db->sql_case($this->column_parent_id . ' = ' . $current_parent_id, $new_parent_id, $this->column_parent_id) . ', + ' . $this->column_item_parents . " = '' + WHERE " . $this->db->sql_in_set($this->column_item_id, $move_items) . ' + ' . $this->get_sql_where('AND'); + $this->db->sql_query($sql); + + $this->db->sql_transaction('commit'); + $this->lock->release(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function change_parent($item_id, $new_parent_id) + { + $item_id = (int) $item_id; + $new_parent_id = (int) $new_parent_id; + + if ($item_id == $new_parent_id) + { + return false; + } + + if (!$item_id) + { + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + $this->acquire_lock(); + + $item_data = $this->get_subtree_data($item_id); + if (!isset($item_data[$item_id])) + { + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_ITEM'); + } + + $item = $item_data[$item_id]; + $move_items = array_keys($item_data); + + if (in_array($new_parent_id, $move_items)) + { + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_PARENT'); + } + + $diff = sizeof($move_items) * 2; + $sql_exclude_moved_items = $this->db->sql_in_set($this->column_item_id, $move_items, true); + + $this->db->sql_transaction('begin'); + + $this->remove_subset($move_items, $item, false, true); + + if ($new_parent_id) + { + // Retrieve new-parent again, it may have been changed... + $sql = 'SELECT * + FROM ' . $this->table_name . ' + WHERE ' . $this->column_item_id . ' = ' . $new_parent_id; + $result = $this->db->sql_query($sql); + $new_parent = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if (!$new_parent) + { + $this->db->sql_transaction('rollback'); + $this->lock->release(); + throw new \OutOfBoundsException($this->message_prefix . 'INVALID_PARENT'); + } + + $new_right_id = $this->prepare_adding_subset($move_items, $new_parent, true); + + if ($new_right_id > (int) $item[$this->column_right_id]) + { + $diff = ' + ' . ($new_right_id - (int) $item[$this->column_right_id] - 1); + } + else + { + $diff = ' - ' . abs($new_right_id - (int) $item[$this->column_right_id] - 1); + } + } + else + { + $sql = 'SELECT MAX(' . $this->column_right_id . ') AS ' . $this->column_right_id . ' + FROM ' . $this->table_name . ' + WHERE ' . $sql_exclude_moved_items . ' + ' . $this->get_sql_where('AND'); + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $diff = ' + ' . ($row[$this->column_right_id] - (int) $item[$this->column_left_id] + 1); + } + + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->column_left_id . ' = ' . $this->column_left_id . $diff . ', + ' . $this->column_right_id . ' = ' . $this->column_right_id . $diff . ', + ' . $this->column_parent_id . ' = ' . $this->db->sql_case($this->column_item_id . ' = ' . $item_id, $new_parent_id, $this->column_parent_id) . ', + ' . $this->column_item_parents . " = '' + WHERE " . $this->db->sql_in_set($this->column_item_id, $move_items) . ' + ' . $this->get_sql_where('AND'); + $this->db->sql_query($sql); + + $this->db->sql_transaction('commit'); + $this->lock->release(); + + return true; + } + + /** + * {@inheritdoc} + */ + public function get_path_and_subtree_data($item_id, $order_asc = true, $include_item = true) + { + $condition = 'i2.' . $this->column_left_id . ' BETWEEN i1.' . $this->column_left_id . ' AND i1.' . $this->column_right_id . ' + OR i1.' . $this->column_left_id . ' BETWEEN i2.' . $this->column_left_id . ' AND i2.' . $this->column_right_id; + + return $this->get_set_of_nodes_data($item_id, $condition, $order_asc, $include_item); + } + + /** + * {@inheritdoc} + */ + public function get_path_data($item_id, $order_asc = true, $include_item = true) + { + $condition = 'i1.' . $this->column_left_id . ' BETWEEN i2.' . $this->column_left_id . ' AND i2.' . $this->column_right_id . ''; + + return $this->get_set_of_nodes_data($item_id, $condition, $order_asc, $include_item); + } + + /** + * {@inheritdoc} + */ + public function get_subtree_data($item_id, $order_asc = true, $include_item = true) + { + $condition = 'i2.' . $this->column_left_id . ' BETWEEN i1.' . $this->column_left_id . ' AND i1.' . $this->column_right_id . ''; + + return $this->get_set_of_nodes_data($item_id, $condition, $order_asc, $include_item); + } + + /** + * Get items that are related to the given item by the condition + * + * @param int $item_id Id of the item to retrieve the node set from + * @param string $condition Query string restricting the item list + * @param bool $order_asc Order the items ascending by their left_id + * @param bool $include_item Should the item matching the given item id be included in the list as well + * @return array Array of items (containing all columns from the item table) + * ID => Item data + */ + protected function get_set_of_nodes_data($item_id, $condition, $order_asc = true, $include_item = true) + { + $rows = array(); + + $sql = 'SELECT i2.* + FROM ' . $this->table_name . ' i1 + LEFT JOIN ' . $this->table_name . " i2 + ON (($condition) " . $this->get_sql_where('AND', 'i2.') . ') + WHERE i1.' . $this->column_item_id . ' = ' . (int) $item_id . ' + ' . $this->get_sql_where('AND', 'i1.') . ' + ORDER BY i2.' . $this->column_left_id . ' ' . ($order_asc ? 'ASC' : 'DESC'); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + if (!$include_item && $item_id == $row[$this->column_item_id]) + { + continue; + } + + $rows[(int) $row[$this->column_item_id]] = $row; + } + $this->db->sql_freeresult($result); + + return $rows; + } + + /** + * Get basic data of all parent items + * + * Basic data is defined in the $item_basic_data property. + * Data is cached in the item_parents column in the item table + * + * @param array $item The item to get the path from + * @return array Array of items (containing basic columns from the item table) + * ID => Item data + */ + public function get_path_basic_data(array $item) + { + $parents = array(); + if ($item[$this->column_parent_id]) + { + if (!$item[$this->column_item_parents]) + { + $sql = 'SELECT ' . implode(', ', $this->item_basic_data) . ' + FROM ' . $this->table_name . ' + WHERE ' . $this->column_left_id . ' < ' . (int) $item[$this->column_left_id] . ' + AND ' . $this->column_right_id . ' > ' . (int) $item[$this->column_right_id] . ' + ' . $this->get_sql_where('AND') . ' + ORDER BY ' . $this->column_left_id . ' ASC'; + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $parents[$row[$this->column_item_id]] = $row; + } + $this->db->sql_freeresult($result); + + $item_parents = serialize($parents); + + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->column_item_parents . " = '" . $this->db->sql_escape($item_parents) . "' + WHERE " . $this->column_parent_id . ' = ' . (int) $item[$this->column_parent_id]; + $this->db->sql_query($sql); + } + else + { + $parents = unserialize($item[$this->column_item_parents]); + } + } + + return $parents; + } + + /** + * Get all items from the tree + * + * @param bool $order_asc Order the items ascending by their left_id + * @return array Array of items (containing all columns from the item table) + * ID => Item data + */ + public function get_all_tree_data($order_asc = true) + { + $rows = array(); + + $sql = 'SELECT * + FROM ' . $this->table_name . ' ' . + $this->get_sql_where('WHERE') . ' + ORDER BY ' . $this->column_left_id . ' ' . ($order_asc ? 'ASC' : 'DESC'); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $rows[(int) $row[$this->column_item_id]] = $row; + } + $this->db->sql_freeresult($result); + + return $rows; + } + + /** + * Remove a subset from the nested set + * + * @param array $subset_items Subset of items to remove + * @param array $bounding_item Item containing the right bound of the subset + * @param bool $set_subset_zero Should the parent, left and right id of the items be set to 0, or kept unchanged? + * In case of removing an item from the tree, we should the values to 0 + * In case of moving an item, we shouldkeep the original values, in order to allow "+ diff" later + * @return null + */ + protected function remove_subset(array $subset_items, array $bounding_item, $set_subset_zero = true) + { + $acquired_new_lock = $this->acquire_lock(); + + $diff = sizeof($subset_items) * 2; + $sql_subset_items = $this->db->sql_in_set($this->column_item_id, $subset_items); + $sql_not_subset_items = $this->db->sql_in_set($this->column_item_id, $subset_items, true); + + $sql_is_parent = $this->column_left_id . ' <= ' . (int) $bounding_item[$this->column_right_id] . ' + AND ' . $this->column_right_id . ' >= ' . (int) $bounding_item[$this->column_right_id]; + + $sql_is_right = $this->column_left_id . ' > ' . (int) $bounding_item[$this->column_right_id]; + + $set_left_id = $this->db->sql_case($sql_is_right, $this->column_left_id . ' - ' . $diff, $this->column_left_id); + $set_right_id = $this->db->sql_case($sql_is_parent . ' OR ' . $sql_is_right, $this->column_right_id . ' - ' . $diff, $this->column_right_id); + + if ($set_subset_zero) + { + $set_left_id = $this->db->sql_case($sql_subset_items, 0, $set_left_id); + $set_right_id = $this->db->sql_case($sql_subset_items, 0, $set_right_id); + } + + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . (($set_subset_zero) ? $this->column_parent_id . ' = ' . $this->db->sql_case($sql_subset_items, 0, $this->column_parent_id) . ',' : '') . ' + ' . $this->column_left_id . ' = ' . $set_left_id . ', + ' . $this->column_right_id . ' = ' . $set_right_id . ' + ' . ((!$set_subset_zero) ? ' WHERE ' . $sql_not_subset_items . ' ' . $this->get_sql_where('AND') : $this->get_sql_where('WHERE')); + $this->db->sql_query($sql); + + if ($acquired_new_lock) + { + $this->lock->release(); + } + } + + /** + * Prepare adding a subset to the nested set + * + * @param array $subset_items Subset of items to add + * @param array $new_parent Item containing the right bound of the new parent + * @return int New right id of the parent item + */ + protected function prepare_adding_subset(array $subset_items, array $new_parent) + { + $diff = sizeof($subset_items) * 2; + $sql_not_subset_items = $this->db->sql_in_set($this->column_item_id, $subset_items, true); + + $set_left_id = $this->db->sql_case($this->column_left_id . ' > ' . (int) $new_parent[$this->column_right_id], $this->column_left_id . ' + ' . $diff, $this->column_left_id); + $set_right_id = $this->db->sql_case($this->column_right_id . ' >= ' . (int) $new_parent[$this->column_right_id], $this->column_right_id . ' + ' . $diff, $this->column_right_id); + + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->column_left_id . ' = ' . $set_left_id . ', + ' . $this->column_right_id . ' = ' . $set_right_id . ' + WHERE ' . $sql_not_subset_items . ' + ' . $this->get_sql_where('AND'); + $this->db->sql_query($sql); + + return $new_parent[$this->column_right_id] + $diff; + } + + /** + * Resets values required for the nested set system + * + * @param array $item Original item data + * @return array Original item data + nested set defaults + */ + protected function reset_nestedset_values(array $item) + { + $item_data = array_merge($item, array( + $this->column_parent_id => 0, + $this->column_left_id => 0, + $this->column_right_id => 0, + $this->column_item_parents => '', + )); + + unset($item_data[$this->column_item_id]); + + return $item_data; + } + + /** + * Regenerate left/right ids from parent/child relationship + * + * This method regenerates the left/right ids for the tree based on + * the parent/child relations. This function executes three queries per + * item, so it should only be called, when the set has one of the following + * problems: + * - The set has a duplicated value inside the left/right id chain + * - The set has a missing value inside the left/right id chain + * - The set has items that do not have a left/right id set + * + * When regenerating the items, the items are sorted by parent id and their + * current left id, so the current child/parent relationships are kept + * and running the function on a working set will not change the order. + * + * @param int $new_id First left_id to be used (should start with 1) + * @param int $parent_id parent_id of the current set (default = 0) + * @param bool $reset_ids Should we reset all left_id/right_id on the first call? + * @return int $new_id The next left_id/right_id that should be used + */ + public function regenerate_left_right_ids($new_id, $parent_id = 0, $reset_ids = false) + { + if ($acquired_new_lock = $this->acquire_lock()) + { + $this->db->sql_transaction('begin'); + + if (!$reset_ids) + { + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->column_item_parents . " = '' + " . $this->get_sql_where('WHERE'); + $this->db->sql_query($sql); + } + } + + if ($reset_ids) + { + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->db->sql_build_array('UPDATE', array( + $this->column_left_id => 0, + $this->column_right_id => 0, + $this->column_item_parents => '', + )) . ' + ' . $this->get_sql_where('WHERE'); + $this->db->sql_query($sql); + } + + $sql = 'SELECT * + FROM ' . $this->table_name . ' + WHERE ' . $this->column_parent_id . ' = ' . (int) $parent_id . ' + ' . $this->get_sql_where('AND') . ' + ORDER BY ' . $this->column_left_id . ', ' . $this->column_item_id . ' ASC'; + $result = $this->db->sql_query($sql); + $rows = $this->db->sql_fetchrowset($result); + $this->db->sql_freeresult($result); + + foreach ($rows as $row) + { + // First we update the left_id for this module + if ($row[$this->column_left_id] != $new_id) + { + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->db->sql_build_array('UPDATE', array($this->column_left_id => $new_id)) . ' + WHERE ' . $this->column_item_id . ' = ' . (int) $row[$this->column_item_id]; + $this->db->sql_query($sql); + } + $new_id++; + + // Then we go through any children and update their left/right id's + $new_id = $this->regenerate_left_right_ids($new_id, $row[$this->column_item_id]); + + // Then we come back and update the right_id for this module + if ($row[$this->column_right_id] != $new_id) + { + $sql = 'UPDATE ' . $this->table_name . ' + SET ' . $this->db->sql_build_array('UPDATE', array($this->column_right_id => $new_id)) . ' + WHERE ' . $this->column_item_id . ' = ' . (int) $row[$this->column_item_id]; + $this->db->sql_query($sql); + } + $new_id++; + } + + if ($acquired_new_lock) + { + $this->db->sql_transaction('commit'); + $this->lock->release(); + } + + return $new_id; + } +} diff --git a/phpBB/phpbb/tree/nestedset_forum.php b/phpBB/phpbb/tree/nestedset_forum.php new file mode 100644 index 0000000000..890fc804c0 --- /dev/null +++ b/phpBB/phpbb/tree/nestedset_forum.php @@ -0,0 +1,44 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\tree; + +class nestedset_forum extends \phpbb\tree\nestedset +{ + /** + * Construct + * + * @param \phpbb\db\driver\driver_interface $db Database connection + * @param \phpbb\lock\db $lock Lock class used to lock the table when moving forums around + * @param string $table_name Table name + */ + public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\lock\db $lock, $table_name) + { + parent::__construct( + $db, + $lock, + $table_name, + 'FORUM_NESTEDSET_', + '', + array( + 'forum_id', + 'forum_name', + 'forum_type', + ), + array( + 'item_id' => 'forum_id', + 'item_parents' => 'forum_parents', + ) + ); + } +} diff --git a/phpBB/phpbb/tree/tree_interface.php b/phpBB/phpbb/tree/tree_interface.php new file mode 100644 index 0000000000..5df01a89cf --- /dev/null +++ b/phpBB/phpbb/tree/tree_interface.php @@ -0,0 +1,120 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb\tree; + +interface tree_interface +{ + /** + * Inserts an item into the database table and into the tree. + * + * @param array $additional_data The item to be added + * @return array Array with item data as set in the database + */ + public function insert(array $additional_data); + + /** + * Delete an item from the tree and from the database table + * + * Also deletes the subtree from the tree and from the database table + * + * @param int $item_id The item to be deleted + * @return array Item ids that have been deleted + */ + public function delete($item_id); + + /** + * Move an item by a given delta + * + * An item is only moved up/down within the same parent. If the delta is + * larger then the number of children, the item is moved to the top/bottom + * of the list of children within this parent. + * + * @param int $item_id The item to be moved + * @param int $delta Number of steps to move this item, < 0 => down, > 0 => up + * @return bool True if the item was moved + */ + public function move($item_id, $delta); + + /** + * Move an item down by 1 + * + * @param int $item_id The item to be moved + * @return bool True if the item was moved + */ + public function move_down($item_id); + + /** + * Move an item up by 1 + * + * @param int $item_id The item to be moved + * @return bool True if the item was moved + */ + public function move_up($item_id); + + /** + * Moves all children of one item to another item + * + * If the new parent already has children, the new children are appended + * to the list. + * + * @param int $current_parent_id The current parent item + * @param int $new_parent_id The new parent item + * @return bool True if any items where moved + */ + public function move_children($current_parent_id, $new_parent_id); + + /** + * Change parent item + * + * Moves the item to the bottom of the new \parent's list of children + * + * @param int $item_id The item to be moved + * @param int $new_parent_id The new parent item + * @return bool True if the parent was set successfully + */ + public function change_parent($item_id, $new_parent_id); + + /** + * Get all items that are either ancestors or descendants of the item + * + * @param int $item_id Id of the item to retrieve the ancestors/descendants from + * @param bool $order_asc Order the items ascendingly (most outer ancestor first) + * @param bool $include_item Should the item matching the given item id be included in the list as well + * @return array Array of items (containing all columns from the item table) + * ID => Item data + */ + public function get_path_and_subtree_data($item_id, $order_asc, $include_item); + + /** + * Get all of the item's ancestors + * + * @param int $item_id Id of the item to retrieve the ancestors from + * @param bool $order_asc Order the items ascendingly (most outer ancestor first) + * @param bool $include_item Should the item matching the given item id be included in the list as well + * @return array Array of items (containing all columns from the item table) + * ID => Item data + */ + public function get_path_data($item_id, $order_asc, $include_item); + + /** + * Get all of the item's descendants + * + * @param int $item_id Id of the item to retrieve the descendants from + * @param bool $order_asc Order the items ascendingly + * @param bool $include_item Should the item matching the given item id be included in the list as well + * @return array Array of items (containing all columns from the item table) + * ID => Item data + */ + public function get_subtree_data($item_id, $order_asc, $include_item); +} diff --git a/phpBB/phpbb/user.php b/phpBB/phpbb/user.php new file mode 100644 index 0000000000..faedd79703 --- /dev/null +++ b/phpBB/phpbb/user.php @@ -0,0 +1,936 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* Base user class +* +* This is the overarching class which contains (through session extend) +* all methods utilised for user functionality during a session. +*/ +class user extends \phpbb\session +{ + var $lang = array(); + var $help = array(); + var $style = array(); + var $date_format; + + /** + * DateTimeZone object holding the timezone of the user + */ + public $timezone; + + /** + * @var string Class name of datetime object + */ + protected $datetime; + + var $lang_name = false; + var $lang_id = false; + var $lang_path; + var $img_lang; + var $img_array = array(); + + // Able to add new options (up to id 31) + var $keyoptions = array('viewimg' => 0, 'viewflash' => 1, 'viewsmilies' => 2, 'viewsigs' => 3, 'viewavatars' => 4, 'viewcensors' => 5, 'attachsig' => 6, 'bbcode' => 8, 'smilies' => 9, 'sig_bbcode' => 15, 'sig_smilies' => 16, 'sig_links' => 17); + + /** + * Constructor to set the lang path + * @param string $datetime_class Class name of datetime class + */ + function __construct($datetime_class) + { + global $phpbb_root_path; + + $this->lang_path = $phpbb_root_path . 'language/'; + $this->datetime = $datetime_class; + } + + /** + * Function to set custom language path (able to use directory outside of phpBB) + * + * @param string $lang_path New language path used. + * @access public + */ + function set_custom_lang_path($lang_path) + { + $this->lang_path = $lang_path; + + if (substr($this->lang_path, -1) != '/') + { + $this->lang_path .= '/'; + } + } + + /** + * Setup basic user-specific items (style, language, ...) + */ + function setup($lang_set = false, $style_id = false) + { + global $db, $request, $template, $config, $auth, $phpEx, $phpbb_root_path, $cache; + global $phpbb_dispatcher; + + if ($this->data['user_id'] != ANONYMOUS) + { + $user_lang_name = (file_exists($this->lang_path . $this->data['user_lang'] . "/common.$phpEx")) ? $this->data['user_lang'] : basename($config['default_lang']); + $user_date_format = $this->data['user_dateformat']; + $user_timezone = $this->data['user_timezone']; + } + else + { + $lang_override = $request->variable('language', ''); + if ($lang_override) + { + $this->set_cookie('lang', $lang_override, 0, false); + } + else + { + $lang_override = $request->variable($config['cookie_name'] . '_lang', '', true, \phpbb\request\request_interface::COOKIE); + } + if ($lang_override) + { + $use_lang = basename($lang_override); + $user_lang_name = (file_exists($this->lang_path . $use_lang . "/common.$phpEx")) ? $use_lang : basename($config['default_lang']); + $this->data['user_lang'] = $user_lang_name; + } + else + { + $user_lang_name = basename($config['default_lang']); + } + $user_date_format = $config['default_dateformat']; + $user_timezone = $config['board_timezone']; + + /** + * If a guest user is surfing, we try to guess his/her language first by obtaining the browser language + * If re-enabled we need to make sure only those languages installed are checked + * Commented out so we do not loose the code. + + if ($request->header('Accept-Language')) + { + $accept_lang_ary = explode(',', $request->header('Accept-Language')); + + foreach ($accept_lang_ary as $accept_lang) + { + // Set correct format ... guess full xx_YY form + $accept_lang = substr($accept_lang, 0, 2) . '_' . strtoupper(substr($accept_lang, 3, 2)); + $accept_lang = basename($accept_lang); + + if (file_exists($this->lang_path . $accept_lang . "/common.$phpEx")) + { + $user_lang_name = $config['default_lang'] = $accept_lang; + break; + } + else + { + // No match on xx_YY so try xx + $accept_lang = substr($accept_lang, 0, 2); + $accept_lang = basename($accept_lang); + + if (file_exists($this->lang_path . $accept_lang . "/common.$phpEx")) + { + $user_lang_name = $config['default_lang'] = $accept_lang; + break; + } + } + } + } + */ + } + + $user_data = $this->data; + $lang_set_ext = array(); + + /** + * Event to load language files and modify user data on every page + * + * @event core.user_setup + * @var array user_data Array with user's data row + * @var string user_lang_name Basename of the user's langauge + * @var string user_date_format User's date/time format + * @var string user_timezone User's timezone, should be one of + * http://www.php.net/manual/en/timezones.php + * @var mixed lang_set String or array of language files + * @var array lang_set_ext Array containing entries of format + * array( + * 'ext_name' => (string) [extension name], + * 'lang_set' => (string|array) [language files], + * ) + * For performance reasons, only load translations + * that are absolutely needed globally using this + * event. Use local events otherwise. + * @var mixed style_id Style we are going to display + * @since 3.1.0-a1 + */ + $vars = array( + 'user_data', + 'user_lang_name', + 'user_date_format', + 'user_timezone', + 'lang_set', + 'lang_set_ext', + 'style_id', + ); + extract($phpbb_dispatcher->trigger_event('core.user_setup', compact($vars))); + + $this->data = $user_data; + $this->lang_name = $user_lang_name; + $this->date_format = $user_date_format; + + try + { + $this->timezone = new \DateTimeZone($user_timezone); + } + catch (\Exception $e) + { + // If the timezone the user has selected is invalid, we fall back to UTC. + $this->timezone = new \DateTimeZone('UTC'); + } + + // We include common language file here to not load it every time a custom language file is included + $lang = &$this->lang; + + // Do not suppress error if in DEBUG mode + $include_result = (defined('DEBUG')) ? (include $this->lang_path . $this->lang_name . "/common.$phpEx") : (@include $this->lang_path . $this->lang_name . "/common.$phpEx"); + + if ($include_result === false) + { + die('Language file ' . $this->lang_path . $this->lang_name . "/common.$phpEx" . " couldn't be opened."); + } + + $this->add_lang($lang_set); + unset($lang_set); + + foreach ($lang_set_ext as $ext_lang_pair) + { + $this->add_lang_ext($ext_lang_pair['ext_name'], $ext_lang_pair['lang_set']); + } + unset($lang_set_ext); + + $style_request = $request->variable('style', 0); + if ($style_request && (!$config['override_user_style'] || $auth->acl_get('a_styles')) && !defined('ADMIN_START')) + { + global $SID, $_EXTRA_URL; + + $style_id = $style_request; + $SID .= '&style=' . $style_id; + $_EXTRA_URL = array('style=' . $style_id); + } + else + { + // Set up style + $style_id = ($style_id) ? $style_id : ((!$config['override_user_style']) ? $this->data['user_style'] : $config['default_style']); + } + + $sql = 'SELECT * + FROM ' . STYLES_TABLE . " s + WHERE s.style_id = $style_id"; + $result = $db->sql_query($sql, 3600); + $this->style = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + + // Fallback to user's standard style + if (!$this->style && $style_id != $this->data['user_style']) + { + $style_id = $this->data['user_style']; + + $sql = 'SELECT * + FROM ' . STYLES_TABLE . " s + WHERE s.style_id = $style_id"; + $result = $db->sql_query($sql, 3600); + $this->style = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + } + + // User has wrong style + if (!$this->style && $style_id == $this->data['user_style']) + { + $style_id = $this->data['user_style'] = $config['default_style']; + + $sql = 'UPDATE ' . USERS_TABLE . " + SET user_style = $style_id + WHERE user_id = {$this->data['user_id']}"; + $db->sql_query($sql); + + $sql = 'SELECT * + FROM ' . STYLES_TABLE . " s + WHERE s.style_id = $style_id"; + $result = $db->sql_query($sql, 3600); + $this->style = $db->sql_fetchrow($result); + $db->sql_freeresult($result); + } + + if (!$this->style) + { + trigger_error('NO_STYLE_DATA', E_USER_ERROR); + } + + // Now parse the cfg file and cache it + $parsed_items = $cache->obtain_cfg_items($this->style); + + $check_for = array( + 'pagination_sep' => (string) ', ' + ); + + foreach ($check_for as $key => $default_value) + { + $this->style[$key] = (isset($parsed_items[$key])) ? $parsed_items[$key] : $default_value; + settype($this->style[$key], gettype($default_value)); + + if (is_string($default_value)) + { + $this->style[$key] = htmlspecialchars($this->style[$key]); + } + } + + $template->set_style(); + + $this->img_lang = $this->lang_name; + + // Call phpbb_user_session_handler() in case external application want to "bend" some variables or replace classes... + // After calling it we continue script execution... + phpbb_user_session_handler(); + + /** + * Execute code at the end of user setup + * + * @event core.user_setup_after + * @since 3.1.6-RC1 + */ + $phpbb_dispatcher->dispatch('core.user_setup_after'); + + // If this function got called from the error handler we are finished here. + if (defined('IN_ERROR_HANDLER')) + { + return; + } + + // Disable board if the install/ directory is still present + // For the brave development army we do not care about this, else we need to comment out this everytime we develop locally + if (!defined('DEBUG') && !defined('ADMIN_START') && !defined('IN_INSTALL') && !defined('IN_LOGIN') && file_exists($phpbb_root_path . 'install') && !is_file($phpbb_root_path . 'install')) + { + // Adjust the message slightly according to the permissions + if ($auth->acl_gets('a_', 'm_') || $auth->acl_getf_global('m_')) + { + $message = 'REMOVE_INSTALL'; + } + else + { + $message = (!empty($config['board_disable_msg'])) ? $config['board_disable_msg'] : 'BOARD_DISABLE'; + } + trigger_error($message); + } + + // Is board disabled and user not an admin or moderator? + if ($config['board_disable'] && !defined('IN_LOGIN') && !defined('SKIP_CHECK_DISABLED') && !$auth->acl_gets('a_', 'm_') && !$auth->acl_getf_global('m_')) + { + if ($this->data['is_bot']) + { + send_status_line(503, 'Service Unavailable'); + } + + $message = (!empty($config['board_disable_msg'])) ? $config['board_disable_msg'] : 'BOARD_DISABLE'; + trigger_error($message); + } + + // Is load exceeded? + if ($config['limit_load'] && $this->load !== false) + { + if ($this->load > floatval($config['limit_load']) && !defined('IN_LOGIN') && !defined('IN_ADMIN')) + { + // Set board disabled to true to let the admins/mods get the proper notification + $config['board_disable'] = '1'; + + if (!$auth->acl_gets('a_', 'm_') && !$auth->acl_getf_global('m_')) + { + if ($this->data['is_bot']) + { + send_status_line(503, 'Service Unavailable'); + } + trigger_error('BOARD_UNAVAILABLE'); + } + } + } + + if (isset($this->data['session_viewonline'])) + { + // Make sure the user is able to hide his session + if (!$this->data['session_viewonline']) + { + // Reset online status if not allowed to hide the session... + if (!$auth->acl_get('u_hideonline')) + { + $sql = 'UPDATE ' . SESSIONS_TABLE . ' + SET session_viewonline = 1 + WHERE session_user_id = ' . $this->data['user_id']; + $db->sql_query($sql); + $this->data['session_viewonline'] = 1; + } + } + else if (!$this->data['user_allow_viewonline']) + { + // the user wants to hide and is allowed to -> cloaking device on. + if ($auth->acl_get('u_hideonline')) + { + $sql = 'UPDATE ' . SESSIONS_TABLE . ' + SET session_viewonline = 0 + WHERE session_user_id = ' . $this->data['user_id']; + $db->sql_query($sql); + $this->data['session_viewonline'] = 0; + } + } + } + + // Does the user need to change their password? If so, redirect to the + // ucp profile reg_details page ... of course do not redirect if we're already in the ucp + if (!defined('IN_ADMIN') && !defined('ADMIN_START') && $config['chg_passforce'] && !empty($this->data['is_registered']) && $auth->acl_get('u_chgpasswd') && $this->data['user_passchg'] < time() - ($config['chg_passforce'] * 86400)) + { + if (strpos($this->page['query_string'], 'mode=reg_details') === false && $this->page['page_name'] != "ucp.$phpEx") + { + redirect(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=profile&mode=reg_details')); + } + } + + return; + } + + /** + * More advanced language substitution + * Function to mimic sprintf() with the possibility of using phpBB's language system to substitute nullar/singular/plural forms. + * Params are the language key and the parameters to be substituted. + * This function/functionality is inspired by SHS` and Ashe. + * + * Example call: <samp>$user->lang('NUM_POSTS_IN_QUEUE', 1);</samp> + * + * If the first parameter is an array, the elements are used as keys and subkeys to get the language entry: + * Example: <samp>$user->lang(array('datetime', 'AGO'), 1)</samp> uses $user->lang['datetime']['AGO'] as language entry. + */ + function lang() + { + $args = func_get_args(); + $key = $args[0]; + + if (is_array($key)) + { + $lang = &$this->lang[array_shift($key)]; + + foreach ($key as $_key) + { + $lang = &$lang[$_key]; + } + } + else + { + $lang = &$this->lang[$key]; + } + + // Return if language string does not exist + if (!isset($lang) || (!is_string($lang) && !is_array($lang))) + { + return $key; + } + + // If the language entry is a string, we simply mimic sprintf() behaviour + if (is_string($lang)) + { + if (sizeof($args) == 1) + { + return $lang; + } + + // Replace key with language entry and simply pass along... + $args[0] = $lang; + return call_user_func_array('sprintf', $args); + } + else if (sizeof($lang) == 0) + { + // If the language entry is an empty array, we just return the language key + return $args[0]; + } + + // It is an array... now handle different nullar/singular/plural forms + $key_found = false; + + // We now get the first number passed and will select the key based upon this number + for ($i = 1, $num_args = sizeof($args); $i < $num_args; $i++) + { + if (is_int($args[$i]) || is_float($args[$i])) + { + if ($args[$i] == 0 && isset($lang[0])) + { + // We allow each translation using plural forms to specify a version for the case of 0 things, + // so that "0 users" may be displayed as "No users". + $key_found = 0; + break; + } + else + { + $use_plural_form = $this->get_plural_form($args[$i]); + if (isset($lang[$use_plural_form])) + { + // The key we should use exists, so we use it. + $key_found = $use_plural_form; + } + else + { + // If the key we need to use does not exist, we fall back to the previous one. + $numbers = array_keys($lang); + + foreach ($numbers as $num) + { + if ($num > $use_plural_form) + { + break; + } + + $key_found = $num; + } + } + break; + } + } + } + + // Ok, let's check if the key was found, else use the last entry (because it is mostly the plural form) + if ($key_found === false) + { + $numbers = array_keys($lang); + $key_found = end($numbers); + } + + // Use the language string we determined and pass it to sprintf() + $args[0] = $lang[$key_found]; + return call_user_func_array('sprintf', $args); + } + + /** + * Determine which plural form we should use. + * For some languages this is not as simple as for English. + * + * @param $number int|float The number we want to get the plural case for. Float numbers are floored. + * @param $force_rule mixed False to use the plural rule of the language package + * or an integer to force a certain plural rule + * @return int The plural-case we need to use for the number plural-rule combination + */ + function get_plural_form($number, $force_rule = false) + { + $number = (int) $number; + + // Default to English system + $plural_rule = ($force_rule !== false) ? $force_rule : ((isset($this->lang['PLURAL_RULE'])) ? $this->lang['PLURAL_RULE'] : 1); + + return phpbb_get_plural_form($plural_rule, $number); + } + + /** + * Add Language Items - use_db and use_help are assigned where needed (only use them to force inclusion) + * + * @param mixed $lang_set specifies the language entries to include + * @param bool $use_db internal variable for recursion, do not use + * @param bool $use_help internal variable for recursion, do not use + * @param string $ext_name The extension to load language from, or empty for core files + * + * Examples: + * <code> + * $lang_set = array('posting', 'help' => 'faq'); + * $lang_set = array('posting', 'viewtopic', 'help' => array('bbcode', 'faq')) + * $lang_set = array(array('posting', 'viewtopic'), 'help' => array('bbcode', 'faq')) + * $lang_set = 'posting' + * $lang_set = array('help' => 'faq', 'db' => array('help:faq', 'posting')) + * </code> + */ + function add_lang($lang_set, $use_db = false, $use_help = false, $ext_name = '') + { + global $phpEx; + + if (is_array($lang_set)) + { + foreach ($lang_set as $key => $lang_file) + { + // Please do not delete this line. + // We have to force the type here, else [array] language inclusion will not work + $key = (string) $key; + + if ($key == 'db') + { + $this->add_lang($lang_file, true, $use_help, $ext_name); + } + else if ($key == 'help') + { + $this->add_lang($lang_file, $use_db, true, $ext_name); + } + else if (!is_array($lang_file)) + { + $this->set_lang($this->lang, $this->help, $lang_file, $use_db, $use_help, $ext_name); + } + else + { + $this->add_lang($lang_file, $use_db, $use_help, $ext_name); + } + } + unset($lang_set); + } + else if ($lang_set) + { + $this->set_lang($this->lang, $this->help, $lang_set, $use_db, $use_help, $ext_name); + } + } + + /** + * Add Language Items from an extension - use_db and use_help are assigned where needed (only use them to force inclusion) + * + * @param string $ext_name The extension to load language from, or empty for core files + * @param mixed $lang_set specifies the language entries to include + * @param bool $use_db internal variable for recursion, do not use + * @param bool $use_help internal variable for recursion, do not use + */ + function add_lang_ext($ext_name, $lang_set, $use_db = false, $use_help = false) + { + if ($ext_name === '/') + { + $ext_name = ''; + } + + $this->add_lang($lang_set, $use_db, $use_help, $ext_name); + } + + /** + * Set language entry (called by add_lang) + * @access private + */ + function set_lang(&$lang, &$help, $lang_file, $use_db = false, $use_help = false, $ext_name = '') + { + global $phpbb_root_path, $phpEx; + + // Make sure the language name is set (if the user setup did not happen it is not set) + if (!$this->lang_name) + { + global $config; + $this->lang_name = basename($config['default_lang']); + } + + // $lang == $this->lang + // $help == $this->help + // - add appropriate variables here, name them as they are used within the language file... + if (!$use_db) + { + if ($use_help && strpos($lang_file, '/') !== false) + { + $filename = dirname($lang_file) . '/help_' . basename($lang_file); + } + else + { + $filename = (($use_help) ? 'help_' : '') . $lang_file; + } + + if ($ext_name) + { + global $phpbb_extension_manager; + $ext_path = $phpbb_extension_manager->get_extension_path($ext_name, true); + + $lang_path = $ext_path . 'language/'; + } + else + { + $lang_path = $this->lang_path; + } + + if (strpos($phpbb_root_path . $filename, $lang_path) === 0) + { + $language_filename = $phpbb_root_path . $filename; + } + else + { + $language_filename = $lang_path . $this->lang_name . '/' . $filename . '.' . $phpEx; + } + + // If we are in install, try to use the updated version, when available + $install_language_filename = str_replace('language/', 'install/update/new/language/', $language_filename); + if (defined('IN_INSTALL') && file_exists($install_language_filename)) + { + $language_filename = $install_language_filename; + } + + if (!file_exists($language_filename)) + { + global $config; + + if ($this->lang_name == 'en') + { + // The user's selected language is missing the file, the board default's language is missing the file, and the file doesn't exist in /en. + $language_filename = str_replace($lang_path . 'en', $lang_path . $this->data['user_lang'], $language_filename); + trigger_error('Language file ' . $language_filename . ' couldn\'t be opened.', E_USER_ERROR); + } + else if ($this->lang_name == basename($config['default_lang'])) + { + // Fall back to the English Language + $reset_lang_name = $this->lang_name; + $this->lang_name = 'en'; + $this->set_lang($lang, $help, $lang_file, $use_db, $use_help, $ext_name); + $this->lang_name = $reset_lang_name; + } + else if ($this->lang_name == $this->data['user_lang']) + { + // Fall back to the board default language + $reset_lang_name = $this->lang_name; + $this->lang_name = basename($config['default_lang']); + $this->set_lang($lang, $help, $lang_file, $use_db, $use_help, $ext_name); + $this->lang_name = $reset_lang_name; + } + + return; + } + + // Do not suppress error if in DEBUG mode + $include_result = (defined('DEBUG')) ? (include $language_filename) : (@include $language_filename); + + if ($include_result === false) + { + trigger_error('Language file ' . $language_filename . ' couldn\'t be opened.', E_USER_ERROR); + } + } + else if ($use_db) + { + // Get Database Language Strings + // Put them into $lang if nothing is prefixed, put them into $help if help: is prefixed + // For example: help:faq, posting + } + } + + /** + * Format user date + * + * @param int $gmepoch unix timestamp + * @param string $format date format in date() notation. | used to indicate relative dates, for example |d m Y|, h:i is translated to Today, h:i. + * @param bool $forcedate force non-relative date format. + * + * @return mixed translated date + */ + function format_date($gmepoch, $format = false, $forcedate = false) + { + static $utc; + + if (!isset($utc)) + { + $utc = new \DateTimeZone('UTC'); + } + + $time = new $this->datetime($this, '@' . (int) $gmepoch, $utc); + $time->setTimezone($this->timezone); + + return $time->format($format, $forcedate); + } + + /** + * Create a \phpbb\datetime object in the context of the current user + * + * @since 3.1 + * @param string $time String in a format accepted by strtotime(). + * @param DateTimeZone $timezone Time zone of the time. + * @return \phpbb\datetime Date time object linked to the current users locale + */ + public function create_datetime($time = 'now', \DateTimeZone $timezone = null) + { + $timezone = $timezone ?: $this->timezone; + return new $this->datetime($this, $time, $timezone); + } + + /** + * Get the UNIX timestamp for a datetime in the users timezone, so we can store it in the database. + * + * @param string $format Format of the entered date/time + * @param string $time Date/time with the timezone applied + * @param DateTimeZone $timezone Timezone of the date/time, falls back to timezone of current user + * @return int Returns the unix timestamp + */ + public function get_timestamp_from_format($format, $time, \DateTimeZone $timezone = null) + { + $timezone = $timezone ?: $this->timezone; + $date = \DateTime::createFromFormat($format, $time, $timezone); + return ($date !== false) ? $date->format('U') : false; + } + + /** + * Get language id currently used by the user + */ + function get_iso_lang_id() + { + global $config, $db; + + if (!empty($this->lang_id)) + { + return $this->lang_id; + } + + if (!$this->lang_name) + { + $this->lang_name = $config['default_lang']; + } + + $sql = 'SELECT lang_id + FROM ' . LANG_TABLE . " + WHERE lang_iso = '" . $db->sql_escape($this->lang_name) . "'"; + $result = $db->sql_query($sql); + $this->lang_id = (int) $db->sql_fetchfield('lang_id'); + $db->sql_freeresult($result); + + return $this->lang_id; + } + + /** + * Get users profile fields + */ + function get_profile_fields($user_id) + { + global $db; + + if (isset($this->profile_fields)) + { + return; + } + + $sql = 'SELECT * + FROM ' . PROFILE_FIELDS_DATA_TABLE . " + WHERE user_id = $user_id"; + $result = $db->sql_query_limit($sql, 1); + $this->profile_fields = (!($row = $db->sql_fetchrow($result))) ? array() : $row; + $db->sql_freeresult($result); + } + + /** + * Specify/Get image + */ + function img($img, $alt = '') + { + $title = ''; + + if ($alt) + { + $alt = $this->lang($alt); + $title = ' title="' . $alt . '"'; + } + return '<span class="imageset ' . $img . '"' . $title . '>' . $alt . '</span>'; + } + + /** + * Get option bit field from user options. + * + * @param int $key option key, as defined in $keyoptions property. + * @param int $data bit field value to use, or false to use $this->data['user_options'] + * @return bool true if the option is set in the bit field, false otherwise + */ + function optionget($key, $data = false) + { + $var = ($data !== false) ? $data : $this->data['user_options']; + return phpbb_optionget($this->keyoptions[$key], $var); + } + + /** + * Set option bit field for user options. + * + * @param int $key Option key, as defined in $keyoptions property. + * @param bool $value True to set the option, false to clear the option. + * @param int $data Current bit field value, or false to use $this->data['user_options'] + * @return int|bool If $data is false, the bit field is modified and + * written back to $this->data['user_options'], and + * return value is true if the bit field changed and + * false otherwise. If $data is not false, the new + * bitfield value is returned. + */ + function optionset($key, $value, $data = false) + { + $var = ($data !== false) ? $data : $this->data['user_options']; + + $new_var = phpbb_optionset($this->keyoptions[$key], $value, $var); + + if ($data === false) + { + if ($new_var != $var) + { + $this->data['user_options'] = $new_var; + return true; + } + else + { + return false; + } + } + else + { + return $new_var; + } + } + + /** + * Funtion to make the user leave the NEWLY_REGISTERED system group. + * @access public + */ + function leave_newly_registered() + { + global $db; + + if (empty($this->data['user_new'])) + { + return false; + } + + if (!function_exists('remove_newly_registered')) + { + global $phpbb_root_path, $phpEx; + + include($phpbb_root_path . 'includes/functions_user.' . $phpEx); + } + if ($group = remove_newly_registered($this->data['user_id'], $this->data)) + { + $this->data['group_id'] = $group; + + } + $this->data['user_permissions'] = ''; + $this->data['user_new'] = 0; + + return true; + } + + /** + * Returns all password protected forum ids the user is currently NOT authenticated for. + * + * @return array Array of forum ids + * @access public + */ + function get_passworded_forums() + { + global $db; + + $sql = 'SELECT f.forum_id, fa.user_id + FROM ' . FORUMS_TABLE . ' f + LEFT JOIN ' . FORUMS_ACCESS_TABLE . " fa + ON (fa.forum_id = f.forum_id + AND fa.session_id = '" . $db->sql_escape($this->session_id) . "') + WHERE f.forum_password <> ''"; + $result = $db->sql_query($sql); + + $forum_ids = array(); + while ($row = $db->sql_fetchrow($result)) + { + $forum_id = (int) $row['forum_id']; + + if ($row['user_id'] != $this->data['user_id']) + { + $forum_ids[$forum_id] = $forum_id; + } + } + $db->sql_freeresult($result); + + return $forum_ids; + } +} diff --git a/phpBB/phpbb/user_loader.php b/phpBB/phpbb/user_loader.php new file mode 100644 index 0000000000..967d96d73a --- /dev/null +++ b/phpBB/phpbb/user_loader.php @@ -0,0 +1,229 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* User loader class +* +* This handles loading users from the database and +* storing in them in a temporary cache so we do not +* have to query the same user multiple times in +* different services. +*/ +class user_loader +{ + /** @var \phpbb\db\driver\driver_interface */ + protected $db = null; + + /** @var string */ + protected $phpbb_root_path = null; + + /** @var string */ + protected $php_ext = null; + + /** @var string */ + protected $users_table = null; + + /** + * Users loaded from the DB + * + * @var array Array of user data that we've loaded from the DB + */ + protected $users = array(); + + /** + * User loader constructor + * + * @param \phpbb\db\driver\driver_interface $db A database connection + * @param string $phpbb_root_path Path to the phpbb includes directory. + * @param string $php_ext php file extension + * @param string $users_table The name of the database table (phpbb_users) + */ + public function __construct(\phpbb\db\driver\driver_interface $db, $phpbb_root_path, $php_ext, $users_table) + { + $this->db = $db; + + $this->phpbb_root_path = $phpbb_root_path; + $this->php_ext = $php_ext; + + $this->users_table = $users_table; + } + + /** + * Load user helper + * + * @param array $user_ids + */ + public function load_users(array $user_ids) + { + $user_ids[] = ANONYMOUS; + + // Make user_ids unique and convert to integer. + $user_ids = array_map('intval', array_unique($user_ids)); + + // Do not load users we already have in $this->users + $user_ids = array_diff($user_ids, array_keys($this->users)); + + if (sizeof($user_ids)) + { + $sql = 'SELECT * + FROM ' . $this->users_table . ' + WHERE ' . $this->db->sql_in_set('user_id', $user_ids); + $result = $this->db->sql_query($sql); + + while ($row = $this->db->sql_fetchrow($result)) + { + $this->users[$row['user_id']] = $row; + } + $this->db->sql_freeresult($result); + } + } + + /** + * Load a user by username + * + * Stores the full data in the user cache so they do not need to be loaded again + * Returns the user id so you may use get_user() from the returned value + * + * @param string $username Raw username to load (will be cleaned) + * @return int User ID for the username + */ + public function load_user_by_username($username) + { + $sql = 'SELECT * + FROM ' . $this->users_table . " + WHERE username_clean = '" . $this->db->sql_escape(utf8_clean_string($username)) . "'"; + $result = $this->db->sql_query($sql); + $row = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + if ($row) + { + $this->users[$row['user_id']] = $row; + + return $row['user_id']; + } + + return ANONYMOUS; + } + + /** + * Get a user row from our users cache + * + * @param int $user_id User ID of the user you want to retreive + * @param bool $query Should we query the database if this user has not yet been loaded? + * Typically this should be left as false and you should make sure + * you load users ahead of time with load_users() + * @return array|bool Row from the database of the user or Anonymous if the user wasn't loaded/does not exist + * or bool False if the anonymous user was not loaded + */ + public function get_user($user_id, $query = false) + { + if (isset($this->users[$user_id])) + { + return $this->users[$user_id]; + } + // Query them if we must (if ANONYMOUS is sent as the user_id and we have not loaded Anonymous yet, we must load Anonymous as a last resort) + else if ($query || $user_id == ANONYMOUS) + { + $this->load_users(array($user_id)); + + return $this->get_user($user_id); + } + + return $this->get_user(ANONYMOUS); + } + + /** + * Get username + * + * @param int $user_id User ID of the user you want to retreive the username for + * @param string $mode The mode to load (same as get_username_string). One of the following: + * profile (for getting an url to the profile) + * username (for obtaining the username) + * colour (for obtaining the user colour) + * full (for obtaining a html string representing a coloured link to the users profile) + * no_profile (the same as full but forcing no profile link) + * @param string $guest_username Optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then. + * @param string $custom_profile_url Optional parameter to specify a profile url. The user id get appended to this url as &u={user_id} + * @param bool $query Should we query the database if this user has not yet been loaded? + * Typically this should be left as false and you should make sure + * you load users ahead of time with load_users() + * @return string + */ + public function get_username($user_id, $mode, $guest_username = false, $custom_profile_url = false, $query = false) + { + if (!($user = $this->get_user($user_id, $query))) + { + return ''; + } + + return get_username_string($mode, $user['user_id'], $user['username'], $user['user_colour'], $guest_username, $custom_profile_url); + } + + /** + * Get avatar + * + * @param int $user_id User ID of the user you want to retreive the avatar for + * @param bool $query Should we query the database if this user has not yet been loaded? + * Typically this should be left as false and you should make sure + * you load users ahead of time with load_users() + * @param bool @lazy If true, will be lazy loaded (requires JS) + * @return string + */ + public function get_avatar($user_id, $query = false, $lazy = false) + { + if (!($user = $this->get_user($user_id, $query))) + { + return ''; + } + + return phpbb_get_avatar(\phpbb\avatar\manager::clean_row($user, 'user'), 'USER_AVATAR', false, $lazy); + } + + /** + * Get rank + * + * @param int $user_id User ID of the user you want to retreive the rank for + * @param bool $query Should we query the database if this user has not yet been loaded? + * Typically this should be left as false and you should make sure + * you load users ahead of time with load_users() + * @return array Array with keys 'rank_title', 'rank_img', and 'rank_img_src' + */ + public function get_rank($user_id, $query = false) + { + if (!($user = $this->get_user($user_id, $query))) + { + return ''; + } + + if (!function_exists('phpbb_get_user_rank')) + { + include($this->phpbb_root_path . 'includes/functions_display.' . $this->php_ext); + } + + $rank = array( + 'rank_title', + 'rank_img', + 'rank_img_src', + ); + + $user_rank_data = phpbb_get_user_rank($user, (($user['user_id'] == ANONYMOUS) ? false : $user['user_posts'])); + $rank['rank_title'] = $user_rank_data['title']; + $rank['rank_img'] = $user_rank_data['img']; + $rank['rank_img_src'] = $user_rank_data['img_src']; + + return $rank; + } +} diff --git a/phpBB/phpbb/version_helper.php b/phpBB/phpbb/version_helper.php new file mode 100644 index 0000000000..7e5edbf522 --- /dev/null +++ b/phpBB/phpbb/version_helper.php @@ -0,0 +1,520 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** + * Class to handle version checking and comparison + */ +class version_helper +{ + /** + * @var string Host + */ + protected $host = 'version.phpbb.com'; + + /** + * @var string Path to file + */ + protected $path = '/phpbb'; + + /** + * @var string File name + */ + protected $file = 'versions.json'; + + /** + * @var bool Use SSL or not + */ + protected $use_ssl = false; + + /** + * @var string Current version installed + */ + protected $current_version; + + /** + * @var null|string Null to not force stability, 'unstable' or 'stable' to + * force the corresponding stability + */ + protected $force_stability; + + /** @var \phpbb\cache\service */ + protected $cache; + + /** @var \phpbb\config\config */ + protected $config; + + /** @var \phpbb\file_downloader */ + protected $file_downloader; + + /** @var \phpbb\user */ + protected $user; + + protected $version_schema = array( + 'stable' => array( + 'current' => 'version', + 'download' => 'url', + 'announcement' => 'url', + 'eol' => 'url', + 'security' => 'bool', + ), + 'unstable' => array( + 'current' => 'version', + 'download' => 'url', + 'announcement' => 'url', + 'eol' => 'url', + 'security' => 'bool', + ), + ); + + /** + * Constructor + * + * @param \phpbb\cache\service $cache + * @param \phpbb\config\config $config + * @param \phpbb\file_downloader $file_downloader + * @param \phpbb\user $user + */ + public function __construct(\phpbb\cache\service $cache, \phpbb\config\config $config, \phpbb\file_downloader $file_downloader, \phpbb\user $user) + { + $this->cache = $cache; + $this->config = $config; + $this->file_downloader = $file_downloader; + $this->user = $user; + + if (defined('PHPBB_QA')) + { + $this->force_stability = 'unstable'; + } + + $this->current_version = $this->config['version']; + } + + /** + * Set location to the file + * + * @param string $host Host (e.g. version.phpbb.com) + * @param string $path Path to file (e.g. /phpbb) + * @param string $file File name (Default: versions.json) + * @param bool $use_ssl Use SSL or not (Default: false) + * @return version_helper + */ + public function set_file_location($host, $path, $file = 'versions.json', $use_ssl = false) + { + $this->host = $host; + $this->path = $path; + $this->file = $file; + $this->use_ssl = $use_ssl; + + return $this; + } + + /** + * Set current version + * + * @param string $version The current version + * @return version_helper + */ + public function set_current_version($version) + { + $this->current_version = $version; + + return $this; + } + + /** + * Over-ride the stability to force check to include unstable versions + * + * @param null|string Null to not force stability, 'unstable' or 'stable' to + * force the corresponding stability + * @return version_helper + */ + public function force_stability($stability) + { + $this->force_stability = $stability; + + return $this; + } + + /** + * Wrapper for version_compare() that allows using uppercase A and B + * for alpha and beta releases. + * + * See http://www.php.net/manual/en/function.version-compare.php + * + * @param string $version1 First version number + * @param string $version2 Second version number + * @param string $operator Comparison operator (optional) + * + * @return mixed Boolean (true, false) if comparison operator is specified. + * Integer (-1, 0, 1) otherwise. + */ + public function compare($version1, $version2, $operator = null) + { + return phpbb_version_compare($version1, $version2, $operator); + } + + /** + * Check whether or not a version is "stable" + * + * Stable means only numbers OR a pl release + * + * @param string $version + * @return bool Bool true or false + */ + public function is_stable($version) + { + $matches = false; + preg_match('/^[\d\.]+/', $version, $matches); + + if (empty($matches[0])) + { + return false; + } + + return $this->compare($version, $matches[0], '>='); + } + + /** + * Gets the latest version for the current branch the user is on + * + * @param bool $force_update Ignores cached data. Defaults to false. + * @param bool $force_cache Force the use of the cache. Override $force_update. + * @return string + * @throws \RuntimeException + */ + public function get_latest_on_current_branch($force_update = false, $force_cache = false) + { + $versions = $this->get_versions_matching_stability($force_update, $force_cache); + + $self = $this; + $current_version = $this->current_version; + + // Filter out any versions less than the current version + $versions = array_filter($versions, function($data) use ($self, $current_version) { + return $self->compare($data['current'], $current_version, '>='); + }); + + // Get the lowest version from the previous list. + return array_reduce($versions, function($value, $data) use ($self) { + if ($value === null || $self->compare($data['current'], $value, '<')) + { + return $data['current']; + } + + return $value; + }); + } + + /** + * Gets the latest update for the current branch the user is on + * Will suggest versions from newer branches when EoL has been reached + * and/or version from newer branch is needed for having all known security + * issues fixed. + * + * @param bool $force_update Ignores cached data. Defaults to false. + * @param bool $force_cache Force the use of the cache. Override $force_update. + * @return array Version info or empty array if there are no updates + * @throws \RuntimeException + */ + public function get_update_on_branch($force_update = false, $force_cache = false) + { + $versions = $this->get_versions_matching_stability($force_update, $force_cache); + + $self = $this; + $current_version = $this->current_version; + + // Filter out any versions less than the current version + $versions = array_filter($versions, function($data) use ($self, $current_version) { + return $self->compare($data['current'], $current_version, '>='); + }); + + // Get the lowest version from the previous list. + $update_info = array_reduce($versions, function($value, $data) use ($self, $current_version) { + if ($value === null && $self->compare($data['current'], $current_version, '>=')) + { + if (!$data['eol'] && (!$data['security'] || $self->compare($data['security'], $data['current'], '<='))) + { + return ($self->compare($data['current'], $current_version, '>')) ? $data : array(); + } + else + { + return null; + } + } + + return $value; + }); + + return $update_info === null ? array() : $update_info; + } + + /** + * Gets the latest extension update for the current phpBB branch the user is on + * Will suggest versions from newer branches when EoL has been reached + * and/or version from newer branch is needed for having all known security + * issues fixed. + * + * @param bool $force_update Ignores cached data. Defaults to false. + * @param bool $force_cache Force the use of the cache. Override $force_update. + * @return array Version info or empty array if there are no updates + * @throws \RuntimeException + */ + public function get_ext_update_on_branch($force_update = false, $force_cache = false) + { + $versions = $this->get_versions_matching_stability($force_update, $force_cache); + + $self = $this; + $current_version = $this->current_version; + + // Get current phpBB branch from version, e.g.: 3.2 + preg_match('/^(\d+\.\d+).*$/', $this->config['version'], $matches); + $current_branch = $matches[1]; + + // Filter out any versions less than the current version + $versions = array_filter($versions, function($data) use ($self, $current_version) { + return $self->compare($data['current'], $current_version, '>='); + }); + + // Filter out any phpbb branches less than the current version + $branches = array_filter(array_keys($versions), function($branch) use ($self, $current_branch) { + return $self->compare($branch, $current_branch, '>='); + }); + if (!empty($branches)) + { + $versions = array_intersect_key($versions, array_flip($branches)); + } + else + { + // If branches are empty, it means the current phpBB branch is newer than any branch the + // extension was validated against. Reverse sort the versions array so we get the newest + // validated release available. + krsort($versions); + } + + // Get the first available version from the previous list. + $update_info = array_reduce($versions, function($value, $data) use ($self, $current_version) { + if ($value === null && $self->compare($data['current'], $current_version, '>=')) + { + if (!$data['eol'] && (!$data['security'] || $self->compare($data['security'], $data['current'], '<='))) + { + return $self->compare($data['current'], $current_version, '>') ? $data : array(); + } + else + { + return null; + } + } + + return $value; + }); + + return $update_info === null ? array() : $update_info; + } + + /** + * Obtains the latest version information + * + * @param bool $force_update Ignores cached data. Defaults to false. + * @param bool $force_cache Force the use of the cache. Override $force_update. + * @return array + * @throws \RuntimeException + */ + public function get_suggested_updates($force_update = false, $force_cache = false) + { + $versions = $this->get_versions_matching_stability($force_update, $force_cache); + + $self = $this; + $current_version = $this->current_version; + + // Filter out any versions less than or equal to the current version + return array_filter($versions, function($data) use ($self, $current_version) { + return $self->compare($data['current'], $current_version, '>'); + }); + } + + /** + * Obtains the latest version information matching the stability of the current install + * + * @param bool $force_update Ignores cached data. Defaults to false. + * @param bool $force_cache Force the use of the cache. Override $force_update. + * @return array Version info + * @throws \RuntimeException + */ + public function get_versions_matching_stability($force_update = false, $force_cache = false) + { + $info = $this->get_versions($force_update, $force_cache); + + if ($this->force_stability !== null) + { + return ($this->force_stability === 'unstable') ? $info['unstable'] : $info['stable']; + } + + return ($this->is_stable($this->current_version)) ? $info['stable'] : $info['unstable']; + } + + /** + * Obtains the latest version information + * + * @param bool $force_update Ignores cached data. Defaults to false. + * @param bool $force_cache Force the use of the cache. Override $force_update. + * @return array Version info, includes stable and unstable data + * @throws \RuntimeException + */ + public function get_versions($force_update = false, $force_cache = false) + { + $cache_file = '_versioncheck_' . $this->host . $this->path . $this->file . $this->use_ssl; + + $info = $this->cache->get($cache_file); + + if ($info === false && $force_cache) + { + throw new \RuntimeException($this->user->lang('VERSIONCHECK_FAIL')); + } + else if ($info === false || $force_update) + { + try { + $info = $this->file_downloader->get($this->host, $this->path, $this->file, $this->use_ssl ? 443 : 80); + } + catch (\phpbb\exception\runtime_exception $exception) + { + $prepare_parameters = array_merge(array($exception->getMessage()), $exception->get_parameters()); + throw new \RuntimeException(call_user_func_array(array($this->user, 'lang'), $prepare_parameters)); + } + $error_string = $this->file_downloader->get_error_string(); + + if (!empty($error_string)) + { + throw new \RuntimeException($error_string); + } + + $info = json_decode($info, true); + + // Sanitize any data we retrieve from a server + if (!empty($info)) + { + $json_sanitizer = function (&$value, $key) { + $type_cast_helper = new \phpbb\request\type_cast_helper(); + $type_cast_helper->set_var($value, $value, gettype($value), true); + }; + array_walk_recursive($info, $json_sanitizer); + } + + if (empty($info['stable']) && empty($info['unstable'])) + { + $this->user->add_lang('acp/common'); + + throw new \RuntimeException($this->user->lang('VERSIONCHECK_FAIL')); + } + + $info['stable'] = (empty($info['stable'])) ? array() : $info['stable']; + $info['unstable'] = (empty($info['unstable'])) ? $info['stable'] : $info['unstable']; + + $info = $this->validate_versions($info); + + $this->cache->put($cache_file, $info, 86400); // 24 hours + } + + return $info; + } + + /** + * Validate versions info input + * + * @param array $versions_info Decoded json data array. Will be modified + * and cleaned by this method + * + * @return array Versions info array + */ + public function validate_versions($versions_info) + { + $array_diff = array_diff_key($versions_info, array($this->version_schema)); + + // Remove excessive data + if (count($array_diff) > 0) + { + $old_versions_info = $versions_info; + $versions_info = array( + 'stable' => !empty($old_versions_info['stable']) ? $old_versions_info['stable'] : array(), + 'unstable' => !empty($old_versions_info['unstable']) ? $old_versions_info['unstable'] : array(), + ); + unset($old_versions_info); + } + + foreach ($versions_info as $stability_type => &$versions_data) + { + foreach ($versions_data as $branch => &$version_data) + { + if (!preg_match('/^[0-9a-z\-\.]+$/i', $branch)) + { + unset($versions_data[$branch]); + continue; + } + + $stability_diff = array_diff_key($version_data, $this->version_schema[$stability_type]); + + if (count($stability_diff) > 0) + { + $old_version_data = $version_data; + $version_data = array(); + foreach ($this->version_schema[$stability_type] as $key => $value) + { + if (isset($old_version_data[$key])) + { + $version_data[$key] = $old_version_data[$key]; + } + } + unset($old_version_data); + } + + foreach ($version_data as $key => &$value) + { + if (!isset($this->version_schema[$stability_type][$key])) + { + unset($version_data[$key]); + throw new \RuntimeException($this->user->lang('VERSIONCHECK_INVALID_ENTRY')); + } + + switch ($this->version_schema[$stability_type][$key]) + { + case 'bool': + $value = (bool) $value; + break; + + case 'url': + if (!empty($value) && !preg_match('#^' . get_preg_expression('url') . '$#iu', $value) && + !preg_match('#^' . get_preg_expression('www_url') . '$#iu', $value)) + { + throw new \RuntimeException($this->user->lang('VERSIONCHECK_INVALID_URL')); + } + break; + + case 'version': + if (!empty($value) && !preg_match(get_preg_expression('semantic_version'), $value)) + { + throw new \RuntimeException($this->user->lang('VERSIONCHECK_INVALID_VERSION')); + } + break; + + default: + // Shouldn't be possible to trigger this + throw new \RuntimeException($this->user->lang('VERSIONCHECK_INVALID_ENTRY')); + } + } + } + } + + return $versions_info; + } +} diff --git a/phpBB/phpbb/viewonline_helper.php b/phpBB/phpbb/viewonline_helper.php new file mode 100644 index 0000000000..b722f9d911 --- /dev/null +++ b/phpBB/phpbb/viewonline_helper.php @@ -0,0 +1,54 @@ +<?php +/** +* +* This file is part of the phpBB Forum Software package. +* +* @copyright (c) phpBB Limited <https://www.phpbb.com> +* @license GNU General Public License, version 2 (GPL-2.0) +* +* For full copyright and license information, please see +* the docs/CREDITS.txt file. +* +*/ + +namespace phpbb; + +/** +* Class to handle viewonline related tasks +*/ +class viewonline_helper +{ + /** @var \phpbb\filesystem */ + protected $filesystem; + + /** + * @param \phpbb\filesystem $filesystem + */ + public function __construct(\phpbb\filesystem $filesystem) + { + $this->filesystem = $filesystem; + } + + /** + * Get user page + * + * @param string $session_page User's session page + * @return array Match array filled by preg_match() + */ + public function get_user_page($session_page) + { + $session_page = $this->filesystem->clean_path($session_page); + if (strpos($session_page, './') === 0) + { + $session_page = substr($session_page, 2); + } + + preg_match('#^((\.\./)*([a-z0-9/_-]+))#i', $session_page, $on_page); + if (empty($on_page)) + { + $on_page[1] = ''; + } + + return $on_page; + } +} |