diff --git a/README.md b/README.md
index 078474aa4..6441d6622 100644
--- a/README.md
+++ b/README.md
@@ -13,9 +13,9 @@
## About TorrentPier
-TorrentPier - bull-powered BitTorrent tracker engine, written in php. High speed, simple modification, high load
+TorrentPier — bull-powered BitTorrent tracker engine, written in php. High speed, simple modification, high load
architecture, built-in support for alternative compiled announcers (Ocelot, XBT). In addition we have very helpful
-[official support forum](https://torrentpier.me/forum) , where among other things it is possible to test the live
+[official support forum](https://torrentpier.me/forum), where among other things it is possible to test the live
demo, get any support and download modifications for engine.
## Current status
@@ -29,6 +29,7 @@ and go from there. The documentation will be translated into english in the near
* Apache / nginx
* MySQL / MariaDB / Percona
* PHP: 5.5 / 5.6 / 7.0 / 7.1
+* PHP Extensions: bcmath, intl, tidy (optional)
## Installation
@@ -37,7 +38,7 @@ For installation you need to follow a few simple steps:
1. Распаковываем на сервер содержимое скачанной вами папки
1. Создаем базу данных, в которую при помощи phpmyadmin (или любого другого удобного инструмента) импортируем дамп, расположенный в папке **install/sql/mysql.sql**
1. Правим файл конфигурации **library/config.php**, загруженный на сервер:
-> ***'db1' => array('localhost', 'tp_216', 'user', 'pass', $charset, $pconnect)***
+> ***'db' => array('localhost', 'tp_216', 'user', 'pass', $charset, $pconnect)***
В данной строке изменяем данные входа в базу данных
***$domain_name = 'torrentpier.me';***
В данной строке указываем ваше доменное имя. Остальные правки в файле вносятся по усмотрению, исходя из необходимости из внесения (ориентируйтесь на описания, указанные у полей).
diff --git a/admin/admin_bt_forum_cfg.php b/admin/admin_bt_forum_cfg.php
index 3502dff46..9c58313f0 100644
--- a/admin/admin_bt_forum_cfg.php
+++ b/admin/admin_bt_forum_cfg.php
@@ -132,16 +132,16 @@ foreach ($db_fields_bool as $field_name => $field_def_val) {
foreach ($rowset as $rid => $forum) {
foreach ($db_fields_bool as $field_name => $field_def_val) {
$forum_name = $forum['forum_name'];
- $selected = ($forum[$field_name]) ? ' selected="selected"' : '';
+ $selected = $forum[$field_name] ? ' selected="selected"' : '';
$forum_name = str_short($forum_name, $max_forum_name_len);
- $$field_name .= '\n";
+ $$field_name .= '\n";
}
}
foreach ($db_fields_bool as $field_name => $field_def_val) {
- $$field_name = '';
+ $$field_name = '';
$template->assign_vars(array('S_' . strtoupper($field_name) => $$field_name));
}
diff --git a/admin/admin_log.php b/admin/admin_log.php
index db6a6f4a6..a15053c59 100644
--- a/admin/admin_log.php
+++ b/admin/admin_log.php
@@ -302,7 +302,7 @@ if ($log_rowset) {
'USER_ID' => $row['log_user_id'],
'USERNAME' => $row['log_username'],
'USER_HREF_S' => url_arg($url, $user_key, $row['log_user_id']),
- 'USER_IP' => decode_ip($row['log_user_ip']),
+ 'USER_IP' => Longman\IPTools\Ip::isValid($row['log_user_ip']) ? decode_ip($row['log_user_ip']) : '127.0.0.1',
'FORUM_ID' => $row['log_forum_id'],
'FORUM_HREF' => BB_ROOT . FORUM_URL . $row['log_forum_id'],
diff --git a/admin/admin_user_ban.php b/admin/admin_user_ban.php
index 96ac84fa7..f5cc03faf 100644
--- a/admin/admin_user_ban.php
+++ b/admin/admin_user_ban.php
@@ -35,7 +35,7 @@ if (isset($_POST['submit'])) {
$email_bansql = '';
$ip_bansql = '';
- $user_list = array();
+ $user_list = [];
if (!empty($_POST['username'])) {
$this_userdata = get_userdata($_POST['username'], true);
if (!$this_userdata) {
@@ -45,73 +45,18 @@ if (isset($_POST['submit'])) {
$user_list[] = $this_userdata['user_id'];
}
- $ip_list = array();
+ $ip_list = [];
if (isset($_POST['ban_ip'])) {
$ip_list_temp = explode(',', $_POST['ban_ip']);
- for ($i = 0, $iMax = count($ip_list_temp); $i < $iMax; $i++) {
- if (preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/', trim($ip_list_temp[$i]), $ip_range_explode)) {
- $ip_1_counter = $ip_range_explode[1];
- $ip_1_end = $ip_range_explode[5];
-
- while ($ip_1_counter <= $ip_1_end) {
- $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
- $ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
-
- if ($ip_2_counter == 0 && $ip_2_end == 254) {
- $ip_2_counter = 255;
- $ip_2_fragment = 255;
-
- $ip_list[] = encode_ip("$ip_1_counter.255.255.255");
- }
-
- while ($ip_2_counter <= $ip_2_end) {
- $ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
- $ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
-
- if ($ip_3_counter == 0 && $ip_3_end == 254) {
- $ip_3_counter = 255;
- $ip_3_fragment = 255;
-
- $ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.255.255");
- }
-
- while ($ip_3_counter <= $ip_3_end) {
- $ip_4_counter = ($ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[4] : 0;
- $ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
-
- if ($ip_4_counter == 0 && $ip_4_end == 254) {
- $ip_4_counter = 255;
- $ip_4_fragment = 255;
-
- $ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.255");
- }
-
- while ($ip_4_counter <= $ip_4_end) {
- $ip_list[] = encode_ip("$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter");
- $ip_4_counter++;
- }
- $ip_3_counter++;
- }
- $ip_2_counter++;
- }
- $ip_1_counter++;
- }
- } elseif (preg_match('/^([\w\-_]\.?){2,}$/is', trim($ip_list_temp[$i]))) {
- $ip = gethostbynamel(trim($ip_list_temp[$i]));
-
- for ($j = 0, $jMax = count($ip); $j < $jMax; $j++) {
- if (!empty($ip[$j])) {
- $ip_list[] = encode_ip($ip[$j]);
- }
- }
- } elseif (preg_match('/^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$/', trim($ip_list_temp[$i]))) {
- $ip_list[] = encode_ip(str_replace('*', '255', trim($ip_list_temp[$i])));
+ foreach ($ip_list_temp as $ip) {
+ if (Longman\IPTools\Ip::isValid($ip)) {
+ $ip_list[] = encode_ip($ip);
}
}
}
- $email_list = array();
+ $email_list = [];
if (isset($_POST['ban_email'])) {
$email_list_temp = explode(',', $_POST['ban_email']);
@@ -269,7 +214,7 @@ if (isset($_POST['submit'])) {
$select_userlist = '';
}
- $select_userlist = '';
+ $select_userlist = '';
$sql = "SELECT ban_id, ban_ip, ban_email FROM " . BB_BANLIST . " ORDER BY ban_ip";
if (!($result = DB()->sql_query($sql))) {
@@ -304,8 +249,8 @@ if (isset($_POST['submit'])) {
$select_emaillist = '';
}
- $select_iplist = '';
- $select_emaillist = '';
+ $select_iplist = '';
+ $select_emaillist = '';
$template->assign_vars(array(
'U_SEARCH_USER' => './../search.php?mode=searchuser',
diff --git a/admin/admin_user_search.php b/admin/admin_user_search.php
index a5b651f06..4a6f66a83 100644
--- a/admin/admin_user_search.php
+++ b/admin/admin_user_search.php
@@ -314,35 +314,11 @@ if (!isset($_REQUEST['dosearch'])) {
$text = sprintf($lang['SEARCH_FOR_IP'], strip_tags(htmlspecialchars(stripslashes($ip_address))));
unset($users);
- $users = array();
+ $users = [];
- // Let's see if they entered a full valid IPv4 address
- if (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) {
+ if (Longman\IPTools\Ip::isValid($ip_address)) {
$ip = encode_ip($ip_address);
$users[] = $ip;
- } elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){0,2}\.\*/', $ip_address)) {
- $ip_split = explode('.', $ip_address);
- switch (count($ip_split)) {
- case 4:
- $users[] = encode_ip($ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".255");
- break;
- case 3:
- $users[] = encode_ip($ip_split[0] . "." . $ip_split[1] . ".255.255");
- break;
- case 2:
- $users[] = encode_ip($ip_split[0] . ".255.255.255");
- break;
- }
- } elseif (preg_match('/^([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}(\s)*-(\s)*([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/', $ip_address)) {
- $range = preg_split('/[-\s]+/', $ip_address);
- $start_range = explode('.', $range[0]);
- $end_range = explode('.', $range[1]);
- if (($start_range[0] . $start_range[1] . $start_range[2] != $end_range[0] . $end_range[1] . $end_range[2]) || ($start_range[3] > $end_range[3])) {
- bb_die($lang['SEARCH_INVALID_IP']);
- }
- for ($i = $start_range[3]; $i <= $end_range[3]; $i++) {
- $users[] = encode_ip($start_range[0] . "." . $start_range[1] . "." . $start_range[2] . "." . $i);
- }
} else {
bb_die($lang['SEARCH_INVALID_IP']);
}
@@ -350,25 +326,12 @@ if (!isset($_REQUEST['dosearch'])) {
$ip_in_sql = $ip_like_sql = $ip_like_sql_flylast = $ip_like_sql_flyreg = '';
foreach ($users as $address) {
- if (preg_match('/(ff){1,3}$/i', $address)) {
- if (preg_match('/[0-9a-f]{2}ffffff/i', $address)) {
- $ip_start = substr($address, 0, 2);
- } elseif (preg_match('/[0-9a-f]{4}ffff/i', $address)) {
- $ip_start = substr($address, 0, 4);
- } elseif (preg_match('/[0-9a-f]{6}ff/i', $address)) {
- $ip_start = substr($address, 0, 6);
- }
- $ip_like_sql_flylast = $ip_like_sql . ($ip_like_sql != '') ? " OR user_last_ip LIKE '" . $ip_start . "%'" : "user_last_ip LIKE '" . $ip_start . "%'";
- $ip_like_sql_flyreg = $ip_like_sql . ($ip_like_sql != '') ? " OR user_reg_ip LIKE '" . $ip_start . "%'" : "user_reg_ip LIKE '" . $ip_start . "%'";
- $ip_like_sql .= ($ip_like_sql != '') ? " OR poster_ip LIKE '" . $ip_start . "%'" : "poster_ip LIKE '" . $ip_start . "%'";
- } else {
- $ip_in_sql .= ($ip_in_sql == '') ? "'$address'" : ", '$address'";
- }
+ $ip_in_sql .= ($ip_in_sql == '') ? "'$address'" : ", '$address'";
}
$where_sql = '';
- $where_sql .= ($ip_in_sql != '') ? "poster_ip IN ($ip_in_sql)" : "";
- $where_sql .= ($ip_like_sql != '') ? ($where_sql != "") ? " OR $ip_like_sql" : "$ip_like_sql" : "";
+ $where_sql .= ($ip_in_sql != '') ? "poster_ip IN ($ip_in_sql)" : '';
+ $where_sql .= ($ip_like_sql != '') ? ($where_sql != "") ? " OR $ip_like_sql" : "$ip_like_sql" : '';
if (!$where_sql) {
bb_die('invalid request');
diff --git a/admin/pagestart.php b/admin/pagestart.php
index 11874c1ca..2290522b0 100644
--- a/admin/pagestart.php
+++ b/admin/pagestart.php
@@ -24,7 +24,6 @@
*/
define('BB_ROOT', './../');
-define('IN_FORUM', true);
define('IN_ADMIN', true);
require dirname(__DIR__) . '/common.php';
diff --git a/callseed.php b/callseed.php
index d71714316..ac56f2f18 100644
--- a/callseed.php
+++ b/callseed.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'callseed');
define('BB_ROOT', './');
require __DIR__ . '/common.php';
diff --git a/common.php b/common.php
index eafc2712b..084acf3c6 100644
--- a/common.php
+++ b/common.php
@@ -47,12 +47,17 @@ if (empty($_SERVER['SERVER_NAME'])) {
if (!defined('BB_ROOT')) {
define('BB_ROOT', './');
}
-if (!defined('IN_FORUM') && !defined('IN_TRACKER')) {
- define('IN_FORUM', true);
-}
header('X-Frame-Options: SAMEORIGIN');
+// Cloudflare
+if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
+ $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
+}
+
+// Get all constants
+require_once __DIR__ . '/library/defines.php';
+
// Composer
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
die('Please install composer and run composer install
');
@@ -60,7 +65,7 @@ if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
// Get initial config
-require __DIR__ . '/library/config.php';
+require_once __DIR__ . '/library/config.php';
// Bugsnag error reporting
if ($bb_cfg['bugsnag']['enabled'] && !empty($bb_cfg['bugsnag']['api_key'])) {
@@ -78,7 +83,7 @@ unset($server_protocol, $server_port);
// Debug options
define('DBG_USER', (isset($_COOKIE[COOKIE_DBG])));
-// Board/Tracker shared constants and functions
+// Board / tracker shared constants and functions
define('BB_BT_TORRENTS', 'bb_bt_torrents');
define('BB_BT_TRACKER', 'bb_bt_tracker');
define('BB_BT_TRACKER_SNAP', 'bb_bt_tracker_snap');
@@ -108,7 +113,7 @@ define('BOT_UID', -746);
*/
$DBS = new TorrentPier\Legacy\Dbs($bb_cfg);
-function DB($db_alias = 'db1')
+function DB($db_alias = 'db')
{
global $DBS;
return $DBS->get_db_obj($db_alias);
@@ -197,7 +202,7 @@ function file_write($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $replac
{
$bytes_written = false;
- if ($max_size && @filesize($file) >= $max_size) {
+ if ($max_size && file_exists($file) && filesize($file) >= $max_size) {
$old_name = $file;
$ext = '';
if (preg_match('#^(.+)(\.[^\\/]+)$#', $file, $matches)) {
@@ -206,25 +211,25 @@ function file_write($str, $file, $max_size = LOG_MAX_SIZE, $lock = true, $replac
}
$new_name = $old_name . '_[old]_' . date('Y-m-d_H-i-s_') . getmypid() . $ext;
clearstatcache();
- if (@file_exists($file) && @filesize($file) >= $max_size && !@file_exists($new_name)) {
- @rename($file, $new_name);
+ if (!file_exists($new_name)) {
+ rename($file, $new_name);
}
}
- if (!$fp = @fopen($file, 'ab')) {
+ if (!$fp = fopen($file, 'ab')) {
if ($dir_created = bb_mkdir(dirname($file))) {
- $fp = @fopen($file, 'ab');
+ $fp = fopen($file, 'ab');
}
}
if ($fp) {
if ($lock) {
- @flock($fp, LOCK_EX);
+ flock($fp, LOCK_EX);
}
if ($replace_content) {
- @ftruncate($fp, 0);
- @fseek($fp, 0, SEEK_SET);
+ ftruncate($fp, 0);
+ fseek($fp, 0, SEEK_SET);
}
- $bytes_written = @fwrite($fp, $str);
- @fclose($fp);
+ $bytes_written = fwrite($fp, $str);
+ fclose($fp);
}
return $bytes_written;
@@ -258,28 +263,35 @@ function clean_filename($fname)
return str_replace($s, '_', str_compact($fname));
}
+/**
+ * Декодирование оригинального IP
+ * @param $ip
+ * @return string
+ */
function encode_ip($ip)
{
- $d = explode('.', $ip);
- return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]);
+ return Longman\IPTools\Ip::ip2long($ip);
}
+/**
+ * Восстановление декодированного IP
+ * @param $ip
+ * @return string
+ */
function decode_ip($ip)
{
- return long2ip("0x{$ip}");
+ return Longman\IPTools\Ip::long2ip($ip);
}
-function ip2int($ip)
+/**
+ * Проверка IP на валидность
+ *
+ * @param $ip
+ * @return bool
+ */
+function verify_ip($ip)
{
- return (float)sprintf('%u', ip2long($ip)); // для совместимости с 32 битными системами
-}
-
-// long2ip( mask_ip_int(ip2int('1.2.3.4'), 24) ) = '1.2.3.255'
-function mask_ip_int($ip, $mask)
-{
- $ip_int = is_numeric($ip) ? $ip : ip2int($ip);
- $ip_masked = $ip_int | ((1 << (32 - $mask)) - 1);
- return (float)sprintf('%u', $ip_masked);
+ return Longman\IPTools\Ip::isValid($ip);
}
function bb_crc32($str)
@@ -292,11 +304,6 @@ function hexhex($value)
return dechex(hexdec($value));
}
-function verify_ip($ip)
-{
- return preg_match('#^(\d{1,3}\.){3}\d{1,3}$#', $ip);
-}
-
function str_compact($str)
{
return preg_replace('#\s+#u', ' ', trim($str));
@@ -407,12 +414,11 @@ function log_request($file = '', $prepend_str = false, $add_post = true)
bb_log($str, $file);
}
-// Board init
-if (defined('IN_FORUM')) {
+// Board or tracker init
+if (!defined('IN_TRACKER')) {
require INC_DIR . '/init_bb.php';
-} // Tracker init
-elseif (defined('IN_TRACKER')) {
- define('DUMMY_PEER', pack('Nn', ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? (int) $_GET['port'] : mt_rand(1000, 65000)));
+} else {
+ define('DUMMY_PEER', pack('Nn', ip2long($_SERVER['REMOTE_ADDR']), !empty($_GET['port']) ? (int)$_GET['port'] : mt_rand(1000, 65000)));
function dummy_exit($interval = 1800)
{
diff --git a/composer.json b/composer.json
index 027a40233..21093c36c 100644
--- a/composer.json
+++ b/composer.json
@@ -1,6 +1,6 @@
{
"name": "torrentpier/torrentpier",
- "description": "TorrentPier. Bittorrent-tracker engine",
+ "description": "TorrentPier. Bull-powered BitTorrent tracker engine",
"type": "project",
"keywords": [
"bittorrent",
@@ -32,7 +32,6 @@
"email": "support@torrentpier.me",
"issues": "https://github.com/torrentpier/torrentpier/issues",
"forum": "https://torrentpier.me/forum/",
- "get": "https://get.torrentpier.me/",
"docs": "https://docs.torrentpier.me/"
},
"require": {
@@ -40,6 +39,7 @@
"bugsnag/bugsnag": "^3.0",
"gigablah/sphinxphp": "^2.0",
"google/recaptcha": "^1.0",
+ "longman/ip-tools": "^1.2",
"roave/security-advisories": "dev-master",
"rych/bencode": "^1.0",
"swiftmailer/swiftmailer": "^5.4"
diff --git a/dl.php b/dl.php
index 6e8223518..c61f6f4c3 100644
--- a/dl.php
+++ b/dl.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'dl');
define('NO_GZIP', true);
define('BB_ROOT', './');
diff --git a/dl_list.php b/dl_list.php
index 48706c0d5..8a06777e3 100644
--- a/dl_list.php
+++ b/dl_list.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'dl_list');
define('BB_ROOT', './');
require __DIR__ . '/common.php';
diff --git a/feed.php b/feed.php
index d7de75514..3f2ad3c51 100644
--- a/feed.php
+++ b/feed.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'feed');
define('BB_ROOT', './');
require __DIR__ . '/common.php';
diff --git a/group.php b/group.php
index 62a57df1d..cdb6772c5 100644
--- a/group.php
+++ b/group.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'group');
define('BB_ROOT', './');
require __DIR__ . '/common.php';
diff --git a/group_edit.php b/group_edit.php
index 960fc3b1c..6d3c3fe38 100644
--- a/group_edit.php
+++ b/group_edit.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'group_edit');
define('BB_ROOT', './');
require __DIR__ . '/common.php';
diff --git a/index.php b/index.php
index ed60a32bf..7cceaad50 100644
--- a/index.php
+++ b/index.php
@@ -23,7 +23,6 @@
* SOFTWARE.
*/
-define('IN_FORUM', true);
define('BB_SCRIPT', 'index');
define('BB_ROOT', './');
require __DIR__ . '/common.php';
diff --git a/install/upgrade/r496-user_birthday.php b/install/upgrade/r496-user_birthday.php
deleted file mode 100644
index 4e451b3e2..000000000
--- a/install/upgrade/r496-user_birthday.php
+++ /dev/null
@@ -1,60 +0,0 @@
-session_start();
-
-set_die_append_msg();
-if (!IS_SUPER_ADMIN) {
- bb_die($lang['ONLY_FOR_SUPER_ADMIN']);
-}
-
-$confirm = request_var('confirm', '');
-
-if ($confirm) {
- DB()->query("ALTER TABLE " . BB_USERS . " CHANGE COLUMN user_birthday user_birthday_old int(11) NOT NULL DEFAULT 0 AFTER user_gender");
- DB()->query("ALTER TABLE " . BB_USERS . " ADD user_birthday date NOT NULL DEFAULT '0000-00-00' AFTER user_gender");
-
- $sql = "SELECT user_id, user_birthday_old FROM " . BB_USERS . " WHERE user_birthday_old != 0 AND user_id NOT IN ('" . EXCLUDED_USERS_CSV . "')";
-
- foreach (DB()->fetch_rowset($sql) as $row) {
- $birthday = bb_date($row['user_birthday_old'] * 86400 + 1, 'Y-m-d', 0);
- DB()->query("UPDATE " . BB_USERS . " SET user_birthday = '" . $birthday . "' WHERE user_id = " . $row['user_id'] . "");
- }
-
- DB()->query("ALTER TABLE " . BB_USERS . " DROP user_birthday_old");
-
- bb_die('
\n"; - - while (true) { - set_time_limit(600); - echo "$start [ $avatars_ok / $avatars_err ]\n"; - $end = $start + $rows_per_cycle - 1; - $sql = " - SELECT user_id, avatar_ext_id, user_avatar - FROM " . BB_USERS . " - WHERE user_avatar != '' - AND avatar_ext_id = 0 - AND user_id BETWEEN $start AND $end - ORDER BY NULL - "; - - foreach (DB()->fetch_rowset($sql) as $row) { - $FILE = array( - 'name' => '', - 'type' => '', - 'size' => 0, - 'tmp_name' => BB_ROOT . $bb_cfg['avatar_path'] . '/' . basename($row['user_avatar']), - 'error' => 0, - ); - $upload = new TorrentPier\Legacy\Common\Upload(); - - if ($upload->init($bb_cfg['avatars'], $FILE, false) and $upload->store('avatar', $row)) { - DB()->query("UPDATE " . BB_USERS . " SET avatar_ext_id = {$upload->file_ext_id} WHERE user_id = {$row['user_id']} LIMIT 1"); - $avatars_ok++; - } else { - echo "{$row['user_id']}: ", implode("\n{$row['user_id']}: ", $upload->errors), "\n"; - $avatars_err++; - } - } - - if ($end > $end_id) { - break; - } - $start += $rows_per_cycle; - sleep(1); - } - - echo "---------- База данных успешно обновлена. Аватары указанных выше пользователей перенесены не были. ----------\n"; - - DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar`"); - DB()->query("ALTER TABLE " . BB_USERS . " DROP `user_avatar_type`"); -} else { - $msg = ''; - - bb_die($msg); -} diff --git a/install/upgrade/r588-short_lang.php b/install/upgrade/r588-short_lang.php deleted file mode 100644 index 0e6bd0c76..000000000 --- a/install/upgrade/r588-short_lang.php +++ /dev/null @@ -1,77 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) { - bb_die($lang['ONLY_FOR_SUPER_ADMIN']); -} - -$confirm = request_var('confirm', ''); - -if ($confirm) { - DB()->query("UPDATE " . BB_CONFIG . " SET `config_value` = 'ru' WHERE `config_name` = 'default_lang'"); - DB()->query("ALTER TABLE " . BB_USERS . " ADD `user_twitter` varchar (15) NOT NULL DEFAULT '' AFTER `user_skype`"); - - $rows_per_cycle = 10000; - - $row = DB()->fetch_row("SELECT MAX(user_id) AS end_id FROM " . BB_USERS); - $end_id = (int)$row['end_id']; - $start = 0; - - while (true) { - set_time_limit(600); - $end = $start + $rows_per_cycle - 1; - - DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'ru' WHERE user_lang = 'russian'"); - DB()->query("UPDATE " . BB_USERS . " SET user_lang = 'en' WHERE user_lang = 'english'"); - - if ($end > $end_id) { - break; - } - $start += $rows_per_cycle; - sleep(1); - } - - bb_die("База данных успешно обновлена. Можно приступать к обновлению файлов. Не забудьте удалить этот файл."); -} else { - $msg = ''; - - bb_die($msg); -} diff --git a/install/upgrade/r600-stable.php b/install/upgrade/r600-stable.php deleted file mode 100644 index 91bdd591e..000000000 --- a/install/upgrade/r600-stable.php +++ /dev/null @@ -1,247 +0,0 @@ -session_start(); - -set_die_append_msg(); -if (!IS_SUPER_ADMIN) { - bb_die($lang['ONLY_FOR_SUPER_ADMIN']); -} - -bb_die(' -
' . (($title) ? "$title\n\n" : '') . htmlspecialchars(print_r($var, true)) . ''; + $r = '
' . ($title ? "$title\n\n" : '') . htmlspecialchars(print_r($var, true)) . ''; if ($print) { echo $r; } return $r; } -function pre($var, $title = '', $print = true) -{ - prn_r($var, $title, $print); -} - -function prn() -{ - if (!DBG_USER) { - return; - } - foreach (func_get_args() as $var) { - prn_r($var); - } -} - -function vdump($var, $title = '') -{ - echo '
' . (($title) ? "$title\n\n" : ''); - var_dump($var); - echo ''; -} - +/** + * @param $txt + * @param bool $double_encode + * @param int $quote_style + * @param string $charset + * @return string + */ function htmlCHR($txt, $double_encode = false, $quote_style = ENT_QUOTES, $charset = 'UTF-8') { return (string)htmlspecialchars($txt, $quote_style, $charset, $double_encode); } +/** + * @param $txt + * @param int $quote_style + * @param string $charset + * @return string + */ function html_ent_decode($txt, $quote_style = ENT_QUOTES, $charset = 'UTF-8') { return (string)html_entity_decode($txt, $quote_style, $charset); } +/** + * @param string $path + * @return string + */ function make_url($path = '') { return FULL_URL . preg_replace('#^\/?(.*?)\/?$#', '\1', $path); @@ -453,9 +468,6 @@ function make_url($path = '') require INC_DIR . '/functions.php'; require INC_DIR . '/sessions.php'; -require INC_DIR . '/template.php'; - -define('SQL_LAYER', 'mysql'); $bb_cfg = array_merge(bb_get_config(BB_CONFIG), $bb_cfg); @@ -505,22 +517,6 @@ if ((empty($_POST) && !defined('IN_ADMIN') && !defined('IN_AJAX') && !file_exist } } -$dl_link_css = array( - DL_STATUS_RELEASER => 'genmed', - DL_STATUS_WILL => 'dlWill', - DL_STATUS_DOWN => 'leechmed', - DL_STATUS_COMPLETE => 'seedmed', - DL_STATUS_CANCEL => 'dlCancel', -); - -$dl_status_css = array( - DL_STATUS_RELEASER => 'genmed', - DL_STATUS_WILL => 'dlWill', - DL_STATUS_DOWN => 'dlDown', - DL_STATUS_COMPLETE => 'dlComplete', - DL_STATUS_CANCEL => 'dlCancel', -); - // Exit if board is disabled via ON/OFF trigger or by admin if (($bb_cfg['board_disable'] || file_exists(BB_DISABLED)) && !defined('IN_ADMIN') && !defined('IN_AJAX') && !defined('IN_LOGIN')) { header('HTTP/1.0 503 Service Unavailable'); @@ -536,7 +532,9 @@ if (($bb_cfg['board_disable'] || file_exists(BB_DISABLED)) && !defined('IN_ADMIN } } -// Cron functions +/** + * Снятие блокировки крона + */ function cron_release_deadlock() { if (file_exists(CRON_RUNNING)) { @@ -547,23 +545,39 @@ function cron_release_deadlock() } } +/** + * Блокировка крона + */ function cron_release_file_lock() { - $lock_released = @rename(CRON_RUNNING, CRON_ALLOWED); + rename(CRON_RUNNING, CRON_ALLOWED); cron_touch_lock_file(CRON_ALLOWED); } +/** + * @param $lock_file + */ function cron_touch_lock_file($lock_file) { file_write(make_rand_str(20), $lock_file, 0, true, true); } +/** + * Включение форума (при блокировке крона) + */ function cron_enable_board() { - @rename(BB_DISABLED, BB_ENABLED); + if (file_exists(BB_DISABLED)) { + rename(BB_DISABLED, BB_ENABLED); + } } +/** + * Отключение форума (при блокировке крона) + */ function cron_disable_board() { - @rename(BB_ENABLED, BB_DISABLED); + if (file_exists(BB_ENABLED)) { + rename(BB_ENABLED, BB_DISABLED); + } } diff --git a/library/includes/template.php b/library/includes/template.php deleted file mode 100644 index 4d1540874..000000000 --- a/library/includes/template.php +++ /dev/null @@ -1,56 +0,0 @@ -execute() scope!) - * "#" - constant, {#CON} is eq to CON - * - */ - -if (!defined('BB_ROOT')) { - die(basename(__FILE__)); -} - -define('XS_SEPARATOR', '.'); -define('XS_USE_ISSET', '1'); - -// cache filenames prefix -define('XS_TPL_PREFIX', 'tpl_'); -define('XS_TPL_PREFIX2', 'tpl2_'); - -// internal xs mod definitions. do not edit. -define('XS_TAG_NONE', 0); -define('XS_TAG_PHP', 1); -define('XS_TAG_BEGIN', 2); -define('XS_TAG_END', 3); -define('XS_TAG_INCLUDE', 4); -define('XS_TAG_IF', 5); -define('XS_TAG_ELSE', 6); -define('XS_TAG_ELSEIF', 7); -define('XS_TAG_ENDIF', 8); -define('XS_TAG_BEGINELSE', 11); diff --git a/library/includes/ucp/activate.php b/library/includes/ucp/activate.php index 588571dd7..a282d93ca 100644 --- a/library/includes/ucp/activate.php +++ b/library/includes/ucp/activate.php @@ -23,8 +23,8 @@ * SOFTWARE. */ -if (!defined('IN_FORUM')) { - die('Hacking attempt'); +if (!defined('BB_ROOT')) { + die(basename(__FILE__)); } if (empty($_GET['u']) || empty($_GET['act_key'])) { diff --git a/library/includes/ucp/email.php b/library/includes/ucp/email.php index 55b12eb56..ccd798619 100644 --- a/library/includes/ucp/email.php +++ b/library/includes/ucp/email.php @@ -23,8 +23,8 @@ * SOFTWARE. */ -if (!defined('IN_FORUM')) { - die("Hacking attempt"); +if (!defined('BB_ROOT')) { + die(basename(__FILE__)); } // Is send through board enabled? No, return to index diff --git a/library/includes/ucp/sendpasswd.php b/library/includes/ucp/sendpasswd.php index 895c45da4..12ecdb8cd 100644 --- a/library/includes/ucp/sendpasswd.php +++ b/library/includes/ucp/sendpasswd.php @@ -23,8 +23,8 @@ * SOFTWARE. */ -if (!defined('IN_FORUM')) { - die("Hacking attempt"); +if (!defined('BB_ROOT')) { + die(basename(__FILE__)); } set_die_append_msg(); diff --git a/library/language/source/main.php b/library/language/source/main.php index ce85bdf40..421b1635e 100644 --- a/library/language/source/main.php +++ b/library/language/source/main.php @@ -1546,7 +1546,7 @@ $lang['DL_UL_SPEED'] = 'UL speed'; $lang['DL_DL_SPEED'] = 'DL speed'; $lang['DL_PORT'] = 'Port'; $lang['DL_FORMULA'] = 'Formula: Uploaded/TorrentSize'; -$lang['DL_ULR'] = 'ULR'; +$lang['DL_ULR'] = 'URL'; $lang['DL_STOPPED'] = 'stopped'; $lang['DL_UPD'] = 'upd: '; $lang['DL_INFO'] = 'shows data only for the current session'; @@ -1738,7 +1738,7 @@ $lang['CLICK_RETURN_FORUMAUTH'] = 'Click %sHere%s to return to Forum Permissions // Banning $lang['BAN_CONTROL'] = 'Ban Control'; -$lang['BAN_EXPLAIN'] = 'Here you can control the banning of users. You can achieve this by banning either or both of a specific user or an individual or range of IP addresses or hostnames. These methods prevent a user from even reaching the index page of your board. To prevent a user from registering under a different username you can also specify a banned email address. Please note that banning an email address alone will not prevent that user from being able to log on or post to your board. You should use one of the first two methods to achieve this.'; +$lang['BAN_EXPLAIN'] = 'Here you can control the banning of users. You can achieve this by banning either or both of a specific user or an individual or range of IP addresses. These methods prevent a user from even reaching the index page of your board. To prevent a user from registering under a different username you can also specify a banned email address. Please note that banning an email address alone will not prevent that user from being able to log on or post to your board. You should use one of the first two methods to achieve this.'; $lang['BAN_EXPLAIN_WARN'] = 'Please note that entering a range of IP addresses results in all the addresses between the start and end being added to the banlist. Attempts will be made to minimise the number of addresses added to the database by introducing wildcards automatically where appropriate. If you really must enter a range, try to keep it small or better yet state specific addresses.'; $lang['SELECT_IP'] = 'Select an IP address'; @@ -1747,9 +1747,9 @@ $lang['SELECT_EMAIL'] = 'Select an Email address'; $lang['BAN_USERNAME'] = 'Ban one or more specific users'; $lang['BAN_USERNAME_EXPLAIN'] = 'You can ban multiple users in one go using the appropriate combination of mouse and keyboard for your computer and browser'; -$lang['BAN_IP'] = 'Ban one or more IP addresses or hostnames'; -$lang['IP_HOSTNAME'] = 'IP addresses or hostnames'; -$lang['BAN_IP_EXPLAIN'] = 'To specify several different IP addresses or hostnames separate them with commas. To specify a range of IP addresses, separate the start and end with a hyphen (-); to specify a wildcard, use an asterisk (*).'; +$lang['BAN_IP'] = 'Ban one or more IP addresses'; +$lang['IP_HOSTNAME'] = 'IP addresses'; +$lang['BAN_IP_EXPLAIN'] = 'To specify several different IP addresses separate them with commas.'; $lang['BAN_EMAIL'] = 'Ban one or more email addresses'; $lang['BAN_EMAIL_EXPLAIN'] = 'To specify more than one email address, separate them with commas. To specify a wildcard username, use * like *@hotmail.com'; @@ -2661,7 +2661,7 @@ $lang['SEARCH_USERS_ADVANCED'] = 'Advanced User Search'; $lang['SEARCH_USERS_EXPLAIN'] = 'This Module allows you to perform advanced searches for users on a wide range of criteria. Please read the descriptions under each field to understand each search option completely.'; $lang['SEARCH_USERNAME_EXPLAIN'] = 'Here you can perform a case insensitive search for usernames. If you would like to match part of the username, use * (an asterix) as a wildcard.'; $lang['SEARCH_EMAIL_EXPLAIN'] = 'Enter an expression to match a user\'s email address. This is case insensitive. If you want to do a partial match, use * (an asterix) as a wildcard.'; -$lang['SEARCH_IP_EXPLAIN'] = 'Search for users by a specific IP address (xxx.xxx.xxx.xxx), wildcard (xxx.xxx.xxx.*) or range (xxx.xxx.xxx.xxx-yyy.yyy.yyy.yyy). Note: the last quad .255 is considered the range of all the IPs in that quad. If you enter 10.0.0.255, it is just like entering 10.0.0.* (No IP is assigned .255 for that matter, it is reserved). Where you may encounter this is in ranges, 10.0.0.5-10.0.0.255 is the same as "10.0.0.*" . You should really enter 10.0.0.5-10.0.0.254 .'; +$lang['SEARCH_IP_EXPLAIN'] = 'Search for users by a specific IP address (xxx.xxx.xxx.xxx).'; $lang['SEARCH_USERS_JOINED'] = 'Users that joined'; $lang['SEARCH_USERS_LASTVISITED'] = 'Users whom have visited'; $lang['IN_THE_LAST'] = 'in the last'; diff --git a/login.php b/login.php index f5222e9ca..a4b9771ca 100644 --- a/login.php +++ b/login.php @@ -23,7 +23,6 @@ * SOFTWARE. */ -define('IN_FORUM', true); define('BB_SCRIPT', 'login'); define('IN_LOGIN', true); define('BB_ROOT', './'); diff --git a/memberlist.php b/memberlist.php index f1f17f4a4..34d73498b 100644 --- a/memberlist.php +++ b/memberlist.php @@ -23,7 +23,6 @@ * SOFTWARE. */ -define('IN_FORUM', true); define('BB_SCRIPT', 'memberlist'); define('BB_ROOT', './'); require __DIR__ . '/common.php'; diff --git a/modcp.php b/modcp.php index f37468b8f..a56feb8f7 100644 --- a/modcp.php +++ b/modcp.php @@ -23,7 +23,6 @@ * SOFTWARE. */ -define('IN_FORUM', true); define('BB_SCRIPT', 'modcp'); define('BB_ROOT', './'); require __DIR__ . '/common.php'; diff --git a/posting.php b/posting.php index 61e36ec14..cca42ee34 100644 --- a/posting.php +++ b/posting.php @@ -23,7 +23,6 @@ * SOFTWARE. */ -define('IN_FORUM', true); define('BB_SCRIPT', 'posting'); define('BB_ROOT', './'); require __DIR__ . '/common.php'; diff --git a/privmsg.php b/privmsg.php index 985eda4e3..985952e28 100644 --- a/privmsg.php +++ b/privmsg.php @@ -23,7 +23,6 @@ * SOFTWARE. */ -define('IN_FORUM', true); define('BB_SCRIPT', 'pm'); define('IN_PM', true); define('BB_ROOT', './'); diff --git a/src/Legacy/Common/Html.php b/src/Legacy/Common/Html.php index 4d9368ff7..f6b1184dc 100644 --- a/src/Legacy/Common/Html.php +++ b/src/Legacy/Common/Html.php @@ -66,8 +66,8 @@ class Html $this->_build_select_rec($params); - $select_params = ($js) ? " $js" : ''; - $select_params .= ($multiple_size) ? ' multiple="multiple" size="' . $multiple_size . '"' : ''; + $select_params = $js ? " $js" : ''; + $select_params .= $multiple_size ? ' multiple size="' . $multiple_size . '"' : ''; $select_params .= ' name="' . htmlCHR($name) . '"'; $select_params .= ' id="' . htmlCHR($name) . '"'; diff --git a/src/Legacy/Common/User.php b/src/Legacy/Common/User.php index e4ed7cff7..89c3685a8 100644 --- a/src/Legacy/Common/User.php +++ b/src/Legacy/Common/User.php @@ -34,17 +34,21 @@ use TorrentPier\Legacy\DateDelta; class User { /** - * Config + * Config + * + * @var array */ - public $cfg = array( + public $cfg = [ 'req_login' => false, // requires user to be logged in 'req_session_admin' => false, // requires active admin session (for moderation or admin actions) - ); + ]; /** - * 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 array */ - public $opt_js = array( + public $opt_js = [ 'only_new' => 0, // show ony new posts or topics 'h_av' => 0, // hide avatar 'h_rnk_i' => 0, // hide rank images @@ -57,39 +61,47 @@ class User 'hl_tr' => 1, // show cursor in tracker.php 'i_aft_l' => 0, // show images only after full loading 'h_tsp' => 0, // show released title {...} - ); + ]; /** - * Defaults options for guests + * Defaults options for guests + * + * @var array */ - public $opt_js_guest = array( + public $opt_js_guest = [ 'h_av' => 1, // hide avatar 'h_rnk_i' => 1, // hide rank images 'h_smile' => 1, // hide smilies 'h_sig' => 1, // hide signatures - ); + ]; /** - * Sessiondata + * Sessiondata + * + * @var array */ - public $sessiondata = array( + public $sessiondata = [ 'uk' => null, 'uid' => null, 'sid' => '', - ); + ]; /** - * Old $userdata + * Old $userdata + * + * @var array */ - public $data = array(); + public $data = []; /** - * Shortcuts + * Shortcuts + * + * @var */ public $id; /** - * Constructor + * User constructor */ public function __construct() { @@ -97,9 +109,13 @@ class User } /** - * Start session (restore existent session or create new) + * Start session (restore existent session or create new) + * + * @param array $cfg + * + * @return array|bool */ - public function session_start(array $cfg = array()) + public function session_start(array $cfg = []) { global $bb_cfg; @@ -170,7 +186,7 @@ class User } $this->set_session_cookies($this->data['user_id']); } else { - $this->data = array(); + $this->data = []; } } // If we reach here then no (valid) session exists. So we'll create a new one, @@ -186,20 +202,20 @@ class User } } } - if (!$userdata || ($userdata['user_id'] != GUEST_UID && !$login)) { + if (!$userdata || ((int)$userdata['user_id'] !== GUEST_UID && !$login)) { $userdata = get_userdata(GUEST_UID, false, true); } $this->session_create($userdata, true); } - define('IS_GUEST', (!$this->data['session_logged_in'])); - define('IS_ADMIN', (!IS_GUEST && $this->data['user_level'] == ADMIN)); - define('IS_MOD', (!IS_GUEST && $this->data['user_level'] == MOD)); - define('IS_GROUP_MEMBER', (!IS_GUEST && $this->data['user_level'] == GROUP_MEMBER)); - define('IS_USER', (!IS_GUEST && $this->data['user_level'] == USER)); - define('IS_SUPER_ADMIN', (IS_ADMIN && isset($bb_cfg['super_admins'][$this->data['user_id']]))); - define('IS_AM', (IS_ADMIN || IS_MOD)); + define('IS_GUEST', !$this->data['session_logged_in']); + define('IS_ADMIN', !IS_GUEST && (int)$this->data['user_level'] === ADMIN); + define('IS_MOD', !IS_GUEST && (int)$this->data['user_level'] === MOD); + define('IS_GROUP_MEMBER', !IS_GUEST && (int)$this->data['user_level'] === GROUP_MEMBER); + define('IS_USER', !IS_GUEST && (int)$this->data['user_level'] === USER); + define('IS_SUPER_ADMIN', IS_ADMIN && isset($bb_cfg['super_admins'][$this->data['user_id']])); + define('IS_AM', IS_ADMIN || IS_MOD); $this->set_shortcuts(); @@ -214,7 +230,12 @@ class User } /** - * Create new session for the given user + * Create new session for the given user + * + * @param $userdata + * @param bool $auto_created + * + * @return array */ public function session_create($userdata, $auto_created = false) { @@ -223,17 +244,15 @@ class User $this->data = $userdata; $session_id = $this->sessiondata['sid']; - $login = (int)($this->data['user_id'] != GUEST_UID); - $is_user = ($this->data['user_level'] != ADMIN); + $login = ((int)$this->data['user_id'] !== GUEST_UID); + $is_user = ((int)$this->data['user_level'] !== ADMIN); $user_id = (int)$this->data['user_id']; - $mod_admin_session = ($this->data['user_level'] == ADMIN || $this->data['user_level'] == MOD); + $mod_admin_session = ((int)$this->data['user_level'] === ADMIN || (int)$this->data['user_level'] === MOD); // Initial ban check against user_id or IP address if ($is_user) { - preg_match('#(..)(..)(..)(..)#', USER_IP, $ip); - - $where_sql = "ban_ip IN('" . USER_IP . "', '$ip[1]$ip[2]$ip[3]ff', '$ip[1]$ip[2]ffff', '$ip[1]ffffff')"; - $where_sql .= ($login) ? " OR ban_userid = $user_id" : ''; + $where_sql = 'ban_ip = ' . USER_IP; + $where_sql .= $login ? " OR ban_userid = $user_id" : ''; $sql = "SELECT ban_id FROM " . BB_BANLIST . " WHERE $where_sql LIMIT 1"; @@ -246,7 +265,7 @@ class User for ($i = 0, $max_try = 5; $i <= $max_try; $i++) { $session_id = make_rand_str(SID_LENGTH); - $args = DB()->build_array('INSERT', array( + $args = DB()->build_array('INSERT', [ 'session_id' => (string)$session_id, 'session_user_id' => (int)$user_id, 'session_start' => (int)TIMENOW, @@ -254,10 +273,10 @@ class User 'session_ip' => (string)USER_IP, 'session_logged_in' => (int)$login, 'session_admin' => (int)$mod_admin_session, - )); + ]); $sql = "INSERT INTO " . BB_SESSIONS . $args; - if (@DB()->query($sql)) { + if (DB()->query($sql)) { break; } if ($i == $max_try) { @@ -320,7 +339,10 @@ class User } /** - * Initialize sessiondata stored in cookies + * Initialize sessiondata stored in cookies + * + * @param bool $update_lastvisit + * @param bool $set_cookie */ public function session_end($update_lastvisit = false, $set_cookie = true) { @@ -358,7 +380,12 @@ class User } /** - * Login + * Login + * + * @param $args + * @param bool $mod_admin_login + * + * @return array */ public function login($args, $mod_admin_login = false) { @@ -411,15 +438,15 @@ class User } } - return array(); + return []; } /** - * Initialize sessiondata stored in cookies + * Initialize sessiondata stored in cookies */ 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]) : []; // autologin_id if (!empty($sd_resv['uk']) && verify_id($sd_resv['uk'], LOGIN_KEY_LENGTH)) { @@ -436,21 +463,23 @@ class User } /** - * Store sessiondata in cookies + * Store sessiondata in cookies + * + * @param $user_id */ public function set_session_cookies($user_id) { global $bb_cfg; if ($user_id == GUEST_UID) { - $delete_cookies = array( + $delete_cookies = [ COOKIE_DATA, COOKIE_DBG, 'torhelp', 'explain', 'sql_log', 'sql_log_full', - ); + ]; foreach ($delete_cookies as $cookie) { if (isset($_COOKIE[$cookie])) { @@ -471,7 +500,13 @@ class User } /** - * Verify autologin_id + * Verify autologin_id + * + * @param $userdata + * @param bool $expire_check + * @param bool $create_new + * + * @return bool|string */ public function verify_autologin_id($userdata, $expire_check = false, $create_new = true) { @@ -495,7 +530,12 @@ class User } /** - * Create autologin_id + * Create autologin_id + * + * @param $userdata + * @param bool $create_new + * + * @return bool|string */ public function create_autologin_id($userdata, $create_new = true) { @@ -512,7 +552,7 @@ class User } /** - * Set shortcuts + * Set shortcuts */ public function set_shortcuts() { @@ -523,12 +563,11 @@ class User $this->regdate =& $this->data['user_regdate']; $this->level =& $this->data['user_level']; $this->opt =& $this->data['user_opt']; - $this->ip = CLIENT_IP; } /** - * Initialise user settings + * Initialise user settings */ public function init_userprefs() { @@ -575,7 +614,9 @@ class User } /** - * Mark read + * Mark read + * + * @param $type */ public function mark_read($type) { @@ -593,10 +634,10 @@ class User $this->data['user_lastvisit'] = TIMENOW; // Update lastvisit - db_update_userdata($this->data, array( + db_update_userdata($this->data, [ 'user_session_time' => $this->data['session_time'], 'user_lastvisit' => $this->data['user_lastvisit'], - )); + ]); // Delete cookies bb_setcookie(COOKIE_TOPIC, ''); @@ -606,7 +647,7 @@ class User } /** - * Load misc options + * Load misc options */ public function load_opt_js() { @@ -622,7 +663,11 @@ class User } /** - * Get not auth forums + * Get not auth forums + * + * @param $auth_type + * + * @return string */ public function get_not_auth_forums($auth_type) { @@ -648,7 +693,7 @@ class User } } - $auth_field_match = array( + $auth_field_match = [ AUTH_VIEW => 'auth_view', AUTH_READ => 'auth_read', AUTH_POST => 'auth_post', @@ -661,9 +706,9 @@ class User AUTH_POLLCREATE => 'auth_pollcreate', AUTH_ATTACH => 'auth_attachments', AUTH_DOWNLOAD => 'auth_download', - ); + ]; - $not_auth_forums = array(); + $not_auth_forums = []; $auth_field = $auth_field_match[$auth_type]; $is_auth_ary = auth($auth_type, AUTH_LIST_ALL, $this->data); @@ -677,11 +722,16 @@ class User } /** - * Get excluded forums + * Get excluded forums + * + * @param $auth_type + * @param string $return_as + * + * @return array|bool|string */ public function get_excluded_forums($auth_type, $return_as = 'csv') { - $excluded = array(); + $excluded = []; if ($not_auth = $this->get_not_auth_forums($auth_type)) { $excluded[] = $not_auth; diff --git a/src/Legacy/Dbs.php b/src/Legacy/Dbs.php index 63a4c438d..87cdc9ccd 100644 --- a/src/Legacy/Dbs.php +++ b/src/Legacy/Dbs.php @@ -31,9 +31,9 @@ namespace TorrentPier\Legacy; */ class Dbs { - public $cfg = []; // $srv_name => $srv_cfg - public $srv = []; // $srv_name => $db_obj - public $alias = []; // $srv_alias => $srv_name + public $cfg = []; + public $srv = []; + public $alias = []; public $log_file = 'sql_queries'; public $log_counter = 0; @@ -41,6 +41,11 @@ class Dbs public $sql_inittime = 0; public $sql_timetotal = 0; + /** + * Dbs constructor + * + * @param $cfg + */ public function __construct($cfg) { $this->cfg = $cfg['db']; @@ -51,8 +56,14 @@ class Dbs } } - // получение/инициализация класса для сервера $srv_name - public function get_db_obj($srv_name_or_alias = 'db1') + /** + * Получение / инициализация класса сервера $srv_name + * + * @param string $srv_name_or_alias + * + * @return mixed + */ + public function get_db_obj($srv_name_or_alias = 'db') { $srv_name = $this->get_srv_name($srv_name_or_alias); @@ -63,16 +74,23 @@ class Dbs return $this->srv[$srv_name]; } - // определение имени сервера + /** + * Определение имени сервера + * + * @param $name + * + * @return mixed|string + */ public function get_srv_name($name) { + $srv_name = 'db'; + if (isset($this->alias[$name])) { $srv_name = $this->alias[$name]; } elseif (isset($this->cfg[$name])) { $srv_name = $name; - } else { - $srv_name = 'db1'; } + return $srv_name; } } diff --git a/src/Legacy/Template.php b/src/Legacy/Template.php index 93286a89c..bdf5060f8 100644 --- a/src/Legacy/Template.php +++ b/src/Legacy/Template.php @@ -31,82 +31,87 @@ namespace TorrentPier\Legacy; */ class Template { - // variable that holds all the data we'll be substituting into - // the compiled templates. - // ... - // This will end up being a multi-dimensional array like this: - // $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value - // if it's a root-level variable, it'll be like this: - // $this->vars[varname] == value or $this->_tpldata['.'][0][varname] == value - // array "vars" is added for easier access to data - public $_tpldata = array('.' => array(0 => array())); + /** + * Variable that holds all the data we'll be substituting into the compiled templates. + * This will end up being a multi-dimensional array like this: + * $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value + * if it's a root-level variable, it'll be like this: + * $this->vars[varname] == value or $this->_tpldata['.'][0][varname] == value + * + * @var array + */ + public $_tpldata = [ + '.' => [ + 0 => [] + ] + ]; + + /** @var array added for easier access to data */ public $vars; - // Hash of filenames for each template handle. - public $files = array(); - public $files_cache = array(); // array of cache files that exists - public $files_cache2 = array(); // array of cache files (exists or not exists) + /** @var array hash of filenames for each template handle */ + public $files = []; - // Root template directory. + /** @var array cache files that exists */ + public $files_cache = []; + + /** @var array cache files (exists or not exists) */ + public $files_cache2 = []; + + /** @var string root template directory */ public $root = ''; - // Cache directory + /** @var string cache directory */ public $cachedir = CACHE_DIR . '/'; - // Template root directory + /** @var string template root directory */ public $tpldir = ''; - // Default template directory. - // If file for default template isn't found file from this template is used. + /** @var string default template directory */ public $tpldef = 'default'; - // this will hash handle names to the compiled code for that handle. - public $compiled_code = array(); + /** @var array this will hash handle names to the compiled code for that handle */ + public $compiled_code = []; - // This will hold the uncompiled code for that handle. - public $uncompiled_code = array(); + /** @var array this will hold the uncompiled code for that handle */ + public $uncompiled_code = []; - // Cache settings + /** @var int cache settings */ public $use_cache = 1; public $cache_writable = 1; - // Auto-compile setting + /** @var int auto-compile setting */ public $auto_compile = 1; - // Current template name + /** @var string current template name */ public $tpl = ''; public $cur_tpl = ''; - // List of replacements. tpl files in this list will be replaced with other tpl files - // according to configuration in xs.cfg - public $replace = array(); + /** @var array list of replacements */ + public $replace = []; - // counter for include + /** @var int counter for include */ public $include_count = 0; - // extension tpl-cache files + /** @var string extension tpl-cache files */ public $cached_tpl_ext = 'php'; - // eXtreme Styles variables - public $xs_started = 0; - public $xs_version = 8; // number version. internal. do not change. - public $xs_versiontxt = '2.3.1'; // text version - - // These handles will be parsed if pparse() is executed. - // Can be used to automatically include header/footer if there is any content. + /** @var string these handles will be parsed if pparse() is executed */ public $preparse = ''; public $postparse = ''; - // subtemplates mod detection + /** @var bool subtemplates mod detection */ public $subtemplates = false; - // style configuration - public $style_config = array(); + /** @var array style configuration */ + public $style_config = []; - public $lang = array(); + public $lang = []; /** * Constructor. Installs XS mod on first run or updates it and sets the root dir. + * + * @param string $root */ public function __construct($root = '.') { @@ -122,21 +127,14 @@ class Template $this->use_cache = $bb_cfg['xs_use_cache']; } - /** - * 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. - */ - public function destroy() - { - $this->_tpldata = array('.' => array(0 => array())); - $this->vars = &$this->_tpldata['.'][0]; - $this->xs_started = 0; - } - /** * Generates a full path+filename for the given filename, which can either - * be an absolute name, or a name relative to the rootdir for this Template - * object. + * be an absolute name, or a name relative to the rootdir for this Template object. + * + * @param $filename + * @param bool $xs_include + * + * @return mixed|string */ public function make_filename($filename, $xs_include = false) { @@ -147,15 +145,19 @@ class Template // Check if it's an absolute or relative path. if (($filename[0] !== '/') && ($filename[1] !== ':')) { return $this->root . '/' . $filename; - } else { - return $filename; } + + return $filename; } /** * Converts template filename to cache filename. * Returns empty string if non-cachable (for tpl files outside of root dir). * $filename should be absolute filename + * + * @param $filename + * + * @return string */ public function make_filename_cache($filename) { @@ -165,8 +167,10 @@ class Template } /** - * Sets the template filenames for handles. $filename_array - * should be a hash of handle => filename pairs. + * Sets the template filenames for handles. + * $filename_array should be a hash of handle => filename pairs. + * + * @param $filenames */ public function set_filenames($filenames) { @@ -177,6 +181,13 @@ class Template /** * Assigns template filename for handle. + * + * @param $handle + * @param $filename + * @param bool $xs_include + * @param bool $quiet + * + * @return bool */ public function set_filename($handle, $filename, $xs_include = false, $quiet = false) { @@ -188,9 +199,9 @@ class Template if (!$this->files[$handle]) { if ($xs_include || $quiet) { return false; - } else { - die("Template->make_filename(): Error - invalid template $filename"); } + + die("Template->make_filename(): Error - invalid template $filename"); } // creating cache filename if ($can_cache) { @@ -219,6 +230,10 @@ class Template /** * includes file or executes code + * + * @param $filename + * @param $code + * @param $handle */ public function execute($filename, $code, $handle) { @@ -230,16 +245,19 @@ class Template $V =& $this->vars; if ($filename) { - include($filename); + include $filename; } else { eval($code); } } /** - * Load the file for the handle, compile the file, - * and run the compiled code. This will print out - * the results of executing the template. + * Load the file for the handle, compile the file and run the compiled code. + * This will print out the results of executing the template. + * + * @param $handle + * + * @return bool */ public function pparse($handle) { @@ -291,77 +309,14 @@ class Template return true; } - /** - * Precompile file - */ - public function precompile($template, $filename) - { - global $precompile_num; - if (empty($precompile_num)) { - $precompile_num = 0; - } - $precompile_num++; - $handle = 'precompile_' . $precompile_num; - // save old configuration - $root = $this->root; - $tpl_name = $this->tpl; - $old_config = $this->use_cache; - $old_autosave = $this->auto_compile; - // set temporary configuration - $this->root = $this->tpldir . $template; - $this->tpl = $template; - $this->use_cache = 1; - $this->auto_compile = 1; - // set filename - $res = $this->set_filename($handle, $filename, true, true); - if (!$res || !$this->files_cache2[$handle]) { - $this->root = $root; - $this->tpl = $tpl_name; - $this->use_cache = $old_config; - $this->auto_compile = $old_autosave; - return false; - } - $this->files_cache[$handle] = ''; - // load template - $res = $this->loadfile($handle); - if (!$res || empty($this->uncompiled_code[$handle])) { - $this->root = $root; - $this->tpl = $tpl_name; - $this->use_cache = $old_config; - $this->auto_compile = $old_autosave; - return false; - } - // compile the code - $this->compile2($this->uncompiled_code[$handle], $handle, $this->files_cache2[$handle]); - // restore confirugation - $this->root = $root; - $this->tpl = $tpl_name; - $this->use_cache = $old_config; - $this->auto_compile = $old_autosave; - return true; - } - - /** - * Inserts the uncompiled code for $handle as the - * value of $varname in the root-level. This can be used - * to effectively include a template in the middle of another - * template. - * Note that all desired assignments to the variables in $handle should be done - * BEFORE calling this function. - */ - public function assign_var_from_handle($varname, $handle) - { - ob_start(); - $res = $this->pparse($handle); - $this->vars[$varname] = ob_get_contents(); - ob_end_clean(); - return $res; - } - /** * Block-level variable assignment. Adds a new block iteration with the given - * variable assignments. Note that this should only be called once per block - * iteration. + * variable assignments. Note that this should only be called once per block iteration. + * + * @param $blockname + * @param $vararray + * + * @return bool */ public function assign_block_vars($blockname, $vararray) { @@ -392,6 +347,8 @@ class Template /** * Root-level variable assignment. Adds to current assignments, overriding * any existing variable assignment with the same name. + * + * @param $vararray */ public function assign_vars($vararray) { @@ -403,27 +360,22 @@ class Template /** * Root-level variable assignment. Adds to current assignments, overriding * any existing variable assignment with the same name. + * + * @param $varname + * @param bool $varval */ public function assign_var($varname, $varval = true) { $this->vars[$varname] = $varval; } - /** - * TODO: Add type check [??] - * Root-level. Adds to current assignments, appends - * to any existing variable assignment with the same name. - */ - public function append_vars($vararray) - { - foreach ($vararray as $key => $val) { - $this->vars[$key] = !isset($this->vars[$key]) ? $val : $this->vars[$key] . $val; - } - } - /** * If not already done, load the file for the given handle and populate * the uncompiled_code[] hash with its code. Do not compile. + * + * @param $handle + * + * @return bool */ public function loadfile($handle) { @@ -459,6 +411,11 @@ class Template * ' . $this->_tpldata['parent.'][$_parent_i]['$child1.'][$_child1_i]['$child2.'][$_child2_i]...['varname'] . ' * It's ready to be inserted into an "echo" line in one of the templates. * NOTE: expects a trailing "." on the namespace. + * + * @param $namespace + * @param $varname + * + * @return string */ public function generate_block_varref($namespace, $varname) { @@ -484,6 +441,11 @@ class Template * * 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. + * + * @param $blockname + * @param $include_last_iterator + * + * @return string */ public function generate_block_data_ref($blockname, $include_last_iterator) { @@ -492,9 +454,9 @@ class Template $blockcount = count($blocks) - 1; if ($include_last_iterator) { return '$' . $blocks[$blockcount] . '_item'; - } else { - return '$' . $blocks[$blockcount - 1] . '_item[\'' . $blocks[$blockcount] . '.\']'; } + + return '$' . $blocks[$blockcount - 1] . '_item[\'' . $blocks[$blockcount] . '.\']'; } public function compile_code($filename, $code) @@ -521,7 +483,7 @@ class Template $block_nesting_level = 0; $block_names = array(); - $block_names[0] = "."; + $block_names[0] = '.'; $block_items = array(); $count_if = 0; @@ -654,7 +616,7 @@ class Template $line .= ' $' . $var . '_item = &$this->_tpldata[\'' . $var . '.\'][$' . $var . '_i];' . "\n"; $line .= " \${$var}_item['S_ROW_COUNT'] = \${$var}_i;\n"; $line .= " \${$var}_item['S_NUM_ROWS'] = \${$var}_count;\n"; - $line .= "\n?" . ">"; + $line .= "\n?" . '>'; } else { // This block is nested. // Generate a namespace string for this block. @@ -672,7 +634,7 @@ class Template $line .= ' $' . $var . '_item = &' . $varref . '[$' . $var . '_i];' . "\n"; $line .= " \${$var}_item['S_ROW_COUNT'] = \${$var}_i;\n"; $line .= " \${$var}_item['S_NUM_ROWS'] = \${$var}_count;\n"; - $line .= "\n?" . ">"; + $line .= "\n?" . '>'; } $compiled[] = $line; continue; @@ -697,7 +659,7 @@ class Template $line = '<' . "?php\n\n"; $line .= '} // END ' . $var . "\n\n"; $line .= 'if(isset($' . $var . '_item)) { unset($' . $var . '_item); } '; - $line .= "\n\n?" . ">"; + $line .= "\n\n?" . '>'; if (isset($block_items[$var])) { $block_items[$var]--; } else { @@ -781,9 +743,13 @@ class Template return $code_header . implode('', $compiled) . $code_footer; } - /* - * Compile code between tags - */ + /** + * Compile code between tags + * + * @param $code + * + * @return mixed + */ public function _compile_text($code) { if (strlen($code) < 3) { @@ -814,10 +780,13 @@ class Template return $code; } - // - // Compile IF tags - much of this is from Smarty with - // some adaptions for our block level methods - // + /** + * Compile IF tags - much of this is from Smarty with some adaptions for our block level methods + * + * @param $tag_args + * @param $elseif + * @return string + */ public function compile_tag_if($tag_args, $elseif) { /* Tokenize args for 'if' tag. */ @@ -928,7 +897,14 @@ class Template return $code; } - // This is from Smarty + /** + * This is from Smarty + * + * @param $is_arg + * @param $tokens + * + * @return mixed + */ public function _parse_is_expr($is_arg, $tokens) { $expr_end = 0; @@ -985,10 +961,16 @@ class Template /** * Compiles code and writes to cache if needed + * + * @param $code + * @param $handle + * @param $cache_file + * + * @return string */ public function compile2($code, $handle, $cache_file) { - $code = $this->compile_code('', $code, XS_USE_ISSET); + $code = $this->compile_code('', $code); if ($cache_file && !empty($this->use_cache) && !empty($this->auto_compile)) { $res = $this->write_cache($cache_file, $code); if ($handle && $res) { @@ -999,25 +981,11 @@ class Template return $code; } - /** - * Compiles the given string of code, and returns - * the result in a string. - * If "do_not_echo" is true, the returned code will not be directly - * executable, but can be used as part of a variable assignment - * for use in assign_code_from_handle(). - * This function isn't used and kept only for compatibility with original template.php - */ - public function compile($code, $do_not_echo = false, $retvar = '') - { - $code = ' ?' . '>' . $this->compile_code('', $code, true) . '<' . "?php \n"; - if ($do_not_echo) { - $code = "ob_start();\n" . $code . "\n\${$retvar} = ob_get_contents();\nob_end_clean();\n"; - } - return $code; - } - /** * Write cache to disk + * + * @param $filename + * @param $code */ public function write_cache($filename, $code) { @@ -1028,24 +996,15 @@ class Template { global $bb_cfg; - if (empty($this->xs_started)) { // adding predefined variables - $this->xs_started = 1; - // adding language variable (eg: "english" or "german") - // can be used to make truly multi-lingual templates - $this->vars['LANG'] = isset($this->vars['LANG']) ? $this->vars['LANG'] : $bb_cfg['default_lang']; - // adding current template - $tpl = $this->root . '/'; - if (substr($tpl, 0, 2) === './') { - $tpl = substr($tpl, 2, strlen($tpl)); - } - $this->vars['TEMPLATE'] = isset($this->vars['TEMPLATE']) ? $this->vars['TEMPLATE'] : $tpl; - $this->vars['TEMPLATE_NAME'] = isset($this->vars['TEMPLATE_NAME']) ? $this->vars['TEMPLATE_NAME'] : $this->tpl; + // adding language variable (eg: "english" or "german") + // can be used to make truly multi-lingual templates + $this->vars['LANG'] = isset($this->vars['LANG']) ? $this->vars['LANG'] : $bb_cfg['default_lang']; + // adding current template + $tpl = $this->root . '/'; + if (substr($tpl, 0, 2) === './') { + $tpl = substr($tpl, 2, strlen($tpl)); } - } - - public function lang_error($var) - { - trigger_error(basename($this->cur_tpl) . " : undefined language variable {L_{$var}}", E_USER_WARNING); - return "Undefined: {L_{$var}}"; + $this->vars['TEMPLATE'] = isset($this->vars['TEMPLATE']) ? $this->vars['TEMPLATE'] : $tpl; + $this->vars['TEMPLATE_NAME'] = isset($this->vars['TEMPLATE_NAME']) ? $this->vars['TEMPLATE_NAME'] : $this->tpl; } } diff --git a/styles/templates/admin/admin_attachments.tpl b/styles/templates/admin/admin_attachments.tpl index 950b8ab95..638029408 100644 --- a/styles/templates/admin/admin_attachments.tpl +++ b/styles/templates/admin/admin_attachments.tpl @@ -214,7 +214,7 @@