Merge pull request #107 from diolektor/php7-future

Master branch up to php 7 compatibility
This commit is contained in:
Yuriy Pikhtarev 2017-01-13 00:09:05 +03:00 committed by GitHub
commit a04df19607
34 changed files with 649 additions and 654 deletions

View file

@ -24,7 +24,7 @@ echo '
foreach ($sql as $i => $query) foreach ($sql as $i => $query)
{ {
$row = mysql_fetch_row(DB()->query($query)); $row = mysqli_fetch_row(DB()->query($query));
echo "<tr><td>{$lang['TR_STATS'][$i]}</td><td><b>{$row[0]}</b></td>"; echo "<tr><td>{$lang['TR_STATS'][$i]}</td><td><b>{$row[0]}</b></td>";
} }

View file

@ -54,33 +54,33 @@ function error_exit ($msg = '')
// Database // Database
class sql_db class sql_db
{ {
var $cfg = array(); public $cfg = array();
var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); public $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist');
var $link = null; public $link = null;
var $result = null; public $result = null;
var $db_server = ''; public $db_server = '';
var $selected_db = null; public $selected_db = null;
var $locked = false; public $locked = false;
var $num_queries = 0; public $num_queries = 0;
var $sql_starttime = 0; public $sql_starttime = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
var $sql_last_time = 0; public $sql_last_time = 0;
var $slow_time = 0; public $slow_time = 0;
var $dbg = array(); public $dbg = array();
var $dbg_id = 0; public $dbg_id = 0;
var $dbg_enabled = false; public $dbg_enabled = false;
var $cur_query = null; public $cur_query = null;
var $DBS = array(); public $DBS = array();
/** /**
* Constructor * Constructor
*/ */
function sql_db ($cfg_values) function __construct ($cfg_values)
{ {
global $DBS; global $DBS;

View file

@ -304,7 +304,7 @@ function make_rand_str ($len = 10)
$str = ''; $str = '';
while (strlen($str) < $len) while (strlen($str) < $len)
{ {
$str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', crypt(uniqid(mt_rand(), true)))); $str .= str_shuffle(preg_replace('#[^0-9a-zA-Z]#', '', password_hash(uniqid(mt_rand(), true), PASSWORD_BCRYPT)));
} }
return substr($str, 0, $len); return substr($str, 0, $len);
} }

View file

@ -48,18 +48,18 @@ function build_tor_filelist ($file_contents)
class torrent class torrent
{ {
var $tor_decoded = array(); public $tor_decoded = array();
var $files_ary = array('/' => ''); public $files_ary = array('/' => '');
var $multiple = null; public $multiple = null;
var $root_dir = ''; public $root_dir = '';
var $files_html = ''; public $files_html = '';
function torrent ($decoded_file_contents) public function __construct ($decoded_file_contents)
{ {
$this->tor_decoded = $decoded_file_contents; $this->tor_decoded = $decoded_file_contents;
} }
function get_filelist () public function get_filelist ()
{ {
$this->build_filelist_array(); $this->build_filelist_array();
@ -79,7 +79,7 @@ class torrent
} }
} }
function build_filelist_array () public function build_filelist_array ()
{ {
$info = $this->tor_decoded['info']; $info = $this->tor_decoded['info'];
@ -154,7 +154,7 @@ class torrent
} }
} }
function build_file_item ($name, $length) public function build_file_item ($name, $length)
{ {
global $bb_cfg, $images, $lang; global $bb_cfg, $images, $lang;
@ -169,7 +169,7 @@ class torrent
return "$name <i>$length</i> $magnet_name $magnet_ext"; return "$name <i>$length</i> $magnet_name $magnet_ext";
} }
function build_filelist_html () public function build_filelist_html ()
{ {
global $html; global $html;
return $html->array2html($this->files_ary); return $html->array2html($this->files_ary);

View file

@ -588,7 +588,7 @@ function get_var($var_name, $default, $multibyte = false)
*/ */
function attach_mod_sql_escape($text) function attach_mod_sql_escape($text)
{ {
if (function_exists('mysql_real_escape_string')) if (function_exists('mysqli_real_escape_string'))
{ {
return DB()->escape_string($text); return DB()->escape_string($text);
} }

View file

@ -10,26 +10,26 @@ define('FILENAME_CRYPTIC_LENGTH', 64);
class attach_parent class attach_parent
{ {
var $post_attach = false; public $post_attach = false;
var $attach_filename = ''; public $attach_filename = '';
var $filename = ''; public $filename = '';
var $type = ''; public $type = '';
var $extension = ''; public $extension = '';
var $file_comment = ''; public $file_comment = '';
var $num_attachments = 0; // number of attachments in message public $num_attachments = 0; // number of attachments in message
var $filesize = 0; public $filesize = 0;
var $filetime = 0; public $filetime = 0;
var $thumbnail = 0; public $thumbnail = 0;
var $page = 0; // On which page we are on ? This should be filled by child classes. public $page = 0; // On which page we are on ? This should be filled by child classes.
// Switches // Switches
var $add_attachment_body = 0; public $add_attachment_body = 0;
var $posted_attachments_body = 0; public $posted_attachments_body = 0;
/** /**
* Constructor * Constructor
*/ */
function attach_parent() public function __construct()
{ {
$this->add_attachment_body = get_var('add_attachment_body', 0); $this->add_attachment_body = get_var('add_attachment_body', 0);
$this->posted_attachments_body = get_var('posted_attachments_body', 0); $this->posted_attachments_body = get_var('posted_attachments_body', 0);
@ -52,7 +52,7 @@ class attach_parent
/** /**
* Get Quota Limits * Get Quota Limits
*/ */
function get_quota_limits($userdata_quota, $user_id = 0) public function get_quota_limits($userdata_quota, $user_id = 0)
{ {
global $attach_config; global $attach_config;
@ -206,7 +206,7 @@ class attach_parent
* Handle all modes... (intern) * Handle all modes... (intern)
* @private * @private
*/ */
function handle_attachments($mode) public function handle_attachments($mode)
{ {
global $is_auth, $attach_config, $refresh, $post_id, $submit, $preview, $error, $error_msg, $lang; global $is_auth, $attach_config, $refresh, $post_id, $submit, $preview, $error, $error_msg, $lang;
@ -594,7 +594,7 @@ class attach_parent
/** /**
* Basic Insert Attachment Handling for all Message Types * Basic Insert Attachment Handling for all Message Types
*/ */
function do_insert_attachment($mode, $message_type, $message_id) public function do_insert_attachment($mode, $message_type, $message_id)
{ {
global $upload_dir; global $upload_dir;
@ -735,7 +735,7 @@ class attach_parent
* Attachment Mod entry switch/output (intern) * Attachment Mod entry switch/output (intern)
* @private * @private
*/ */
function display_attachment_bodies() public function display_attachment_bodies()
{ {
global $attach_config, $is_auth, $lang, $template, $upload_dir, $forum_id; global $attach_config, $is_auth, $lang, $template, $upload_dir, $forum_id;
@ -831,7 +831,7 @@ class attach_parent
/** /**
* Upload an Attachment to Filespace (intern) * Upload an Attachment to Filespace (intern)
*/ */
function upload_attachment() public function upload_attachment()
{ {
global $error, $error_msg, $lang, $attach_config, $userdata, $upload_dir, $forum_id; global $error, $error_msg, $lang, $attach_config, $userdata, $upload_dir, $forum_id;
@ -1186,7 +1186,7 @@ class attach_parent
} }
// Copy the temporary attachment to the right location (copy, move_uploaded_file) // Copy the temporary attachment to the right location (copy, move_uploaded_file)
function move_uploaded_attachment($upload_mode, $file) public function move_uploaded_attachment($upload_mode, $file)
{ {
global $error, $error_msg, $lang, $upload_dir; global $error, $error_msg, $lang, $upload_dir;
@ -1262,7 +1262,7 @@ class attach_posting extends attach_parent
/** /**
* Constructor * Constructor
*/ */
function attach_posting() public function __construct()
{ {
$this->attach_parent(); $this->attach_parent();
$this->page = 0; $this->page = 0;
@ -1271,7 +1271,7 @@ class attach_posting extends attach_parent
/** /**
* Insert an Attachment into a Post (this is the second function called from posting.php) * Insert an Attachment into a Post (this is the second function called from posting.php)
*/ */
function insert_attachment($post_id) public function insert_attachment($post_id)
{ {
global $is_auth, $mode; global $is_auth, $mode;
@ -1313,7 +1313,7 @@ class attach_posting extends attach_parent
/** /**
* Handle Attachments (Add/Delete/Edit/Show) - This is the first function called from every message handler * Handle Attachments (Add/Delete/Edit/Show) - This is the first function called from every message handler
*/ */
function posting_attachment_mod() public function posting_attachment_mod()
{ {
global $mode, $confirm, $is_auth, $post_id, $delete, $refresh; global $mode, $confirm, $is_auth, $post_id, $delete, $refresh;

View file

@ -379,51 +379,51 @@ function sphFixUint ( $value )
/// sphinx searchd client class /// sphinx searchd client class
class SphinxClient extends cache_common class SphinxClient extends cache_common
{ {
var $_host; ///< searchd host (default is "localhost") public $_host; ///< searchd host (default is "localhost")
var $_port; ///< searchd port (default is 9312) public $_port; ///< searchd port (default is 9312)
var $_offset; ///< how many records to seek from result-set start (default is 0) public $_offset; ///< how many records to seek from result-set start (default is 0)
var $_limit; ///< how many records to return from result-set starting at offset (default is 20) public $_limit; ///< how many records to return from result-set starting at offset (default is 20)
var $_mode; ///< query matching mode (default is SPH_MATCH_ALL) public $_mode; ///< query matching mode (default is SPH_MATCH_ALL)
var $_weights; ///< per-field weights (default is 1 for all fields) public $_weights; ///< per-field weights (default is 1 for all fields)
var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) public $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE)
var $_sortby; ///< attribute to sort by (defualt is "") public $_sortby; ///< attribute to sort by (defualt is "")
var $_min_id; ///< min ID to match (default is 0, which means no limit) public $_min_id; ///< min ID to match (default is 0, which means no limit)
var $_max_id; ///< max ID to match (default is 0, which means no limit) public $_max_id; ///< max ID to match (default is 0, which means no limit)
var $_filters; ///< search filters public $_filters; ///< search filters
var $_groupby; ///< group-by attribute name public $_groupby; ///< group-by attribute name
var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) public $_groupfunc; ///< group-by function (to pre-process group-by attribute value with)
var $_groupsort; ///< group-by sorting clause (to sort groups in result set with) public $_groupsort; ///< group-by sorting clause (to sort groups in result set with)
var $_groupdistinct;///< group-by count-distinct attribute public $_groupdistinct;///< group-by count-distinct attribute
var $_maxmatches; ///< max matches to retrieve public $_maxmatches; ///< max matches to retrieve
var $_cutoff; ///< cutoff to stop searching at (default is 0) public $_cutoff; ///< cutoff to stop searching at (default is 0)
var $_retrycount; ///< distributed retries count public $_retrycount; ///< distributed retries count
var $_retrydelay; ///< distributed retries delay public $_retrydelay; ///< distributed retries delay
var $_anchor; ///< geographical anchor point public $_anchor; ///< geographical anchor point
var $_indexweights; ///< per-index weights public $_indexweights; ///< per-index weights
var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) public $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25)
var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) public $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit)
var $_fieldweights; ///< per-field-name weights public $_fieldweights; ///< per-field-name weights
var $_overrides; ///< per-query attribute values overrides public $_overrides; ///< per-query attribute values overrides
var $_select; ///< select-list (attributes or expressions, with optional aliases) public $_select; ///< select-list (attributes or expressions, with optional aliases)
var $_error; ///< last error message public $_error; ///< last error message
var $_warning; ///< last warning message public $_warning; ///< last warning message
var $_connerror; ///< connection error vs remote error flag public $_connerror; ///< connection error vs remote error flag
var $_reqs; ///< requests array for multi-query public $_reqs; ///< requests array for multi-query
var $_mbenc; ///< stored mbstring encoding public $_mbenc; ///< stored mbstring encoding
var $_arrayresult; ///< whether $result["matches"] should be a hash or an array public $_arrayresult; ///< whether $result["matches"] should be a hash or an array
var $_timeout; ///< connect timeout public $_timeout; ///< connect timeout
var $bb_queries = array(); public $bb_queries = array();
var $bb_indexes = array(); public $bb_indexes = array();
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// common stuff // common stuff
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
/// create a new client object and fill defaults /// create a new client object and fill defaults
function SphinxClient () public function __construct ()
{ {
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
@ -469,32 +469,32 @@ class SphinxClient extends cache_common
$this->_timeout = 0; $this->_timeout = 0;
} }
function __destruct() public function __destruct()
{ {
if ( $this->_socket !== false ) if ( $this->_socket !== false )
fclose ( $this->_socket ); fclose ( $this->_socket );
} }
/// get last error message (string) /// get last error message (string)
function GetLastError () public function GetLastError ()
{ {
return $this->_error; return $this->_error;
} }
/// get last warning message (string) /// get last warning message (string)
function GetLastWarning () public function GetLastWarning ()
{ {
return $this->_warning; return $this->_warning;
} }
/// get last error flag (to tell network connection errors from searchd errors or broken responses) /// get last error flag (to tell network connection errors from searchd errors or broken responses)
function IsConnectError() public function IsConnectError()
{ {
return $this->_connerror; return $this->_connerror;
} }
/// set searchd host name (string) and port (integer) /// set searchd host name (string) and port (integer)
function SetServer ( $host, $port = 0 ) public function SetServer ( $host, $port = 0 )
{ {
assert ( is_string($host) ); assert ( is_string($host) );
if ( $host[0] == '/') if ( $host[0] == '/')
@ -516,14 +516,14 @@ class SphinxClient extends cache_common
} }
/// set server connection timeout (0 to remove) /// set server connection timeout (0 to remove)
function SetConnectTimeout ( $timeout ) public function SetConnectTimeout ( $timeout )
{ {
assert ( is_numeric($timeout) ); assert ( is_numeric($timeout) );
$this->_timeout = $timeout; $this->_timeout = $timeout;
} }
function _Send ( $handle, $data, $length ) public function _Send ( $handle, $data, $length )
{ {
if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length ) if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length )
{ {
@ -537,7 +537,7 @@ class SphinxClient extends cache_common
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
/// enter mbstring workaround mode /// enter mbstring workaround mode
function _MBPush () public function _MBPush ()
{ {
$this->_mbenc = ""; $this->_mbenc = "";
if ( ini_get ( "mbstring.func_overload" ) & 2 ) if ( ini_get ( "mbstring.func_overload" ) & 2 )
@ -548,14 +548,14 @@ class SphinxClient extends cache_common
} }
/// leave mbstring workaround mode /// leave mbstring workaround mode
function _MBPop () public function _MBPop ()
{ {
if ( $this->_mbenc ) if ( $this->_mbenc )
mb_internal_encoding ( $this->_mbenc ); mb_internal_encoding ( $this->_mbenc );
} }
/// connect to searchd server /// connect to searchd server
function _Connect () public function _Connect ()
{ {
$this->cur_query = "connect to: {$this->_host}"; $this->cur_query = "connect to: {$this->_host}";
$this->debug('start'); $this->debug('start');
@ -630,7 +630,7 @@ class SphinxClient extends cache_common
} }
/// get and check response packet from searchd server /// get and check response packet from searchd server
function _GetResponse ( $fp, $client_ver ) public function _GetResponse ( $fp, $client_ver )
{ {
$response = ""; $response = "";
$len = 0; $len = 0;
@ -702,7 +702,7 @@ class SphinxClient extends cache_common
/// set offset and count into result set, /// set offset and count into result set,
/// and optionally set max-matches and cutoff limits /// and optionally set max-matches and cutoff limits
function SetLimits ( $offset, $limit, $max=0, $cutoff=0 ) public function SetLimits ( $offset, $limit, $max=0, $cutoff=0 )
{ {
assert ( is_int($offset) ); assert ( is_int($offset) );
assert ( is_int($limit) ); assert ( is_int($limit) );
@ -719,7 +719,7 @@ class SphinxClient extends cache_common
/// set maximum query time, in milliseconds, per-index /// set maximum query time, in milliseconds, per-index
/// integer, 0 means "do not limit" /// integer, 0 means "do not limit"
function SetMaxQueryTime ( $max ) public function SetMaxQueryTime ( $max )
{ {
assert ( is_int($max) ); assert ( is_int($max) );
assert ( $max>=0 ); assert ( $max>=0 );
@ -727,7 +727,7 @@ class SphinxClient extends cache_common
} }
/// set matching mode /// set matching mode
function SetMatchMode ( $mode ) public function SetMatchMode ( $mode )
{ {
assert ( $mode==SPH_MATCH_ALL assert ( $mode==SPH_MATCH_ALL
|| $mode==SPH_MATCH_ANY || $mode==SPH_MATCH_ANY
@ -740,7 +740,7 @@ class SphinxClient extends cache_common
} }
/// set ranking mode /// set ranking mode
function SetRankingMode ( $ranker ) public function SetRankingMode ( $ranker )
{ {
assert ( $ranker==SPH_RANK_PROXIMITY_BM25 assert ( $ranker==SPH_RANK_PROXIMITY_BM25
|| $ranker==SPH_RANK_BM25 || $ranker==SPH_RANK_BM25
@ -751,7 +751,7 @@ class SphinxClient extends cache_common
} }
/// set matches sorting mode /// set matches sorting mode
function SetSortMode ( $mode, $sortby="" ) public function SetSortMode ( $mode, $sortby="" )
{ {
assert ( assert (
$mode==SPH_SORT_RELEVANCE || $mode==SPH_SORT_RELEVANCE ||
@ -769,7 +769,7 @@ class SphinxClient extends cache_common
/// bind per-field weights by order /// bind per-field weights by order
/// DEPRECATED; use SetFieldWeights() instead /// DEPRECATED; use SetFieldWeights() instead
function SetWeights ( $weights ) public function SetWeights ( $weights )
{ {
assert ( is_array($weights) ); assert ( is_array($weights) );
foreach ( $weights as $weight ) foreach ( $weights as $weight )
@ -779,7 +779,7 @@ class SphinxClient extends cache_common
} }
/// bind per-field weights by name /// bind per-field weights by name
function SetFieldWeights ( $weights ) public function SetFieldWeights ( $weights )
{ {
assert ( is_array($weights) ); assert ( is_array($weights) );
foreach ( $weights as $name=>$weight ) foreach ( $weights as $name=>$weight )
@ -791,7 +791,7 @@ class SphinxClient extends cache_common
} }
/// bind per-index weights by name /// bind per-index weights by name
function SetIndexWeights ( $weights ) public function SetIndexWeights ( $weights )
{ {
assert ( is_array($weights) ); assert ( is_array($weights) );
foreach ( $weights as $index=>$weight ) foreach ( $weights as $index=>$weight )
@ -804,7 +804,7 @@ class SphinxClient extends cache_common
/// set IDs range to match /// set IDs range to match
/// only match records if document ID is beetwen $min and $max (inclusive) /// only match records if document ID is beetwen $min and $max (inclusive)
function SetIDRange ( $min, $max ) public function SetIDRange ( $min, $max )
{ {
assert ( is_numeric($min) ); assert ( is_numeric($min) );
assert ( is_numeric($max) ); assert ( is_numeric($max) );
@ -815,7 +815,7 @@ class SphinxClient extends cache_common
/// set values set filter /// set values set filter
/// only match records where $attribute value is in given set /// only match records where $attribute value is in given set
function SetFilter ( $attribute, $values, $exclude=false ) public function SetFilter ( $attribute, $values, $exclude=false )
{ {
assert ( is_string($attribute) ); assert ( is_string($attribute) );
assert ( is_array($values) ); assert ( is_array($values) );
@ -832,7 +832,7 @@ class SphinxClient extends cache_common
/// set range filter /// set range filter
/// only match records if $attribute value is beetwen $min and $max (inclusive) /// only match records if $attribute value is beetwen $min and $max (inclusive)
function SetFilterRange ( $attribute, $min, $max, $exclude=false ) public function SetFilterRange ( $attribute, $min, $max, $exclude=false )
{ {
assert ( is_string($attribute) ); assert ( is_string($attribute) );
assert ( is_numeric($min) ); assert ( is_numeric($min) );
@ -844,7 +844,7 @@ class SphinxClient extends cache_common
/// set float range filter /// set float range filter
/// only match records if $attribute value is beetwen $min and $max (inclusive) /// only match records if $attribute value is beetwen $min and $max (inclusive)
function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false ) public function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false )
{ {
assert ( is_string($attribute) ); assert ( is_string($attribute) );
assert ( is_float($min) ); assert ( is_float($min) );
@ -857,7 +857,7 @@ class SphinxClient extends cache_common
/// setup anchor point for geosphere distance calculations /// setup anchor point for geosphere distance calculations
/// required to use @geodist in filters and sorting /// required to use @geodist in filters and sorting
/// latitude and longitude must be in radians /// latitude and longitude must be in radians
function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long ) public function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long )
{ {
assert ( is_string($attrlat) ); assert ( is_string($attrlat) );
assert ( is_string($attrlong) ); assert ( is_string($attrlong) );
@ -868,7 +868,7 @@ class SphinxClient extends cache_common
} }
/// set grouping attribute and function /// set grouping attribute and function
function SetGroupBy ( $attribute, $func, $groupsort="@group desc" ) public function SetGroupBy ( $attribute, $func, $groupsort="@group desc" )
{ {
assert ( is_string($attribute) ); assert ( is_string($attribute) );
assert ( is_string($groupsort) ); assert ( is_string($groupsort) );
@ -885,14 +885,14 @@ class SphinxClient extends cache_common
} }
/// set count-distinct attribute for group-by queries /// set count-distinct attribute for group-by queries
function SetGroupDistinct ( $attribute ) public function SetGroupDistinct ( $attribute )
{ {
assert ( is_string($attribute) ); assert ( is_string($attribute) );
$this->_groupdistinct = $attribute; $this->_groupdistinct = $attribute;
} }
/// set distributed retries count and delay /// set distributed retries count and delay
function SetRetries ( $count, $delay=0 ) public function SetRetries ( $count, $delay=0 )
{ {
assert ( is_int($count) && $count>=0 ); assert ( is_int($count) && $count>=0 );
assert ( is_int($delay) && $delay>=0 ); assert ( is_int($delay) && $delay>=0 );
@ -902,7 +902,7 @@ class SphinxClient extends cache_common
/// set result set format (hash or array; hash by default) /// set result set format (hash or array; hash by default)
/// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs
function SetArrayResult ( $arrayresult ) public function SetArrayResult ( $arrayresult )
{ {
assert ( is_bool($arrayresult) ); assert ( is_bool($arrayresult) );
$this->_arrayresult = $arrayresult; $this->_arrayresult = $arrayresult;
@ -911,7 +911,7 @@ class SphinxClient extends cache_common
/// set attribute values override /// set attribute values override
/// there can be only one override per attribute /// there can be only one override per attribute
/// $values must be a hash that maps document IDs to attribute values /// $values must be a hash that maps document IDs to attribute values
function SetOverride ( $attrname, $attrtype, $values ) public function SetOverride ( $attrname, $attrtype, $values )
{ {
assert ( is_string ( $attrname ) ); assert ( is_string ( $attrname ) );
assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) ); assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) );
@ -921,7 +921,7 @@ class SphinxClient extends cache_common
} }
/// set select-list (attributes or expressions), SQL-like syntax /// set select-list (attributes or expressions), SQL-like syntax
function SetSelect ( $select ) public function SetSelect ( $select )
{ {
assert ( is_string ( $select ) ); assert ( is_string ( $select ) );
$this->_select = $select; $this->_select = $select;
@ -930,14 +930,14 @@ class SphinxClient extends cache_common
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
/// clear all filters (for multi-queries) /// clear all filters (for multi-queries)
function ResetFilters () public function ResetFilters ()
{ {
$this->_filters = array(); $this->_filters = array();
$this->_anchor = array(); $this->_anchor = array();
} }
/// clear groupby settings (for multi-queries) /// clear groupby settings (for multi-queries)
function ResetGroupBy () public function ResetGroupBy ()
{ {
$this->_groupby = ""; $this->_groupby = "";
$this->_groupfunc = SPH_GROUPBY_DAY; $this->_groupfunc = SPH_GROUPBY_DAY;
@ -946,7 +946,7 @@ class SphinxClient extends cache_common
} }
/// clear all attribute value overrides (for multi-queries) /// clear all attribute value overrides (for multi-queries)
function ResetOverrides () public function ResetOverrides ()
{ {
$this->_overrides = array (); $this->_overrides = array ();
} }
@ -955,7 +955,7 @@ class SphinxClient extends cache_common
/// connect to searchd server, run given search query through given indexes, /// connect to searchd server, run given search query through given indexes,
/// and return the search results /// and return the search results
function Query ( $query, $index="*", $comment="" ) public function Query ( $query, $index="*", $comment="" )
{ {
assert ( empty($this->_reqs) ); assert ( empty($this->_reqs) );
@ -977,7 +977,7 @@ class SphinxClient extends cache_common
} }
/// helper to pack floats in network byte order /// helper to pack floats in network byte order
function _PackFloat ( $f ) public function _PackFloat ( $f )
{ {
$t1 = pack ( "f", $f ); // machine order $t1 = pack ( "f", $f ); // machine order
list(,$t2) = unpack ( "L*", $t1 ); // int in machine order list(,$t2) = unpack ( "L*", $t1 ); // int in machine order
@ -986,7 +986,7 @@ class SphinxClient extends cache_common
/// add query to multi-query batch /// add query to multi-query batch
/// returns index into results array from RunQueries() call /// returns index into results array from RunQueries() call
function AddQuery ( $query, $index="*", $comment="" ) public function AddQuery ( $query, $index="*", $comment="" )
{ {
// mbstring workaround // mbstring workaround
$this->_MBPush (); $this->_MBPush ();
@ -1101,7 +1101,7 @@ class SphinxClient extends cache_common
} }
/// connect to searchd, run queries batch, and return an array of result sets /// connect to searchd, run queries batch, and return an array of result sets
function RunQueries () public function RunQueries ()
{ {
if ( empty($this->_reqs) ) if ( empty($this->_reqs) )
{ {
@ -1146,7 +1146,7 @@ class SphinxClient extends cache_common
} }
/// parse and return search query (or queries) response /// parse and return search query (or queries) response
function _ParseSearchResponse ( $response, $nreqs ) public function _ParseSearchResponse ( $response, $nreqs )
{ {
$p = 0; // current position $p = 0; // current position
$max = strlen($response); // max position for checks, to protect against broken responses $max = strlen($response); // max position for checks, to protect against broken responses
@ -1309,7 +1309,7 @@ class SphinxClient extends cache_common
/// connect to searchd server, and generate exceprts (snippets) /// connect to searchd server, and generate exceprts (snippets)
/// of given documents for given query. returns false on failure, /// of given documents for given query. returns false on failure,
/// an array of snippets on success /// an array of snippets on success
function BuildExcerpts ( $docs, $index, $words, $opts=array() ) public function BuildExcerpts ( $docs, $index, $words, $opts=array() )
{ {
assert ( is_array($docs) ); assert ( is_array($docs) );
assert ( is_string($index) ); assert ( is_string($index) );
@ -1414,7 +1414,7 @@ class SphinxClient extends cache_common
/// connect to searchd server, and generate keyword list for a given query /// connect to searchd server, and generate keyword list for a given query
/// returns false on failure, /// returns false on failure,
/// an array of words on success /// an array of words on success
function BuildKeywords ( $query, $index, $hits ) public function BuildKeywords ( $query, $index, $hits )
{ {
assert ( is_string($query) ); assert ( is_string($query) );
assert ( is_string($index) ); assert ( is_string($index) );
@ -1491,7 +1491,7 @@ class SphinxClient extends cache_common
return $res; return $res;
} }
function EscapeString ( $string ) public function EscapeString ( $string )
{ {
$from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' ); $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' );
$to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' ); $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' );
@ -1505,7 +1505,7 @@ class SphinxClient extends cache_common
/// batch update given attributes in given rows in given indexes /// batch update given attributes in given rows in given indexes
/// returns amount of updated documents (0 or more) on success, or -1 on failure /// returns amount of updated documents (0 or more) on success, or -1 on failure
function UpdateAttributes ( $index, $attrs, $values, $mva=false ) public function UpdateAttributes ( $index, $attrs, $values, $mva=false )
{ {
// verify everything // verify everything
assert ( is_string($index) ); assert ( is_string($index) );
@ -1577,7 +1577,7 @@ class SphinxClient extends cache_common
// persistent connections // persistent connections
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
function Open() public function Open()
{ {
if ( $this->_socket !== false ) if ( $this->_socket !== false )
{ {
@ -1596,7 +1596,7 @@ class SphinxClient extends cache_common
return true; return true;
} }
function Close() public function Close()
{ {
if ( $this->_socket === false ) if ( $this->_socket === false )
{ {
@ -1614,7 +1614,7 @@ class SphinxClient extends cache_common
// status // status
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
function Status () public function Status ()
{ {
$this->_MBPush (); $this->_MBPush ();
if (!( $fp = $this->_Connect() )) if (!( $fp = $this->_Connect() ))

View file

@ -441,11 +441,11 @@ function add_search_words ($post_id, $post_message, $topic_title = '', $only_ret
class bbcode class bbcode
{ {
var $tpl = array(); // шаблоны для замены тегов public $tpl = array(); // шаблоны для замены тегов
var $smilies = null; // смайлы public $smilies = null; // смайлы
var $found_spam = null; // найденные спам "слова" public $found_spam = null; // найденные спам "слова"
var $del_words = array(); // см. get_words_rate() public $del_words = array(); // см. get_words_rate()
var $tidy_cfg = array( public $tidy_cfg = array(
'drop-empty-paras' => false, 'drop-empty-paras' => false,
'fix-uri' => false, 'fix-uri' => false,
'force-output' => true, 'force-output' => true,
@ -464,7 +464,7 @@ class bbcode
'show-warnings' => false, 'show-warnings' => false,
'wrap' => 0, 'wrap' => 0,
); );
var $block_tags = array( public $block_tags = array(
'align', 'align',
'br', 'br',
'clear', 'clear',
@ -474,17 +474,17 @@ class bbcode
'quote', 'quote',
'spoiler', 'spoiler',
); );
var $preg = array(); public $preg = array();
var $str = array(); public $str = array();
var $preg_search = array(); public $preg_search = array();
var $preg_repl = array(); public $preg_repl = array();
var $str_search = array(); public $str_search = array();
var $str_repl = array(); public $str_repl = array();
/** /**
* Constructor * Constructor
*/ */
function bbcode () public function __construct ()
{ {
$this->tpl = get_bbcode_tpl(); $this->tpl = get_bbcode_tpl();
@ -494,7 +494,7 @@ class bbcode
/** /**
* init_replacements * init_replacements
*/ */
function init_replacements () public function init_replacements ()
{ {
$tpl = $this->tpl; $tpl = $this->tpl;
$img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?'; $img_exp = '(https?:)?//[^\s\?&;=\#\"<>]+?\.(jpg|jpeg|gif|png)([a-z0-9/?&%;][^\[\]]*)?';
@ -556,7 +556,7 @@ class bbcode
* bbcode2html * bbcode2html
* $text должен быть уже обработан htmlCHR($text, false, ENT_NOQUOTES); * $text должен быть уже обработан htmlCHR($text, false, ENT_NOQUOTES);
*/ */
function bbcode2html ($text) public function bbcode2html ($text)
{ {
global $bb_cfg; global $bb_cfg;
@ -606,7 +606,7 @@ class bbcode
/** /**
* Clean up * Clean up
*/ */
static function clean_up ($text) static public function clean_up ($text)
{ {
$text = trim($text); $text = trim($text);
$text = str_replace("\r", '', $text); $text = str_replace("\r", '', $text);
@ -683,7 +683,7 @@ class bbcode
/** /**
* [code] callback * [code] callback
*/ */
function code_callback ($m) public function code_callback ($m)
{ {
$code = trim($m[2]); $code = trim($m[2]);
$code = str_replace(' ', '&nbsp; ', $code); $code = str_replace(' ', '&nbsp; ', $code);
@ -696,7 +696,7 @@ class bbcode
/** /**
* [url] callback * [url] callback
*/ */
function url_callback ($m) public function url_callback ($m)
{ {
global $bb_cfg; global $bb_cfg;
@ -720,7 +720,7 @@ class bbcode
/** /**
* Escape tags inside tiltes in [quote="tilte"] * Escape tags inside tiltes in [quote="tilte"]
*/ */
function escape_tiltes_callback ($m) public function escape_tiltes_callback ($m)
{ {
$tilte = substr($m[3], 0, 250); $tilte = substr($m[3], 0, 250);
$tilte = str_replace(array('[', ']', ':', ')', '"'), array('&#91;', '&#93;', '&#58;', '&#41;', '&#34;'), $tilte); $tilte = str_replace(array('[', ']', ':', ')', '"'), array('&#91;', '&#93;', '&#58;', '&#41;', '&#34;'), $tilte);
@ -732,7 +732,7 @@ class bbcode
/** /**
* make_clickable * make_clickable
*/ */
function make_clickable ($text) public function make_clickable ($text)
{ {
$url_regexp = "# $url_regexp = "#
(?<![\"'=]) (?<![\"'=])
@ -762,7 +762,7 @@ class bbcode
/** /**
* make_url_clickable_callback * make_url_clickable_callback
*/ */
function make_url_clickable_callback ($m) public function make_url_clickable_callback ($m)
{ {
global $bb_cfg; global $bb_cfg;
@ -785,7 +785,7 @@ class bbcode
/** /**
* smilies_pass * smilies_pass
*/ */
function smilies_pass ($text) public function smilies_pass ($text)
{ {
global $datastore; global $datastore;
@ -805,7 +805,7 @@ class bbcode
/** /**
* new_line2html * new_line2html
*/ */
function new_line2html ($text) public function new_line2html ($text)
{ {
$text = preg_replace('#\n{2,}#', '<span class="post-br"><br /></span>', $text); $text = preg_replace('#\n{2,}#', '<span class="post-br"><br /></span>', $text);
$text = str_replace("\n", '<br />', $text); $text = str_replace("\n", '<br />', $text);
@ -815,7 +815,7 @@ class bbcode
/** /**
* tidy * tidy
*/ */
function tidy ($text) public function tidy ($text)
{ {
$text = tidy_repair_string($text, $this->tidy_cfg, 'utf8'); $text = tidy_repair_string($text, $this->tidy_cfg, 'utf8');
return $text; return $text;
@ -842,14 +842,14 @@ function bbcode2html ($text)
class words_rate class words_rate
{ {
var $dbg_mode = false; public $dbg_mode = false;
var $words_rate = 0; public $words_rate = 0;
var $deleted_words = array(); public $deleted_words = array();
var $del_text_hl = ''; public $del_text_hl = '';
var $words_del_exp = ''; public $words_del_exp = '';
var $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#'; public $words_cnt_exp = '#[a-zA-Zа-яА-ЯёЁ]{4,}#';
function words_rate () public function __construct ()
{ {
// слова начинающиеся на.. // слова начинающиеся на..
$del_list = file_get_contents(BB_ROOT .'/library/words_rate_del_list.txt'); $del_list = file_get_contents(BB_ROOT .'/library/words_rate_del_list.txt');
@ -863,7 +863,7 @@ class words_rate
/** /**
* возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д. * возвращает "показатель полезности" сообщения используемый для автоудаления коротких сообщений типа "спасибо", "круто" и т.д.
*/ */
function get_words_rate ($text) public function get_words_rate ($text)
{ {
$this->words_rate = 127; // максимальное значение по умолчанию $this->words_rate = 127; // максимальное значение по умолчанию
$this->deleted_words = array(); $this->deleted_words = array();

View file

@ -4,11 +4,11 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_apc extends cache_common class cache_apc extends cache_common
{ {
var $used = true; public $used = true;
var $engine = 'APC'; public $engine = 'APC';
var $prefix = null; public $prefix = null;
function cache_apc ($prefix = null) public function __construct ($prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -18,7 +18,7 @@ class cache_apc extends cache_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function get ($name, $get_miss_key_callback = '', $ttl = 0) public function get ($name, $get_miss_key_callback = '', $ttl = 0)
{ {
$this->cur_query = "cache->get('$name')"; $this->cur_query = "cache->get('$name')";
$this->debug('start'); $this->debug('start');
@ -29,7 +29,7 @@ class cache_apc extends cache_common
return apc_fetch($this->prefix . $name); return apc_fetch($this->prefix . $name);
} }
function set ($name, $value, $ttl = 0) public function set ($name, $value, $ttl = 0)
{ {
$this->cur_query = "cache->set('$name')"; $this->cur_query = "cache->set('$name')";
$this->debug('start'); $this->debug('start');
@ -40,7 +40,7 @@ class cache_apc extends cache_common
return apc_store($this->prefix . $name, $value, $ttl); return apc_store($this->prefix . $name, $value, $ttl);
} }
function rm ($name = '') public function rm ($name = '')
{ {
if ($name) if ($name)
{ {
@ -58,7 +58,7 @@ class cache_apc extends cache_common
} }
} }
function is_installed () public function is_installed ()
{ {
return function_exists('apc_fetch'); return function_exists('apc_fetch');
} }

View file

@ -4,11 +4,11 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_common class cache_common
{ {
var $used = false; public $used = false;
/** /**
* Returns value of variable * Returns value of variable
*/ */
function get ($name, $get_miss_key_callback = '', $ttl = 604800) public function get ($name, $get_miss_key_callback = '', $ttl = 604800)
{ {
if ($get_miss_key_callback) return $get_miss_key_callback($name); if ($get_miss_key_callback) return $get_miss_key_callback($name);
return is_array($name) ? array() : false; return is_array($name) ? array() : false;
@ -16,30 +16,30 @@ class cache_common
/** /**
* Store value of variable * Store value of variable
*/ */
function set ($name, $value, $ttl = 604800) public function set ($name, $value, $ttl = 604800)
{ {
return false; return false;
} }
/** /**
* Remove variable * Remove variable
*/ */
function rm ($name = '') public function rm ($name = '')
{ {
return false; return false;
} }
var $num_queries = 0; public $num_queries = 0;
var $sql_starttime = 0; public $sql_starttime = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
var $cur_query_time = 0; public $cur_query_time = 0;
var $dbg = array(); public $dbg = array();
var $dbg_id = 0; public $dbg_id = 0;
var $dbg_enabled = false; public $dbg_enabled = false;
var $cur_query = null; public $cur_query = null;
function debug ($mode, $cur_query = null) public function debug ($mode, $cur_query = null)
{ {
if (!$this->dbg_enabled) return; if (!$this->dbg_enabled) return;
@ -65,7 +65,7 @@ class cache_common
} }
} }
function debug_find_source ($mode = '') public function debug_find_source ($mode = '')
{ {
foreach (debug_backtrace() as $trace) foreach (debug_backtrace() as $trace)
{ {

View file

@ -4,19 +4,19 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_file extends cache_common class cache_file extends cache_common
{ {
var $used = true; public $used = true;
var $engine = 'Filecache'; public $engine = 'Filecache';
var $dir = null; public $dir = null;
var $prefix = null; public $prefix = null;
function cache_file ($dir, $prefix = null) public function __construct ($dir, $prefix = null)
{ {
$this->dir = $dir; $this->dir = $dir;
$this->prefix = $prefix; $this->prefix = $prefix;
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function get ($name, $get_miss_key_callback = '', $ttl = 0) public function get ($name, $get_miss_key_callback = '', $ttl = 0)
{ {
$filename = $this->dir . clean_filename($this->prefix . $name) . '.php'; $filename = $this->dir . clean_filename($this->prefix . $name) . '.php';
@ -34,7 +34,7 @@ class cache_file extends cache_common
return (!empty($filecache['value'])) ? $filecache['value'] : false; return (!empty($filecache['value'])) ? $filecache['value'] : false;
} }
function set ($name, $value, $ttl = 86400) public function set ($name, $value, $ttl = 86400)
{ {
if (!function_exists('var_export')) if (!function_exists('var_export'))
{ {
@ -63,7 +63,7 @@ class cache_file extends cache_common
return (bool) file_write($filecache, $filename, false, true, true); return (bool) file_write($filecache, $filename, false, true, true);
} }
function rm ($name = '') public function rm ($name = '')
{ {
$clear = false; $clear = false;
if ($name) if ($name)
@ -104,7 +104,7 @@ class cache_file extends cache_common
return $clear; return $clear;
} }
function gc ($expire_time = TIMENOW) public function gc ($expire_time = TIMENOW)
{ {
$clear = false; $clear = false;

View file

@ -4,14 +4,14 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_memcache extends cache_common class cache_memcache extends cache_common
{ {
var $used = true; public $used = true;
var $engine = 'Memcache'; public $engine = 'Memcache';
var $cfg = null; public $cfg = null;
var $prefix = null; public $prefix = null;
var $memcache = null; public $memcache = null;
var $connected = false; public $connected = false;
function cache_memcache ($cfg, $prefix = null) public function __construct ($cfg, $prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -24,7 +24,7 @@ class cache_memcache extends cache_common
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function connect () public function connect ()
{ {
$connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect';
@ -47,7 +47,7 @@ class cache_memcache extends cache_common
$this->cur_query = null; $this->cur_query = null;
} }
function get ($name, $get_miss_key_callback = '', $ttl = 0) public function get ($name, $get_miss_key_callback = '', $ttl = 0)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -60,7 +60,7 @@ class cache_memcache extends cache_common
return ($this->connected) ? $this->memcache->get($this->prefix . $name) : false; return ($this->connected) ? $this->memcache->get($this->prefix . $name) : false;
} }
function set ($name, $value, $ttl = 0) public function set ($name, $value, $ttl = 0)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -73,7 +73,7 @@ class cache_memcache extends cache_common
return ($this->connected) ? $this->memcache->set($this->prefix . $name, $value, false, $ttl) : false; return ($this->connected) ? $this->memcache->set($this->prefix . $name, $value, false, $ttl) : false;
} }
function rm ($name = '') public function rm ($name = '')
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -93,7 +93,7 @@ class cache_memcache extends cache_common
} }
} }
function is_installed () public function is_installed ()
{ {
return class_exists('Memcache'); return class_exists('Memcache');
} }

View file

@ -4,14 +4,14 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_redis extends cache_common class cache_redis extends cache_common
{ {
var $used = true; public $used = true;
var $engine = 'Redis'; public $engine = 'Redis';
var $cfg = null; public $cfg = null;
var $redis = null; public $redis = null;
var $prefix = null; public $prefix = null;
var $connected = false; public $connected = false;
function cache_redis ($cfg, $prefix = null) public function __construct ($cfg, $prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -24,7 +24,7 @@ class cache_redis extends cache_common
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function connect () public function connect ()
{ {
$this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port']; $this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port'];
$this->debug('start'); $this->debug('start');
@ -43,7 +43,7 @@ class cache_redis extends cache_common
$this->cur_query = null; $this->cur_query = null;
} }
function get ($name, $get_miss_key_callback = '', $ttl = 0) public function get ($name, $get_miss_key_callback = '', $ttl = 0)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -56,7 +56,7 @@ class cache_redis extends cache_common
return ($this->connected) ? unserialize($this->redis->get($this->prefix . $name)) : false; return ($this->connected) ? unserialize($this->redis->get($this->prefix . $name)) : false;
} }
function set ($name, $value, $ttl = 0) public function set ($name, $value, $ttl = 0)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -82,7 +82,7 @@ class cache_redis extends cache_common
} }
} }
function rm ($name = '') public function rm ($name = '')
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -102,7 +102,7 @@ class cache_redis extends cache_common
} }
} }
function is_installed () public function is_installed ()
{ {
return class_exists('Redis'); return class_exists('Redis');
} }

View file

@ -4,10 +4,10 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_sqlite extends cache_common class cache_sqlite extends cache_common
{ {
var $used = true; public $used = true;
var $db = null; public $db = null;
var $prefix = null; public $prefix = null;
var $cfg = array( public $cfg = array(
'db_file_path' => '/path/to/cache.db.sqlite', 'db_file_path' => '/path/to/cache.db.sqlite',
'table_name' => 'cache', 'table_name' => 'cache',
'table_schema' => 'CREATE TABLE cache ( 'table_schema' => 'CREATE TABLE cache (
@ -21,7 +21,7 @@ class cache_sqlite extends cache_common
'log_name' => 'CACHE', 'log_name' => 'CACHE',
); );
function cache_sqlite ($cfg, $prefix = null) function __construct ($cfg, $prefix = null)
{ {
$this->cfg = array_merge($this->cfg, $cfg); $this->cfg = array_merge($this->cfg, $cfg);
$this->db = new sqlite_common($this->cfg); $this->db = new sqlite_common($this->cfg);
@ -111,7 +111,7 @@ class cache_sqlite extends cache_common
class sqlite_common extends cache_common class sqlite_common extends cache_common
{ {
var $cfg = array( public $cfg = array(
'db_file_path' => 'sqlite.db', 'db_file_path' => 'sqlite.db',
'table_name' => 'table_name', 'table_name' => 'table_name',
'table_schema' => 'CREATE TABLE table_name (...)', 'table_schema' => 'CREATE TABLE table_name (...)',
@ -121,20 +121,20 @@ class sqlite_common extends cache_common
'shard_type' => 'none', # none, string, int (тип перевичного ключа для шардинга) 'shard_type' => 'none', # none, string, int (тип перевичного ключа для шардинга)
'shard_val' => 0, # для string - кол. начальных символов, для int - делитель (будет использован остаток от деления) 'shard_val' => 0, # для string - кол. начальных символов, для int - делитель (будет использован остаток от деления)
); );
var $engine = 'SQLite'; public $engine = 'SQLite';
var $dbh = null; public $dbh = null;
var $connected = false; public $connected = false;
var $shard_val = false; public $shard_val = false;
var $table_create_attempts = 0; public $table_create_attempts = 0;
function sqlite_common ($cfg) public function __construct ($cfg)
{ {
$this->cfg = array_merge($this->cfg, $cfg); $this->cfg = array_merge($this->cfg, $cfg);
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function connect () public function connect ()
{ {
$this->cur_query = ($this->dbg_enabled) ? 'connect to: '. $this->cfg['db_file_path'] : 'connect'; $this->cur_query = ($this->dbg_enabled) ? 'connect to: '. $this->cfg['db_file_path'] : 'connect';
$this->debug('start'); $this->debug('start');
@ -155,13 +155,13 @@ class sqlite_common extends cache_common
$this->cur_query = null; $this->cur_query = null;
} }
function create_table () public function create_table ()
{ {
$this->table_create_attempts++; $this->table_create_attempts++;
return $this->dbh->query($this->cfg['table_schema']); return $this->dbh->query($this->cfg['table_schema']);
} }
function shard ($name) public function shard ($name)
{ {
$type = $this->cfg['shard_type']; $type = $this->cfg['shard_type'];
@ -193,7 +193,7 @@ class sqlite_common extends cache_common
$this->cfg['db_file_path'] = str_replace('*', $shard_val, $this->cfg['db_file_path']); $this->cfg['db_file_path'] = str_replace('*', $shard_val, $this->cfg['db_file_path']);
} }
function query ($query) public function query ($query)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
@ -229,13 +229,13 @@ class sqlite_common extends cache_common
return $result; return $result;
} }
function fetch_row ($query) public function fetch_row ($query)
{ {
$result = $this->query($query); $result = $this->query($query);
return is_resource($result) ? $result->fetchArray(SQLITE3_ASSOC) : false; return is_resource($result) ? $result->fetchArray(SQLITE3_ASSOC) : false;
} }
function fetch_rowset ($query) public function fetch_rowset ($query)
{ {
$result = $this->query($query); $result = $this->query($query);
$rowset = array(); $rowset = array();
@ -246,22 +246,22 @@ class sqlite_common extends cache_common
return $rowset; return $rowset;
} }
function changes () public function changes ()
{ {
return is_resource($this->dbh) ? $this->dbh->changes() : 0; return is_resource($this->dbh) ? $this->dbh->changes() : 0;
} }
function escape ($str) public function escape ($str)
{ {
return SQLite3::escapeString($str); return SQLite3::escapeString($str);
} }
function get_error_msg () public function get_error_msg ()
{ {
return 'SQLite error #'. ($err_code = $this->dbh->lastErrorCode()) .': '. $this->dbh->lastErrorMsg(); return 'SQLite error #'. ($err_code = $this->dbh->lastErrorCode()) .': '. $this->dbh->lastErrorMsg();
} }
function rm ($name = '') public function rm ($name = '')
{ {
if ($name) if ($name)
{ {
@ -275,13 +275,13 @@ class sqlite_common extends cache_common
return (bool) $result; return (bool) $result;
} }
function gc ($expire_time = TIMENOW) public function gc ($expire_time = TIMENOW)
{ {
$result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time"); $result = $this->db->query("DELETE FROM ". $this->cfg['table_name'] ." WHERE cache_expire_time < $expire_time");
return ($result) ? sqlite_changes($this->db->dbh) : 0; return ($result) ? sqlite_changes($this->db->dbh) : 0;
} }
function trigger_error ($msg = 'DB Error') public function trigger_error ($msg = 'DB Error')
{ {
if (error_reporting()) trigger_error($msg, E_USER_ERROR); if (error_reporting()) trigger_error($msg, E_USER_ERROR);
} }

View file

@ -4,11 +4,11 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class cache_xcache extends cache_common class cache_xcache extends cache_common
{ {
var $used = true; public $used = true;
var $engine = 'XCache'; public $engine = 'XCache';
var $prefix = null; public $prefix = null;
function cache_xcache ($prefix = null) public function __construct ($prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -18,7 +18,7 @@ class cache_xcache extends cache_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function get ($name, $get_miss_key_callback = '', $ttl = 0) public function get ($name, $get_miss_key_callback = '', $ttl = 0)
{ {
$this->cur_query = "cache->get('$name')"; $this->cur_query = "cache->get('$name')";
$this->debug('start'); $this->debug('start');
@ -29,7 +29,7 @@ class cache_xcache extends cache_common
return xcache_get($this->prefix . $name); return xcache_get($this->prefix . $name);
} }
function set ($name, $value, $ttl = 0) public function set ($name, $value, $ttl = 0)
{ {
$this->cur_query = "cache->set('$name')"; $this->cur_query = "cache->set('$name')";
$this->debug('start'); $this->debug('start');
@ -40,7 +40,7 @@ class cache_xcache extends cache_common
return xcache_set($this->prefix . $name, $value, $ttl); return xcache_set($this->prefix . $name, $value, $ttl);
} }
function rm ($name = '') public function rm ($name = '')
{ {
if ($name) if ($name)
{ {
@ -60,7 +60,7 @@ class cache_xcache extends cache_common
} }
} }
function is_installed () public function is_installed ()
{ {
return function_exists('xcache_get'); return function_exists('xcache_get');
} }

View file

@ -4,14 +4,14 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class emailer class emailer
{ {
var $msg, $subject, $extra_headers; public $msg, $subject, $extra_headers;
var $addresses, $reply_to, $from; public $addresses, $reply_to, $from;
var $use_smtp; public $use_smtp;
var $tpl_msg = array(); public $tpl_msg = array();
var $vars = array(); public $vars = array();
function emailer ($use_smtp/*$tpl_name, $sbj, $to_address*/) public function __construct ($use_smtp/*$tpl_name, $sbj, $to_address*/)
{ {
global $bb_cfg; global $bb_cfg;
@ -25,7 +25,7 @@ class emailer
$this->email_address($to_address);*/ $this->email_address($to_address);*/
} }
function set_default_vars () public function set_default_vars ()
{ {
global $bb_cfg; global $bb_cfg;
@ -37,7 +37,7 @@ class emailer
} }
// Resets all the data (address, template file, etc etc to default // Resets all the data (address, template file, etc etc to default
function reset () public function reset ()
{ {
$this->addresses = array(); $this->addresses = array();
$this->msg = $this->extra_headers = ''; $this->msg = $this->extra_headers = '';
@ -45,44 +45,44 @@ class emailer
} }
// Sets an email address to send to // Sets an email address to send to
function email_address ($address) public function email_address ($address)
{ {
$this->addresses['to'] = trim($address); $this->addresses['to'] = trim($address);
} }
function cc ($address) public function cc ($address)
{ {
$this->addresses['cc'][] = trim($address); $this->addresses['cc'][] = trim($address);
} }
function bcc ($address) public function bcc ($address)
{ {
$this->addresses['bcc'][] = trim($address); $this->addresses['bcc'][] = trim($address);
} }
function replyto ($address) public function replyto ($address)
{ {
$this->reply_to = trim($address); $this->reply_to = trim($address);
} }
function from ($address) public function from ($address)
{ {
$this->from = trim($address); $this->from = trim($address);
} }
// set up subject for mail // set up subject for mail
function set_subject ($subject = '') public function set_subject ($subject = '')
{ {
$this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject)); $this->subject = trim(preg_replace('#[\n\r]+#s', '', $subject));
} }
// set up extra mail headers // set up extra mail headers
function extra_headers ($headers) public function extra_headers ($headers)
{ {
$this->extra_headers .= trim($headers) . "\n"; $this->extra_headers .= trim($headers) . "\n";
} }
function use_template ($template_file, $template_lang = '') public function use_template ($template_file, $template_lang = '')
{ {
global $bb_cfg; global $bb_cfg;
@ -125,13 +125,13 @@ class emailer
} }
// assign variables // assign variables
function assign_vars ($vars) public function assign_vars ($vars)
{ {
$this->vars = array_merge($this->vars, $vars); $this->vars = array_merge($this->vars, $vars);
} }
// Send the mail out to the recipients set previously in var $this->address // Send the mail out to the recipients set previously in var $this->address
function send ($email_format = 'text') public function send ($email_format = 'text')
{ {
global $bb_cfg, $userdata; global $bb_cfg, $userdata;
@ -225,7 +225,7 @@ class emailer
return true; return true;
} }
function encode ($str) public function encode ($str)
{ {
if ($this->encoding == '') if ($this->encoding == '')
{ {

View file

@ -54,7 +54,7 @@ class ReCaptcha
* *
* @param string $secret shared secret between site and ReCAPTCHA server. * @param string $secret shared secret between site and ReCAPTCHA server.
*/ */
function ReCaptcha($secret) public function __construct($secret)
{ {
if ($secret == null || $secret == "") { if ($secret == null || $secret == "") {
die("To use Google reCAPTCHA you must get an API key from <a href='" . self::$_signupUrl . "'>" . self::$_signupUrl . "</a>"); die("To use Google reCAPTCHA you must get an API key from <a href='" . self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");

View file

@ -4,18 +4,18 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class sitemap class sitemap
{ {
var $home = ''; public $home = '';
var $limit = 0; public $limit = 0;
var $topic_priority = '0.5'; public $topic_priority = '0.5';
var $stat_priority = '0.5'; public $stat_priority = '0.5';
var $priority = '0.6'; public $priority = '0.6';
var $cat_priority = '0.7'; public $cat_priority = '0.7';
function sitemap () { public function __construct () {
$this->home = make_url(); $this->home = make_url();
} }
function build_map () { public function build_map () {
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_static(); $map .= $this->get_static();
$map .= $this->get_forum(); $map .= $this->get_forum();
@ -25,7 +25,7 @@ class sitemap
return $map; return $map;
} }
function build_index ($count) { public function build_index ($count) {
$lm = date('c'); $lm = date('c');
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap1.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n"; $map .= "<sitemap>\n<loc>{$this->home}internal_data/sitemap/sitemap1.xml</loc>\n<lastmod>{$lm}</lastmod>\n</sitemap>\n";
@ -38,7 +38,7 @@ class sitemap
return $map; return $map;
} }
function build_stat () { public function build_stat () {
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_static(); $map .= $this->get_static();
$map .= $this->get_forum(); $map .= $this->get_forum();
@ -47,7 +47,7 @@ class sitemap
return $map; return $map;
} }
function build_map_topic ($n) { public function build_map_topic ($n) {
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"; $map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$map .= $this->get_topic($n); $map .= $this->get_topic($n);
$map .= "</urlset>"; $map .= "</urlset>";
@ -55,7 +55,7 @@ class sitemap
return $map; return $map;
} }
function get_forum () { public function get_forum () {
global $datastore; global $datastore;
$this->priority = $this->cat_priority; $this->priority = $this->cat_priority;
@ -81,7 +81,7 @@ class sitemap
return $xml; return $xml;
} }
function get_topic ($page = false) { public function get_topic ($page = false) {
global $datastore; global $datastore;
$xml = ''; $xml = '';
@ -119,7 +119,7 @@ class sitemap
return $xml; return $xml;
} }
function get_static () { public function get_static () {
global $bb_cfg; global $bb_cfg;
$xml = ''; $xml = '';
@ -142,7 +142,7 @@ class sitemap
return $xml; return $xml;
} }
function get_xml ($loc, $lm) { public function get_xml ($loc, $lm) {
$xml = "\t<url>\n"; $xml = "\t<url>\n";
$xml .= "\t\t<loc>$loc</loc>\n"; $xml .= "\t\t<loc>$loc</loc>\n";
$xml .= "\t\t<lastmod>$lm</lastmod>\n"; $xml .= "\t\t<lastmod>$lm</lastmod>\n";
@ -152,7 +152,7 @@ class sitemap
return $xml; return $xml;
} }
function send_url ($url, $map) { public function send_url ($url, $map) {
$data = false; $data = false;
$file = $url.urlencode($map); $file = $url.urlencode($map);
@ -174,7 +174,7 @@ class sitemap
} }
} }
function create () { public function create () {
$row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS); $row = DB()->fetch_row("SELECT COUNT(*) AS count FROM " . BB_TOPICS);
if (!$this->limit) $this->limit = $row['count']; if (!$this->limit) $this->limit = $row['count'];

View file

@ -4,17 +4,17 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class CACHES class CACHES
{ {
var $cfg = array(); // конфиг public $cfg = array(); // конфиг
var $obj = array(); // кеш-объекты public $obj = array(); // кеш-объекты
var $ref = array(); // ссылки на $obj (имя_кеша => кеш_объект) public $ref = array(); // ссылки на $obj (имя_кеша => кеш_объект)
function CACHES ($cfg) public function __construct ($cfg)
{ {
$this->cfg = $cfg['cache']; $this->cfg = $cfg['cache'];
$this->obj['__stub'] = new cache_common(); $this->obj['__stub'] = new cache_common();
} }
function get_cache_obj ($cache_name) public function get_cache_obj ($cache_name)
{ {
if (!isset($this->ref[$cache_name])) if (!isset($this->ref[$cache_name]))
{ {
@ -99,7 +99,7 @@ class CACHES
return $this->ref[$cache_name]; return $this->ref[$cache_name];
} }
function get_db_path ($name, $cfg, $ext) public function get_db_path ($name, $cfg, $ext)
{ {
if (!empty($cfg['shard_type']) && $cfg['shard_type'] != 'none') if (!empty($cfg['shard_type']) && $cfg['shard_type'] != 'none')
{ {
@ -111,7 +111,7 @@ class CACHES
} }
} }
function get_table_schema ($cfg) public function get_table_schema ($cfg)
{ {
return "CREATE TABLE {$cfg['table_name']} ( {$cfg['columns']} )"; return "CREATE TABLE {$cfg['table_name']} ( {$cfg['columns']} )";
} }

View file

@ -4,17 +4,17 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class DBS class DBS
{ {
var $cfg = array(); // $srv_name => $srv_cfg public $cfg = array(); // $srv_name => $srv_cfg
var $srv = array(); // $srv_name => $db_obj public $srv = array(); // $srv_name => $db_obj
var $alias = array(); // $srv_alias => $srv_name public $alias = array(); // $srv_alias => $srv_name
var $log_file = 'sql_queries'; public $log_file = 'sql_queries';
var $log_counter = 0; public $log_counter = 0;
var $num_queries = 0; public $num_queries = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
function DBS ($cfg) public function __construct ($cfg)
{ {
$this->cfg = $cfg['db']; $this->cfg = $cfg['db'];
$this->alias = $cfg['db_alias']; $this->alias = $cfg['db_alias'];
@ -26,7 +26,7 @@ class DBS
} }
// получение/инициализация класса для сервера $srv_name // получение/инициализация класса для сервера $srv_name
function get_db_obj ($srv_name_or_alias = 'db1') public function get_db_obj ($srv_name_or_alias = 'db1')
{ {
$srv_name = $this->get_srv_name($srv_name_or_alias); $srv_name = $this->get_srv_name($srv_name_or_alias);
@ -39,7 +39,7 @@ class DBS
} }
// определение имени сервера // определение имени сервера
function get_srv_name ($name) public function get_srv_name ($name)
{ {
if (isset($this->alias[$name])) if (isset($this->alias[$name]))
{ {

View file

@ -4,41 +4,41 @@ if (!defined('SQL_DEBUG')) die(basename(__FILE__));
class sql_db class sql_db
{ {
var $cfg = array(); public $cfg = array();
var $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist'); public $cfg_keys = array('dbhost', 'dbname', 'dbuser', 'dbpasswd', 'charset', 'persist');
var $link = null; private $link = null;
var $result = null; public $result = null;
var $db_server = ''; public $db_server = '';
var $selected_db = null; public $selected_db = null;
var $inited = false; public $inited = false;
var $locked = false; public $locked = false;
var $locks = array(); public $locks = array();
var $num_queries = 0; public $num_queries = 0;
var $sql_starttime = 0; public $sql_starttime = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
var $cur_query_time = 0; public $cur_query_time = 0;
var $slow_time = 0; public $slow_time = 0;
var $dbg = array(); public $dbg = array();
var $dbg_id = 0; public $dbg_id = 0;
var $dbg_enabled = false; public $dbg_enabled = false;
var $cur_query = null; public $cur_query = null;
var $do_explain = false; public $do_explain = false;
var $explain_hold = ''; public $explain_hold = '';
var $explain_out = ''; public $explain_out = '';
var $shutdown = array(); public $shutdown = array();
var $DBS = array(); public $DBS = array();
/** /**
* Constructor * Constructor
*/ */
function sql_db ($cfg_values) public function __construct ($cfg_values)
{ {
global $DBS; global $DBS;
@ -58,16 +58,13 @@ class sql_db
/** /**
* Initialize connection * Initialize connection
*/ */
function init () public function init ()
{ {
// Connect to server // Connect to server
$this->link = $this->connect(); $this->connect();
// Select database
$this->selected_db = $this->select_db();
// Set charset // Set charset
if ($this->cfg['charset'] && !@mysql_set_charset($this->cfg['charset'], $this->link)) if ($this->cfg['charset'] && !mysqli_set_charset($this->link, $this->cfg['charset']))
{ {
if (!$this->sql_query("SET NAMES {$this->cfg['charset']}")) if (!$this->sql_query("SET NAMES {$this->cfg['charset']}"))
{ {
@ -84,14 +81,15 @@ class sql_db
/** /**
* Open connection * Open connection
*/ */
function connect () public function connect ()
{ {
$this->cur_query = ($this->dbg_enabled) ? ($this->cfg['persist'] ? 'p' : '') . "connect to: {$this->cfg['dbhost']}" : 'connect'; $this->cur_query = ($this->dbg_enabled) ? "connect to: {$this->cfg['dbhost']}" : 'connect';
$this->debug('start'); $this->debug('start');
$connect_type = ($this->cfg['persist']) ? 'mysql_pconnect' : 'mysql_connect'; $p = ((bool)$this->cfg['persist']) ? 'p:' : '';
$this->link = mysqli_connect($p . $this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'], $this->cfg['dbname']);
if (!$link = @$connect_type($this->cfg['dbhost'], $this->cfg['dbuser'], $this->cfg['dbpasswd'])) if (mysqli_connect_error())
{ {
$server = (DBG_USER) ? $this->cfg['dbhost'] : ''; $server = (DBG_USER) ? $this->cfg['dbhost'] : '';
header("HTTP/1.0 503 Service Unavailable"); header("HTTP/1.0 503 Service Unavailable");
@ -103,37 +101,14 @@ class sql_db
$this->debug('stop'); $this->debug('stop');
$this->cur_query = null; $this->cur_query = null;
return $link;
}
/**
* Select database
*/
function select_db ()
{
$this->cur_query = ($this->dbg_enabled) ? "select db: {$this->cfg['dbname']}" : 'select db';
$this->debug('start');
if (!@mysql_select_db($this->cfg['dbname'], $this->link))
{
$database = (DBG_USER) ? $this->cfg['dbhost'] : '';
die("Could not select database $database");
}
$this->debug('stop');
$this->cur_query = null;
return $this->cfg['dbname'];
} }
/** /**
* Base query method * Base query method
*/ */
function sql_query ($query) public function sql_query ($query)
{
if (!is_resource($this->link))
{ {
if (!$this->link) {
$this->init(); $this->init();
} }
if (is_array($query)) if (is_array($query))
@ -147,7 +122,7 @@ class sql_db
$this->cur_query = $query; $this->cur_query = $query;
$this->debug('start'); $this->debug('start');
if (!$this->result = mysql_query($query, $this->link)) if (!$this->result = mysqli_query($this->link, $query))
{ {
$this->log_error(); $this->log_error();
} }
@ -167,7 +142,7 @@ class sql_db
/** /**
* Execute query WRAPPER (with error handling) * Execute query WRAPPER (with error handling)
*/ */
function query ($query) public function query ($query)
{ {
if (!$result = $this->sql_query($query)) if (!$result = $this->sql_query($query))
{ {
@ -180,13 +155,13 @@ class sql_db
/** /**
* Return number of rows * Return number of rows
*/ */
function num_rows ($result = false) public function num_rows ($result = false)
{ {
$num_rows = false; $num_rows = false;
if ($result OR $result = $this->result) if ($result OR $result = $this->result)
{ {
$num_rows = is_resource($result) ? mysql_num_rows($result) : false; $num_rows = $result instanceof mysqli_result ? mysqli_num_rows($result) : false;
} }
return $num_rows; return $num_rows;
@ -195,15 +170,15 @@ class sql_db
/** /**
* Return number of affected rows * Return number of affected rows
*/ */
function affected_rows () public function affected_rows ()
{ {
return is_resource($this->link) ? mysql_affected_rows($this->link) : -1; return mysqli_affected_rows($this->link);
} }
/** /**
* Fetch current field * Fetch current field
*/ */
function sql_fetchfield($field, $rownum = -1, $query_id = 0) public function sql_fetchfield($field, $rownum = -1, $query_id = 0)
{ {
if(!$query_id) if(!$query_id)
{ {
@ -213,7 +188,7 @@ class sql_db
{ {
if($rownum > -1) if($rownum > -1)
{ {
$result = @mysql_result($query_id, $rownum, $field); $result = $this->sql_result($query_id, $rownum, $field);
} }
else else
{ {
@ -244,12 +219,19 @@ class sql_db
} }
} }
private function sql_result(mysqli_result $res, $row, $field = 0)
{
$res->data_seek($row);
$dataRow = $res->fetch_array();
return $dataRow[$field];
}
/** /**
* Fetch current row * Fetch current row
*/ */
function sql_fetchrow ($result, $field_name = '') public function sql_fetchrow ($result, $field_name = '')
{ {
$row = mysql_fetch_assoc($result); $row = mysqli_fetch_assoc($result);
if ($field_name) if ($field_name)
{ {
@ -264,7 +246,7 @@ class sql_db
/** /**
* Alias of sql_fetchrow() * Alias of sql_fetchrow()
*/ */
function fetch_next ($result) public function fetch_next ($result)
{ {
return $this->sql_fetchrow($result); return $this->sql_fetchrow($result);
} }
@ -272,7 +254,7 @@ class sql_db
/** /**
* Fetch row WRAPPER (with error handling) * Fetch row WRAPPER (with error handling)
*/ */
function fetch_row ($query, $field_name = '') public function fetch_row ($query, $field_name = '')
{ {
if (!$result = $this->sql_query($query)) if (!$result = $this->sql_query($query))
{ {
@ -285,11 +267,11 @@ class sql_db
/** /**
* Fetch all rows * Fetch all rows
*/ */
function sql_fetchrowset ($result, $field_name = '') public function sql_fetchrowset ($result, $field_name = '')
{ {
$rowset = array(); $rowset = array();
while ($row = mysql_fetch_assoc($result)) while ($row = mysqli_fetch_assoc($result))
{ {
$rowset[] = ($field_name) ? $row[$field_name] : $row; $rowset[] = ($field_name) ? $row[$field_name] : $row;
} }
@ -300,7 +282,7 @@ class sql_db
/** /**
* Fetch all rows WRAPPER (with error handling) * Fetch all rows WRAPPER (with error handling)
*/ */
function fetch_rowset ($query, $field_name = '') public function fetch_rowset ($query, $field_name = '')
{ {
if (!$result = $this->sql_query($query)) if (!$result = $this->sql_query($query))
{ {
@ -313,7 +295,7 @@ class sql_db
/** /**
* Fetch all rows WRAPPER (with error handling) * Fetch all rows WRAPPER (with error handling)
*/ */
function fetch_all ($query, $field_name = '') public function fetch_all ($query, $field_name = '')
{ {
if (!$result = $this->sql_query($query)) if (!$result = $this->sql_query($query))
{ {
@ -326,19 +308,21 @@ class sql_db
/** /**
* Get last inserted id after insert statement * Get last inserted id after insert statement
*/ */
function sql_nextid () public function sql_nextid ()
{ {
return mysql_insert_id($this->link); return mysqli_insert_id($this->link);
} }
/** /**
* Free sql result * Free sql result
*/ */
function sql_freeresult ($result = false) public function sql_freeresult ($result = false)
{ {
if ($result OR $result = $this->result) if ($result OR $result = $this->result)
{ {
$return_value = is_resource($result) ? mysql_free_result($result) : false; if ($result instanceof mysqli_result) {
mysqli_free_result($result);
}
} }
$this->result = null; $this->result = null;
@ -347,7 +331,7 @@ class sql_db
/** /**
* Escape data used in sql query * Escape data used in sql query
*/ */
function escape ($v, $check_type = false, $dont_escape = false) public function escape ($v, $check_type = false, $dont_escape = false)
{ {
if ($dont_escape) return $v; if ($dont_escape) return $v;
if (!$check_type) return $this->escape_string($v); if (!$check_type) return $this->escape_string($v);
@ -367,14 +351,13 @@ class sql_db
/** /**
* Escape string * Escape string
*/ */
function escape_string ($str) public function escape_string ($str)
{
if (!is_resource($this->link))
{ {
if (!$this->link) {
$this->init(); $this->init();
} }
return mysql_real_escape_string($str, $this->link); return mysqli_real_escape_string($this->link, $str);
} }
/** /**
@ -382,7 +365,7 @@ class sql_db
* *
* Possible $query_type values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT * Possible $query_type values: INSERT, INSERT_SELECT, MULTI_INSERT, UPDATE, SELECT
*/ */
function build_array ($query_type, $input_ary, $data_already_escaped = false, $check_data_type_in_escape = true) public function build_array ($query_type, $input_ary, $data_already_escaped = false, $check_data_type_in_escape = true)
{ {
$fields = $values = $ary = $query = array(); $fields = $values = $ary = $query = array();
$dont_escape = $data_already_escaped; $dont_escape = $data_already_escaped;
@ -448,7 +431,7 @@ class sql_db
return "\n". $query ."\n"; return "\n". $query ."\n";
} }
function get_empty_sql_array () public function get_empty_sql_array ()
{ {
return array( return array(
'SELECT' => array(), 'SELECT' => array(),
@ -464,7 +447,7 @@ class sql_db
); );
} }
function build_sql ($sql_ary) public function build_sql ($sql_ary)
{ {
$sql = ''; $sql = '';
array_deep($sql_ary, 'array_unique', false, true); array_deep($sql_ary, 'array_unique', false, true);
@ -509,11 +492,10 @@ class sql_db
/** /**
* Return sql error array * Return sql error array
*/ */
function sql_error () public function sql_error ()
{ {
if (is_resource($this->link)) if ($this->link) {
{ return array('code' => mysqli_errno($this->link), 'message' => mysqli_error($this->link));
return array('code' => mysql_errno($this->link), 'message' => mysql_error($this->link));
} }
else else
{ {
@ -524,10 +506,9 @@ class sql_db
/** /**
* Close sql connection * Close sql connection
*/ */
function close () public function close ()
{
if (is_resource($this->link))
{ {
if ($this->link) {
$this->unlock(); $this->unlock();
if (!empty($this->locks)) if (!empty($this->locks))
@ -540,7 +521,7 @@ class sql_db
$this->exec_shutdown_queries(); $this->exec_shutdown_queries();
mysql_close($this->link); mysqli_close($this->link);
} }
$this->link = $this->selected_db = null; $this->link = $this->selected_db = null;
@ -549,7 +530,7 @@ class sql_db
/** /**
* Add shutdown query * Add shutdown query
*/ */
function add_shutdown_query ($sql) public function add_shutdown_query ($sql)
{ {
$this->shutdown['__sql'][] = $sql; $this->shutdown['__sql'][] = $sql;
} }
@ -557,7 +538,7 @@ class sql_db
/** /**
* Exec shutdown queries * Exec shutdown queries
*/ */
function exec_shutdown_queries () public function exec_shutdown_queries ()
{ {
if (empty($this->shutdown)) return; if (empty($this->shutdown)) return;
@ -579,7 +560,7 @@ class sql_db
/** /**
* Lock tables * Lock tables
*/ */
function lock ($tables, $lock_type = 'WRITE') public function lock ($tables, $lock_type = 'WRITE')
{ {
if ($this->cfg['persist']) if ($this->cfg['persist'])
{ {
@ -603,7 +584,7 @@ class sql_db
/** /**
* Unlock tables * Unlock tables
*/ */
function unlock () public function unlock ()
{ {
if ($this->locked && $this->sql_query("UNLOCK TABLES")) if ($this->locked && $this->sql_query("UNLOCK TABLES"))
{ {
@ -616,7 +597,7 @@ class sql_db
/** /**
* Obtain user level lock * Obtain user level lock
*/ */
function get_lock ($name, $timeout = 0) public function get_lock ($name, $timeout = 0)
{ {
$lock_name = $this->get_lock_name($name); $lock_name = $this->get_lock_name($name);
$timeout = (int) $timeout; $timeout = (int) $timeout;
@ -633,7 +614,7 @@ class sql_db
/** /**
* Obtain user level lock status * Obtain user level lock status
*/ */
function release_lock ($name) public function release_lock ($name)
{ {
$lock_name = $this->get_lock_name($name); $lock_name = $this->get_lock_name($name);
$row = $this->fetch_row("SELECT RELEASE_LOCK('$lock_name') AS lock_result"); $row = $this->fetch_row("SELECT RELEASE_LOCK('$lock_name') AS lock_result");
@ -649,7 +630,7 @@ class sql_db
/** /**
* Release user level lock * Release user level lock
*/ */
function is_free_lock ($name) public function is_free_lock ($name)
{ {
$lock_name = $this->get_lock_name($name); $lock_name = $this->get_lock_name($name);
$row = $this->fetch_row("SELECT IS_FREE_LOCK('$lock_name') AS lock_result"); $row = $this->fetch_row("SELECT IS_FREE_LOCK('$lock_name') AS lock_result");
@ -659,7 +640,7 @@ class sql_db
/** /**
* Make per db unique lock name * Make per db unique lock name
*/ */
function get_lock_name ($name) public function get_lock_name ($name)
{ {
if (!$this->selected_db) if (!$this->selected_db)
{ {
@ -672,7 +653,7 @@ class sql_db
/** /**
* Get info about last query * Get info about last query
*/ */
function query_info () public function query_info ()
{ {
$info = array(); $info = array();
@ -681,7 +662,7 @@ class sql_db
$info[] = "$num rows"; $info[] = "$num rows";
} }
if (is_resource($this->link) AND $ext = mysql_info($this->link)) if ($this->link AND $ext = mysqli_info($this->link))
{ {
$info[] = "$ext"; $info[] = "$ext";
} }
@ -690,15 +671,15 @@ class sql_db
$info[] = "$aff rows"; $info[] = "$aff rows";
} }
return str_compact(join(', ', $info)); return str_compact(implode(', ', $info));
} }
/** /**
* Get server version * Get server version
*/ */
function server_version () public function server_version ()
{ {
preg_match('#^(\d+\.\d+\.\d+).*#', mysql_get_server_info(), $m); preg_match('#^(\d+\.\d+\.\d+).*#', mysqli_get_server_info($this->link), $m);
return $m[1]; return $m[1];
} }
@ -706,7 +687,7 @@ class sql_db
* Set slow query marker for xx seconds * Set slow query marker for xx seconds
* This will disable counting other queries as "slow" during this time * This will disable counting other queries as "slow" during this time
*/ */
function expect_slow_query ($ignoring_time = 60, $new_priority = 10) public function expect_slow_query ($ignoring_time = 60, $new_priority = 10)
{ {
if ($old_priority = CACHE('bb_cache')->get('dont_log_slow_query')) if ($old_priority = CACHE('bb_cache')->get('dont_log_slow_query'))
{ {
@ -723,7 +704,7 @@ class sql_db
/** /**
* Store debug info * Store debug info
*/ */
function debug ($mode) public function debug ($mode)
{ {
if (!SQL_DEBUG) return; if (!SQL_DEBUG) return;
@ -787,7 +768,7 @@ class sql_db
/** /**
* Trigger error * Trigger error
*/ */
function trigger_error ($msg = 'DB Error') public function trigger_error ($msg = 'DB Error')
{ {
if (error_reporting()) if (error_reporting())
{ {
@ -808,7 +789,7 @@ class sql_db
/** /**
* Find caller source * Find caller source
*/ */
function debug_find_source ($mode = '') public function debug_find_source ($mode = '')
{ {
foreach (debug_backtrace() as $trace) foreach (debug_backtrace() as $trace)
{ {
@ -828,7 +809,7 @@ class sql_db
/** /**
* Prepare for logging * Prepare for logging
*/ */
function log_next_query ($queries_count = 1, $log_file = 'sql_queries') public function log_next_query ($queries_count = 1, $log_file = 'sql_queries')
{ {
$this->DBS['log_file'] = $log_file; $this->DBS['log_file'] = $log_file;
$this->DBS['log_counter'] = $queries_count; $this->DBS['log_counter'] = $queries_count;
@ -837,7 +818,7 @@ class sql_db
/** /**
* Log query * Log query
*/ */
function log_query ($log_file = 'sql_queries') public function log_query ($log_file = 'sql_queries')
{ {
$q_time = ($this->cur_query_time >= 10) ? round($this->cur_query_time, 0) : sprintf('%.4f', $this->cur_query_time); $q_time = ($this->cur_query_time >= 10) ? round($this->cur_query_time, 0) : sprintf('%.4f', $this->cur_query_time);
$msg = array(); $msg = array();
@ -858,7 +839,7 @@ class sql_db
/** /**
* Log slow query * Log slow query
*/ */
function log_slow_query ($log_file = 'sql_slow_bb') public function log_slow_query ($log_file = 'sql_slow_bb')
{ {
if (!defined('IN_FIRST_SLOW_QUERY') && CACHE('bb_cache')->get('dont_log_slow_query')) if (!defined('IN_FIRST_SLOW_QUERY') && CACHE('bb_cache')->get('dont_log_slow_query'))
{ {
@ -870,7 +851,7 @@ class sql_db
/** /**
* Log error * Log error
*/ */
function log_error () public function log_error ()
{ {
if (!SQL_LOG_ERRORS) return; if (!SQL_LOG_ERRORS) return;
@ -896,7 +877,7 @@ class sql_db
/** /**
* Explain queries (based on code from phpBB3) * Explain queries (based on code from phpBB3)
*/ */
function explain ($mode, $html_table = '', $row = '') public function explain ($mode, $html_table = '', $row = '')
{ {
$query = str_compact($this->cur_query); $query = str_compact($this->cur_query);
// remove comments // remove comments
@ -920,9 +901,9 @@ class sql_db
{ {
$html_table = false; $html_table = false;
if ($result = @mysql_query("EXPLAIN $query", $this->link)) if ($result = mysqli_query($this->link, "EXPLAIN $query"))
{ {
while ($row = @mysql_fetch_assoc($result)) while ($row = mysqli_fetch_assoc($result))
{ {
$html_table = $this->explain('add_explain_row', $html_table, $row); $html_table = $this->explain('add_explain_row', $html_table, $row);
} }

View file

@ -4,10 +4,10 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class datastore_apc extends datastore_common class datastore_apc extends datastore_common
{ {
var $engine = 'APC'; public $engine = 'APC';
var $prefix = null; public $prefix = null;
function datastore_apc ($prefix = null) public function __construct ($prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -17,7 +17,7 @@ class datastore_apc extends datastore_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store ($title, $var) public function store ($title, $var)
{ {
$this->data[$title] = $var; $this->data[$title] = $var;
@ -30,7 +30,7 @@ class datastore_apc extends datastore_common
return (bool) apc_store($this->prefix . $title, $var); return (bool) apc_store($this->prefix . $title, $var);
} }
function clean () public function clean ()
{ {
foreach ($this->known_items as $title => $script_name) foreach ($this->known_items as $title => $script_name)
{ {
@ -44,7 +44,7 @@ class datastore_apc extends datastore_common
} }
} }
function _fetch_from_store () public function _fetch_from_store ()
{ {
if (!$items = $this->queued_items) if (!$items = $this->queued_items)
{ {
@ -64,7 +64,7 @@ class datastore_apc extends datastore_common
} }
} }
function is_installed () public function is_installed ()
{ {
return function_exists('apc_fetch'); return function_exists('apc_fetch');
} }

View file

@ -7,24 +7,24 @@ class datastore_common
/** /**
* Директория с builder-скриптами (внутри INC_DIR) * Директория с builder-скриптами (внутри INC_DIR)
*/ */
var $ds_dir = 'datastore/'; public $ds_dir = 'datastore/';
/** /**
* Готовая к употреблению data * Готовая к употреблению data
* array('title' => data) * array('title' => data)
*/ */
var $data = array(); public $data = array();
/** /**
* Список элементов, которые будут извлечены из хранилища при первом же запросе get() * Список элементов, которые будут извлечены из хранилища при первом же запросе get()
* до этого момента они ставятся в очередь $queued_items для дальнейшего извлечения _fetch()'ем * до этого момента они ставятся в очередь $queued_items для дальнейшего извлечения _fetch()'ем
* всех элементов одним запросом * всех элементов одним запросом
* array('title1', 'title2'...) * array('title1', 'title2'...)
*/ */
var $queued_items = array(); public $queued_items = array();
/** /**
* 'title' => 'builder script name' inside "includes/datastore" dir * 'title' => 'builder script name' inside "includes/datastore" dir
*/ */
var $known_items = array( public $known_items = array(
'cat_forums' => 'build_cat_forums.php', 'cat_forums' => 'build_cat_forums.php',
'jumpbox' => 'build_cat_forums.php', 'jumpbox' => 'build_cat_forums.php',
'viewtopic_forum_select' => 'build_cat_forums.php', 'viewtopic_forum_select' => 'build_cat_forums.php',
@ -41,12 +41,12 @@ class datastore_common
/** /**
* Constructor * Constructor
*/ */
function datastore_common () {} public function __construct () {}
/** /**
* @param array(item1_title, item2_title...) or single item's title * @param array(item1_title, item2_title...) or single item's title
*/ */
function enqueue ($items) public function enqueue ($items)
{ {
foreach ((array) $items as $item) foreach ((array) $items as $item)
{ {
@ -58,7 +58,7 @@ class datastore_common
} }
} }
function &get ($title) public function &get ($title)
{ {
if (!isset($this->data[$title])) if (!isset($this->data[$title]))
{ {
@ -68,9 +68,9 @@ class datastore_common
return $this->data[$title]; return $this->data[$title];
} }
function store ($item_name, $item_data) {} public function store ($item_name, $item_data) {}
function rm ($items) public function rm ($items)
{ {
foreach ((array) $items as $item) foreach ((array) $items as $item)
{ {
@ -78,7 +78,7 @@ class datastore_common
} }
} }
function update ($items) public function update ($items)
{ {
if ($items == 'all') if ($items == 'all')
{ {
@ -90,7 +90,7 @@ class datastore_common
} }
} }
function _fetch () public function _fetch ()
{ {
$this->_fetch_from_store(); $this->_fetch_from_store();
@ -105,9 +105,9 @@ class datastore_common
$this->queued_items = array(); $this->queued_items = array();
} }
function _fetch_from_store () {} public function _fetch_from_store () {}
function _build_item ($title) public function _build_item ($title)
{ {
if (!empty($this->known_items[$title])) if (!empty($this->known_items[$title]))
{ {
@ -119,18 +119,18 @@ class datastore_common
} }
} }
var $num_queries = 0; public $num_queries = 0;
var $sql_starttime = 0; public $sql_starttime = 0;
var $sql_inittime = 0; public $sql_inittime = 0;
var $sql_timetotal = 0; public $sql_timetotal = 0;
var $cur_query_time = 0; public $cur_query_time = 0;
var $dbg = array(); public $dbg = array();
var $dbg_id = 0; public $dbg_id = 0;
var $dbg_enabled = false; public $dbg_enabled = false;
var $cur_query = null; public $cur_query = null;
function debug ($mode, $cur_query = null) public function debug ($mode, $cur_query = null)
{ {
if (!$this->dbg_enabled) return; if (!$this->dbg_enabled) return;
@ -156,7 +156,7 @@ class datastore_common
} }
} }
function debug_find_source ($mode = '') public function debug_find_source ($mode = '')
{ {
foreach (debug_backtrace() as $trace) foreach (debug_backtrace() as $trace)
{ {

View file

@ -4,18 +4,18 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class datastore_file extends datastore_common class datastore_file extends datastore_common
{ {
var $dir = null; public $dir = null;
var $prefix = null; public $prefix = null;
var $engine = 'Filecache'; public $engine = 'Filecache';
function datastore_file ($dir, $prefix = null) public function __construct ($dir, $prefix = null)
{ {
$this->prefix = $prefix; $this->prefix = $prefix;
$this->dir = $dir; $this->dir = $dir;
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function store ($title, $var) public function store ($title, $var)
{ {
$this->cur_query = "cache->set('$title')"; $this->cur_query = "cache->set('$title')";
$this->debug('start'); $this->debug('start');
@ -36,7 +36,7 @@ class datastore_file extends datastore_common
return (bool) file_write($filecache, $filename, false, true, true); return (bool) file_write($filecache, $filename, false, true, true);
} }
function clean () public function clean ()
{ {
$dir = $this->dir; $dir = $this->dir;
@ -58,7 +58,7 @@ class datastore_file extends datastore_common
} }
} }
function _fetch_from_store () public function _fetch_from_store ()
{ {
if (!$items = $this->queued_items) if (!$items = $this->queued_items)
{ {

View file

@ -4,13 +4,13 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class datastore_memcache extends datastore_common class datastore_memcache extends datastore_common
{ {
var $cfg = null; public $cfg = null;
var $memcache = null; public $memcache = null;
var $connected = false; public $connected = false;
var $engine = 'Memcache'; public $engine = 'Memcache';
var $prefix = null; public $prefix = null;
function datastore_memcache ($cfg, $prefix = null) public function __construct ($cfg, $prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -23,7 +23,7 @@ class datastore_memcache extends datastore_common
$this->dbg_enabled = sql_dbg_enabled(); $this->dbg_enabled = sql_dbg_enabled();
} }
function connect () public function connect ()
{ {
$connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect'; $connect_type = ($this->cfg['pconnect']) ? 'pconnect' : 'connect';
@ -46,7 +46,7 @@ class datastore_memcache extends datastore_common
$this->cur_query = null; $this->cur_query = null;
} }
function store ($title, $var) public function store ($title, $var)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
$this->data[$title] = $var; $this->data[$title] = $var;
@ -60,7 +60,7 @@ class datastore_memcache extends datastore_common
return (bool) $this->memcache->set($this->prefix . $title, $var); return (bool) $this->memcache->set($this->prefix . $title, $var);
} }
function clean () public function clean ()
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
foreach ($this->known_items as $title => $script_name) foreach ($this->known_items as $title => $script_name)
@ -75,7 +75,7 @@ class datastore_memcache extends datastore_common
} }
} }
function _fetch_from_store () public function _fetch_from_store ()
{ {
if (!$items = $this->queued_items) if (!$items = $this->queued_items)
{ {
@ -96,7 +96,7 @@ class datastore_memcache extends datastore_common
} }
} }
function is_installed () public function is_installed ()
{ {
return class_exists('Memcache'); return class_exists('Memcache');
} }

View file

@ -4,13 +4,13 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class datastore_redis extends datastore_common class datastore_redis extends datastore_common
{ {
var $cfg = null; public $cfg = null;
var $redis = null; public $redis = null;
var $prefix = null; public $prefix = null;
var $connected = false; public $connected = false;
var $engine = 'Redis'; public $engine = 'Redis';
function datastore_redis ($cfg, $prefix = null) public function __construct ($cfg, $prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -23,7 +23,7 @@ class datastore_redis extends datastore_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function connect () public function connect ()
{ {
$this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port']; $this->cur_query = 'connect '. $this->cfg['host'] .':'. $this->cfg['port'];
$this->debug('start'); $this->debug('start');
@ -42,7 +42,7 @@ class datastore_redis extends datastore_common
$this->cur_query = null; $this->cur_query = null;
} }
function store ($title, $var) public function store ($title, $var)
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
$this->data[$title] = $var; $this->data[$title] = $var;
@ -56,7 +56,7 @@ class datastore_redis extends datastore_common
return (bool) $this->redis->set($this->prefix . $title, serialize($var)); return (bool) $this->redis->set($this->prefix . $title, serialize($var));
} }
function clean () public function clean ()
{ {
if (!$this->connected) $this->connect(); if (!$this->connected) $this->connect();
foreach ($this->known_items as $title => $script_name) foreach ($this->known_items as $title => $script_name)
@ -71,7 +71,7 @@ class datastore_redis extends datastore_common
} }
} }
function _fetch_from_store () public function _fetch_from_store ()
{ {
if (!$items = $this->queued_items) if (!$items = $this->queued_items)
{ {
@ -92,7 +92,7 @@ class datastore_redis extends datastore_common
} }
} }
function is_installed () public function is_installed ()
{ {
return class_exists('Redis'); return class_exists('Redis');
} }

View file

@ -4,10 +4,10 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class datastore_sqlite extends datastore_common class datastore_sqlite extends datastore_common
{ {
var $engine = 'SQLite'; public $engine = 'SQLite';
var $db = null; public $db = null;
var $prefix = null; public $prefix = null;
var $cfg = array( public $cfg = array(
'db_file_path' => '/path/to/datastore.db.sqlite', 'db_file_path' => '/path/to/datastore.db.sqlite',
'table_name' => 'datastore', 'table_name' => 'datastore',
'table_schema' => 'CREATE TABLE datastore ( 'table_schema' => 'CREATE TABLE datastore (
@ -20,14 +20,14 @@ class datastore_sqlite extends datastore_common
'log_name' => 'DATASTORE', 'log_name' => 'DATASTORE',
); );
function datastore_sqlite ($cfg, $prefix = null) public function __construct ($cfg, $prefix = null)
{ {
$this->cfg = array_merge($this->cfg, $cfg); $this->cfg = array_merge($this->cfg, $cfg);
$this->db = new sqlite_common($this->cfg); $this->db = new sqlite_common($this->cfg);
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store ($item_name, $item_data) public function store ($item_name, $item_data)
{ {
$this->data[$item_name] = $item_data; $this->data[$item_name] = $item_data;
@ -39,12 +39,12 @@ class datastore_sqlite extends datastore_common
return (bool) $result; return (bool) $result;
} }
function clean () public function clean ()
{ {
$this->db->query("DELETE FROM ". $this->cfg['table_name']); $this->db->query("DELETE FROM ". $this->cfg['table_name']);
} }
function _fetch_from_store () public function _fetch_from_store ()
{ {
if (!$items = $this->queued_items) return; if (!$items = $this->queued_items) return;

View file

@ -4,10 +4,10 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class datastore_xcache extends datastore_common class datastore_xcache extends datastore_common
{ {
var $prefix = null; public $prefix = null;
var $engine = 'XCache'; public $engine = 'XCache';
function datastore_xcache ($prefix = null) public function __construct ($prefix = null)
{ {
if (!$this->is_installed()) if (!$this->is_installed())
{ {
@ -18,7 +18,7 @@ class datastore_xcache extends datastore_common
$this->prefix = $prefix; $this->prefix = $prefix;
} }
function store ($title, $var) public function store ($title, $var)
{ {
$this->data[$title] = $var; $this->data[$title] = $var;
@ -31,7 +31,7 @@ class datastore_xcache extends datastore_common
return (bool) xcache_set($this->prefix . $title, $var); return (bool) xcache_set($this->prefix . $title, $var);
} }
function clean () public function clean ()
{ {
foreach ($this->known_items as $title => $script_name) foreach ($this->known_items as $title => $script_name)
{ {
@ -45,7 +45,7 @@ class datastore_xcache extends datastore_common
} }
} }
function _fetch_from_store () public function _fetch_from_store ()
{ {
if (!$items = $this->queued_items) if (!$items = $this->queued_items)
{ {
@ -65,7 +65,7 @@ class datastore_xcache extends datastore_common
} }
} }
function is_installed () public function is_installed ()
{ {
return function_exists('xcache_get'); return function_exists('xcache_get');
} }

View file

@ -118,13 +118,13 @@ function is_unread ($ref, $topic_id = 0, $forum_id = 0)
// //
class ads_common class ads_common
{ {
var $ad_blocks = array(); public $ad_blocks = array();
var $active_ads = array(); public $active_ads = array();
/** /**
* Constructor * Constructor
*/ */
function ads_common () function __construct ()
{ {
global $bb_cfg; global $bb_cfg;
@ -536,18 +536,18 @@ function auth_check ($bf_ary, $bf_key, $perm_ary, $perm_key, $is_admin = false)
class Date_Delta class Date_Delta
{ {
var $auto_granularity = array( public $auto_granularity = array(
60 => 'seconds', // set granularity to "seconds" if delta less then 1 minute 60 => 'seconds', // set granularity to "seconds" if delta less then 1 minute
10800 => 'minutes', // 3 hours 10800 => 'minutes', // 3 hours
259200 => 'hours', // 3 days 259200 => 'hours', // 3 days
31363200 => 'mday', // 12 months 31363200 => 'mday', // 12 months
311040000 => 'mon', // 10 years 311040000 => 'mon', // 10 years
); );
var $intervals = array(); public $intervals = array();
var $format = ''; public $format = '';
// Creates new object. // Creates new object.
function Date_Delta() function __construct()
{ {
global $lang; global $lang;
@ -694,11 +694,11 @@ function get_select ($select, $selected = null, $return_as = 'html', $first_opt
class html_common class html_common
{ {
var $options = ''; public $options = '';
var $attr = array(); public $attr = array();
var $cur_attr = null; public $cur_attr = null;
var $max_length = HTML_SELECT_MAX_LENGTH; public $max_length = HTML_SELECT_MAX_LENGTH;
var $selected = array(); public $selected = array();
function build_select ($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '') function build_select ($name, $params, $selected = null, $max_length = HTML_SELECT_MAX_LENGTH, $multiple_size = null, $js = '')
{ {
@ -2106,7 +2106,7 @@ function cat_exists ($cat_id)
// //
class log_action class log_action
{ {
var $log_type = array( public $log_type = array(
# LOG_TYPE_NAME LOG_TYPE_ID # LOG_TYPE_NAME LOG_TYPE_ID
'mod_topic_delete' => 1, 'mod_topic_delete' => 1,
'mod_topic_move' => 2, 'mod_topic_move' => 2,
@ -2118,10 +2118,10 @@ class log_action
'adm_user_ban' => 8, 'adm_user_ban' => 8,
'adm_user_unban' => 9, 'adm_user_unban' => 9,
); );
var $log_type_select = array(); public $log_type_select = array();
var $log_disabled = false; public $log_disabled = false;
function init () public function init ()
{ {
global $lang, $bb_cfg; global $lang, $bb_cfg;
@ -2131,7 +2131,7 @@ class log_action
} }
} }
function mod ($type_name, $args = array()) public function mod ($type_name, $args = array())
{ {
global $userdata; global $userdata;
@ -2178,7 +2178,7 @@ class log_action
DB()->query("INSERT INTO ". BB_LOG ." $sql_args"); DB()->query("INSERT INTO ". BB_LOG ." $sql_args");
} }
function admin ($type_name, $args = array()) public function admin ($type_name, $args = array())
{ {
$this->mod($type_name, $args); $this->mod($type_name, $args);
} }

View file

@ -4,28 +4,28 @@ if (!defined('BB_ROOT')) die(basename(__FILE__));
class upload_common class upload_common
{ {
var $cfg = array( public $cfg = array(
'max_size' => 0, 'max_size' => 0,
'max_width' => 0, 'max_width' => 0,
'max_height' => 0, 'max_height' => 0,
'allowed_ext' => array(), 'allowed_ext' => array(),
'upload_path' => '', 'upload_path' => '',
); );
var $file = array( public $file = array(
'name' => '', 'name' => '',
'type' => '', 'type' => '',
'size' => 0, 'size' => 0,
'tmp_name' => '', 'tmp_name' => '',
'error' => UPLOAD_ERR_NO_FILE, 'error' => UPLOAD_ERR_NO_FILE,
); );
var $orig_name = ''; public $orig_name = '';
var $file_path = ''; // Stored file path public $file_path = ''; // Stored file path
var $file_ext = ''; public $file_ext = '';
var $file_ext_id = ''; public $file_ext_id = '';
var $file_size = ''; public $file_size = '';
var $ext_ids = array(); // array_flip($bb_cfg['file_id_ext']) public $ext_ids = array(); // array_flip($bb_cfg['file_id_ext'])
var $errors = array(); public $errors = array();
var $img_types = array( public $img_types = array(
1 => 'gif', 1 => 'gif',
2 => 'jpg', 2 => 'jpg',
3 => 'png', 3 => 'png',
@ -34,7 +34,7 @@ class upload_common
8 => 'tiff', 8 => 'tiff',
); );
function init ($cfg = array(), $post_params = array(), $uploaded_only = true) public function init ($cfg = array(), $post_params = array(), $uploaded_only = true)
{ {
global $bb_cfg, $lang; global $bb_cfg, $lang;
@ -116,7 +116,7 @@ class upload_common
return true; return true;
} }
function store ($mode = '', $params = array()) public function store ($mode = '', $params = array())
{ {
if ($mode == 'avatar') if ($mode == 'avatar')
{ {
@ -135,7 +135,7 @@ class upload_common
} }
} }
function _move ($file_path) public function _move ($file_path)
{ {
$dir = dirname($file_path); $dir = dirname($file_path);
if (!file_exists($dir)) if (!file_exists($dir))

View file

@ -10,7 +10,7 @@ class user_common
/** /**
* Config * Config
*/ */
var $cfg = array( public $cfg = array(
'req_login' => false, // requires user to be logged in 'req_login' => false, // requires user to be logged in
'req_session_admin' => false, // requires active admin session (for moderation or admin actions) 'req_session_admin' => false, // requires active admin session (for moderation or admin actions)
); );
@ -18,7 +18,7 @@ class user_common
/** /**
* PHP-JS exchangeable options (JSON'ized as {USER_OPTIONS_JS} in TPL) * PHP-JS exchangeable options (JSON'ized as {USER_OPTIONS_JS} in TPL)
*/ */
var $opt_js = array( public $opt_js = array(
'only_new' => 0, // show ony new posts or topics 'only_new' => 0, // show ony new posts or topics
'h_av' => 0, // hide avatar 'h_av' => 0, // hide avatar
'h_rnk_i' => 0, // hide rank images 'h_rnk_i' => 0, // hide rank images
@ -36,7 +36,7 @@ class user_common
/** /**
* Defaults options for guests * Defaults options for guests
*/ */
var $opt_js_guest = array( public $opt_js_guest = array(
'h_av' => 1, // hide avatar 'h_av' => 1, // hide avatar
'h_rnk_i' => 1, // hide rank images 'h_rnk_i' => 1, // hide rank images
'h_smile' => 1, // hide smilies 'h_smile' => 1, // hide smilies
@ -46,7 +46,7 @@ class user_common
/** /**
* Sessiondata * Sessiondata
*/ */
var $sessiondata = array( public $sessiondata = array(
'uk' => null, 'uk' => null,
'uid' => null, 'uid' => null,
'sid' => '', 'sid' => '',
@ -55,22 +55,22 @@ class user_common
/** /**
* Old $userdata * Old $userdata
*/ */
var $data = array(); public $data = array();
/** /**
* Shortcuts * Shortcuts
*/ */
var $id = null; public $id = null;
/** /**
* Misc * Misc
*/ */
var $show_ads = false; public $show_ads = false;
/** /**
* Constructor * Constructor
*/ */
function user_common () public function __construct ()
{ {
$this->get_sessiondata(); $this->get_sessiondata();
} }
@ -78,7 +78,7 @@ class user_common
/** /**
* Start session (restore existent session or create new) * Start session (restore existent session or create new)
*/ */
function session_start ($cfg = array()) public function session_start ($cfg = array())
{ {
global $bb_cfg; global $bb_cfg;
@ -214,7 +214,7 @@ class user_common
/** /**
* Create new session for the given user * Create new session for the given user
*/ */
function session_create ($userdata, $auto_created = false) public function session_create ($userdata, $auto_created = false)
{ {
global $bb_cfg; global $bb_cfg;
@ -333,7 +333,7 @@ class user_common
/** /**
* Initialize sessiondata stored in cookies * Initialize sessiondata stored in cookies
*/ */
function session_end ($update_lastvisit = false, $set_cookie = true) public function session_end ($update_lastvisit = false, $set_cookie = true)
{ {
DB()->query(" DB()->query("
DELETE FROM ". BB_SESSIONS ." DELETE FROM ". BB_SESSIONS ."
@ -375,7 +375,7 @@ class user_common
/** /**
* Login * Login
*/ */
function login ($args, $mod_admin_login = false) public function login ($args, $mod_admin_login = false)
{ {
$username = !empty($args['login_username']) ? clean_username($args['login_username']) : ''; $username = !empty($args['login_username']) ? clean_username($args['login_username']) : '';
$password = !empty($args['login_password']) ? $args['login_password'] : ''; $password = !empty($args['login_password']) ? $args['login_password'] : '';
@ -440,7 +440,7 @@ class user_common
/** /**
* Initialize sessiondata stored in cookies * Initialize sessiondata stored in cookies
*/ */
function get_sessiondata () public function get_sessiondata ()
{ {
$sd_resv = !empty($_COOKIE[COOKIE_DATA]) ? @unserialize($_COOKIE[COOKIE_DATA]) : array(); $sd_resv = !empty($_COOKIE[COOKIE_DATA]) ? @unserialize($_COOKIE[COOKIE_DATA]) : array();
@ -464,7 +464,7 @@ class user_common
/** /**
* Store sessiondata in cookies * Store sessiondata in cookies
*/ */
function set_session_cookies ($user_id) public function set_session_cookies ($user_id)
{ {
global $bb_cfg; global $bb_cfg;
@ -506,7 +506,7 @@ class user_common
/** /**
* Verify autologin_id * Verify autologin_id
*/ */
function verify_autologin_id ($userdata, $expire_check = false, $create_new = true) public function verify_autologin_id ($userdata, $expire_check = false, $create_new = true)
{ {
global $bb_cfg; global $bb_cfg;
@ -533,7 +533,7 @@ class user_common
/** /**
* Create autologin_id * Create autologin_id
*/ */
function create_autologin_id ($userdata, $create_new = true) public function create_autologin_id ($userdata, $create_new = true)
{ {
$autologin_id = ($create_new) ? make_rand_str(LOGIN_KEY_LENGTH) : ''; $autologin_id = ($create_new) ? make_rand_str(LOGIN_KEY_LENGTH) : '';
@ -550,7 +550,7 @@ class user_common
/** /**
* Set shortcuts * Set shortcuts
*/ */
function set_shortcuts () public function set_shortcuts ()
{ {
$this->id =& $this->data['user_id']; $this->id =& $this->data['user_id'];
$this->active =& $this->data['user_active']; $this->active =& $this->data['user_active'];
@ -566,7 +566,7 @@ class user_common
/** /**
* Initialise user settings * Initialise user settings
*/ */
function init_userprefs () public function init_userprefs ()
{ {
global $bb_cfg, $theme, $lang, $DeltaTime; global $bb_cfg, $theme, $lang, $DeltaTime;
@ -613,7 +613,7 @@ class user_common
/** /**
* Mark read * Mark read
*/ */
function mark_read ($type) public function mark_read ($type)
{ {
if ($type === 'all_forums') if ($type === 'all_forums')
{ {
@ -645,7 +645,7 @@ class user_common
/** /**
* Load misc options * Load misc options
*/ */
function load_opt_js () public function load_opt_js ()
{ {
if (IS_GUEST) if (IS_GUEST)
{ {
@ -665,7 +665,7 @@ class user_common
/** /**
* Get not auth forums * Get not auth forums
*/ */
function get_not_auth_forums ($auth_type) public function get_not_auth_forums ($auth_type)
{ {
global $datastore; global $datastore;
@ -725,7 +725,7 @@ class user_common
/** /**
* Get excluded forums * Get excluded forums
*/ */
function get_excluded_forums ($auth_type, $return_as = 'csv') public function get_excluded_forums ($auth_type, $return_as = 'csv')
{ {
$excluded = array(); $excluded = array();
@ -764,7 +764,7 @@ class user_common
/** /**
* Enqueue ads * Enqueue ads
*/ */
function enqueue_ads () public function enqueue_ads ()
{ {
global $datastore, $bb_cfg; global $datastore, $bb_cfg;

View file

@ -35,7 +35,7 @@ define('XS_TAG_BEGINELSE', 11);
class Template class Template
{ {
var $classname = "Template"; public $classname = "Template";
// variable that holds all the data we'll be substituting into // variable that holds all the data we'll be substituting into
// the compiled templates. // the compiled templates.
@ -45,76 +45,76 @@ class Template
// if it's a root-level variable, it'll be like this: // if it's a root-level variable, it'll be like this:
// $this->vars[varname] == value or $this->_tpldata['.'][0][varname] == value // $this->vars[varname] == value or $this->_tpldata['.'][0][varname] == value
// array "vars" is added for easier access to data // array "vars" is added for easier access to data
var $_tpldata = array('.' => array(0 => array())); public $_tpldata = array('.' => array(0 => array()));
var $vars; public $vars;
// Hash of filenames for each template handle. // Hash of filenames for each template handle.
var $files = array(); public $files = array();
var $files_cache = array(); // array of cache files that exists public $files_cache = array(); // array of cache files that exists
var $files_cache2 = array(); // array of cache files (exists or not exists) public $files_cache2 = array(); // array of cache files (exists or not exists)
// Root template directory. // Root template directory.
var $root = ''; public $root = '';
// Cache directory // Cache directory
var $cachedir = CACHE_DIR; public $cachedir = CACHE_DIR;
// Template root directory // Template root directory
var $tpldir = ''; public $tpldir = '';
// Default template directory. // Default template directory.
// If file for default template isn't found file from this template is used. // If file for default template isn't found file from this template is used.
var $tpldef = 'default'; public $tpldef = 'default';
// this will hash handle names to the compiled code for that handle. // this will hash handle names to the compiled code for that handle.
var $compiled_code = array(); public $compiled_code = array();
// This will hold the uncompiled code for that handle. // This will hold the uncompiled code for that handle.
var $uncompiled_code = array(); public $uncompiled_code = array();
// Cache settings // Cache settings
var $use_cache = 1; public $use_cache = 1;
var $cache_writable = 1; public $cache_writable = 1;
// Auto-compile setting // Auto-compile setting
var $auto_compile = 1; public $auto_compile = 1;
// Current template name // Current template name
var $tpl = ''; public $tpl = '';
var $cur_tpl = ''; public $cur_tpl = '';
// List of replacements. tpl files in this list will be replaced with other tpl files // List of replacements. tpl files in this list will be replaced with other tpl files
// according to configuration in xs.cfg // according to configuration in xs.cfg
var $replace = array(); public $replace = array();
// counter for include // counter for include
var $include_count = 0; public $include_count = 0;
// extension tpl-cache files // extension tpl-cache files
var $cached_tpl_ext = 'php'; public $cached_tpl_ext = 'php';
// eXtreme Styles variables // eXtreme Styles variables
var $xs_started = 0; public $xs_started = 0;
var $xs_version = 8; // number version. internal. do not change. public $xs_version = 8; // number version. internal. do not change.
var $xs_versiontxt = '2.3.1'; // text version public $xs_versiontxt = '2.3.1'; // text version
// These handles will be parsed if pparse() is executed. // These handles will be parsed if pparse() is executed.
// Can be used to automatically include header/footer if there is any content. // Can be used to automatically include header/footer if there is any content.
var $preparse = ''; public $preparse = '';
var $postparse = ''; public $postparse = '';
// subtemplates mod detection // subtemplates mod detection
var $subtemplates = false; public $subtemplates = false;
// style configuration // style configuration
var $style_config = array(); public $style_config = array();
var $lang = array(); public $lang = array();
/** /**
* Constructor. Installs XS mod on first run or updates it and sets the root dir. * Constructor. Installs XS mod on first run or updates it and sets the root dir.
*/ */
function Template($root = '.') public function __construct($root = '.')
{ {
global $bb_cfg, $lang; global $bb_cfg, $lang;
@ -132,7 +132,7 @@ class Template
* Destroys this template object. Should be called when you're done with it, in order * Destroys this template object. Should be called when you're done with it, in order
* to clear out the template data so you can load/parse a new template set. * to clear out the template data so you can load/parse a new template set.
*/ */
function destroy() public function destroy()
{ {
$this->_tpldata = array('.' => array(0 => array())); $this->_tpldata = array('.' => array(0 => array()));
$this->vars = &$this->_tpldata['.'][0]; $this->vars = &$this->_tpldata['.'][0];
@ -144,7 +144,7 @@ class Template
* be an absolute name, or a name relative to the rootdir for this Template * be an absolute name, or a name relative to the rootdir for this Template
* object. * object.
*/ */
function make_filename($filename, $xs_include = false) public function make_filename($filename, $xs_include = false)
{ {
// Check replacements list // Check replacements list
if(!$xs_include && isset($this->replace[$filename])) if(!$xs_include && isset($this->replace[$filename]))
@ -167,7 +167,7 @@ class Template
* Returns empty string if non-cachable (for tpl files outside of root dir). * Returns empty string if non-cachable (for tpl files outside of root dir).
* $filename should be absolute filename * $filename should be absolute filename
*/ */
function make_filename_cache ($filename) public function make_filename_cache ($filename)
{ {
$filename = clean_filename(str_replace(TEMPLATES_DIR, '', $filename)); $filename = clean_filename(str_replace(TEMPLATES_DIR, '', $filename));
@ -178,7 +178,7 @@ class Template
* Sets the template filenames for handles. $filename_array * Sets the template filenames for handles. $filename_array
* should be a hash of handle => filename pairs. * should be a hash of handle => filename pairs.
*/ */
function set_filenames ($filenames) public function set_filenames ($filenames)
{ {
foreach ($filenames as $handle => $filename) foreach ($filenames as $handle => $filename)
{ {
@ -189,7 +189,7 @@ class Template
/** /**
* Assigns template filename for handle. * Assigns template filename for handle.
*/ */
function set_filename($handle, $filename, $xs_include = false, $quiet = false) public function set_filename($handle, $filename, $xs_include = false, $quiet = false)
{ {
$can_cache = $this->use_cache; $can_cache = $this->use_cache;
$this->files[$handle] = $this->make_filename($filename, $xs_include); $this->files[$handle] = $this->make_filename($filename, $xs_include);
@ -241,7 +241,7 @@ class Template
/** /**
* includes file or executes code * includes file or executes code
*/ */
function execute($filename, $code, $handle) public function execute($filename, $code, $handle)
{ {
$this->cur_tpl = $filename; $this->cur_tpl = $filename;
@ -265,7 +265,7 @@ class Template
* and run the compiled code. This will print out * and run the compiled code. This will print out
* the results of executing the template. * the results of executing the template.
*/ */
function pparse($handle) public function pparse($handle)
{ {
// parsing header if there is one // parsing header if there is one
if($this->preparse || $this->postparse) if($this->preparse || $this->postparse)
@ -331,7 +331,7 @@ class Template
/** /**
* Precompile file * Precompile file
*/ */
function precompile($template, $filename) public function precompile($template, $filename)
{ {
global $precompile_num; global $precompile_num;
if(empty($precompile_num)) if(empty($precompile_num))
@ -389,7 +389,7 @@ class Template
* Note that all desired assignments to the variables in $handle should be done * Note that all desired assignments to the variables in $handle should be done
* BEFORE calling this function. * BEFORE calling this function.
*/ */
function assign_var_from_handle($varname, $handle) public function assign_var_from_handle($varname, $handle)
{ {
ob_start(); ob_start();
$res = $this->pparse($handle); $res = $this->pparse($handle);
@ -403,7 +403,7 @@ class Template
* variable assignments. Note that this should only be called once per block * variable assignments. Note that this should only be called once per block
* iteration. * iteration.
*/ */
function assign_block_vars($blockname, $vararray) public function assign_block_vars($blockname, $vararray)
{ {
if (strstr($blockname, '.')) if (strstr($blockname, '.'))
{ {
@ -437,7 +437,7 @@ class Template
* Root-level variable assignment. Adds to current assignments, overriding * Root-level variable assignment. Adds to current assignments, overriding
* any existing variable assignment with the same name. * any existing variable assignment with the same name.
*/ */
function assign_vars ($vararray) public function assign_vars ($vararray)
{ {
foreach ($vararray as $key => $val) foreach ($vararray as $key => $val)
{ {
@ -449,7 +449,7 @@ class Template
* Root-level variable assignment. Adds to current assignments, overriding * Root-level variable assignment. Adds to current assignments, overriding
* any existing variable assignment with the same name. * any existing variable assignment with the same name.
*/ */
function assign_var ($varname, $varval = true) public function assign_var ($varname, $varval = true)
{ {
$this->vars[$varname] = $varval; $this->vars[$varname] = $varval;
} }
@ -459,7 +459,7 @@ class Template
* Root-level. Adds to current assignments, appends * Root-level. Adds to current assignments, appends
* to any existing variable assignment with the same name. * to any existing variable assignment with the same name.
*/ */
function append_vars ($vararray) public function append_vars ($vararray)
{ {
foreach ($vararray as $key => $val) foreach ($vararray as $key => $val)
{ {
@ -471,7 +471,7 @@ class Template
* If not already done, load the file for the given handle and populate * If not already done, load the file for the given handle and populate
* the uncompiled_code[] hash with its code. Do not compile. * the uncompiled_code[] hash with its code. Do not compile.
*/ */
function loadfile($handle) public function loadfile($handle)
{ {
// If cached file exists do nothing - it will be included via include() // If cached file exists do nothing - it will be included via include()
if(!empty($this->files_cache[$handle])) if(!empty($this->files_cache[$handle]))
@ -510,7 +510,7 @@ class Template
* It's ready to be inserted into an "echo" line in one of the templates. * It's ready to be inserted into an "echo" line in one of the templates.
* NOTE: expects a trailing "." on the namespace. * NOTE: expects a trailing "." on the namespace.
*/ */
function generate_block_varref($namespace, $varname) public function generate_block_varref($namespace, $varname)
{ {
// Strip the trailing period. // Strip the trailing period.
$namespace = substr($namespace, 0, strlen($namespace) - 1); $namespace = substr($namespace, 0, strlen($namespace) - 1);
@ -535,7 +535,7 @@ class Template
* If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above. * If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above.
* NOTE: does not expect a trailing "." on the blockname. * NOTE: does not expect a trailing "." on the blockname.
*/ */
function generate_block_data_ref($blockname, $include_last_iterator) public function generate_block_data_ref($blockname, $include_last_iterator)
{ {
// Get an array of the blocks involved. // Get an array of the blocks involved.
$blocks = explode('.', $blockname); $blocks = explode('.', $blockname);
@ -550,7 +550,7 @@ class Template
} }
} }
function compile_code($filename, $code) public function compile_code($filename, $code)
{ {
// $filename - file to load code from. used if $code is empty // $filename - file to load code from. used if $code is empty
// $code - tpl code // $code - tpl code
@ -905,7 +905,7 @@ class Template
/* /*
* Compile code between tags * Compile code between tags
*/ */
function _compile_text($code) public function _compile_text($code)
{ {
if(strlen($code) < 3) if(strlen($code) < 3)
{ {
@ -942,7 +942,7 @@ class Template
// Compile IF tags - much of this is from Smarty with // Compile IF tags - much of this is from Smarty with
// some adaptions for our block level methods // some adaptions for our block level methods
// //
function compile_tag_if($tag_args, $elseif) public function compile_tag_if($tag_args, $elseif)
{ {
/* Tokenize args for 'if' tag. */ /* Tokenize args for 'if' tag. */
preg_match_all('/(?: preg_match_all('/(?:
@ -1066,7 +1066,7 @@ class Template
} }
// This is from Smarty // This is from Smarty
function _parse_is_expr($is_arg, $tokens) public function _parse_is_expr($is_arg, $tokens)
{ {
$expr_end = 0; $expr_end = 0;
$negate_expr = false; $negate_expr = false;
@ -1135,7 +1135,7 @@ class Template
/** /**
* Compiles code and writes to cache if needed * Compiles code and writes to cache if needed
*/ */
function compile2($code, $handle, $cache_file) public function compile2($code, $handle, $cache_file)
{ {
$code = $this->compile_code('', $code, XS_USE_ISSET); $code = $this->compile_code('', $code, XS_USE_ISSET);
if ($cache_file && !empty($this->use_cache) && !empty($this->auto_compile)) if ($cache_file && !empty($this->use_cache) && !empty($this->auto_compile))
@ -1158,7 +1158,7 @@ class Template
* for use in assign_code_from_handle(). * for use in assign_code_from_handle().
* This function isn't used and kept only for compatibility with original template.php * This function isn't used and kept only for compatibility with original template.php
*/ */
function compile($code, $do_not_echo = false, $retvar = '') public function compile($code, $do_not_echo = false, $retvar = '')
{ {
$code = ' ?'.'>' . $this->compile_code('', $code, true) . '<'."?php \n"; $code = ' ?'.'>' . $this->compile_code('', $code, true) . '<'."?php \n";
if ($do_not_echo) if ($do_not_echo)
@ -1171,12 +1171,12 @@ class Template
/** /**
* Write cache to disk * Write cache to disk
*/ */
function write_cache($filename, $code) public function write_cache($filename, $code)
{ {
file_write($code, $filename, false, true, true); file_write($code, $filename, false, true, true);
} }
function xs_startup() public function xs_startup()
{ {
global $bb_cfg; global $bb_cfg;
@ -1197,7 +1197,7 @@ class Template
} }
} }
function lang_error($var) public function lang_error($var)
{ {
trigger_error(basename($this->cur_tpl) ." : undefined language variable {L_{$var}}", E_USER_WARNING); trigger_error(basename($this->cur_tpl) ." : undefined language variable {L_{$var}}", E_USER_WARNING);
return "Undefined: {L_{$var}}"; return "Undefined: {L_{$var}}";

View file

@ -497,7 +497,7 @@ foreach ($topic_rowset as $topic)
'TOR_STATUS_ICON' => isset($topic['tor_status']) ? $bb_cfg['tor_icons'][$topic['tor_status']] : '', 'TOR_STATUS_ICON' => isset($topic['tor_status']) ? $bb_cfg['tor_icons'][$topic['tor_status']] : '',
'TOR_STATUS_TEXT' => isset($topic['tor_status']) ? $lang['TOR_STATUS_NAME'][$topic['tor_status']] : '', 'TOR_STATUS_TEXT' => isset($topic['tor_status']) ? $lang['TOR_STATUS_NAME'][$topic['tor_status']] : '',
'ATTACH' => $topic['topic_attachment'], 'ATTACH' => isset($topic['topic_attachment']) ? $topic['topic_attachment'] : false,
'STATUS' => $topic['topic_status'], 'STATUS' => $topic['topic_status'],
'TYPE' => $topic['topic_type'], 'TYPE' => $topic['topic_type'],
'DL' => ($topic['topic_dl_type'] == TOPIC_DL_TYPE_DL && !$forum_data['allow_reg_tracker']), 'DL' => ($topic['topic_dl_type'] == TOPIC_DL_TYPE_DL && !$forum_data['allow_reg_tracker']),

View file

@ -131,7 +131,7 @@ if ($userdata['session_admin'] && !empty($_REQUEST['mod']))
$datastore->enqueue(array('viewtopic_forum_select')); $datastore->enqueue(array('viewtopic_forum_select'));
} }
} }
if ($t_data['topic_attachment']) if (isset($t_data['topic_attachment']))
{ {
$datastore->enqueue(array( $datastore->enqueue(array(
'attach_extensions', 'attach_extensions',
@ -604,7 +604,7 @@ $template->assign_vars(array(
)); ));
require(INC_DIR .'torrent_show_dl_list.php'); require(INC_DIR .'torrent_show_dl_list.php');
if ($t_data['topic_attachment']) if (isset($t_data['topic_attachment']))
{ {
require(ATTACH_DIR .'attachment_mod.php'); require(ATTACH_DIR .'attachment_mod.php');
init_display_post_attachments($t_data['topic_attachment']); init_display_post_attachments($t_data['topic_attachment']);
@ -722,10 +722,24 @@ for($i = 0; $i < $total_posts; $i++)
{ {
if ($user_sig) if ($user_sig)
{ {
$user_sig = str_replace('\"', '"', substr(@preg_replace('#(\>(((?>([^><]+|(?R)))*)\<))#se', "@preg_replace(\$orig_word, \$replacement_word, '\\0')", '>' . $user_sig . '<'), 1, -1)); $user_sig = str_replace(
'\"', '"',
substr(
preg_replace_callback('#(\>(((?>([^><]+|(?R)))*)\<))#s', function ($matches) use ($orig_word, $replacement_word) {
return preg_replace($orig_word, $replacement_word, $matches[0]);
}, '>' . $user_sig . '<'), 1, -1
)
);
} }
$message = str_replace('\"', '"', substr(@preg_replace('#(\>(((?>([^><]+|(?R)))*)\<))#se', "@preg_replace(\$orig_word, \$replacement_word, '\\0')", '>' . $message . '<'), 1, -1)); $message = str_replace(
'\"', '"',
substr(
preg_replace_callback('#(\>(((?>([^><]+|(?R)))*)\<))#s', function ($matches) use ($orig_word, $replacement_word) {
return preg_replace($orig_word, $replacement_word, $matches[0]);
}, '>' . $message . '<'), 1, -1
)
);
} }
// Replace newlines (we use this rather than nl2br because till recently it wasn't XHTML compliant) // Replace newlines (we use this rather than nl2br because till recently it wasn't XHTML compliant)
@ -825,7 +839,7 @@ for($i = 0; $i < $total_posts; $i++)
'RG_SIG_ATTACH' => $postrow[$i]['attach_rg_sig'], 'RG_SIG_ATTACH' => $postrow[$i]['attach_rg_sig'],
)); ));
if ($postrow[$i]['post_attachment'] && $is_auth['auth_download'] && function_exists('display_post_attachments')) if (isset($postrow[$i]['post_attachment']) && $is_auth['auth_download'] && function_exists('display_post_attachments'))
{ {
display_post_attachments($post_id, $postrow[$i]['post_attachment']); display_post_attachments($post_id, $postrow[$i]['post_attachment']);
} }