2018-03-08

This commit is contained in:
Visman 2018-03-08 19:39:54 +07:00
parent a89b78391f
commit 1ed9421500
73 changed files with 607 additions and 606 deletions

View file

@ -30,14 +30,14 @@ class Install
public function routing()
{
$uri = $_SERVER['REQUEST_URI'];
if (($pos = strpos($uri, '?')) !== false) {
$uri = substr($uri, 0, $pos);
if (($pos = \strpos($uri, '?')) !== false) {
$uri = \substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$uri = \rawurldecode($uri);
$this->c->BASE_URL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://'
. preg_replace('%:(80|443)$%', '', $_SERVER['HTTP_HOST'])
. substr($uri, 0, (int) strrpos($uri, '/'));
. \preg_replace('%:(80|443)$%', '', $_SERVER['HTTP_HOST'])
. \substr($uri, 0, (int) \strrpos($uri, '/'));
$this->c->Lang->load('common', $this->c->config->o_default_lang);
$this->c->user = $this->c->users->create(['id' => 2, 'group_id' => $this->c->GROUP_ADMIN]);
@ -52,7 +52,7 @@ class Install
switch ($route[0]) {
case $r::OK:
// ... 200 OK
list($page, $action) = explode(':', $route[1], 2);
list($page, $action) = \explode(':', $route[1], 2);
$page = $this->c->$page->$action($route[2], $method);
break;
default:

View file

@ -32,8 +32,8 @@ class Primary
public function check()
{
if ($this->c->config->o_maintenance && ! $this->c->MAINTENANCE_OFF) {
if (! in_array($this->c->Cookie->uId, $this->c->admins->list) //????
|| ! in_array($this->c->user->id, $this->c->admins->list) //????
if (! \in_array($this->c->Cookie->uId, $this->c->admins->list) //????
|| ! \in_array($this->c->user->id, $this->c->admins->list) //????
) {
if (! $this->c->isInit('user')) {
$this->c->user = $this->c->users->create(['id' => 1, 'group_id' => $this->c->GROUP_GUEST]);
@ -43,7 +43,7 @@ class Primary
}
if ($this->c->config->i_fork_revision < $this->c->FORK_REVISION) {
header('Location: db_update.php'); //????
\header('Location: db_update.php'); //????
exit;
}

View file

@ -23,11 +23,11 @@ class FileCache implements ProviderCacheInterface
*/
public function __construct($dir)
{
if (empty($dir) || ! is_string($dir)) {
if (empty($dir) || ! \is_string($dir)) {
throw new InvalidArgumentException('Cache directory must be set to a string');
} elseif (! is_dir($dir)) {
} elseif (! \is_dir($dir)) {
throw new RuntimeException("`$dir`: Not a directory");
} elseif (! is_writable($dir)) {
} elseif (! \is_writable($dir)) {
throw new RuntimeException("No write access to `$dir` directory");
}
$this->cacheDir = $dir;
@ -44,11 +44,11 @@ class FileCache implements ProviderCacheInterface
public function get($key, $default = null)
{
$file = $this->file($key);
if (file_exists($file)) {
if (\file_exists($file)) {
require $file;
if (isset($expire) && isset($data)
&& ($expire < 1 || $expire > time())
&& ($expire < 1 || $expire > \time())
) {
return $data;
}
@ -70,9 +70,9 @@ class FileCache implements ProviderCacheInterface
public function set($key, $value, $ttl = null)
{
$file = $this->file($key);
$expire = null === $ttl || $ttl < 1 ? 0 : time() + $ttl;
$content = "<?php\n\n" . '$expire = ' . $expire . ";\n\n" . '$data = ' . var_export($value, true) . ";\n";
if (false === file_put_contents($file, $content, LOCK_EX)) {
$expire = null === $ttl || $ttl < 1 ? 0 : \time() + $ttl;
$content = "<?php\n\n" . '$expire = ' . $expire . ";\n\n" . '$data = ' . \var_export($value, true) . ";\n";
if (false === \file_put_contents($file, $content, \LOCK_EX)) {
throw new RuntimeException("The key '$key' can not be saved");
} else {
$this->invalidate($file);
@ -92,8 +92,8 @@ class FileCache implements ProviderCacheInterface
public function delete($key)
{
$file = $this->file($key);
if (file_exists($file)) {
if (unlink($file)) {
if (\file_exists($file)) {
if (\unlink($file)) {
$this->invalidate($file);
return true;
} else {
@ -111,14 +111,14 @@ class FileCache implements ProviderCacheInterface
*/
public function clear()
{
$d = dir($this->cacheDir);
$d = \dir($this->cacheDir);
if (! $d) {
return false;
}
$result = true;
while (($entry = $d->read()) !== false) {
if (substr($entry, -4) == '.php') {
$f = unlink($this->cacheDir . '/' . $entry);
if (\substr($entry, -4) == '.php') {
$f = \unlink($this->cacheDir . '/' . $entry);
$result = $result && $f;
}
}
@ -149,7 +149,7 @@ class FileCache implements ProviderCacheInterface
*/
protected function file($key)
{
if (is_string($key) && preg_match('%^[a-z0-9_-]+$%Di', $key)) {
if (\is_string($key) && \preg_match('%^[a-z0-9_-]+$%Di', $key)) {
return $this->cacheDir . '/cache_' . $key . '.php';
}
throw new InvalidArgumentException("Key '$key' contains invalid characters.");
@ -162,10 +162,10 @@ class FileCache implements ProviderCacheInterface
*/
protected function invalidate($file)
{
if (function_exists('opcache_invalidate')) {
opcache_invalidate($file, true);
} elseif (function_exists('apc_delete_file')) {
apc_delete_file($file);
if (\function_exists('opcache_invalidate')) {
\opcache_invalidate($file, true);
} elseif (\function_exists('apc_delete_file')) {
\apc_delete_file($file);
}
}
}

View file

@ -44,13 +44,13 @@ class Container
public function config(array $config)
{
if (isset($config['shared'])) {
$this->shared = array_replace_recursive($this->shared, $config['shared']);
$this->shared = \array_replace_recursive($this->shared, $config['shared']);
}
if (isset($config['multiple'])) {
$this->multiple = array_replace_recursive($this->multiple, $config['multiple']);
$this->multiple = \array_replace_recursive($this->multiple, $config['multiple']);
}
unset($config['shared'], $config['multiple']);
$this->config = array_replace_recursive($this->config, $config);
$this->config = \array_replace_recursive($this->config, $config);
}
/**
@ -66,10 +66,10 @@ class Container
{
if (isset($this->instances[$id])) {
return $this->instances[$id];
} elseif (strpos($id, '.') !== false) {
$tree = explode('.', $id);
$service = $this->__get(array_shift($tree));
if (is_array($service)) {
} elseif (\strpos($id, '.') !== false) {
$tree = \explode('.', $id);
$service = $this->__get(\array_shift($tree));
if (\is_array($service)) {
return $this->fromArray($service, $tree);
} elseif (is_object($service)) {
return $service->{$tree[0]};
@ -87,15 +87,15 @@ class Container
throw new InvalidArgumentException('Wrong property name: ' . $id);
}
// N.B. "class" is just the first element, regardless of its key
$class = array_shift($config);
$class = \array_shift($config);
$args = [];
// If you want to susbtitute some values in arguments, use non-numeric keys for them
foreach ($config as $k => $v) {
$args[] = is_numeric($k) ? $v : $this->resolve($v);
$args[] = \is_numeric($k) ? $v : $this->resolve($v);
}
// Special case: reference to factory method
if ($class{0} == '@' && strpos($class, ':') !== false) {
list($name, $method) = explode(':', substr($class, 1), 2);
if ($class{0} == '@' && \strpos($class, ':') !== false) {
list($name, $method) = \explode(':', \substr($class, 1), 2);
$factory = $this->__get($name);
$service = $factory->$method(...$args);
} else {
@ -118,7 +118,7 @@ class Container
*/
public function __set($id, $service)
{
if (strpos($id, '.') !== false) {
if (\strpos($id, '.') !== false) {
//????
} else {
$this->instances[$id] = $service;
@ -159,14 +159,14 @@ class Container
*/
public function setParameter($name, $value)
{
$segments = explode('.', $name);
$n = count($segments);
$segments = \explode('.', $name);
$n = \count($segments);
$ptr = &$this->config;
foreach ($segments as $s) {
if (--$n) {
if (! array_key_exists($s, $ptr)) {
if (! \array_key_exists($s, $ptr)) {
$ptr[$s] = [];
} elseif (! is_array($ptr[$s])) {
} elseif (! \is_array($ptr[$s])) {
throw new InvalidArgumentException("Scalar '{$s}' in the path '{$name}'");
}
$ptr = &$ptr[$s];
@ -180,14 +180,14 @@ class Container
protected function resolve($value)
{
if (is_string($value)) {
if (strpos($value, '%') !== false) {
if (\is_string($value)) {
if (\strpos($value, '%') !== false) {
// whole string substitution can return any type of value
if (preg_match('~^%([a-z0-9_]+(?:\.[a-z0-9_]+)*)%$~i', $value, $matches)) {
if (\preg_match('~^%([a-z0-9_]+(?:\.[a-z0-9_]+)*)%$~i', $value, $matches)) {
$value = $this->__get($matches[1]);
} else {
// partial string substitution casts value to string
$value = preg_replace_callback(
$value = \preg_replace_callback(
'~%([a-z0-9_]+(?:\.[a-z0-9_]+)*)%~i',
function ($matches) {
return $this->__get($matches[1]);
@ -196,9 +196,9 @@ class Container
);
}
} elseif (isset($value{0}) && $value{0} === '@') {
return $this->__get(substr($value, 1));
return $this->__get(\substr($value, 1));
}
} elseif (is_array($value)) {
} elseif (\is_array($value)) {
foreach ($value as &$v) {
$v = $this->resolve($v);
}
@ -209,11 +209,11 @@ class Container
/**
* @param string $name
*
*
* @return bool
*/
public function isInit($name)
{
return array_key_exists($name, $this->instances);
return \array_key_exists($name, $this->instances);
}
}

View file

@ -25,7 +25,7 @@ class Csrf
public function __construct(Secury $secury, $key)
{
$this->secury = $secury;
$this->key = sha1($key);
$this->key = \sha1($key);
}
/**
@ -40,12 +40,12 @@ class Csrf
public function create($marker, array $args = [], $time = null)
{
unset($args['token'], $args['#']);
ksort($args);
\ksort($args);
$marker .= '|';
foreach ($args as $key => $value) {
$marker .= $key . '|' . (string) $value . '|';
}
$time = $time ?: time();
$time = $time ?: \time();
return $this->secury->hmac($marker, $time . $this->key) . 'f' . $time;
}
@ -60,10 +60,10 @@ class Csrf
*/
public function verify($token, $marker, array $args = [])
{
return is_string($token)
&& preg_match('%f(\d+)$%D', $token, $matches)
&& $matches[1] < time()
&& $matches[1] + 1800 > time()
&& hash_equals($this->create($marker, $args, $matches[1]), $token);
return \is_string($token)
&& \preg_match('%f(\d+)$%D', $token, $matches)
&& $matches[1] < \time()
&& $matches[1] + 1800 > \time()
&& \hash_equals($this->create($marker, $args, $matches[1]), $token);
}
}

View file

@ -58,8 +58,8 @@ class DB extends PDO
*/
public function __construct($dsn, $username = null, $password = null, array $options = [], $prefix = '')
{
$type = strstr($dsn, ':', true);
if (! $type || ! file_exists(__DIR__ . '/DB/' . ucfirst($type) . '.php')) {
$type = \strstr($dsn, ':', true);
if (! $type || ! \file_exists(__DIR__ . '/DB/' . \ucfirst($type) . '.php')) {
throw new PDOException("Driver isn't found for '$type'");
}
$this->dbType = $type;
@ -86,7 +86,7 @@ class DB extends PDO
public function __call($name, array $args)
{
if (empty($this->dbDrv)) {
$drv = 'ForkBB\\Core\\DB\\' . ucfirst($this->dbType);
$drv = 'ForkBB\\Core\\DB\\' . \ucfirst($this->dbType);
$this->dbDrv = new $drv($this, $this->dbPrefix);
}
return $this->dbDrv->$name(...$args);
@ -104,7 +104,7 @@ class DB extends PDO
$verify = [self::ATTR_CURSOR => [self::CURSOR_FWDONLY, self::CURSOR_SCROLL]];
foreach ($arr as $key => $value) {
if (! isset($verify[$key]) || ! in_array($value, $verify[$key])) {
if (! isset($verify[$key]) || ! \in_array($value, $verify[$key])) {
return false;
}
}
@ -126,7 +126,7 @@ class DB extends PDO
$idxIn = 0;
$idxOut = 1;
$map = [];
$query = preg_replace_callback(
$query = \preg_replace_callback(
'%(?=[?:])(?<![\w?:])(?:::(\w+)|\?(?![?:])(?:(\w+)(?::(\w+))?)?|:(\w+))%',
function($matches) use ($params, &$idxIn, &$idxOut, &$map) {
if (! empty($matches[1])) {
@ -155,7 +155,7 @@ class DB extends PDO
break;
}
if (! is_array($value)) {
if (! \is_array($value)) {
throw new PDOException("Expected array: key='{$key}', type='{$type}'");
}
@ -169,7 +169,7 @@ class DB extends PDO
$res[] = $name;
$map[$key][] = $name;
}
return implode(',', $res);
return \implode(',', $res);
},
$query
);
@ -189,13 +189,13 @@ class DB extends PDO
public function getValue($key, array $params)
{
if (
is_string($key)
&& (isset($params[':' . $key]) || array_key_exists(':' . $key, $params))
\is_string($key)
&& (isset($params[':' . $key]) || \array_key_exists(':' . $key, $params))
) {
return $params[':' . $key];
} elseif (
(is_string($key) || is_int($key))
&& (isset($params[$key]) || array_key_exists($key, $params))
(\is_string($key) || \is_int($key))
&& (isset($params[$key]) || \array_key_exists($key, $params))
) {
return $params[$key];
}
@ -249,15 +249,15 @@ class DB extends PDO
$map = $this->parse($query, $params);
if (empty($params)) {
$start = microtime(true);
$start = \microtime(true);
$result = parent::exec($query);
$this->saveQuery($query, microtime(true) - $start);
$this->saveQuery($query, \microtime(true) - $start);
return $result;
}
$start = microtime(true);
$start = \microtime(true);
$stmt = parent::prepare($query);
$this->delta = microtime(true) - $start;
$this->delta = \microtime(true) - $start;
$stmt->setMap($map);
@ -292,9 +292,9 @@ class DB extends PDO
$map = $this->parse($query, $params);
$start = microtime(true);
$start = \microtime(true);
$stmt = parent::prepare($query, $options);
$this->delta = microtime(true) - $start;
$this->delta = \microtime(true) - $start;
$stmt->setMap($map);
@ -313,8 +313,8 @@ class DB extends PDO
*/
public function query($query, ...$args)
{
if (isset($args[0]) && is_array($args[0])) {
$params = array_shift($args);
if (isset($args[0]) && \is_array($args[0])) {
$params = \array_shift($args);
} else {
$params = [];
}
@ -322,15 +322,15 @@ class DB extends PDO
$map = $this->parse($query, $params);
if (empty($params)) {
$start = microtime(true);
$start = \microtime(true);
$result = parent::query($query, ...$args);
$this->saveQuery($query, microtime(true) - $start);
$this->saveQuery($query, \microtime(true) - $start);
return $result;
}
$start = microtime(true);
$start = \microtime(true);
$stmt = parent::prepare($query);
$this->delta = microtime(true) - $start;
$this->delta = \microtime(true) - $start;
$stmt->setMap($map);

View file

@ -81,7 +81,7 @@ class Mysql
*/
protected function testStr($str)
{
if (! is_string($str) || preg_match('%[^a-zA-Z0-9_]%', $str)) {
if (! \is_string($str) || \preg_match('%[^a-zA-Z0-9_]%', $str)) {
throw new PDOException("Name '{$str}' have bad characters.");
}
}
@ -96,7 +96,7 @@ class Mysql
protected function replIdxs(array $arr)
{
foreach ($arr as &$value) {
if (preg_match('%^(.*)\s*(\(\d+\))$%', $value, $matches)) {
if (\preg_match('%^(.*)\s*(\(\d+\))$%', $value, $matches)) {
$this->testStr($matches[1]);
$value = "`{$matches[1]}`{$matches[2]}";
} else {
@ -105,7 +105,7 @@ class Mysql
}
unset($value);
}
return implode(',', $arr);
return \implode(',', $arr);
}
/**
@ -117,7 +117,7 @@ class Mysql
*/
protected function replType($type)
{
return preg_replace(array_keys($this->dbTypeRepl), array_values($this->dbTypeRepl), $type);
return \preg_replace(\array_keys($this->dbTypeRepl), \array_values($this->dbTypeRepl), $type);
}
/**
@ -130,11 +130,11 @@ class Mysql
* @return string
*/
protected function convToStr($data) {
if (is_string($data)) {
if (\is_string($data)) {
return $this->db->quote($data);
} elseif (is_numeric($data)) {
} elseif (\is_numeric($data)) {
return (string) $data;
} elseif (is_bool($data)) {
} elseif (\is_bool($data)) {
return $data ? 'true' : 'false';
} else {
throw new PDOException('Invalid data type for DEFAULT.');
@ -226,9 +226,9 @@ class Mysql
// имя и тип
$query .= "`{$field}` " . $this->replType($data[0]);
// сравнение
if (preg_match('%^(?:CHAR|VARCHAR|TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|ENUM|SET)%i', $data[0])) {
if (\preg_match('%^(?:CHAR|VARCHAR|TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|ENUM|SET)%i', $data[0])) {
$query .= ' CHARACTER SET utf8mb4 COLLATE utf8mb4_';
if (isset($data[3]) && is_string($data[3])) {
if (isset($data[3]) && \is_string($data[3])) {
$this->testStr($data[3]);
$query .= $data[3];
} else {
@ -264,7 +264,7 @@ class Mysql
$engine = $schema['ENGINE'];
} else {
// при отсутствии типа таблицы он определяется на основании типов других таблиц в базе
$prefix = str_replace('_', '\\_', $this->dbPrefix);
$prefix = \str_replace('_', '\\_', $this->dbPrefix);
$stmt = $this->db->query("SHOW TABLE STATUS LIKE '{$prefix}%'");
$engine = [];
while ($row = $stmt->fetch()) {
@ -278,14 +278,14 @@ class Mysql
if (empty($engine)) {
$engine = 'MyISAM';
} else {
arsort($engine);
\arsort($engine);
// берем тип наиболее часто встречаемый у имеющихся таблиц
$engine = array_keys($engine);
$engine = array_shift($engine);
$engine = \array_keys($engine);
$engine = \array_shift($engine);
}
}
$this->testStr($engine);
$query = rtrim($query, ', ') . ") ENGINE={$engine} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
$query = \rtrim($query, ', ') . ") ENGINE={$engine} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
return $this->db->exec($query) !== false;
}
@ -507,7 +507,7 @@ class Mysql
$engine[$row['Engine']] = 1;
}
}
arsort($engine);
\arsort($engine);
$tmp = [];
foreach ($engine as $key => $val) {
$tmp[] = "{$key}({$val})";
@ -515,15 +515,15 @@ class Mysql
$other = [];
$stmt = $this->db->query("SHOW VARIABLES LIKE 'character\_set\_%'");
while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$other[$row[0]] = $row[1];
}
return [
'db' => 'MySQL (PDO) ' . $this->db->getAttribute(\PDO::ATTR_SERVER_VERSION) . ' : ' . implode(', ', $tmp),
'db' => 'MySQL (PDO) ' . $this->db->getAttribute(PDO::ATTR_SERVER_VERSION) . ' : ' . implode(', ', $tmp),
'records' => $records,
'size' => $size,
'server info' => $this->db->getAttribute(\PDO::ATTR_SERVER_INFO),
'server info' => $this->db->getAttribute(PDO::ATTR_SERVER_INFO),
] + $other;
}
@ -540,10 +540,10 @@ class Mysql
while ($row = $stmt->fetch()) {
if ($table !== $row['TABLE_NAME']) {
$table = $row['TABLE_NAME'];
$tableNoPref = substr($table, strlen($this->dbPrefix));
$tableNoPref = \substr($table, \strlen($this->dbPrefix));
$result[$tableNoPref] = [];
}
$type = strtolower($row['DATA_TYPE']);
$type = \strtolower($row['DATA_TYPE']);
$result[$tableNoPref][$row['COLUMN_NAME']] = isset($this->types[$type]) ? $this->types[$type] : 's';
}
return $result;

View file

@ -64,16 +64,16 @@ class DBStatement extends PDOStatement
public function bindValueList(array $params)
{
foreach ($this->map as $key => $data) {
$type = array_shift($data);
$type = \array_shift($data);
$bType = $this->types[$type];
$bValue = $this->db->getValue($key, $params);
if ($type{0} === 'a') {
if (! is_array($bValue)) {
if (! \is_array($bValue)) {
throw new PDOException("Expected array: key='{$key}'");
}
foreach ($data as $bParam) {
parent::bindValue($bParam, array_shift($bValue), $bType); //????
parent::bindValue($bParam, \array_shift($bValue), $bType); //????
}
} else {
foreach ($data as $bParam) {
@ -92,12 +92,12 @@ class DBStatement extends PDOStatement
*/
public function execute($params = null)
{
if (is_array($params) && ! empty($params)) {
if (\is_array($params) && ! empty($params)) {
$this->bindValueList($params);
}
$start = microtime(true);
$start = \microtime(true);
$result = parent::execute();
$this->db->saveQuery($this->queryString, microtime(true) - $start);
$this->db->saveQuery($this->queryString, \microtime(true) - $start);
return $result;
}
}

View file

@ -40,9 +40,9 @@ class Func
public function getStyles()
{
if (empty($this->styles)) {
$this->styles = array_map(function($style) {
return str_replace([$this->c->DIR_PUBLIC . '/style/', '/style.css'], '', $style);
}, glob($this->c->DIR_PUBLIC . '/style/*/style.css'));
$this->styles = \array_map(function($style) {
return \str_replace([$this->c->DIR_PUBLIC . '/style/', '/style.css'], '', $style);
}, \glob($this->c->DIR_PUBLIC . '/style/*/style.css'));
}
return $this->styles;
}
@ -55,9 +55,9 @@ class Func
public function getLangs()
{
if (empty($this->langs)) {
$this->langs = array_map(function($lang) {
return str_replace([$this->c->DIR_LANG . '/', '/common.po'], '', $lang);
}, glob($this->c->DIR_LANG . '/*/common.po'));
$this->langs = \array_map(function($lang) {
return \str_replace([$this->c->DIR_LANG . '/', '/common.po'], '', $lang);
}, \glob($this->c->DIR_LANG . '/*/common.po'));
}
return $this->langs;
}
@ -81,7 +81,7 @@ class Func
} else {
if ($cur > 0) {
$pages[] = [\ForkBB\__($info, $cur, $all), 'info', null];
$cur = min(max(1, $cur), $all);
$cur = \min(\max(1, $cur), $all);
if ($cur > 1) {
$pages[] = [$this->c->Router->link($marker, ['page' => $cur - 1] + $args), 'prev', null];
}
@ -94,7 +94,7 @@ class Func
$tpl[$all] = $all;
} else {
$tpl = $all < 7
? array_slice([2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6], 0, $all - 1)
? \array_slice([2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6], 0, $all - 1)
: [2 => 2, 3 => 3, 4 => 4, $all => $all];
}
$k = 1;

View file

@ -79,8 +79,8 @@ class Lang
do {
$flag = true;
$fullPath = $path . '/'. $lang . '/' . $name . '.po';
if (file_exists($fullPath)) {
$file = file_get_contents($fullPath);
if (\file_exists($fullPath)) {
$file = \file_get_contents($fullPath);
if (isset($this->tr[$lang])) {
$this->tr[$lang] += $this->arrayFromStr($file);
} else {
@ -107,8 +107,8 @@ class Lang
*/
protected function arrayFromStr($str)
{
$lines = explode("\n", $str);
$count = count($lines);
$lines = \explode("\n", $str);
$count = \count($lines);
$result = [];
$cur = [];
$curComm = null;
@ -117,7 +117,7 @@ class Lang
$plural = '($n != 1);';
for ($i = 0; $i < $count; ++$i) {
$line = trim($lines[$i]);
$line = \trim($lines[$i]);
// пустая строка
if (! isset($line{0})) {
@ -133,11 +133,11 @@ class Lang
// заголовки
if (! isset($cur['msgid']{0})) {
if (preg_match('%Plural\-Forms:\s+nplurals=(\d+);\s*plural=([^;\n\r]+;)%i', $cur[0], $v)) {
if (\preg_match('%Plural\-Forms:\s+nplurals=(\d+);\s*plural=([^;\n\r]+;)%i', $cur[0], $v)) {
$nplurals = (int) $v[1];
$plural = str_replace('n', '$n', trim($v[2]));
$plural = str_replace(':', ': (', $plural, $curVal);
$plural = str_replace(';', str_repeat(')', $curVal). ';', $plural);
$plural = \str_replace('n', '$n', \trim($v[2]));
$plural = \str_replace(':', ': (', $plural, $curVal);
$plural = \str_replace(';', \str_repeat(')', $curVal). ';', $plural);
}
// перевод
@ -194,9 +194,9 @@ class Lang
}
// выделение команды
$v = explode(' ', $line, 2);
$v = \explode(' ', $line, 2);
$command = $v[0];
$v = isset($v[1]) ? $this->originalLine(trim($v[1])) : '';
$v = isset($v[1]) ? $this->originalLine(\trim($v[1])) : '';
switch ($command) {
case 'msgctxt':
@ -255,10 +255,10 @@ class Lang
*/
protected function originalLine($line)
{
if (isset($line[1]) && $line{0} == '"' && $line{strlen($line) - 1} == '"') {
$line = substr($line, 1, -1);
if (isset($line[1]) && $line{0} == '"' && $line{\strlen($line) - 1} == '"') {
$line = \substr($line, 1, -1);
}
return str_replace(
return \str_replace(
['\\n', '\\t', '\\"', '\\\\'],
["\n", "\t", '"', '\\'],
$line

View file

@ -63,8 +63,8 @@ class Mail
*/
public function __construct($host, $user, $pass, $ssl, $eol)
{
if (is_string($host) && strlen(trim($host)) > 0 ) {
list ($host, $port) = explode(':', $host);
if (\is_string($host) && \strlen(\trim($host)) > 0 ) {
list($host, $port) = \explode(':', $host);
if (empty($port) || $port < 1 || $port > 65535) {
$port = 25;
}
@ -76,7 +76,7 @@ class Mail
];
$this->EOL = "\r\n";
} else {
$this->EOL = in_array($eol, ["\r\n", "\n", "\r"]) ? $eol : PHP_EOL;
$this->EOL = \in_array($eol, ["\r\n", "\n", "\r"]) ? $eol : PHP_EOL;
}
}
@ -91,34 +91,34 @@ class Mail
*/
public function valid($email, $strict = false, $idna = false)
{
if (! is_string($email)
|| mb_strlen($email, 'UTF-8') > 80 //?????
|| ! preg_match('%^([^\x00-\x1F\\\/\s@]+)@([^\x00-\x1F\s@]+)$%Du', $email, $matches)
if (! \is_string($email)
|| \mb_strlen($email, 'UTF-8') > 80 //?????
|| ! \preg_match('%^([^\x00-\x1F\\\/\s@]+)@([^\x00-\x1F\s@]+)$%Du', $email, $matches)
) {
return false;
}
$local = $matches[1];
$domain = mb_strtolower($matches[2], 'UTF-8');
$domain = \mb_strtolower($matches[2], 'UTF-8');
if ($domain{0} === '[' && substr($domain, -1) === ']') {
$ip = substr($domain, 1, -1);
if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
if ($domain{0} === '[' && \substr($domain, -1) === ']') {
$ip = \substr($domain, 1, -1);
if (! \filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
return $false;
}
$domainASCII = $domain;
} else {
$ip = null;
if (! preg_match('%^(?:[\p{L}\p{N}]+(?:\-[\p{L}\p{N}]+)*\.)*\p{L}+$%u', $domain)) {
if (! \preg_match('%^(?:[\p{L}\p{N}]+(?:\-[\p{L}\p{N}]+)*\.)*\p{L}+$%u', $domain)) {
return false;
}
$domainASCII = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46);
$domainASCII = \idn_to_ascii($domain, 0, \INTL_IDNA_VARIANT_UTS46);
}
if ($strict) {
if ($ip) {
$mx = @checkdnsrr($ip, 'MX');
$mx = @\checkdnsrr($ip, 'MX');
} else {
$mx = @dns_get_record($domainASCII, DNS_MX);
$mx = @\dns_get_record($domainASCII, \DNS_MX);
}
if (empty($mx)) {
return false;
@ -149,7 +149,7 @@ class Mail
*/
public function setSubject($subject)
{
$this->headers['Subject'] = $this->encodeText(preg_replace('%[\x00-\x1F]%', '', trim($subject)));
$this->headers['Subject'] = $this->encodeText(\preg_replace('%[\x00-\x1F]%', '', \trim($subject)));
return $this;
}
@ -163,12 +163,12 @@ class Mail
*/
public function addTo($email, $name = null)
{
if (is_array($email)) {
if (\is_array($email)) {
} else {
$email = preg_split('%[,\n\r]%', (string) $email, -1, PREG_SPLIT_NO_EMPTY);
$email = \preg_split('%[,\n\r]%', (string) $email, -1, PREG_SPLIT_NO_EMPTY);
}
foreach($email as $cur) {
$cur = $this->valid(trim((string) $cur), false, true);
$cur = $this->valid(\trim((string) $cur), false, true);
if (false !== $cur) {
$this->to[] = $this->formatAddress($cur, $name);
}
@ -234,11 +234,11 @@ class Mail
*/
protected function formatAddress($email, $name = null)
{
if (! is_string($name) || strlen(trim($name)) == 0) {
if (! \is_string($name) || \strlen(\trim($name)) == 0) {
return $email;
} else {
$name = $this->encodeText($this->filterName($name));
return sprintf('"%s" <%s>', $name, $email);
return \sprintf('"%s" <%s>', $name, $email);
}
}
@ -251,8 +251,8 @@ class Mail
*/
protected function encodeText($str)
{
if (preg_match('%[^\x20-\x7F]%', $str)) {
return '=?UTF-8?B?' . base64_encode($str) . '?=';
if (\preg_match('%[^\x20-\x7F]%', $str)) {
return '=?UTF-8?B?' . \base64_encode($str) . '?=';
} else {
return $str;
}
@ -267,7 +267,7 @@ class Mail
*/
protected function filterName($name)
{
return addcslashes(preg_replace('%[\x00-\x1F]%', '', trim($name)), '\\"');
return \addcslashes(\preg_replace('%[\x00-\x1F]%', '', \trim($name)), '\\"');
}
/**
@ -308,19 +308,19 @@ class Mail
*/
public function setTpl($tpl, array $data)
{
$file = rtrim($this->folder, '\\/') . '/' . $this->language . '/mail/' . $tpl;
if (! file_exists($file)) {
$file = \rtrim($this->folder, '\\/') . '/' . $this->language . '/mail/' . $tpl;
if (! \file_exists($file)) {
throw new MailException('The template isn\'t found (' . $file . ').');
}
$tpl = trim(file_get_contents($file));
$tpl = \trim(\file_get_contents($file));
foreach ($data as $key => $val) {
$tpl = str_replace('<' . $key . '>', (string) $val, $tpl);
$tpl = \str_replace('<' . $key . '>', (string) $val, $tpl);
}
list($subject, $tpl) = explode("\n", $tpl, 2);
list($subject, $tpl) = \explode("\n", $tpl, 2);
if (! isset($tpl)) {
throw new MailException('The template is empty (' . $file . ').');
}
$this->setSubject(substr($subject, 8));
$this->setSubject(\substr($subject, 8));
return $this->setMessage($tpl);
}
@ -333,9 +333,9 @@ class Mail
*/
public function setMessage($message)
{
$this->message = str_replace("\0", $this->EOL,
str_replace(["\r\n", "\n", "\r"], "\0",
str_replace("\0", '', trim($message))));
$this->message = \str_replace("\0", $this->EOL,
\str_replace(["\r\n", "\n", "\r"], "\0",
\str_replace("\0", '', \trim($message))));
// $this->message = wordwrap ($this->message, 75, $this->EOL, false);
return $this;
}
@ -362,15 +362,15 @@ class Mail
throw new MailException('The body of the email is empty.');
}
$this->headers = array_replace($this->headers, [
'Date' => gmdate('r'),
$this->headers = \array_replace($this->headers, [
'Date' => \gmdate('r'),
'MIME-Version' => '1.0',
'Content-transfer-encoding' => '8bit',
'Content-type' => 'text/plain; charset=utf-8',
'X-Mailer' => 'ForkBB Mailer',
]);
if (is_array($this->smtp)) {
if (\is_array($this->smtp)) {
return $this->smtp();
} else {
return $this->mail();
@ -384,12 +384,12 @@ class Mail
*/
protected function mail()
{
$to = implode(', ', $this->to);
$to = \implode(', ', $this->to);
$subject = $this->headers['Subject'];
$headers = $this->headers;
unset($headers['Subject']);
$headers = $this->strHeaders($headers);
return @mail($to, $subject, $this->message, $headers);
return @\mail($to, $subject, $this->message, $headers);
}
/**
@ -405,7 +405,7 @@ class Mail
$value = $key . ': ' . $value;
}
unset($value);
return join($this->EOL, $headers);
return \implode($this->EOL, $headers);
}
/**
@ -418,16 +418,16 @@ class Mail
protected function smtp()
{
// подлючение
if (! is_resource($this->connect)) {
if (($connect = @fsockopen($this->smtp['host'], $this->smtp['port'], $errno, $errstr, 5)) === false) {
if (! \is_resource($this->connect)) {
if (($connect = @\fsockopen($this->smtp['host'], $this->smtp['port'], $errno, $errstr, 5)) === false) {
throw new SmtpException('Couldn\'t connect to smtp host "' . $this->smtp['host'] . ':' . $this->smtp['port'] . '" (' . $errno . ') (' . $errstr . ').');
}
stream_set_timeout($connect, 5);
\stream_set_timeout($connect, 5);
$this->connect = $connect;
$this->smtpData(null, '220');
}
$message = $this->EOL . str_replace("\n.", "\n..", $this->EOL . $this->message) . $this->EOL . '.';
$message = $this->EOL . \str_replace("\n.", "\n..", $this->EOL . $this->message) . $this->EOL . '.';
$headers = $this->strHeaders($this->headers);
// цикл по получателям
@ -456,8 +456,8 @@ class Mail
$code = $this->smtpData('EHLO ' . $this->hostname(), ['250', '500', '501', '502', '550']);
if ($code === '250') {
$this->smtpData('AUTH LOGIN', '334');
$this->smtpData(base64_encode($this->smtp['user']), '334');
$this->smtpData(base64_encode($this->smtp['pass']), '235');
$this->smtpData(\base64_encode($this->smtp['user']), '334');
$this->smtpData(\base64_encode($this->smtp['pass']), '235');
$this->auth = 1;
return;
}
@ -482,23 +482,23 @@ class Mail
*/
protected function smtpData($data, $code)
{
if (is_resource($this->connect) && is_string($data)) {
if (@fwrite($this->connect, $data . $this->EOL) === false) {
if (\is_resource($this->connect) && \is_string($data)) {
if (@\fwrite($this->connect, $data . $this->EOL) === false) {
throw new SmtpException('Couldn\'t send data to mail server.');
}
}
$response = '';
while (is_resource($this->connect) && ! feof($this->connect)) {
if (($get = @fgets($this->connect, 512)) === false) {
while (\is_resource($this->connect) && ! \feof($this->connect)) {
if (($get = @\fgets($this->connect, 512)) === false) {
throw new SmtpException('Couldn\'t get mail server response codes.');
}
$response .= $get;
if (isset($get{3}) && $get{3} === ' ') {
$return = substr($get, 0, 3);
$return = \substr($get, 0, 3);
break;
}
}
if ($code !== null && ! in_array($return, (array) $code)) {
if ($code !== null && ! \in_array($return, (array) $code)) {
throw new SmtpException('Unable to send email. Response of mail server: "' . $get . '"');
}
return $return;
@ -513,9 +513,9 @@ class Mail
*/
protected function getEmailFrom($str)
{
$match = explode('" <', $str);
if (count($match) == 2 && substr($match[1], -1) == '>') {
return rtrim($match[1], '>');
$match = \explode('" <', $str);
if (\count($match) == 2 && \substr($match[1], -1) == '>') {
return \rtrim($match[1], '>');
} else {
return $str;
}
@ -539,13 +539,13 @@ class Mail
public function __destruct()
{
// завершение сеанса smtp
if (is_resource($this->connect)) {
if (\is_resource($this->connect)) {
try {
$this->smtpData('QUIT', null);
} catch (MailException $e) {
//????
}
@fclose($this->connect);
@\fclose($this->connect);
}
}
}

View file

@ -101,7 +101,7 @@ class Parser extends Parserus
$this->detectUrls();
}
return preg_replace('%^(\x20*\n)+|(\n\x20*)+$%D', '', $this->getCode());
return \preg_replace('%^(\x20*\n)+|(\n\x20*)+$%D', '', $this->getCode());
}
/**
@ -118,7 +118,7 @@ class Parser extends Parserus
if (null !== $text) {
$whiteList = $this->c->config->p_message_bbcode == '1' ? null : [];
$blackList = $this->c->config->p_message_img_tag == '1' ? [] : ['img'];
$this->setAttr('isSign', false)
->setWhiteList($whiteList)
->setBlackList($blackList)
@ -145,7 +145,7 @@ class Parser extends Parserus
if (null !== $text) {
$whiteList = $this->c->config->p_sig_bbcode == '1' ? $this->c->BBCODE_INFO['forSign'] : [];
$blackList = $this->c->config->p_sig_img_tag == '1' ? [] : ['img'];
$this->setAttr('isSign', true)
->setWhiteList($whiteList)
->setBlackList($blackList)

View file

@ -27,7 +27,7 @@ class Secury
if (empty($hmac['salt']) || empty($hmac['algo'])) {
throw new InvalidArgumentException('Algorithm and salt can not be empty');
}
if (! in_array($hmac['algo'], hash_algos())) {
if (! \in_array($hmac['algo'], \hash_algos())) {
throw new UnexpectedValueException('Algorithm not supported');
}
$this->hmac = $hmac;
@ -42,7 +42,7 @@ class Secury
*/
public function hash($data)
{
return $this->hmac($data, md5(__DIR__));
return $this->hmac($data, \md5(__DIR__));
}
/**
@ -60,7 +60,7 @@ class Secury
if (empty($key)) {
throw new InvalidArgumentException('Key can not be empty');
}
return hash_hmac($this->hmac['algo'], $data, $key . $this->hmac['salt']);
return \hash_hmac($this->hmac['algo'], $data, $key . $this->hmac['salt']);
}
/**
@ -75,19 +75,19 @@ class Secury
public function randomKey($len)
{
$key = '';
if (function_exists('random_bytes')) {
$key .= (string) random_bytes($len);
if (\function_exists('random_bytes')) {
$key .= (string) \random_bytes($len);
}
if (strlen($key) < $len && function_exists('mcrypt_create_iv')) {
$key .= (string) mcrypt_create_iv($len, MCRYPT_DEV_URANDOM);
if (\strlen($key) < $len && \function_exists('mcrypt_create_iv')) {
$key .= (string) \mcrypt_create_iv($len, \MCRYPT_DEV_URANDOM);
}
if (strlen($key) < $len && function_exists('openssl_random_pseudo_bytes')) {
$tmp = (string) openssl_random_pseudo_bytes($len, $strong);
if (\strlen($key) < $len && \function_exists('openssl_random_pseudo_bytes')) {
$tmp = (string) \openssl_random_pseudo_bytes($len, $strong);
if ($strong) {
$key .= $tmp;
}
}
if (strlen($key) < $len) {
if (\strlen($key) < $len) {
throw new RuntimeException('Could not gather sufficient random data');
}
return $key;
@ -102,7 +102,7 @@ class Secury
*/
public function randomHash($len)
{
return substr(bin2hex($this->randomKey($len)), 0, $len);
return \substr(\bin2hex($this->randomKey($len)), 0, $len);
}
/**
@ -119,7 +119,7 @@ class Secury
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
$result = '';
for ($i = 0; $i < $len; ++$i) {
$result .= substr($chars, (ord($key[$i]) % strlen($chars)), 1);
$result .= \substr($chars, (\ord($key[$i]) % \strlen($chars)), 1);
}
return $result;
}
@ -133,15 +133,15 @@ class Secury
*/
public function replInvalidChars($data)
{
if (is_array($data)) {
return array_map([$this, 'replInvalidChars'], $data);
if (\is_array($data)) {
return \array_map([$this, 'replInvalidChars'], $data);
}
// Replacing invalid UTF-8 characters
// slow, small memory
//$data = mb_convert_encoding((string) $data, 'UTF-8', 'UTF-8');
// fast, large memory
$data = htmlspecialchars_decode(htmlspecialchars((string) $data, ENT_SUBSTITUTE, 'UTF-8'));
$data = \htmlspecialchars_decode(\htmlspecialchars((string) $data, \ENT_SUBSTITUTE, 'UTF-8'));
// Remove control characters
return preg_replace('%[\x00-\x08\x0B-\x0C\x0E-\x1F]%', '', $data);
return \preg_replace('%[\x00-\x08\x0B-\x0C\x0E-\x1F]%', '', $data);
}
}

View file

@ -614,7 +614,7 @@ class Validator
$this->addError('The :alias maximum is :attr');
}
} elseif (\is_array($value)) {
if (count($value) > $attr) {
if (\count($value) > $attr) {
$this->addError('The :alias maximum is :attr elements');
}
} elseif (null !== $value) {
@ -677,7 +677,7 @@ class Validator
protected function vRegex($v, $value, $attr)
{
if (null !== $value
&& (! is_string($value) || ! \preg_match($attr, $value))
&& (! \is_string($value) || ! \preg_match($attr, $value))
) {
$this->addError('The :alias is not valid format');
return null;

View file

@ -14,7 +14,7 @@ class View extends Dirk
'views' => $views,
'cache' => $cache,
'ext' => '.tpl',
'echo' => 'htmlspecialchars(%s, ENT_HTML5 | ENT_QUOTES | ENT_SUBSTITUTE, \'UTF-8\')',
'echo' => '\\htmlspecialchars(%s, \\ENT_HTML5 | \\ENT_QUOTES | \\ENT_SUBSTITUTE, \'UTF-8\')',
'separator' => '/',
];
$this->compilers[] = 'Transformations';

View file

@ -34,11 +34,11 @@ class BanList extends Model
*/
public function trimToNull($val, $toLower = false)
{
$val = trim($val);
$val = \trim($val);
if ($val == '') {
return null;
} elseif ($toLower) {
return mb_strtolower($val, 'UTF-8');
return \mb_strtolower($val, 'UTF-8');
} else {
return $val;
}

View file

@ -23,7 +23,7 @@ class Check extends Method
}
// удаление просроченных банов
$now = time();
$now = \time();
$ids = [];
foreach ($this->model->otherList as $id => $row) {
if (null !== $row['expire'] && $row['expire'] < $now) {
@ -40,11 +40,11 @@ class Check extends Method
if (null === $ip) {
return false; //????
}
$add = strpos($ip, ':') === false ? '.' : ':'; //????
$add = \strpos($ip, ':') === false ? '.' : ':'; //????
$ip .= $add;
foreach ($this->model->ipList as $addr => $id) {
$addr .= $add;
if (substr($ip, 0, strlen($addr)) == $addr) {
if (\substr($ip, 0, \strlen($addr)) == $addr) {
if (isset($this->model->otherList[$id])) {
$user->__banInfo = $this->model->otherList[$id];
}

View file

@ -26,8 +26,8 @@ class Load extends Method
$ips = $this->model->trimToNull($row['ip']);
if (null !== $ips) {
foreach (explode(' ', $ips) as $ip) {
$ip = trim($ip);
foreach (\explode(' ', $ips) as $ip) {
$ip = \trim($ip);
if ($ip != '') {
$ipList[$ip] = $row['id'];
}

View file

@ -8,7 +8,7 @@ class Model extends ParentModel
{
/**
* Загружает список цензуры из кеша/БД
*
*
* @return Censorship
*/
public function init()
@ -35,7 +35,7 @@ class Model extends ParentModel
public function censor($str)
{
if ('1' == $this->c->config->o_censoring) {
return (string) preg_replace($this->searchList, $this->replaceList, $str);
return (string) \preg_replace($this->searchList, $this->replaceList, $str);
} else {
return $str;
}

View file

@ -18,7 +18,7 @@ class Refresh extends Method
$search = [];
$replace = [];
while ($row = $stmt->fetch()) {
$search[$row['id']] = '%(?<![\p{L}\p{N}])('.str_replace('\*', '[\p{L}\p{N}]*?', preg_quote($row['search_for'], '%')).')(?![\p{L}\p{N}])%iu';
$search[$row['id']] = '%(?<![\p{L}\p{N}])(' . \str_replace('\*', '[\p{L}\p{N}]*?', \preg_quote($row['search_for'], '%')).')(?![\p{L}\p{N}])%iu';
$replace[$row['id']] = $row['replace_with'];
}
$this->model->searchList = $search;

View file

@ -54,7 +54,7 @@ class Cookie extends Model
*/
public function set($name, $value, $expire = 0, $path = null, $domain = null, $secure = false, $httponly = true)
{
$result = setcookie(
$result = \setcookie(
$this->prefix . $name,
$value,
$expire,
@ -109,14 +109,14 @@ class Cookie extends Model
$ckUser = $this->get(self::NAME);
if (null === $ckUser
|| ! preg_match('%^(\-)?(\d{1,10})_(\d{10})_([a-f\d]{32,})_([a-f\d]{32,})$%Di', $ckUser, $ms)
|| ! \preg_match('%^(\-)?(\d{1,10})_(\d{10})_([a-f\d]{32,})_([a-f\d]{32,})$%Di', $ckUser, $ms)
) {
return;
}
if (2 > $ms[2]
|| time() > $ms[3]
|| ! hash_equals(
|| \time() > $ms[3]
|| ! \hash_equals(
$this->c->Secury->hmac($ms[1] . $ms[2] . $ms[3] . $ms[4], $this->key1),
$ms[5]
)
@ -140,7 +140,7 @@ class Cookie extends Model
public function verifyUser(User $user)
{
return $this->uId === (int) $user->id
&& hash_equals(
&& \hash_equals(
(string) $this->uHash,
$this->c->Secury->hmac($user->password . $this->uExpire, $this->key2)
);
@ -166,11 +166,11 @@ class Cookie extends Model
&& $this->uRemember
)
) {
$expTime = time() + $this->time;
$expTime = \time() + $this->time;
$expire = $expTime;
$pfx = '';
} else {
$expTime = time() + $this->c->config->o_timeout_visit;
$expTime = \time() + $this->c->config->o_timeout_visit;
$expire = 0;
$pfx = '-';
}

View file

@ -31,9 +31,9 @@ class DataModel extends Model
/**
* Перезапись свойст модели
*
*
* @param array $attrs
*
*
* @return DataModel
*/
public function replAttrs(array $attrs)
@ -43,7 +43,7 @@ class DataModel extends Model
unset($this->aCalc['key']);
}
$modified = array_diff(array_keys($this->modified), array_keys($attrs));
$modified = \array_diff(\array_keys($this->modified), \array_keys($attrs));
$this->modified = [];
foreach ($modified as $key) {
$this->modified[$key] = true;
@ -69,7 +69,7 @@ class DataModel extends Model
*/
public function getModified()
{
return array_keys($this->modified);
return \array_keys($this->modified);
}
/**
@ -89,17 +89,17 @@ class DataModel extends Model
public function __set($name, $val)
{
// без отслеживания
if (strpos($name, '__') === 0) {
if (\strpos($name, '__') === 0) {
$track = null;
$name = substr($name, 2);
// с отслеживанием
} else {
$track = false;
if (array_key_exists($name, $this->a)) {
if (\array_key_exists($name, $this->a)) {
$track = true;
$old = $this->a[$name];
// fix
if (is_int($val) && is_numeric($old) && is_int(0 + $old)) {
if (\is_int($val) && \is_numeric($old) && \is_int(0 + $old)) {
$old = (int) $old;
}
}
@ -111,7 +111,7 @@ class DataModel extends Model
return;
}
if ((! $track && array_key_exists($name, $this->a))
if ((! $track && \array_key_exists($name, $this->a))
|| ($track && $old !== $this->a[$name])
) {
$this->modified[$name] = true;

View file

@ -33,7 +33,7 @@ class Delete extends Action
}
$forums[$arg->id] = $arg;
$all[$arg->id] = true;
foreach (array_keys($arg->descendants) as $id) { //???? а если не админ?
foreach (\array_keys($arg->descendants) as $id) { //???? а если не админ?
$all[$id] = true;
}
} else {
@ -41,7 +41,7 @@ class Delete extends Action
}
}
if (array_diff_key($all, $forums)) {
if (\array_diff_key($all, $forums)) {
throw new RuntimeException('Descendants should not be or they should be deleted too');
}
@ -54,7 +54,7 @@ class Delete extends Action
}
$vars = [
':forums' => array_keys($forums),
':forums' => \array_keys($forums),
];
$sql = 'DELETE FROM ::mark_of_forum
WHERE fid IN (?ai:forums)';

View file

@ -8,9 +8,9 @@ class LoadTree extends Action
{
/**
* Загружает данные в модели для указанного раздела и всех его потомков
*
*
* @param int $rootId
*
*
* @return null|Forum
*/
public function loadTree($rootId)
@ -41,7 +41,7 @@ class LoadTree extends Action
/**
* Загружает данные из БД по списку разделов
*
*
* @param array $list
*/
protected function loadData(array $list)
@ -52,7 +52,7 @@ class LoadTree extends Action
$vars = [
':uid' => $this->c->user->id,
':forums' => array_keys($list),
':forums' => \array_keys($list),
];
if ($this->c->user->isGuest) {
@ -64,15 +64,15 @@ class LoadTree extends Action
$sql = 'SELECT f.id, f.forum_desc, f.num_topics, f.sort_by, f.num_posts,
f.last_post, f.last_post_id, f.last_poster, f.last_topic,
mof.mf_mark_all_read, s.user_id AS is_subscribed
FROM ::forums AS f
LEFT JOIN ::forum_subscriptions AS s ON (s.user_id=?i:uid AND s.forum_id=f.id)
FROM ::forums AS f
LEFT JOIN ::forum_subscriptions AS s ON (s.user_id=?i:uid AND s.forum_id=f.id)
LEFT JOIN ::mark_of_forum AS mof ON (mof.uid=?i:uid AND mof.fid=f.id)
WHERE f.id IN (?ai:forums)';
} else {
$sql = 'SELECT f.id, f.forum_desc, f.num_topics, f.sort_by, f.num_posts,
f.last_post, f.last_post_id, f.last_poster, f.last_topic,
mof.mf_mark_all_read
FROM ::forums AS f
mof.mf_mark_all_read
FROM ::forums AS f
LEFT JOIN ::mark_of_forum AS mof ON (mof.uid=?i:id AND mof.fid=f.id)
WHERE f.id IN (?ai:forums)';
}
@ -85,7 +85,7 @@ class LoadTree extends Action
/**
* Проверяет наличие новых сообщений в разделах по их списку
*
*
* @param array $list
*/
protected function checkForNew(array $list)
@ -96,9 +96,9 @@ class LoadTree extends Action
// предварительная проверка разделов
$time = [];
$max = max((int) $this->c->user->last_visit, (int) $this->c->user->u_mark_all_read);
$max = \max((int) $this->c->user->last_visit, (int) $this->c->user->u_mark_all_read);
foreach ($list as $forum) {
$t = max($max, (int) $forum->mf_mark_all_read);
$t = \max($max, (int) $forum->mf_mark_all_read);
if ($forum->last_post > $t) {
$time[$forum->id] = $t;
}
@ -111,15 +111,15 @@ class LoadTree extends Action
// проверка по темам
$vars = [
':uid' => $this->c->user->id,
':forums' => array_keys($time),
':forums' => \array_keys($time),
':max' => $max,
];
$sql = 'SELECT t.forum_id, t.last_post
FROM ::topics AS t
LEFT JOIN ::mark_of_topic AS mot ON (mot.uid=?i:uid AND mot.tid=t.id)
WHERE t.forum_id IN(?ai:forums)
AND t.last_post>?i:max
AND t.moved_to IS NULL
$sql = 'SELECT t.forum_id, t.last_post
FROM ::topics AS t
LEFT JOIN ::mark_of_topic AS mot ON (mot.uid=?i:uid AND mot.tid=t.id)
WHERE t.forum_id IN(?ai:forums)
AND t.last_post>?i:max
AND t.moved_to IS NULL
AND (mot.mt_last_visit IS NULL OR t.last_post>mot.mt_last_visit)';
$stmt = $this->c->DB->query($sql, $vars);
while ($cur = $stmt->fetch()) {

View file

@ -25,7 +25,7 @@ class Markread extends Action
}
if (0 === $forum->id) {
$user->u_mark_all_read = time();
$user->u_mark_all_read = \time();
$this->c->users->update($user);
@ -41,7 +41,7 @@ class Markread extends Action
$vars = [
':uid' => $user->id,
':fid' => $forum->id,
':mark' => time(),
':mark' => \time(),
];
$sql = 'DELETE FROM ::mark_of_topic
WHERE uid=?i:uid AND tid IN (

View file

@ -17,7 +17,7 @@ class Refresh extends Action
* Обновляет кеш
*
* @param Group $group
*
*
* @return array
*/
public function refresh(Group $group = null)
@ -48,14 +48,14 @@ class Refresh extends Action
$row['moderators'] = $this->formatModers($row['moderators']);
$list[$row['id']] = $row;
}
if (! empty($list)) {
$this->createList($list);
}
}
$this->c->Cache->set('forums_' . $gid, [
'time' => time(),
'time' => \time(),
'list' => $this->list,
]);
return $this->list;
@ -63,14 +63,14 @@ class Refresh extends Action
/**
* Преобразует строку со списком модераторов в массив
*
*
* @param string $str
*
*
* @return null|array
*/
protected function formatModers($str)
{
return empty($str) ? null : array_flip(unserialize($str));
return empty($str) ? null : \array_flip(\unserialize($str));
}
/**
@ -90,7 +90,7 @@ class Refresh extends Action
continue;
}
$sub[] = $id;
$all = array_merge($this->createList($list, $id), $all);
$all = \array_merge($this->createList($list, $id), $all);
}
if (0 === $parent) {
if (empty($sub)) {
@ -99,11 +99,11 @@ class Refresh extends Action
$list[0]['id'] = $parent;
$list[0]['ready'] = true;
}
$all = array_merge($sub, $all);
$all = \array_merge($sub, $all);
$list[$parent]['subforums'] = $sub ?: null;
$list[$parent]['descendants'] = $all ?: null;
$this->list[$parent] = array_filter($list[$parent], function($val) {
$this->list[$parent] = \array_filter($list[$parent], function($val) {
return null !== $val;
});
return $all;

View file

@ -12,9 +12,9 @@ class Save extends Action
* Обновляет раздел в БД
*
* @param Forum $forum
*
*
* @throws RuntimeException
*
*
* @return Forum
*/
public function update(Forum $forum)
@ -41,15 +41,15 @@ class Save extends Action
}
$vars[] = $forum->id;
$this->c->DB->exec('UPDATE ::forums SET ' . implode(', ', $set) . ' WHERE id=?i', $vars);
$this->c->DB->exec('UPDATE ::forums SET ' . \implode(', ', $set) . ' WHERE id=?i', $vars);
// модификация категории у потомков при ее изменении
if (in_array('cat_id', $modified) && $forum->descendants) {
if (\in_array('cat_id', $modified) && $forum->descendants) {
foreach ($forum->descendants as $f) {
$f->__cat_id = $values['cat_id'];
}
$vars = [
':ids' => array_keys($forum->descendants),
':ids' => \array_keys($forum->descendants),
':category' => $values['cat_id'],
];
$sql = 'UPDATE ::forums SET cat_id=?i:category WHERE id IN (?ai:ids)';
@ -66,9 +66,9 @@ class Save extends Action
* Добавляет новый раздел в БД
*
* @param Forum $forum
*
*
* @throws RuntimeException
*
*
* @return int
*/
public function insert(Forum $forum)
@ -90,7 +90,7 @@ class Save extends Action
if (empty($set)) {
throw new RuntimeException('The model is empty');
}
$this->c->DB->query('INSERT INTO ::forums (' . implode(', ', $set) . ') VALUES (' . implode(', ', $set2) . ')', $vars);
$this->c->DB->query('INSERT INTO ::forums (' . \implode(', ', $set) . ') VALUES (' . \implode(', ', $set2) . ')', $vars);
$forum->id = $this->c->DB->lastInsertId();
$forum->resModified();

View file

@ -16,12 +16,12 @@ class Model extends DataModel
protected function getcanDelete()
{
$notDeleted = [
$this->c->GROUP_ADMIN,
$this->c->GROUP_MOD,
$this->c->GROUP_GUEST,
$this->c->GROUP_ADMIN,
$this->c->GROUP_MOD,
$this->c->GROUP_GUEST,
$this->c->GROUP_MEMBER
];
return ! in_array($this->g_id, $notDeleted) && $this->g_id != $this->c->config->o_default_user_group;
return ! \in_array($this->g_id, $notDeleted) && $this->g_id != $this->c->config->o_default_user_group;
}
protected function getlinkDelete()

View file

@ -18,9 +18,9 @@ class Perm extends Action
* Получение таблицы разрешений для раздела
*
* @param Forum $forum
*
*
* @throws RuntimeException
*
*
* @return array
*/
public function get(Forum $forum)
@ -29,9 +29,9 @@ class Perm extends Action
':fid' => $forum->id > 0 ? $forum->id : 0,
':adm' => $this->c->GROUP_ADMIN,
];
$sql = 'SELECT g.g_id, fp.read_forum, fp.post_replies, fp.post_topics
FROM ::groups AS g
LEFT JOIN ::forum_perms AS fp ON (g.g_id=fp.group_id AND fp.forum_id=?i:fid)
$sql = 'SELECT g.g_id, fp.read_forum, fp.post_replies, fp.post_topics
FROM ::groups AS g
LEFT JOIN ::forum_perms AS fp ON (g.g_id=fp.group_id AND fp.forum_id=?i:fid)
WHERE g.g_id!=?i:adm
ORDER BY g.g_id';
$perms = $this->c->DB->query($sql, $vars)->fetchAll(\PDO::FETCH_UNIQUE);
@ -52,7 +52,7 @@ class Perm extends Action
$result[$gid] = $group;
}
$this->fileds = array_keys($perm);
$this->fileds = \array_keys($perm);
return $result;
}
@ -62,7 +62,7 @@ class Perm extends Action
*
* @param Forum $forum
* @param array $perms
*
*
* @throws RuntimeException
*/
public function update(Forum $forum, array $perms)
@ -78,7 +78,7 @@ class Perm extends Action
$row = [];
$modDef = false;
$modPerm = false;
$modPerm = false;
foreach ($this->fileds as $field) {
if ($group->{'dis_' . $field}) {
$row[$field] = $group->{'set_' . $field} ? 1 : 0;
@ -89,26 +89,26 @@ class Perm extends Action
$modPerm = $row[$field] !== (int) $group->{'set_' . $field} ? true : $modPerm;
}
}
if ($modDef || $modPerm) {
$vars = [
':gid' => $id,
':fid' => $forum->id,
];
$sql = 'DELETE FROM ::forum_perms
$sql = 'DELETE FROM ::forum_perms
WHERE group_id=?i:gid AND forum_id=?i:fid';
$this->c->DB->exec($sql, $vars);
}
if ($modDef) {
$vars = array_values($row);
$vars = \array_values($row);
$vars[] = $id;
$vars[] = $forum->id;
$list = array_keys($row);
$list = \array_keys($row);
$list[] = 'group_id';
$list[] = 'forum_id';
$list2 = array_fill(0, count($list), '?i');
$sql = 'INSERT INTO ::forum_perms (' . implode(', ', $list) . ') VALUES (' . implode(', ', $list2) . ')';
$list2 = \array_fill(0, \count($list), '?i');
$sql = 'INSERT INTO ::forum_perms (' . \implode(', ', $list) . ') VALUES (' . \implode(', ', $list2) . ')';
$this->c->DB->exec($sql, $vars);
}
}
@ -118,7 +118,7 @@ class Perm extends Action
* Сброс разрешений для раздела
*
* @param Forum $forum
*
*
* @throws RuntimeException
*/
public function reset(Forum $forum)
@ -130,7 +130,7 @@ class Perm extends Action
$vars = [
':fid' => $forum->id,
];
$sql = 'DELETE FROM ::forum_perms
$sql = 'DELETE FROM ::forum_perms
WHERE forum_id=?i:fid';
$this->c->DB->exec($sql, $vars);
}
@ -139,7 +139,7 @@ class Perm extends Action
* Удаление разрешений для группы
*
* @param Group $group
*
*
* @throws RuntimeException
*/
public function delete(Group $group)
@ -151,7 +151,7 @@ class Perm extends Action
$vars = [
':gid' => $group->g_id,
];
$sql = 'DELETE FROM ::forum_perms
$sql = 'DELETE FROM ::forum_perms
WHERE group_id=?i:gid';
$this->c->DB->exec($sql, $vars);
}
@ -161,7 +161,7 @@ class Perm extends Action
*
* @param Group $from
* @param Group $to
*
*
* @throws RuntimeException
*/
public function copy(Group $from, Group $to)
@ -176,9 +176,9 @@ class Perm extends Action
':old' => $from->g_id,
':new' => $to->g_id,
];
$sql = 'INSERT INTO ::forum_perms (group_id, forum_id, read_forum, post_replies, post_topics)
SELECT ?i:new, forum_id, read_forum, post_replies, post_topics
FROM ::forum_perms
$sql = 'INSERT INTO ::forum_perms (group_id, forum_id, read_forum, post_replies, post_topics)
SELECT ?i:new, forum_id, read_forum, post_replies, post_topics
FROM ::forum_perms
WHERE group_id=?i:old';
$this->c->DB->exec($sql, $vars);

View file

@ -12,9 +12,9 @@ class Save extends Action
* Обновляет группу в БД
*
* @param Group $group
*
*
* @throws RuntimeException
*
*
* @return Group
*/
public function update(Group $group)
@ -40,7 +40,7 @@ class Save extends Action
return $group;
}
$vars[] = $group->g_id;
$this->c->DB->query('UPDATE ::groups SET ' . implode(', ', $set) . ' WHERE g_id=?i', $vars);
$this->c->DB->query('UPDATE ::groups SET ' . \implode(', ', $set) . ' WHERE g_id=?i', $vars);
$group->resModified();
return $group;
@ -50,9 +50,9 @@ class Save extends Action
* Добавляет новую группу в БД
*
* @param Group $group
*
*
* @throws RuntimeException
*
*
* @return int
*/
public function insert(Group $group)
@ -74,7 +74,7 @@ class Save extends Action
if (empty($set)) {
throw new RuntimeException('The model is empty');
}
$this->c->DB->query('INSERT INTO ::groups (' . implode(', ', $set) . ') VALUES (' . implode(', ', $set2) . ')', $vars);
$this->c->DB->query('INSERT INTO ::groups (' . \implode(', ', $set) . ') VALUES (' . \implode(', ', $set2) . ')', $vars);
$group->g_id = $this->c->DB->lastInsertId();
$group->resModified();

View file

@ -25,14 +25,14 @@ class ManagerModel extends Model
/**
* Возвращает action по его имени
*
*
* @param string $name
*
* @return mixed
*/
public function __get($name)
{
$key = str_replace(['ForkBB\\Models\\', 'ForkBB\\', '\\'], '', get_class($this));
$key = \str_replace(['ForkBB\\Models\\', 'ForkBB\\', '\\'], '', \get_class($this));
return $this->c->{$key . $name}->setManager($this);
}
@ -47,8 +47,8 @@ class ManagerModel extends Model
*/
public function __call($name, array $args)
{
$key = str_replace(['ForkBB\\Models\\', 'ForkBB\\', '\\'], '', get_class($this));
$key = \str_replace(['ForkBB\\Models\\', 'ForkBB\\', '\\'], '', \get_class($this));
return $this->c->{$key . ucfirst($name)}->setManager($this)->$name(...$args);
return $this->c->{$key . \ucfirst($name)}->setManager($this)->$name(...$args);
}
}

View file

@ -44,9 +44,9 @@ class Model
*/
public function __isset($name)
{
return array_key_exists($name, $this->a)
|| array_key_exists($name, $this->aCalc)
|| method_exists($this, 'get' . $name);
return \array_key_exists($name, $this->a)
|| \array_key_exists($name, $this->aCalc)
|| \method_exists($this, 'get' . $name);
}
/**
@ -70,7 +70,7 @@ class Model
{
unset($this->aCalc[$name]);
if (method_exists($this, $method = 'set' . $name)) {
if (\method_exists($this, $method = 'set' . $name)) {
$this->$method($val);
} else {
$this->a[$name] = $val;
@ -86,9 +86,9 @@ class Model
*/
public function __get($name)
{
if (array_key_exists($name, $this->aCalc)) {
if (\array_key_exists($name, $this->aCalc)) {
return $this->aCalc[$name];
} elseif (method_exists($this, $method = 'get' . $name)) {
} elseif (\method_exists($this, $method = 'get' . $name)) {
return $this->aCalc[$name] = $this->$method();
} else {
return isset($this->a[$name]) ? $this->a[$name] : null;
@ -105,8 +105,8 @@ class Model
*/
public function __call($name, array $args)
{
$key = str_replace(['ForkBB\\Models\\', 'ForkBB\\', '\\'], '', get_class($this));
$key = \str_replace(['ForkBB\\Models\\', 'ForkBB\\', '\\'], '', \get_class($this));
return $this->c->{$key . ucfirst($name)}->setModel($this)->$name(...$args);
return $this->c->{$key . \ucfirst($name)}->setModel($this)->$name(...$args);
}
}

View file

@ -14,7 +14,7 @@ class Online extends Model
* Возврат данных по пользователям онлайн
*
* @param Page $page
*
*
* @return Online
*/
public function calc(Page $page)
@ -34,7 +34,7 @@ class Online extends Model
$this->updateUser($position);
$all = 0;
$now = time();
$now = \time();
$tOnline = $now - $this->c->config->o_timeout_online;
$tVisit = $now - $this->c->config->o_timeout_visit;
$online = [];
@ -79,7 +79,7 @@ class Online extends Model
if ($filter && $cur['o_position'] !== $position) {
continue;
}
// пользователь
if ($cur['user_id'] > 1) {
$users[$cur['user_id']] = [
@ -143,7 +143,7 @@ class Online extends Model
// гость
if ($this->c->user->isGuest) {
$vars = [
':logged' => time(),
':logged' => \time(),
':pos' => $position,
':name' => (string) $this->c->user->isBot,
':ip' => $this->c->user->ip
@ -156,7 +156,7 @@ class Online extends Model
} else {
// пользователь
$vars = [
':logged' => time(),
':logged' => \time(),
':pos' => $position,
':id' => $this->c->user->id,
':name' => $this->c->user->username,

View file

@ -16,7 +16,7 @@ class Info extends Method
if (! $this->model->detail) {
return null;
}
$this->model->maxNum = $this->c->config->st_max_users;
$this->model->maxTime = $this->c->config->st_max_users_time;
@ -36,11 +36,11 @@ class Info extends Method
$info[] = $user['name'];
}
}
$this->model->numUsers = count($info);
$this->model->numUsers = \count($info);
$s = 0;
foreach ($this->model->bots as $bot => $arr) {
$count = count($arr);
$count = \count($arr);
$s += $count;
if ($count > 1) {
$info[] = '[Bot] ' . $bot . ' (' . $count . ')';
@ -48,7 +48,7 @@ class Info extends Method
$info[] = '[Bot] ' . $bot;
}
}
$this->model->numGuests = $s + count($this->model->guests);
$this->model->numGuests = $s + \count($this->model->guests);
$this->model->info = $info;
return $this->model;

View file

@ -40,7 +40,7 @@ class Categories extends Admin
}
$this->c->categories->update();
if (strlen($v->new) > 0) {
if (\strlen($v->new) > 0) {
$this->c->categories->insert($v->new); //????
}

View file

@ -31,7 +31,7 @@ class Forums extends Admin
unset($categories[$cid]);
}
$indent = str_repeat(\ForkBB\__('Forum indent'), $f->depth);
$indent = \str_repeat(\ForkBB\__('Forum indent'), $f->depth);
if ($f->id === $forum->id || isset($forum->descendants[$f->id]) || $f->redirect_url) {
$options[] = [$f->id, $indent . \ForkBB\__('Forum prefix') . $f->forum_name, true];
@ -58,7 +58,7 @@ class Forums extends Admin
*/
protected function forumPos(Forum $forum)
{
if (is_int($forum->disp_position)) {
if (\is_int($forum->disp_position)) {
return $forum->disp_position;
}

View file

@ -28,10 +28,10 @@ class Groups extends Admin
foreach ($this->c->groups->getList() as $key => $group) {
$groupsList[$key] = [$group->g_title, $group->linkEdit, $group->linkDelete];
if (! in_array($group->g_id, $notForNew)) {
if (! \in_array($group->g_id, $notForNew)) {
$groupsNew[$key] = $group->g_title;
}
if (! in_array($group->g_id, $notForDefault) && $group->g_moderator == 0) {
if (! \in_array($group->g_id, $notForDefault) && $group->g_moderator == 0) {
$groupsDefault[$key] = $group->g_title;
}
}
@ -114,7 +114,7 @@ class Groups extends Admin
$v = $this->c->Validator->reset()
->addRules([
'token' => 'token:AdminGroupsDefault',
'defaultgroup' => 'required|integer|in:' . implode(',', array_keys($this->groupsDefault)),
'defaultgroup' => 'required|integer|in:' . \implode(',', \array_keys($this->groupsDefault)),
])->addAliases([
])->addMessages([
'defaultgroup.in' => 'Invalid default group',
@ -145,7 +145,7 @@ class Groups extends Admin
$v = $this->c->Validator->reset()
->addRules([
'token' => 'token:AdminGroupsNew',
'basegroup' => 'required|integer|in:' . implode(',', array_keys($this->groupsNew)),
'basegroup' => 'required|integer|in:' . \implode(',', \array_keys($this->groupsNew)),
])->addAliases([
])->addMessages([
'basegroup.in' => 'Invalid group to create on base',
@ -201,7 +201,7 @@ class Groups extends Admin
$v = $this->c->Validator->reset()
->addRules([
'token' => 'token:' . $marker,
'g_title' => 'required|string:trim|max:50|not_in:' . implode(',', $reserve),
'g_title' => 'required|string:trim|max:50|not_in:' . \implode(',', $reserve),
'g_user_title' => 'string:trim|max:50',
])->addAliases([
])->addArguments([
@ -620,7 +620,7 @@ class Groups extends Admin
}
$groups[$key] = $cur[0];
}
$move .= implode(',', array_keys($groups));
$move .= \implode(',', \array_keys($groups));
} else {
$move = 'absent';
}

View file

@ -201,7 +201,7 @@ class Maintenance extends Admin
$this->c->DB->beginTransaction();
@set_time_limit(0);
@\set_time_limit(0);
if ('POST' === $method && $v->clear) {
$this->c->search->truncateIndex();

View file

@ -14,28 +14,28 @@ class Statistics extends Admin
public function info()
{
// Is phpinfo() a disabled function?
if (strpos(strtolower((string) ini_get('disable_functions')), 'phpinfo') !== false) {
if (\strpos(\strtolower((string) \ini_get('disable_functions')), 'phpinfo') !== false) {
$this->c->Message->message('PHPinfo disabled message', true, 200);
}
ob_start();
phpinfo();
$page = ob_get_clean();
\ob_start();
\phpinfo();
$page = \ob_get_clean();
if (preg_match('%<body[^>]*>(.*)</body[^>]*>%is', $page, $matches)) {
if (\preg_match('%<body[^>]*>(.*)</body[^>]*>%is', $page, $matches)) {
$phpinfo = $matches[1];
if (preg_match('%<style[^>]*>(.*?)</style[^>]*>%is', $page, $matches)) {
$style = preg_replace_callback(
if (\preg_match('%<style[^>]*>(.*?)</style[^>]*>%is', $page, $matches)) {
$style = \preg_replace_callback(
'%(\S[^{]*)({[^}]+})%',
function($match) {
$result = array_map(
$result = \array_map(
function($val) {
$val = str_replace('body', '.f-phpinfo-div', $val, $count);
$val = \str_replace('body', '.f-phpinfo-div', $val, $count);
return $count ? $val : '.f-phpinfo-div ' . $val;
},
explode(',', $match[1])
\explode(',', $match[1])
);
return implode(', ', $result) . $match[2];
return \implode(', ', $result) . $match[2];
},
$matches[1]
);
@ -66,22 +66,22 @@ class Statistics extends Admin
$this->linkInfo = $this->c->Router->link('AdminInfo');
// Get the server load averages (if possible)
if (@file_exists('/proc/loadavg') && is_readable('/proc/loadavg')) {
if (@\file_exists('/proc/loadavg') && \is_readable('/proc/loadavg')) {
// We use @ just in case
$fh = @fopen('/proc/loadavg', 'r');
$ave = @fread($fh, 64);
@fclose($fh);
$fh = @\fopen('/proc/loadavg', 'r');
$ave = @\fread($fh, 64);
@\fclose($fh);
if (($fh = @fopen('/proc/loadavg', 'r'))) {
$ave = fread($fh, 64);
fclose($fh);
if (($fh = @\fopen('/proc/loadavg', 'r'))) {
$ave = \fread($fh, 64);
\fclose($fh);
} else {
$ave = '';
}
$ave = @explode(' ', $ave);
$ave = @\explode(' ', $ave);
$this->serverLoad = isset($ave[2]) ? $ave[0].' '.$ave[1].' '.$ave[2] : \ForkBB\__('Not available');
} elseif (!in_array(PHP_OS, array('WINNT', 'WIN32')) && preg_match('%averages?: ([\d\.]+),?\s+([\d\.]+),?\s+([\d\.]+)%i', @exec('uptime'), $ave)) {
} elseif (! \in_array(\PHP_OS, ['WINNT', 'WIN32']) && \preg_match('%averages?: ([\d\.]+),?\s+([\d\.]+),?\s+([\d\.]+)%i', @\exec('uptime'), $ave)) {
$this->serverLoad = $ave[1].' '.$ave[2].' '.$ave[3];
} else {
$this->serverLoad = \ForkBB\__('Not available');
@ -98,16 +98,16 @@ class Statistics extends Admin
$this->tOther = $stat;
// Check for the existence of various PHP opcode caches/optimizers
if (ini_get('opcache.enable') && function_exists('opcache_invalidate')) {
if (\ini_get('opcache.enable') && \function_exists('opcache_invalidate')) {
$this->accelerator = 'Zend OPcache';
$this->linkAcc = 'https://secure.php.net/opcache/';
} elseif (ini_get('wincache.fcenabled')) {
} elseif (\ini_get('wincache.fcenabled')) {
$this->accelerator = 'Windows Cache for PHP';
$this->linkAcc = 'https://secure.php.net/wincache/';
} elseif (ini_get('apc.enabled') && function_exists('apc_delete_file')) {
} elseif (\ini_get('apc.enabled') && \function_exists('apc_delete_file')) {
$this->accelerator = 'Alternative PHP Cache (APC)'; //???? частичная эмуляция APCu
$this->linkAcc = 'https://secure.php.net/apc/';
} elseif (ini_get('xcache.cacher')) {
} elseif (\ini_get('xcache.cacher')) {
$this->accelerator = 'XCache';
$this->linkAcc = 'https://xcache.lighttpd.net/';
} else {

View file

@ -108,14 +108,14 @@ class Auth extends Page
$authorized = false;
$hash = $user->password;
// For FluxBB by Visman 1.5.10.74 and above
if (strlen($hash) == 40) {
if (hash_equals($hash, sha1($password . $this->c->SALT1))) {
$hash = password_hash($password, PASSWORD_DEFAULT);
if (\strlen($hash) == 40) {
if (\hash_equals($hash, sha1($password . $this->c->SALT1))) {
$hash = \password_hash($password, \PASSWORD_DEFAULT);
$user->password = $hash;
$authorized = true;
}
} else {
$authorized = password_verify($password, $hash);
$authorized = \password_verify($password, $hash);
}
// ошибка в пароле
if (! $authorized) {
@ -173,9 +173,9 @@ class Auth extends Page
$link = $this->c->Router->link('ChangePassword', ['email' => $v->email, 'key' => $key, 'hash' => $hash]);
$tplData = [
'fRootLink' => $this->c->Router->link('Index'),
'fMailer' => \ForkBB\__('Mailer', $this->c->config->o_board_title),
'username' => $this->tmpUser->username,
'link' => $link,
'fMailer' => \ForkBB\__('Mailer', $this->c->config->o_board_title),
'username' => $this->tmpUser->username,
'link' => $link,
];
try {
@ -193,7 +193,7 @@ class Auth extends Page
if ($isSent) {
$this->tmpUser->activate_string = $key;
$this->tmpUser->last_email_sent = time();
$this->tmpUser->last_email_sent = \time();
$this->c->users->update($this->tmpUser);
return $this->c->Message->message(\ForkBB\__('Forget mail', $this->c->config->o_admin_email), false, 200);
} else {
@ -233,8 +233,8 @@ class Auth extends Page
} elseif (! ($user = $this->c->users->load($email, 'email')) instanceof User) {
$v->addError('Invalid email');
// за последний час уже был запрос на этот email
} elseif ($user->last_email_sent > 0 && time() - $user->last_email_sent < 3600) {
$v->addError(\ForkBB\__('Email flood', (int) (($user->last_email_sent + 3600 - time()) / 60)), 'e');
} elseif ($user->last_email_sent > 0 && \time() - $user->last_email_sent < 3600) {
$v->addError(\ForkBB\__('Email flood', (int) (($user->last_email_sent + 3600 - \time()) / 60)), 'e');
} else {
$this->tmpUser = $user;
}
@ -252,11 +252,11 @@ class Auth extends Page
public function changePass(array $args, $method)
{
// что-то пошло не так
if (! hash_equals($args['hash'], $this->c->Secury->hash($args['email'] . $args['key']))
if (! \hash_equals($args['hash'], $this->c->Secury->hash($args['email'] . $args['key']))
|| ! ($user = $this->c->users->load($args['email'], 'email')) instanceof User
|| empty($user->activate_string)
|| 'p' !== $user->activate_string{0}
|| ! hash_equals($user->activate_string, $args['key'])
|| ! \hash_equals($user->activate_string, $args['key'])
) {
return $this->c->Message->message('Bad request', false);
}
@ -280,7 +280,7 @@ class Auth extends Page
]);
if ($v->validation($_POST)) {
$user->password = password_hash($v->password, PASSWORD_DEFAULT);
$user->password = \password_hash($v->password, PASSWORD_DEFAULT);
$user->email_confirmed = 1;
$user->activate_string = null;
$this->c->users->update($user);

View file

@ -5,14 +5,14 @@ namespace ForkBB\Models\Pages;
use ForkBB\Models\Model;
use ForkBB\Models\Search\Model as Search;
trait CrumbTrait
trait CrumbTrait
{
/**
* Возвращает массив хлебных крошек
* Заполняет массив титула страницы
*
*
* @param mixed $args
*
*
* @return array
*/
protected function crumbs(...$args)
@ -52,7 +52,7 @@ trait CrumbTrait
$arg = $arg->parent;
}
// ссылка
} elseif (is_array($arg)) {
} elseif (\is_array($arg)) {
$this->titles = $arg[1];
$crumbs[] = [$arg[0], $arg[1], $active];
// строка
@ -65,6 +65,6 @@ trait CrumbTrait
// главная страница
$crumbs[] = [$this->c->Router->link('Index'), \ForkBB\__('Index'), $active];
return array_reverse($crumbs);
return \array_reverse($crumbs);
}
}

View file

@ -8,7 +8,7 @@ class Debug extends Page
{
/**
* Подготавливает данные для шаблона
*
*
* @return Page
*/
public function debug()
@ -31,10 +31,10 @@ class Debug extends Page
$this->nameTpl = 'layouts/debug';
$this->onlinePos = null;
$this->memory = memory_get_usage();
$this->peak = memory_get_peak_usage();
$this->time = microtime(true) - $this->c->START;
$this->memory = \memory_get_usage();
$this->peak = \memory_get_peak_usage();
$this->time = \microtime(true) - $this->c->START;
return $this;
}
@ -48,7 +48,7 @@ class Debug extends Page
/**
* Возвращает HTTP заголовки страницы
* $this->httpHeaders
*
*
* @return array
*/
protected function getHttpHeaders()

View file

@ -80,7 +80,7 @@ class Edit extends Page
{
$this->c->DB->beginTransaction();
$now = time();
$now = \time();
$executive = $this->user->isAdmin || $this->user->isModerator($post);
$topic = $post->parent;
$editSubject = $post->id === $topic->first_post_id;

View file

@ -85,7 +85,7 @@ class Install extends Page
// версия PHP
if (\version_compare(PHP_VERSION, self::PHP_MIN, '<')) {
$this->fIswev = ['e', \ForkBB\__('You are running error', 'PHP', PHP_VERSION, $this->c->FORK_REVISION, self::PHP_MIN)];
$this->fIswev = ['e', \ForkBB\__('You are running error', 'PHP', \PHP_VERSION, $this->c->FORK_REVISION, self::PHP_MIN)];
}
// типы БД
@ -345,14 +345,14 @@ class Install extends Page
],
'defaultlang' => [
'type' => 'select',
'options' => array_combine($langs, $langs),
'options' => \array_combine($langs, $langs),
'value' => $v ? $v->defaultlang : $this->user->language,
'title' => \ForkBB\__('Default language'),
'required' => true,
],
'defaultstyle' => [
'type' => 'select',
'options' => array_combine($styles, $styles),
'options' => \array_combine($styles, $styles),
'value' => $v ? $v->defaultstyle : $this->user->style,
'title' => \ForkBB\__('Default style'),
'required' => true,
@ -557,7 +557,7 @@ class Install extends Page
'post_replies' => ['TINYINT(1)', false, 1],
'post_topics' => ['TINYINT(1)', false, 1],
],
'PRIMARY KEY' => array('group_id', 'forum_id'),
'PRIMARY KEY' => ['group_id', 'forum_id'],
'ENGINE' => $this->DBEngine,
];
$this->c->DB->createTable('forum_perms', $schema);
@ -1020,7 +1020,7 @@ class Install extends Page
];
$this->c->DB->createTable('mark_of_topic', $schema);
$now = time();
$now = \time();
$groups = [
// g_id, g_title, g_user_title, g_moderator, g_mod_edit_users, g_mod_rename_users, g_mod_change_passwords, g_mod_ban_users, g_mod_promote_users, g_read_board, g_view_users, g_post_replies, g_post_topics, g_edit_posts, g_delete_posts, g_delete_topics, g_set_title, g_search, g_search_users, g_send_email, g_post_flood, g_search_flood, g_email_flood, g_report_flood
@ -1131,7 +1131,7 @@ class Install extends Page
'o_crypto_salt' => $this->c->Secury->randomPass(13),
'o_enable_acaptcha' => 1, // математическая каптча
'st_max_users' => 1, // статистика по максимуму юзеров - Visman
'st_max_users_time' => time(),
'st_max_users_time' => \time(),
];
foreach ($pun_config as $conf_name => $conf_value) {
$this->c->DB->exec('INSERT INTO ::config (conf_name, conf_value) VALUES (?s, ?s)', [$conf_name, $conf_value]);

View file

@ -125,7 +125,7 @@ class Post extends Page
{
$this->c->DB->beginTransaction();
$now = time();
$now = \time();
$username = $this->user->isGuest ? $v->username : $this->user->username;
$merge = false;
$executive = $this->user->isAdmin || $this->user->isModerator($model);
@ -173,7 +173,7 @@ class Post extends Page
// попытка объеденить новое сообщение с крайним в теме
if ($merge) {
$lastPost = $this->c->posts->load($topic->last_post_id, $topic->id);
$newLength = mb_strlen($lastPost->message . $v->message, 'UTF-8');
$newLength = \mb_strlen($lastPost->message . $v->message, 'UTF-8');
if ($newLength < $this->c->MAX_POST_SIZE - 100) {
$lastPost->message = $lastPost->message . "\n[after=" . ($now - $topic->last_post) . "]\n" . $v->message; //????

View file

@ -41,7 +41,7 @@ trait PostValidatorTrait
$user->username = $username;
// username = Гость
if (preg_match('%^(guest|' . preg_quote(\ForkBB\__('Guest'), '%') . ')$%iu', $username)) {
if (\preg_match('%^(guest|' . \preg_quote(\ForkBB\__('Guest'), '%') . ')$%iu', $username)) { // ???? а зачем?
$v->addError('Username guest');
// цензура
} elseif (\ForkBB\cens($user->username) !== $username) {
@ -68,14 +68,14 @@ trait PostValidatorTrait
$v->addError('No subject after censoring');
// заголовок темы только заглавными буквами
} elseif (! $executive
&& $this->c->config->p_subject_all_caps == '0'
&& preg_match('%\p{Lu}%u', $subject)
&& ! preg_match('%\p{Ll}%u', $subject)
&& '0' == $this->c->config->p_subject_all_caps
&& \preg_match('%\p{Lu}%u', $subject)
&& ! \preg_match('%\p{Ll}%u', $subject)
) {
$v->addError('All caps subject');
} elseif (! $executive
&& $this->user->g_post_links != '1'
&& preg_match('%https?://|www\.%ui', $subject)
&& '1' != $this->user->g_post_links
&& \preg_match('%https?://|www\.%ui', $subject)
) {
$v->addError('You can not post links in subject');
}
@ -97,9 +97,9 @@ trait PostValidatorTrait
$v->addError('No message after censoring');
// текст сообщения только заглавными буквами
} elseif (! $executive
&& $this->c->config->p_message_all_caps == '0'
&& preg_match('%\p{Lu}%u', $message)
&& ! preg_match('%\p{Ll}%u', $message)
&& '0' == $this->c->config->p_message_all_caps
&& \preg_match('%\p{Lu}%u', $message)
&& ! \preg_match('%\p{Ll}%u', $message)
) {
$v->addError('All caps message');
// проверка парсером
@ -128,7 +128,7 @@ trait PostValidatorTrait
return null;
}
$time = time() - (int) $this->user->last_post;
$time = \time() - (int) $this->user->last_post;
if ($time < $this->user->g_post_flood) {
$v->addError(\ForkBB\__('Flood start', $this->user->g_post_flood, $this->user->g_post_flood - $time), 'e');
@ -191,7 +191,7 @@ trait PostValidatorTrait
$executive = false;
}
if ($this->c->config->o_smilies == '1') {
if ('1' == $this->c->config->o_smilies) {
$ruleHideSmilies = 'checkbox';
} else {
$ruleHideSmilies = 'absent';

View file

@ -100,7 +100,7 @@ class Register extends Page
$user = $this->c->users->create(['username' => $username]);
// username = Гость
if (preg_match('%^(guest|' . preg_quote(\ForkBB\__('Guest'), '%') . ')$%iu', $username)) { //????
if (\preg_match('%^(guest|' . \preg_quote(\ForkBB\__('Guest'), '%') . ')$%iu', $username)) { // ???? а зачем?
$v->addError('Username guest');
// цензура
} elseif ($this->c->censorship->censor($username) !== $username) {
@ -140,13 +140,13 @@ class Register extends Page
$user->email = $v->email;
$user->email_confirmed = 0;
$user->activate_string = $key;
$user->u_mark_all_read = time();
$user->u_mark_all_read = \time();
$user->email_setting = $this->c->config->o_default_email_setting;
$user->timezone = $this->c->config->o_default_timezone;
$user->dst = $this->c->config->o_default_dst;
$user->language = $user->language; //????
$user->style = $user->style; //????
$user->registered = time();
$user->registered = \time();
$user->registration_ip = $this->user->ip;
$newUserId = $this->c->users->insert($user);
@ -233,11 +233,11 @@ class Register extends Page
*/
public function activate(array $args)
{
if (! hash_equals($args['hash'], $this->c->Secury->hash($args['id'] . $args['key']))
if (! \hash_equals($args['hash'], $this->c->Secury->hash($args['id'] . $args['key']))
|| ! ($user = $this->c->users->load($args['id'])) instanceof User
|| empty($user->activate_string)
|| 'w' !== $user->activate_string{0}
|| ! hash_equals($user->activate_string, $args['key'])
|| ! \hash_equals($user->activate_string, $args['key'])
) {
return $this->c->Message->message('Bad request', false);
}

View file

@ -27,7 +27,7 @@ class Search extends Page
$options[] = [\ForkBB\__('Category prefix') . $f->cat_name];
}
$indent = str_repeat(\ForkBB\__('Forum indent'), $f->depth);
$indent = \str_repeat(\ForkBB\__('Forum indent'), $f->depth);
if ($f->redirect_url) {
$options[] = [$f->id, $indent . \ForkBB\__('Forum prefix') . $f->forum_name, true];
@ -120,7 +120,7 @@ class Search extends Page
if ('POST' === $method && $v->validation($_POST)) {
return $this->c->Redirect->page($marker, $v->getData());
} elseif ('GET' === $method && $v->validation($args)) {
return $this->action(array_merge($args, $v->getData(), ['action' => 'search']), $method, $advanced);
return $this->action(\array_merge($args, $v->getData(), ['action' => 'search']), $method, $advanced);
}
$this->fIswev = $v->getErrors();
@ -179,9 +179,9 @@ class Search extends Page
'dl' => 'w3',
'type' => 'multiselect',
'options' => $this->listForOptions,
'value' => $v ? explode('.', $v->forums) : null,
'value' => $v ? \explode('.', $v->forums) : null,
'title' => \ForkBB\__('Forum search'),
'size' => min(count($this->listForOptions), 10),
'size' => \min(\count($this->listForOptions), 10),
],
'serch_in' => [
'dl' => 'w3',
@ -290,7 +290,7 @@ class Search extends Page
public function vCheckQuery(Validator $v, $query, $method)
{
if (empty($v->getErrors())) {
$flood = $this->user->last_search && time() - $this->user->last_search < $this->user->g_search_flood;
$flood = $this->user->last_search && \time() - $this->user->last_search < $this->user->g_search_flood;
if ('POST' !== $method || ! $flood) {
$search = $this->c->search;
@ -307,7 +307,7 @@ class Search extends Page
}
if ($search->queryNoCache && $this->user->g_search_flood) {
$this->user->last_search = time();
$this->user->last_search = \time();
$this->c->users->update($this->user); //?????
}
}
@ -315,7 +315,7 @@ class Search extends Page
}
if ($flood) {
$v->addError(\ForkBB\__('Search flood', $this->user->g_search_flood, $this->user->g_search_flood - time() + $this->user->last_search));
$v->addError(\ForkBB\__('Search flood', $this->user->g_search_flood, $this->user->g_search_flood - \time() + $this->user->last_search));
}
}
@ -333,22 +333,22 @@ class Search extends Page
public function vCheckForums(Validator $v, $forums)
{
if ('*' !== $forums) {
if (is_string($forums) && preg_match('%^\d+(?:\.\d+)*$%D', $forums)) {
$forums = explode('.', $forums);
if (\is_string($forums) && \preg_match('%^\d+(?:\.\d+)*$%D', $forums)) {
$forums = \explode('.', $forums);
} elseif (null === $forums) {
$forums = '*';
} elseif (! is_array($forums)) {
} elseif (! \is_array($forums)) {
$v->addError('The :alias contains an invalid value');
$forums = '*';
}
}
if ('*' !== $forums) {
if (! empty(array_diff($forums, $this->listOfIndexes))) {
if (! empty(\array_diff($forums, $this->listOfIndexes))) {
$v->addError('The :alias contains an invalid value');
}
sort($forums, SORT_NUMERIC);
$forums = implode('.', $forums);
\sort($forums, SORT_NUMERIC);
$forums = \implode('.', $forums);
}
return $forums;
@ -364,9 +364,9 @@ class Search extends Page
*/
public function vCheckAuthor(Validator $v, $name)
{
$name = preg_replace('%\*+%', '*', $name);
$name = \preg_replace('%\*+%', '*', $name);
if ('*' !== $name && ! preg_match('%[\p{L}\p{N}]%', $name)) {
if ('*' !== $name && ! \preg_match('%[\p{L}\p{N}]%', $name)) {
$v->addError('The :alias is not valid format');
}

View file

@ -66,10 +66,10 @@ class Delete extends Action
foreach ($posts as $post) {
$users[$post->poster_id] = true;
}
$users = array_keys($users);
$users = \array_keys($users);
$vars = [
':posts' => array_keys($posts),
':posts' => \array_keys($posts),
];
$sql = 'DELETE FROM ::posts
WHERE id IN (?ai:posts)';
@ -88,7 +88,7 @@ class Delete extends Action
}
} elseif ($topics) {
$vars = [
':topics' => array_keys($topics),
':topics' => \array_keys($topics),
];
$sql = 'SELECT p.poster_id
FROM ::posts AS p
@ -101,7 +101,7 @@ class Delete extends Action
$this->c->DB->exec($sql, $vars);
} elseif ($forums) {
$vars = [
':forums' => array_keys($forums),
':forums' => \array_keys($forums),
];
$sql = 'SELECT p.poster_id
FROM ::posts AS p

View file

@ -40,14 +40,14 @@ class Load extends Action
}
$this->aliases = $aliases;
return implode(', ', $result);
return \implode(', ', $result);
}
protected function setData(array $args, array $data)
{
foreach ($args as $aliases => $model) {
$attrs = [];
foreach (explode('.', $aliases) as $alias) {
foreach (\explode('.', $aliases) as $alias) {
if (empty($this->aliases[$alias])) {
continue;
}
@ -63,10 +63,10 @@ class Load extends Action
/**
* Загружает сообщение из БД с проверкой вхождения в указанную тему
* Проверка доступности
*
*
* @param int $id
* @param int $tid
*
*
* @return null|Post
*/
public function loadFromTopic($id, $tid)
@ -75,12 +75,12 @@ class Load extends Action
':pid' => $id,
':tid' => $tid,
];
$sql = 'SELECT p.*
FROM ::posts AS p
$sql = 'SELECT p.*
FROM ::posts AS p
WHERE p.id=?i:pid AND p.topic_id=?i:tid';
$data = $this->c->DB->query($sql, $vars)->fetch();
// сообщение отсутствует или недоступено
if (empty($data)) {
return null;
@ -97,7 +97,7 @@ class Load extends Action
}
/**
* Загружает сообщение из БД
* Загружает сообщение из БД
* Загружает тему этого сообщения
* Проверка доступности
*
@ -111,13 +111,13 @@ class Load extends Action
$vars = [
':pid' => $id,
':fields' => $this->queryFields([
'p' => array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
'p' => \array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => \array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
]),
];
$sql = 'SELECT ?p:fields
FROM ::posts AS p
FROM ::posts AS p
INNER JOIN ::topics AS t ON t.id=p.topic_id
WHERE p.id=?i:pid';
} else {
@ -125,8 +125,8 @@ class Load extends Action
':pid' => $id,
':uid' => $this->c->user->id,
':fields' => $this->queryFields([
'p' => array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
'p' => \array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => \array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
's' => ['user_id' => 'is_subscribed'],
'mof' => ['mf_mark_all_read' => true],
'mot' => ['mt_last_visit' => true, 'mt_last_read' => true],
@ -143,7 +143,7 @@ class Load extends Action
}
$data = $this->c->DB->query($sql, $vars)->fetch();
// сообщение отсутствует или недоступено
if (empty($data)) {
return null;

View file

@ -82,7 +82,7 @@ class Model extends DataModel
)
&& ($this->c->user->g_deledit_interval == '0'
|| $this->edit_post == '1'
|| time() - $this->posted < $this->c->user->g_deledit_interval
|| \time() - $this->posted < $this->c->user->g_deledit_interval
);
}
@ -105,7 +105,7 @@ class Model extends DataModel
&& $this->c->user->g_edit_posts == '1'
&& ($this->c->user->g_deledit_interval == '0'
|| $this->edit_post == '1'
|| time() - $this->posted < $this->c->user->g_deledit_interval
|| \time() - $this->posted < $this->c->user->g_deledit_interval
);
}

View file

@ -12,9 +12,9 @@ class Save extends Action
* Обновляет сообщение в БД
*
* @param Post $post
*
*
* @throws RuntimeException
*
*
* @return Post
*/
public function update(Post $post)
@ -40,7 +40,7 @@ class Save extends Action
return $post;
}
$vars[] = $post->id;
$this->c->DB->query('UPDATE ::posts SET ' . implode(', ', $set) . ' WHERE id=?i', $vars);
$this->c->DB->query('UPDATE ::posts SET ' . \implode(', ', $set) . ' WHERE id=?i', $vars);
$post->resModified();
return $post;
@ -50,9 +50,9 @@ class Save extends Action
* Добавляет новое сообщение в БД
*
* @param Post $post
*
*
* @throws RuntimeException
*
*
* @return int
*/
public function insert(Post $post)
@ -74,7 +74,7 @@ class Save extends Action
if (empty($set)) {
throw new RuntimeException('The model is empty');
}
$this->c->DB->query('INSERT INTO ::posts (' . implode(', ', $set) . ') VALUES (' . implode(', ', $set2) . ')', $vars);
$this->c->DB->query('INSERT INTO ::posts (' . \implode(', ', $set) . ') VALUES (' . \implode(', ', $set2) . ')', $vars);
$post->id = $this->c->DB->lastInsertId();
$post->resModified();

View file

@ -46,14 +46,14 @@ class View extends Action
}
$this->aliases = $aliases;
return implode(', ', $result);
return \implode(', ', $result);
}
protected function setData(array $args, array $data)
{
foreach ($args as $aliases => $model) {
$attrs = [];
foreach (explode('.', $aliases) as $alias) {
foreach (\explode('.', $aliases) as $alias) {
if (empty($this->aliases[$alias])) {
continue;
}
@ -82,7 +82,7 @@ class View extends Action
throw new InvalidArgumentException('Expected Topic or Search');
}
if (empty($arg->idsList) || ! is_array($arg->idsList)) {
if (empty($arg->idsList) || ! \is_array($arg->idsList)) {
throw new RuntimeException('Model does not contain of posts list for display');
}
@ -95,7 +95,7 @@ class View extends Action
$warnings = $this->c->DB->query($sql, $vars)->fetchAll(PDO::FETCH_GROUP);
$userIds = [];
$result = array_flip($arg->idsList);
$result = \array_flip($arg->idsList);
if ($arg instanceof Topic) {
$vars = [
@ -122,8 +122,8 @@ class View extends Action
$vars = [
':ids' => $arg->idsList,
':fields' => $this->queryFields([
'p' => array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
'p' => \array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => \array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
]),
];
$sql = 'SELECT ?p:fields
@ -136,8 +136,8 @@ class View extends Action
':ids' => $arg->idsList,
':uid' => $this->c->user->id,
':fields' => $this->queryFields([
'p' => array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
'p' => \array_map(function($val) {return true;}, $this->c->dbMap->posts), // все поля в true
't' => \array_map(function($val) {return true;}, $this->c->dbMap->topics), // все поля в true
# 's' => ['user_id' => 'is_subscribed'],
'mof' => ['mf_mark_all_read' => true],
'mot' => ['mt_last_visit' => true, 'mt_last_read' => true],

View file

@ -54,7 +54,7 @@ class ActionP extends Method
$list = $this->c->DB->query($sql, $vars)->fetchAll(PDO::FETCH_COLUMN);
}
$this->model->numPages = (int) ceil((count($list) ?: 1) / $this->c->user->disp_posts);
$this->model->numPages = (int) \ceil((\count($list) ?: 1) / $this->c->user->disp_posts);
// нет такой страницы в результате поиска
if (! $this->model->hasPage()) {
@ -64,7 +64,7 @@ class ActionP extends Method
return [];
}
$this->model->idsList = array_slice($list, ($this->model->page - 1) * $this->c->user->disp_posts, $this->c->user->disp_posts);
$this->model->idsList = \array_slice($list, ($this->model->page - 1) * $this->c->user->disp_posts, $this->c->user->disp_posts);
return $this->c->posts->view($this->model);
}

View file

@ -49,12 +49,12 @@ class ActionT extends Method
if (null !== $sql) {
$vars = [
':forums' => array_keys($root->descendants),
':forums' => \array_keys($root->descendants),
];
$list = $this->c->DB->query($sql, $vars)->fetchAll(PDO::FETCH_COLUMN);
}
$this->model->numPages = (int) ceil((count($list) ?: 1) / $this->c->user->disp_topics);
$this->model->numPages = (int) \ceil((\count($list) ?: 1) / $this->c->user->disp_topics);
// нет такой страницы в результате поиска
if (! $this->model->hasPage()) {
@ -64,7 +64,7 @@ class ActionT extends Method
return [];
}
$this->model->idsList = array_slice($list, ($this->model->page - 1) * $this->c->user->disp_topics, $this->c->user->disp_topics);
$this->model->idsList = \array_slice($list, ($this->model->page - 1) * $this->c->user->disp_topics, $this->c->user->disp_topics);
return $this->c->topics->view($this->model);
}

View file

@ -58,13 +58,13 @@ class Delete extends Method
if ($posts) {
$vars = [
':posts' => array_keys($posts),
':posts' => \array_keys($posts),
];
$sql = 'DELETE FROM ::search_matches
WHERE post_id IN (?ai:posts)';
} elseif ($topics) {
$vars = [
':topics' => array_keys($topics),
':topics' => \array_keys($topics),
];
$sql = 'DELETE FROM ::search_matches
WHERE post_id IN (
@ -74,7 +74,7 @@ class Delete extends Method
)';
} elseif ($forums) {
$vars = [
':forums' => array_keys($forums),
':forums' => \array_keys($forums),
];
$sql = 'DELETE FROM ::search_matches
WHERE post_id IN (

View file

@ -34,7 +34,7 @@ class Execute extends Method
*/
public function execute(Validator $v, array $forumIdxs, $flood)
{
if (! is_array($this->model->queryWords) || ! is_string($this->model->queryText)) {
if (! \is_array($this->model->queryWords) || ! \is_string($this->model->queryText)) {
throw new RuntimeException('No query data');
}
@ -62,9 +62,9 @@ class Execute extends Method
LIMIT 1';
$row = $this->c->DB->query($sql, $vars)->fetch();
if (! empty($row['search_time']) && time() - $row['search_time'] < 60 * 5) { //????
$result = explode("\n", $row['search_data']);
$this->model->queryIds = '' == $result[0] ? [] : explode(',', $result[0]);
if (! empty($row['search_time']) && \time() - $row['search_time'] < 60 * 5) { //????
$result = \explode("\n", $row['search_data']);
$this->model->queryIds = '' == $result[0] ? [] : \explode(',', $result[0]);
$this->model->queryNoCache = false;
return true;
} elseif ($flood) {
@ -74,20 +74,20 @@ class Execute extends Method
$ids = $this->exec($this->model->queryWords, $queryVars);
if (1 === $v->sort_dir) {
asort($ids, $this->sortType);
\asort($ids, $this->sortType);
} else {
arsort($ids, $this->sortType);
\arsort($ids, $this->sortType);
}
$ids = array_keys($ids);
$ids = \array_keys($ids);
$data = [
implode(',', $ids),
\implode(',', $ids),
];
$vars = [
':data' => implode("\n", $data),
':data' => \implode("\n", $data),
':key' => $key,
':time' => time(),
':time' => \time(),
];
$sql = 'INSERT INTO ::search_cache (search_key, search_time, search_data)
VALUES (?s:key, ?i:time, ?s:data)';
@ -125,16 +125,16 @@ class Execute extends Method
continue;
}
if (is_array($word) && (! isset($word['type']) || 'CJK' !== $word['type'])) {
if (\is_array($word) && (! isset($word['type']) || 'CJK' !== $word['type'])) {
$ids = $this->exec($word, $vars);
} else {
$CJK = false;
if (isset($word['type']) && 'CJK' === $word['type']) {
$CJK = true;
$word = '*' . trim($word['word'], '*') . '*';
$word = '*' . \trim($word['word'], '*') . '*';
}
$word = str_replace(['*', '?'], ['%', '_'], $word);
$word = \str_replace(['*', '?'], ['%', '_'], $word);
if (isset($this->words[$word])) {
$list = $this->words[$word];
@ -163,11 +163,11 @@ class Execute extends Method
if (! $count) {
$ids = $list;
} elseif ('AND' === $type) {
$ids = array_intersect_key($ids, $list);
$ids = \array_intersect_key($ids, $list);
} elseif ('OR' === $type) {
$ids += $list;
} elseif ('NOT' === $type) {
$ids = array_diff_key($ids, $list);
$ids = \array_diff_key($ids, $list);
}
}
@ -200,14 +200,14 @@ class Execute extends Method
$whereIdx[] = 't.forum_id IN (?ai:forums)';
$whereCJK[] = 't.forum_id IN (?ai:forums)';
$useTCJK = true;
$vars[':forums'] = '*' === $v->forums ? $forumIdxs : explode('.', $v->forums);
$vars[':forums'] = '*' === $v->forums ? $forumIdxs : \explode('.', $v->forums);
}
//???? нужен индекс по авторам сообщений/тем?
//???? что делать с подчеркиванием в именах?
if ('*' !== $v->author) {
$usePIdx = true;
$vars[':author'] = str_replace(['*', '?'], ['%', '_'], $v->author);
$vars[':author'] = \str_replace(['*', '?'], ['%', '_'], $v->author);
$whereIdx[] = 'p.poster LIKE ?s:author';
}
@ -267,21 +267,21 @@ class Execute extends Method
$usePIdx = true;
$usePCJK = true;
}
$this->sortType = SORT_STRING;
$this->sortType = \SORT_STRING;
break;
case 2:
$sortIdx = 't.subject';
$sortCJK = 't.subject';
$useTIdx = true;
$useTCJK = true;
$this->sortType = SORT_STRING;
$this->sortType = \SORT_STRING;
break;
case 3:
$sortIdx = 't.forum_id';
$sortCJK = 't.forum_id';
$useTIdx = true;
$useTCJK = true;
$this->sortType = SORT_NUMERIC;
$this->sortType = \SORT_NUMERIC;
break;
default:
if (1 === $this->model->showAs) {
@ -294,13 +294,13 @@ class Execute extends Method
$sortCJK = 'p.id';
$usePCJK = true;
}
$this->sortType = SORT_NUMERIC;
$this->sortType = \SORT_NUMERIC;
break;
}
$usePIdx = $usePIdx || $useTIdx ? 'INNER JOIN ::posts AS p ON p.id=m.post_id ' : '';
$useTIdx = $useTIdx ? 'INNER JOIN ::topics AS t ON t.id=p.topic_id ' : '';
$whereIdx = empty($whereIdx) ? '' : ' AND ' . implode(' AND ', $whereIdx);
$whereIdx = empty($whereIdx) ? '' : ' AND ' . \implode(' AND ', $whereIdx);
$this->queryIdx = "SELECT {$selectFIdx}, {$sortIdx} FROM ::search_words AS w " .
'INNER JOIN ::search_matches AS m ON m.word_id=w.id ' .
@ -311,10 +311,10 @@ class Execute extends Method
if ($usePCJK) {
$this->queryCJK = "SELECT {$selectFCJK}, {$sortCJK} FROM ::posts AS p " .
($useTCJK ? 'INNER JOIN ::topics AS t ON t.id=p.topic_id ' : '') .
'WHERE ' . implode(' AND ', $whereCJK);
'WHERE ' . \implode(' AND ', $whereCJK);
} else {
$this->queryCJK = "SELECT {$selectFCJK}, {$sortCJK} FROM ::topics AS t " .
'WHERE ' . implode(' AND ', $whereCJK);
'WHERE ' . \implode(' AND ', $whereCJK);
}
return $vars;

View file

@ -20,9 +20,9 @@ class Index extends Method
public function index(Post $post, $mode = 'add')
{
//???? пост после валидации должен иметь дерево тегов
$mesWords = $this->words(mb_strtolower($this->c->Parser->getText(), 'UTF-8'));
$mesWords = $this->words(\mb_strtolower($this->c->Parser->getText(), 'UTF-8'));
$subWords = $post->id === $post->parent->first_post_id
? $this->words(mb_strtolower($post->parent->subject, 'UTF-8'))
? $this->words(\mb_strtolower($post->parent->subject, 'UTF-8'))
: [];
if ('add' !== $mode) {
@ -48,13 +48,13 @@ class Index extends Method
$words = [];
if ('edit' === $mode) {
$words['add']['p'] = array_diff($mesWords, array_keys($mesCurWords));
$words['add']['s'] = array_diff($subWords, array_keys($subCurWords));
$words['del']['p'] = array_diff_key($mesCurWords, array_flip($mesWords));
$words['del']['s'] = array_diff_key($subCurWords, array_flip($subWords));
$words['add']['p'] = \array_diff($mesWords, \array_keys($mesCurWords));
$words['add']['s'] = \array_diff($subWords, \array_keys($subCurWords));
$words['del']['p'] = \array_diff_key($mesCurWords, \array_flip($mesWords));
$words['del']['s'] = \array_diff_key($subCurWords, \array_flip($subWords));
} elseif ('merge' === $mode) {
$words['add']['p'] = array_diff($mesWords, array_keys($mesCurWords));
$words['add']['s'] = array_diff($subWords, array_keys($subCurWords));
$words['add']['p'] = \array_diff($mesWords, \array_keys($mesCurWords));
$words['add']['s'] = \array_diff($subWords, \array_keys($subCurWords));
$words['del']['p'] = [];
$words['del']['s'] = [];
} else {
@ -67,7 +67,7 @@ class Index extends Method
if (empty($words['add']['s'])) {
$allWords = $words['add']['p'];
} else {
$allWords = array_unique(array_merge($words['add']['p'], $words['add']['s']));
$allWords = \array_unique(\array_merge($words['add']['p'], $words['add']['s']));
}
if (! empty($allWords)) {
$vars = [
@ -77,7 +77,7 @@ class Index extends Method
FROM ::search_words
WHERE word IN(?as:words)';
$oldWords = $this->c->DB->query($sql, $vars)->fetchAll(PDO::FETCH_COLUMN);
$newWords = array_diff($allWords, $oldWords);
$newWords = \array_diff($allWords, $oldWords);
if (! empty($newWords)) {
$sql = 'INSERT INTO ::search_words (word) VALUES(?s:word)';
@ -139,7 +139,7 @@ class Index extends Method
$text = $this->model->cleanText($text, true);
$words = [];
foreach (array_unique(explode(' ', $text)) as $word) {
foreach (\array_unique(\explode(' ', $text)) as $word) {
$word = $this->model->word($word, true);
if (null !== $word) {
$words[] = $word;

View file

@ -75,25 +75,25 @@ class Model extends BaseModel
*/
public function cleanText($text, $indexing = false)
{
$text = str_replace(['`', '', 'ё'], ['\'', '\'', 'е'], $text);
$text = \str_replace(['`', '', 'ё'], ['\'', '\'', 'е'], $text);
// четыре одинаковых буквы в одну
$text = preg_replace('%(\p{L})\1{3,}%u', '\1', $text);
$text = \preg_replace('%(\p{L})\1{3,}%u', '\1', $text);
// удаление ' и - вне слов
$text = preg_replace('%((?<![\p{L}\p{N}])[\'\-]|[\'\-](?![\p{L}\p{N}]))%u', ' ', $text);
$text = \preg_replace('%((?<![\p{L}\p{N}])[\'\-]|[\'\-](?![\p{L}\p{N}]))%u', ' ', $text);
if (false !== strpos($text, '-')) {
if (false !== \strpos($text, '-')) {
// удаление слов c -либо|нибу[дт]ь|нить
$text = preg_replace('%\b[\p{L}\p{N}\-\']+\-(?:либо|нибу[дт]ь|нить)(?![\p{L}\p{N}\'\-])%u', '', $text);
$text = \preg_replace('%\b[\p{L}\p{N}\-\']+\-(?:либо|нибу[дт]ь|нить)(?![\p{L}\p{N}\'\-])%u', '', $text);
// удаление из слов все хвосты с 1 или 2 русскими буквами или -таки|чуть
$text = preg_replace('%(?<=[\p{L}\p{N}])(\-(?:таки|чуть|[а-я]{1,2}))+(?![\p{L}\p{N}\'\-])%u', '', $text);
$text = \preg_replace('%(?<=[\p{L}\p{N}])(\-(?:таки|чуть|[а-я]{1,2}))+(?![\p{L}\p{N}\'\-])%u', '', $text);
}
// удаление символов отличающихся от букв и цифр
$text = preg_replace('%(?![\'\-'.($indexing ? '' : '\?\*').'])[^\p{L}\p{N}]+%u', ' ', $text);
$text = \preg_replace('%(?![\'\-'.($indexing ? '' : '\?\*').'])[^\p{L}\p{N}]+%u', ' ', $text);
// сжатие пробелов
$text = preg_replace('% {2,}%', ' ', $text);
$text = \preg_replace('% {2,}%', ' ', $text);
return trim($text);
return \trim($text);
}
/**
@ -117,14 +117,14 @@ class Model extends BaseModel
return $indexing ? null : $word;
}
$len = mb_strlen(trim($word, '?*'), 'UTF-8');
$len = \mb_strlen(trim($word, '?*'), 'UTF-8');
if ($len < 3) {
return null;
}
if ($len > 20) {
$word = mb_substr($word, 0, 20, 'UTF-8');
$word = \mb_substr($word, 0, 20, 'UTF-8');
}
return $word;
@ -139,6 +139,6 @@ class Model extends BaseModel
*/
public function isCJKWord($word)
{
return preg_match('%' . self::CJK_REGEX . '%u', $word) ? true : false; //?????
return \preg_match('%' . self::CJK_REGEX . '%u', $word) ? true : false; //?????
}
}

View file

@ -20,7 +20,7 @@ class Prepare extends Method
*/
public function prepare($query)
{
if (substr_count($query, '"') % 2) {
if (\substr_count($query, '"') % 2) {
$this->model->queryError = 'Odd number of quotes: \'%s\'';
$this->model->queryWords = [];
$this->model->queryText = $query;
@ -37,14 +37,14 @@ class Prepare extends Method
$keyword = true;
$count = 0;
foreach (preg_split('%"%', $query) as $subQuery) {
foreach (\preg_split('%"%', $query) as $subQuery) {
// подстрока внутри кавычек
if ($quotes) {
$subQuery = mb_strtolower(trim($subQuery), 'UTF-8');
$subQuery = \mb_strtolower(trim($subQuery), 'UTF-8');
// не стоп-слово и минимальная длина удовлетворяет условию
if (null !== $this->model->word($subQuery)) {
// подстрока является словом и нет символов CJK языков
if (false === strpos($subQuery, ' ')
if (false === \strpos($subQuery, ' ')
&& ! $this->model->isCJKWord($subQuery)
&& $this->model->cleanText($subQuery) === $subQuery
) {
@ -63,11 +63,11 @@ class Prepare extends Method
// действуют управляющие слова
foreach (
preg_split(
\preg_split(
'%\s*(\b(?:AND|OR|NOT)\b|(?<![\p{L}\p{N}])\-|[()+|!])\s*|\s+%u',
$subQuery,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
\PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY
) as $cur
) {
$key = null;
@ -107,7 +107,7 @@ class Prepare extends Method
$error = 'The order of brackets is broken: \'%s\'';
} else {
$temp = $words;
list($words, $keyword, $count) = array_pop($stack);
list($words, $keyword, $count) = \array_pop($stack);
if (! $keyword) {
$words[] = 'AND';
}
@ -117,11 +117,11 @@ class Prepare extends Method
}
break;
default:
$cur = mb_strtolower($cur, 'UTF-8');
$cur = \mb_strtolower($cur, 'UTF-8');
$cur = $this->model->cleanText($cur); //????
$temp = [];
$countT = 0;
foreach (explode(' ', $cur) as $word) {
foreach (\explode(' ', $cur) as $word) {
$word = $this->model->word($word);
if (null === $word) {
continue;
@ -131,7 +131,7 @@ class Prepare extends Method
}
if ($this->model->isCJKWord($word)) {
$temp[] = ['type' => 'CJK', 'word' => $word];
} elseif (rtrim($word, '?*') === $word) {
} elseif (\rtrim($word, '?*') === $word) {
$temp[] = $word . '*'; //????
} else {
$temp[] = $word;
@ -142,8 +142,8 @@ class Prepare extends Method
if (! $keyword) {
$words[] = 'AND';
}
if (1 === $countT || 'AND' === end($words)) {
$words = array_merge($words, $temp);
if (1 === $countT || 'AND' === \end($words)) {
$words = \array_merge($words, $temp);
$count += $countT;
} else {
$words[] = $temp;
@ -186,7 +186,7 @@ class Prepare extends Method
foreach ($words as $word) {
if (isset($word['type']) && 'CJK' === $word['type']) {
$word = '"' . $word['word'] . '"';
} elseif (is_array($word)) {
} elseif (\is_array($word)) {
$word = '(' . $this->queryText($word) . ')';
}
$result .= $space . $word;

View file

@ -3,6 +3,7 @@
namespace ForkBB\Models\SmileyList;
use ForkBB\Models\Method;
use PDO;
class Load extends Method
{
@ -14,7 +15,7 @@ class Load extends Method
*/
public function load()
{
$list = $this->c->DB->query('SELECT text, image FROM ::smilies ORDER BY disp_position')->fetchAll(\PDO::FETCH_KEY_PAIR); //???? text уникальное?
$list = $this->c->DB->query('SELECT text, image FROM ::smilies ORDER BY disp_position')->fetchAll(PDO::FETCH_KEY_PAIR); //???? text уникальное?
$this->model->list = $list;
$this->c->Cache->set('smilies', $list);
return $this->model;

View file

@ -36,7 +36,7 @@ class Stopwords extends Model
return $this->id;
}
$files = glob($this->c->DIR_LANG . '/*/stopwords.txt');
$files = \glob($this->c->DIR_LANG . '/*/stopwords.txt');
if ($files === false) {
return 'cache_id_error';
}
@ -46,10 +46,10 @@ class Stopwords extends Model
foreach ($files as $file) {
$hash[] = $file;
$hash[] = filemtime($file);
$hash[] = \filemtime($file);
}
return $this->id = sha1(implode('|', $hash));
return $this->id = \sha1(\implode('|', $hash));
}
/**
@ -61,20 +61,20 @@ class Stopwords extends Model
{
$id = $this->generateId();
if (! is_array($this->files)) {
if (! \is_array($this->files)) {
$this->list = [];
return $this;
}
$stopwords = [];
foreach ($this->files as $file) {
$stopwords = array_merge($stopwords, file($file));
$stopwords = \array_merge($stopwords, \file($file));
}
// Tidy up and filter the stopwords
$stopwords = array_map('trim', $stopwords);
$stopwords = array_filter($stopwords);
$stopwords = array_flip($stopwords);
$stopwords = \array_map('trim', $stopwords);
$stopwords = \array_filter($stopwords);
$stopwords = \array_flip($stopwords);
$this->c->Cache->set('stopwords', ['id' => $id, 'stopwords' => $stopwords]);
$this->list = $stopwords;

View file

@ -55,7 +55,7 @@ class Delete extends Action
if ($topics) {
$vars = [
':topics' => array_keys($topics),
':topics' => \array_keys($topics),
];
$sql = 'DELETE FROM ::mark_of_topic
WHERE tid IN (?ai:topics)';
@ -70,7 +70,7 @@ class Delete extends Action
}
} elseif ($forums) {
$vars = [
':forums' => array_keys($forums),
':forums' => \array_keys($forums),
];
$sql = 'DELETE FROM ::mark_of_topic
WHERE tid IN (

View file

@ -108,7 +108,7 @@ class Model extends DataModel
return false;
}
$time = max(
$time = \max(
(int) $this->c->user->u_mark_all_read,
(int) $this->parent->mf_mark_all_read,
(int) $this->c->user->last_visit,
@ -129,7 +129,7 @@ class Model extends DataModel
return false;
}
$time = max(
$time = \max(
(int) $this->c->user->u_mark_all_read,
(int) $this->parent->mf_mark_all_read,
(int) $this->mt_last_read
@ -195,7 +195,7 @@ class Model extends DataModel
throw new RuntimeException('The model does not have the required data');
}
return (int) ceil(($this->num_replies + 1) / $this->c->user->disp_posts);
return (int) \ceil(($this->num_replies + 1) / $this->c->user->disp_posts);
}
/**
@ -250,8 +250,8 @@ class Model extends DataModel
LIMIT ?i:offset, ?i:rows';
$list = $this->c->DB->query($sql, $vars)->fetchAll(PDO::FETCH_COLUMN);
if (! empty($list) && ($this->stick_fp || $this->poll_type) && ! in_array($this->first_post_id, $list)) {
array_unshift($list, $this->first_post_id);
if (! empty($list) && ($this->stick_fp || $this->poll_type) && ! \in_array($this->first_post_id, $list)) {
\array_unshift($list, $this->first_post_id);
}
$this->idsList = $list;
@ -277,7 +277,7 @@ class Model extends DataModel
$result = $this->c->DB->query($sql, $vars)->fetch();
$this->page = empty($result['flag']) ? null : (int) ceil(($result['num'] + 1) / $this->c->user->disp_posts);
$this->page = empty($result['flag']) ? null : (int) \ceil(($result['num'] + 1) / $this->c->user->disp_posts);
}
/**

View file

@ -12,9 +12,9 @@ class Save extends Action
* Обновляет тему в БД
*
* @param Topic $topic
*
*
* @throws RuntimeException
*
*
* @return Topic
*/
public function update(Topic $topic)
@ -40,7 +40,7 @@ class Save extends Action
return $topic;
}
$vars[] = $topic->id;
$this->c->DB->query('UPDATE ::topics SET ' . implode(', ', $set) . ' WHERE id=?i', $vars);
$this->c->DB->query('UPDATE ::topics SET ' . \implode(', ', $set) . ' WHERE id=?i', $vars);
$topic->resModified();
return $topic;
@ -50,9 +50,9 @@ class Save extends Action
* Добавляет новую тему в БД
*
* @param Topic $topic
*
*
* @throws RuntimeException
*
*
* @return int
*/
public function insert(Topic $topic)
@ -74,7 +74,7 @@ class Save extends Action
if (empty($set)) {
throw new RuntimeException('The model is empty');
}
$this->c->DB->query('INSERT INTO ::topics (' . implode(', ', $set) . ') VALUES (' . implode(', ', $set2) . ')', $vars);
$this->c->DB->query('INSERT INTO ::topics (' . \implode(', ', $set) . ') VALUES (' . \implode(', ', $set2) . ')', $vars);
$topic->id = $this->c->DB->lastInsertId();
$topic->resModified();

View file

@ -32,7 +32,7 @@ class View extends Action
throw new InvalidArgumentException('Expected Forum or Search');
}
if (empty($arg->idsList) || ! is_array($arg->idsList)) {
if (empty($arg->idsList) || ! \is_array($arg->idsList)) {
throw new RuntimeException('Model does not contain of topics list for display');
}
@ -47,7 +47,7 @@ class View extends Action
WHERE poster_id=?i:uid AND topic_id IN (?ai:ids)
GROUP BY topic_id';
$dots = $this->c->DB->query($sql, $vars)->fetchAll(PDO::FETCH_COLUMN);
$dots = array_flip($dots);
$dots = \array_flip($dots);
} else {
$dots = [];
}
@ -70,7 +70,7 @@ class View extends Action
}
$stmt = $this->c->DB->query($sql, $vars);
$result = array_flip($arg->idsList);
$result = \array_flip($arg->idsList);
while ($row = $stmt->fetch()) {
$row['dot'] = isset($dots[$row['id']]);
$result[$row['id']] = $this->manager->create($row);

View file

@ -104,7 +104,7 @@ class Current extends Action
*/
protected function getIp()
{
return filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?: 'unknow';
return \filter_var($_SERVER['REMOTE_ADDR'], \FILTER_VALIDATE_IP) ?: 'unknow';
}
/**
@ -115,7 +115,7 @@ class Current extends Action
protected function getUserAgent()
{
$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
return is_string($ua) ? trim($ua) : '';
return \is_string($ua) ? \trim($ua) : '';
}
/**
@ -130,26 +130,26 @@ class Current extends Action
if ($agent == '') {
return false;
}
$agentL = strtolower($agent);
$agentL = \strtolower($agent);
if (strpos($agentL, 'bot') !== false
|| strpos($agentL, 'spider') !== false
|| strpos($agentL, 'crawler') !== false
|| strpos($agentL, 'http') !== false
if (\strpos($agentL, 'bot') !== false
|| \strpos($agentL, 'spider') !== false
|| \strpos($agentL, 'crawler') !== false
|| \strpos($agentL, 'http') !== false
) {
return $this->nameBot($agent, $agentL);
}
if (strpos($agent, 'Mozilla/') !== false
&& (strpos($agent, 'Gecko') !== false
|| (strpos($agent, '(compatible; MSIE ') !== false
&& strpos($agent, 'Windows') !== false
if (\strpos($agent, 'Mozilla/') !== false
&& (\strpos($agent, 'Gecko') !== false
|| (\strpos($agent, '(compatible; MSIE ') !== false
&& \strpos($agent, 'Windows') !== false
)
)
) {
return false;
} elseif (strpos($agent, 'Opera/') !== false
&& strpos($agent, 'Presto/') !== false
} elseif (\strpos($agent, 'Opera/') !== false
&& \strpos($agent, 'Presto/') !== false
) {
return false;
}
@ -166,21 +166,21 @@ class Current extends Action
*/
protected function nameBot($agent, $agentL)
{
if (strpos($agentL, 'mozilla') !== false) {
$agent = preg_replace('%Mozilla.*?compatible%i', ' ', $agent);
if (\strpos($agentL, 'mozilla') !== false) {
$agent = \preg_replace('%Mozilla.*?compatible%i', ' ', $agent);
}
if (strpos($agentL, 'http') !== false || strpos($agentL, 'www.') !== false) {
$agent = preg_replace('%(?:https?://|www\.)[^\)]*(\)[^/]+$)?%i', ' ', $agent);
if (\strpos($agentL, 'http') !== false || \strpos($agentL, 'www.') !== false) {
$agent = \preg_replace('%(?:https?://|www\.)[^\)]*(\)[^/]+$)?%i', ' ', $agent);
}
if (strpos($agent, '@') !== false) {
$agent = preg_replace('%\b[a-z0-9_\.-]+@[^\)]+%i', ' ', $agent);
if (\strpos($agent, '@') !== false) {
$agent = \preg_replace('%\b[a-z0-9_\.-]+@[^\)]+%i', ' ', $agent);
}
$agentL = strtolower($agent);
if (strpos($agentL, 'bot') !== false
|| strpos($agentL, 'spider') !== false
|| strpos($agentL, 'crawler') !== false
|| strpos($agentL, 'engine') !== false
$agentL = \strtolower($agent);
if (\strpos($agentL, 'bot') !== false
|| \strpos($agentL, 'spider') !== false
|| \strpos($agentL, 'crawler') !== false
|| \strpos($agentL, 'engine') !== false
) {
$f = true;
$p = '%(?<=[^a-z\d\.-])(?:robot|bot|spider|crawler)\b.*%i';
@ -189,7 +189,7 @@ class Current extends Action
$p = '%^$%';
}
if ($f && preg_match('%\b(([a-z\d\.! _-]+)?(?:robot|(?<!ro)bot|spider|crawler|engine)(?(2)[a-z\d\.! _-]*|[a-z\d\.! _-]+))%i', $agent, $matches))
if ($f && \preg_match('%\b(([a-z\d\.! _-]+)?(?:robot|(?<!ro)bot|spider|crawler|engine)(?(2)[a-z\d\.! _-]*|[a-z\d\.! _-]+))%i', $agent, $matches))
{
$agent = $matches[1];
@ -229,20 +229,20 @@ class Current extends Action
'',
];
}
$agent = trim(preg_replace($pat, $rep, $agent), ' -');
$agent = \trim(\preg_replace($pat, $rep, $agent), ' -');
if (empty($agent)) {
return 'Unknown';
}
$a = explode(' ', $agent);
$a = \explode(' ', $agent);
$agent = $a[0];
if (strlen($agent) < 20
if (\strlen($agent) < 20
&& ! empty($a[1])
&& strlen($agent . ' ' . $a[1]) < 26
&& \strlen($agent . ' ' . $a[1]) < 26
) {
$agent .= ' ' . $a[1];
} elseif (strlen($agent) > 25) {
} elseif (\strlen($agent) > 25) {
$agent = 'Unknown';
}
return $agent;

View file

@ -9,18 +9,18 @@ class IsUniqueName extends Action
{
/**
* Проверка на уникальность имени пользователя
*
*
* @param User $user
*
*
* @return bool
*/
public function isUniqueName(User $user)
{
$vars = [
':name' => $user->username,
':other' => preg_replace('%[^\p{L}\p{N}]%u', '', $user->username), //????
':other' => \preg_replace('%[^\p{L}\p{N}]%u', '', $user->username), //????
];
$result = $this->c->DB->query('SELECT username FROM ::users WHERE LOWER(username)=LOWER(?s:name) OR LOWER(username)=LOWER(?s:other)', $vars)->fetchAll();
return ! count($result);
return ! \count($result);
}
}

View file

@ -19,7 +19,7 @@ class Load extends Action
*/
public function load($value, $field = 'id')
{
$flag = is_array($value);
$flag = \is_array($value);
switch (($flag ? 'a_' : '') . $field) {
case 'id':
@ -58,7 +58,7 @@ class Load extends Action
}
return $result;
} else {
$count = count($data);
$count = \count($data);
// число найденных пользователей отлично от одного или гость
if (1 !== $count || 1 === $data[0]['id']) {
return $count;

View file

@ -177,7 +177,7 @@ class Model extends DataModel
*/
public function title()
{
if (isset($this->c->bans->userList[mb_strtolower($this->username)])) { //????
if (isset($this->c->bans->userList[\mb_strtolower($this->username)])) { //????
return \ForkBB\__('Banned');
} elseif ($this->title != '') {
return \ForkBB\cens($this->title);

View file

@ -13,14 +13,14 @@ class Promote extends Action
* Обновляет данные пользователя
*
* @param mixed ...$args
*
*
* @throws RuntimeException
*
*
* @return int
*/
public function promote(...$args)
{
$count = count($args);
$count = \count($args);
// перемещение всех пользователей из группы 0 в группу 1
if (2 == $count && $args[0] instanceof Group && $args[1] instanceof Group) {
@ -28,8 +28,8 @@ class Promote extends Action
':old' => $args[0]->g_id,
':new' => $args[1]->g_id,
];
$sql = 'UPDATE ::users
SET group_id=?i:new
$sql = 'UPDATE ::users
SET group_id=?i:new
WHERE group_id=?i:old';
return $this->c->DB->exec($sql, $vars);
// продвижение всех пользователей в группе 0
@ -39,8 +39,8 @@ class Promote extends Action
':new' => $args[0]->g_promote_next_group,
':count' => $args[0]->g_promote_min_posts,
];
$sql = 'UPDATE ::users
SET group_id=?i:new
$sql = 'UPDATE ::users
SET group_id=?i:new
WHERE group_id=?i:old AND num_posts>=?i:count';
return $this->c->DB->exec($sql, $vars);
} else {

View file

@ -12,9 +12,9 @@ class Save extends Action
* Обновляет данные пользователя
*
* @param User $user
*
*
* @throws RuntimeException
*
*
* @return User
*/
public function update(User $user)
@ -53,7 +53,7 @@ class Save extends Action
} else {
$vars[] = $user->id;
}
$this->c->DB->query('UPDATE ::' . $table . ' SET ' . implode(', ', $set) . ' WHERE ' . $where, $vars);
$this->c->DB->query('UPDATE ::' . $table . ' SET ' . \implode(', ', $set) . ' WHERE ' . $where, $vars);
$user->resModified();
return $user;
@ -63,9 +63,9 @@ class Save extends Action
* Добавляет новую запись в таблицу пользователей
*
* @param User $user
*
*
* @throws RuntimeException
*
*
* @return int
*/
public function insert(User $user)
@ -87,7 +87,7 @@ class Save extends Action
if (empty($set)) {
throw new RuntimeException('The model is empty');
}
$this->c->DB->query('INSERT INTO ::users (' . implode(', ', $set) . ') VALUES (' . implode(', ', $set2) . ')', $vars);
$this->c->DB->query('INSERT INTO ::users (' . \implode(', ', $set) . ') VALUES (' . \implode(', ', $set2) . ')', $vars);
$user->id = $this->c->DB->lastInsertId();
$user->resModified();

View file

@ -10,7 +10,7 @@ class UpdateCountPosts extends Action
{
/**
* Обновляет число сообщений пользователя(ей)
*
*
* @param mixed ...$args
*
* @throws InvalidArgumentException
@ -36,7 +36,7 @@ class UpdateCountPosts extends Action
} else {
$where = 'u.id IN (?ai:ids)';
$vars = [
':ids' => array_keys($ids),
':ids' => \array_keys($ids),
];
}