* enforced v7.1 compliance, preparations for v7.2
 * removed deprecated usage of each()
 * prefer array deconstruction via [] instead of calling list()
 * try to catch failed session_start()
 * prefer ... - Token instead of calling func_get_args() func_num_args()
 * enforce return types in AjaxHandler
 * revision push
This commit is contained in:
Sarjuuk
2018-11-27 00:43:32 +01:00
parent f8a34aa98e
commit d9cd24026c
46 changed files with 299 additions and 342 deletions

View File

@@ -18,7 +18,7 @@ Also, this project is not meant to be used for commercial puposes of any kind!
## Requirements
+ Webserver running PHP ≥ 7.0.1 including extensions:
+ Webserver running PHP ≥ 7.1 including extensions:
+ SimpleXML
+ GD
+ Mysqli

View File

@@ -28,7 +28,7 @@ class AjaxHandler
$v = isset($_GET[$k]) ? filter_input(INPUT_GET, $k, $v[0], $v[1]) : null;
}
public function handle(&$out)
public function handle(string &$out) : bool
{
if (!$this->handler)
return false;
@@ -43,46 +43,56 @@ class AjaxHandler
}
$h = $this->handler;
$out = (string)$this->$h();
$out = $this->$h();
if ($out === null)
$out = '';
return true;
}
public function getContentType()
public function getContentType() : string
{
return $this->contentType;
}
protected function checkEmptySet($val)
protected function checkEmptySet(string $val) : bool
{
return $val === ''; // parameter is expected to be empty
}
protected function checkLocale($val)
protected function checkLocale(string $val) : int
{
if (preg_match('/^'.implode('|', array_keys(array_filter(Util::$localeStrings))).'$/', $val))
return intval($val);
return intVal($val);
return null;
return -1;
}
protected function checkInt($val)
protected function checkInt(string $val) : int
{
if (preg_match('/^-?\d+$/', $val))
return intval($val);
return intVal($val);
return null;
return 0;
}
protected function checkIdList($val)
protected function checkIdList(string $val) : array
{
if (preg_match('/^-?\d+(,-?\d+)*$/', $val))
return array_map('intval', explode(',', $val));
return array_map('intVal', explode(',', $val));
return null;
return [];
}
protected function checkFulltext($val)
protected function checkIdListUnsigned(string $val) : array
{
if (preg_match('/\d+(,\d+)*/', $val))
return array_map('intVal', explode(',', $val));
return [];
}
protected function checkFulltext(string $val) : string
{
// trim non-printable chars
return preg_replace('/[\p{C}]/ui', '', $val);

View File

@@ -43,7 +43,7 @@ class AjaxAccount extends AjaxHandler
$this->handler = 'handleFavorites';
}
protected function handleExclude()
protected function handleExclude() : void
{
if ($this->_post['mode'] == 1) // directly set exludes
{
@@ -78,18 +78,16 @@ class AjaxAccount extends AjaxHandler
$mask = $this->_post['groups'] & PR_EXCLUDE_GROUP_ANY;
DB::Aowow()->query('UPDATE ?_account SET excludeGroups = ?d WHERE id = ?d', $mask, User::$id);
return;
}
protected function handleWeightscales()
protected function handleWeightscales() : string
{
if ($this->_post['save'])
{
if (!$this->_post['scale'])
{
trigger_error('AjaxAccount::handleWeightscales - scaleId empty', E_USER_ERROR);
return 0;
return '0';
}
$id = 0;
@@ -99,7 +97,7 @@ class AjaxAccount extends AjaxHandler
if (!DB::Aowow()->selectCell('SELECT 1 FROM ?_account_weightscales WHERE userId = ?d AND id = ?d', User::$id, $id))
{
trigger_error('AjaxAccount::handleWeightscales - scale #'.$id.' not in db or owned by user #'.User::$id, E_USER_ERROR);
return 0;
return '0';
}
DB::Aowow()->query('UPDATE ?_account_weightscales SET `name` = ? WHERE id = ?d', $this->_post['name'], $id);
@@ -108,7 +106,7 @@ class AjaxAccount extends AjaxHandler
{
$nScales = DB::Aowow()->selectCell('SELECT COUNT(id) FROM ?_account_weightscales WHERE userId = ?d', User::$id);
if ($nScales >= 5) // more or less hard-defined in LANG.message_weightscalesaveerror
return 0;
return '0';
$id = DB::Aowow()->query('INSERT INTO ?_account_weightscales (`userId`, `name`) VALUES (?d, ?)', User::$id, $this->_post['name']);
}
@@ -117,25 +115,25 @@ class AjaxAccount extends AjaxHandler
foreach (explode(',', $this->_post['scale']) as $s)
{
list($k, $v) = explode(':', $s);
[$k, $v] = explode(':', $s);
if (!in_array($k, Util::$weightScales) || $v < 1)
continue;
DB::Aowow()->query('INSERT INTO ?_account_weightscale_data VALUES (?d, ?, ?d)', $id, $k, $v);
}
return $id;
return (string)$id;
}
else if ($this->_post['delete'] && $this->_post['id'] && $this->_post['id'][0])
DB::Aowow()->query('DELETE FROM ?_account_weightscales WHERE id = ?d AND userId = ?d', $this->_post['id'][0], User::$id);
else
{
trigger_error('AjaxAccount::handleWeightscales - malformed request received', E_USER_ERROR);
return 0;
return '0';
}
}
protected function handleFavorites()
protected function handleFavorites() : void
{
// omit usage of sessionKey
if (count($this->_post['id']) != 1 || empty($this->_post['id'][0]))
@@ -167,18 +165,20 @@ class AjaxAccount extends AjaxHandler
DB::Aowow()->query('DELETE FROM ?_account_favorites WHERE `userId` = ?d AND `type` = ?d AND `typeId` = ?d', User::$id, $type, $typeId);
}
protected function checkScale($val)
protected function checkScale(string $val) : string
{
if (preg_match('/^((\w+:\d+)(,\w+:\d+)*)$/', $val))
return $val;
return null;
return '';
}
protected function checkName($val)
protected function checkName(string $val) : string
{
$var = trim(urldecode($val));
return filter_var($var, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
}
}
?>

View File

@@ -7,20 +7,20 @@ class AjaxAdmin extends AjaxHandler
{
protected $validParams = ['screenshots', 'siteconfig', 'weight-presets'];
protected $_get = array(
'action' => [FILTER_SANITIZE_STRING, 0xC], // FILTER_FLAG_STRIP_LOW | *_HIGH
'id' => [FILTER_CALLBACK, ['options' => 'AjaxAdmin::checkId']],
'action' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH ],
'id' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkIdListUnsigned']],
'key' => [FILTER_CALLBACK, ['options' => 'AjaxAdmin::checkKey'] ],
'all' => [FILTER_UNSAFE_RAW, null],
'all' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkFulltext'] ],
'type' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkInt'] ],
'typeid' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkInt'] ],
'user' => [FILTER_CALLBACK, ['options' => 'AjaxAdmin::checkUser'] ],
'val' => [FILTER_UNSAFE_RAW, null]
'val' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkFulltext'] ]
);
protected $_post = array(
'alt' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ],
'id' => [FILTER_SANITIZE_NUMBER_INT, null ],
'scale' => [FILTER_CALLBACK, ['options' => 'AjaxAdmin::checkScale']],
'__icon' => [FILTER_CALLBACK, ['options' => 'AjaxAdmin::checkKey']],
'__icon' => [FILTER_CALLBACK, ['options' => 'AjaxAdmin::checkKey'] ]
);
public function __construct(array $params)
@@ -75,7 +75,7 @@ class AjaxAdmin extends AjaxHandler
// get all => null (optional)
// evaled response .. UNK
protected function ssList()
protected function ssList() : string
{
// ssm_screenshotPages
// ssm_numPagesFound
@@ -89,7 +89,7 @@ class AjaxAdmin extends AjaxHandler
// get: [type => type, typeId => typeId] || [user => username]
// evaled response .. UNK
protected function ssManage()
protected function ssManage() : string
{
$res = [];
@@ -104,23 +104,21 @@ class AjaxAdmin extends AjaxHandler
// get: id => SSid
// resp: ''
protected function ssEditAlt()
protected function ssEditAlt() : void
{
// doesn't need to be htmlEscaped, ths javascript does that
if ($this->_get['id'] && $this->_post['alt'] !== null)
DB::Aowow()->query('UPDATE ?_screenshots SET caption = ? WHERE id = ?d', trim($this->_post['alt']), $this->_get['id'][0]);
return '';
}
// get: id => comma-separated SSids
// resp: ''
protected function ssApprove()
protected function ssApprove() : void
{
if (!$this->_get['id'])
{
trigger_error('AjaxAdmin::ssApprove - screenshotId empty', E_USER_ERROR);
return '';
return;
}
// create resized and thumb version of screenshot
@@ -185,17 +183,17 @@ class AjaxAdmin extends AjaxHandler
trigger_error('AjaxAdmin::ssApprove - screenshot #'.$id.' not in db or already approved', E_USER_ERROR);
}
return '';
return;
}
// get: id => comma-separated SSids
// resp: ''
protected function ssSticky()
protected function ssSticky() : void
{
if (!$this->_get['id'])
{
trigger_error('AjaxAdmin::ssSticky - screenshotId empty', E_USER_ERROR);
return '';
return;
}
// approve soon to be sticky screenshots
@@ -212,19 +210,17 @@ class AjaxAdmin extends AjaxHandler
// toggle sticky status
DB::Aowow()->query('UPDATE ?_screenshots SET `status` = IF(`status` & ?d, `status` & ~?d, `status` | ?d) WHERE id = ?d AND `status` & ?d', CC_FLAG_STICKY, CC_FLAG_STICKY, CC_FLAG_STICKY, $id, CC_FLAG_APPROVED);
}
return '';
}
// get: id => comma-separated SSids
// resp: ''
// 2 steps: 1) remove from sight, 2) remove from disk
protected function ssDelete()
protected function ssDelete() : void
{
if (!$this->_get['id'])
{
trigger_error('AjaxAdmin::ssDelete - screenshotId empty', E_USER_ERROR);
return '';
return;
}
$path = 'static/uploads/screenshots/%s/%d.jpg';
@@ -264,22 +260,20 @@ class AjaxAdmin extends AjaxHandler
if ($toUnflag && Util::$typeClasses[$type] && ($tbl = get_class_vars(Util::$typeClasses[$type])['dataTable']))
DB::Aowow()->query('UPDATE '.$tbl.' SET cuFlags = cuFlags & ~?d WHERE id IN (?a)', CUSTOM_HAS_SCREENSHOT, array_keys($toUnflag));
}
return '';
}
// get: id => ssId, typeid => typeId (but not type..?)
// resp: ''
protected function ssRelocate()
protected function ssRelocate() : void
{
if (!$this->_get['id'] || !$this->_get['typeid'])
{
trigger_error('AjaxAdmin::ssRelocate - screenshotId or typeId empty', E_USER_ERROR);
return '';
return;
}
$id = $this->_get['id'][0];
list($type, $oldTypeId) = array_values(DB::Aowow()->selectRow('SELECT type, typeId FROM ?_screenshots WHERE id = ?d', $id));
[$type, $oldTypeId] = array_values(DB::Aowow()->selectRow('SELECT type, typeId FROM ?_screenshots WHERE id = ?d', $id));
$typeId = (int)$this->_get['typeid'];
$tc = new Util::$typeClasses[$type]([['id', $typeId]]);
@@ -298,11 +292,9 @@ class AjaxAdmin extends AjaxHandler
}
else
trigger_error('AjaxAdmin::ssRelocate - invalid typeId #'.$typeId.' for type '.$tc::$brickFile, E_USER_ERROR);
return '';
}
protected function confAdd()
protected function confAdd() : string
{
$key = trim($this->_get['key']);
$val = trim(urldecode($this->_get['val']));
@@ -323,7 +315,7 @@ class AjaxAdmin extends AjaxHandler
return '';
}
protected function confRemove()
protected function confRemove() : string
{
if (!$this->_get['key'])
return 'invalid configuration option given';
@@ -334,7 +326,7 @@ class AjaxAdmin extends AjaxHandler
return 'option name is either protected or was not found';
}
protected function confUpdate()
protected function confUpdate() : string
{
$key = trim($this->_get['key']);
$val = trim(urldecode($this->_get['val']));
@@ -353,8 +345,8 @@ class AjaxAdmin extends AjaxHandler
return "value must be integer";
else if ($cfg['flags'] & CON_FLAG_TYPE_FLOAT && !preg_match('/^-?\d*(,|.)?\d+$/i', $val))
return "value must be float";
else if ($cfg['flags'] & CON_FLAG_TYPE_BOOL)
$val = (int)!!$val; // *snort* bwahahaa
else if ($cfg['flags'] & CON_FLAG_TYPE_BOOL && $val != '1')
$val = '0';
DB::Aowow()->query('UPDATE ?_config SET `value` = ? WHERE `key` = ?', $val, $key);
if (!$this->confOnChange($key, $val, $msg))
@@ -363,51 +355,37 @@ class AjaxAdmin extends AjaxHandler
return $msg;
}
protected function wtSave()
protected function wtSave() : string
{
if (!$this->_post['id'] || !$this->_post['__icon'])
return 3;
return '3';
// save to db
DB::Aowow()->query('DELETE FROM ?_account_weightscale_data WHERE id = ?d', $this->_post['id']);
DB::Aowow()->query('UPDATE ?_account_weightscales SET `icon`= ? WHERE `id` = ?d', $this->_post['__icon'], $this->_post['id']);
foreach (explode(',', $this->_post['scale']) as $s)
{
list($k, $v) = explode(':', $s);
[$k, $v] = explode(':', $s);
if (!in_array($k, Util::$weightScales) || $v < 1)
continue;
if (DB::Aowow()->query('INSERT INTO ?_account_weightscale_data VALUES (?d, ?, ?d)', $this->_post['id'], $k, $v) === null)
return 1;
return '1';
}
// write dataset
exec('php aowow --build=weightPresets', $out);
foreach ($out as $o)
if (strstr($o, 'ERR'))
return 2;
return '2';
// all done
return 0;
return '0';
}
protected function checkId($val)
{
// expecting id-list
if (preg_match('/\d+(,\d+)*/', $val))
return array_map('intVal', explode(',', $val));
return null;
}
protected function checkKey($val)
protected function checkKey(string $val) : string
{
// expecting string
if (preg_match('/[^a-z0-9_\.\-]/i', $val))
@@ -416,25 +394,25 @@ class AjaxAdmin extends AjaxHandler
return strtolower($val);
}
protected function checkUser($val)
protected function checkUser($val) : string
{
$n = Util::lower(trim(urldecode($val)));
if (User::isValidName($n))
return $n;
return null;
return '';
}
protected function checkScale($val)
protected function checkScale($val) : string
{
if (preg_match('/^((\w+:\d+)(,\w+:\d+)*)$/', $val))
return $val;
return null;
return '';
}
private function confOnChange($key, $val, &$msg)
private function confOnChange(string $key, string $val, string &$msg) : bool
{
$fn = $buildList = null;
@@ -482,3 +460,5 @@ class AjaxAdmin extends AjaxHandler
return $fn ? $fn($val) : true;
}
}
?>

View File

@@ -35,7 +35,7 @@ class AjaxArenaTeam extends AjaxHandler
profile: <empty> [optional, also get related chars]
return: 1
*/
protected function handleResync()
protected function handleResync() : string
{
if ($teams = DB::Aowow()->select('SELECT realm, realmGUID FROM ?_profiler_arena_team WHERE id IN (?a)', $this->_get['id']))
foreach ($teams as $t)
@@ -72,7 +72,7 @@ class AjaxArenaTeam extends AjaxHandler
1: char does not exist
2: armory gone
*/
protected function handleStatus()
protected function handleStatus() : string
{
$response = Profiler::resyncStatus(TYPE_ARENA_TEAM, $this->_get['id']);
return Util::toJSON($response);

View File

@@ -11,16 +11,16 @@ class AjaxComment extends AjaxHandler
const REPLY_LENGTH_MAX = 600;
protected $_post = array(
'id' => [FILTER_CALLBACK, ['options' => 'AjaxComment::checkId']],
'body' => [FILTER_UNSAFE_RAW, null],// escaped by json_encode
'commentbody' => [FILTER_UNSAFE_RAW, null],// escaped by json_encode
'id' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkIdListUnsigned']],
'body' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkFulltext'] ],
'commentbody' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkFulltext'] ],
'response' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ],
'reason' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ],
'remove' => [FILTER_SANITIZE_NUMBER_INT, null ],
'commentId' => [FILTER_SANITIZE_NUMBER_INT, null ],
'replyId' => [FILTER_SANITIZE_NUMBER_INT, null ],
'sticky' => [FILTER_SANITIZE_NUMBER_INT, null ],
// 'username' => [FILTER_SANITIZE_STRING, 0xC] // FILTER_FLAG_STRIP_LOW | *_HIGH
// 'username' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH ]
);
protected $_get = array(
@@ -75,19 +75,19 @@ class AjaxComment extends AjaxHandler
}
// i .. have problems believing, that everything uses nifty ajax while adding comments requires a brutal header(Loacation: <wherever>), yet, thats how it is
protected function handleCommentAdd()
protected function handleCommentAdd() : string
{
if (!$this->_get['typeid'] || !$this->_get['type'] || !isset(Util::$typeClasses[$this->_get['type']]))
{
trigger_error('AjaxComment::handleCommentAdd - malforemd request received', E_USER_ERROR);
return; // whatever, we cant even send him back
return ''; // whatever, we cant even send him back
}
// this type cannot be commented on
if (!(get_class_vars(Util::$typeClasses[$this->_get['type']])['contribute'] & CONTRIBUTE_CO))
{
trigger_error('AjaxComment::handleCommentAdd - tried to comment on unsupported type #'.$this->_get['type'], E_USER_ERROR);
return;
return '';
}
// trim to max length
@@ -125,7 +125,7 @@ class AjaxComment extends AjaxHandler
return '?'.Util::$typeStrings[$this->_get['type']].'='.$this->_get['typeid'].'#comments';
}
protected function handleCommentEdit()
protected function handleCommentEdit() : void
{
if (!User::canComment() && !User::isInGroup(U_GROUP_MODERATOR))
{
@@ -162,7 +162,7 @@ class AjaxComment extends AjaxHandler
DB::Aowow()->query('UPDATE ?_comments SET editCount = editCount + 1, ?a WHERE id = ?d', $update, $this->_get['id']);
}
protected function handleCommentDelete()
protected function handleCommentDelete() : void
{
if (!$this->_post['id'] || !User::$id)
{
@@ -190,13 +190,10 @@ class AjaxComment extends AjaxHandler
DB::Aowow()->query('UPDATE '.$tbl.' SET cuFlags = cuFlags & ~?d WHERE id = ?d', CUSTOM_HAS_COMMENT, $coInfo['typeId']);
}
else
{
trigger_error('AjaxComment::handleCommentDelete - user #'.User::$id.' could not flag comment #'.$this->_post['id'].' as deleted', E_USER_ERROR);
return;
}
}
protected function handleCommentUndelete()
protected function handleCommentUndelete() : void
{
if (!$this->_post['id'] || !User::$id)
{
@@ -219,13 +216,10 @@ class AjaxComment extends AjaxHandler
DB::Aowow()->query('UPDATE '.$tbl.' SET cuFlags = cuFlags | ?d WHERE id = ?d', CUSTOM_HAS_COMMENT, $coInfo['typeId']);
}
else
{
trigger_error('AjaxComment::handleCommentUndelete - user #'.User::$id.' could not unflag comment #'.$this->_post['id'].' as deleted', E_USER_ERROR);
return;
}
}
protected function handleCommentRating()
protected function handleCommentRating() : string
{
if (!$this->_get['id'])
return Util::toJSON(['success' => 0]);
@@ -236,7 +230,7 @@ class AjaxComment extends AjaxHandler
return Util::toJSON(['success' => 1, 'up' => 0, 'down' => 0]);
}
protected function handleCommentVote()
protected function handleCommentVote() : string
{
if (!User::$id || !$this->_get['id'] || !$this->_get['rating'])
return Util::toJSON(['error' => 1, 'message' => Lang::main('genericError')]);
@@ -272,7 +266,7 @@ class AjaxComment extends AjaxHandler
return Util::toJSON(['error' => 0]);
}
protected function handleCommentSticky()
protected function handleCommentSticky() : void
{
if (!$this->_post['id'] || !User::isInGroup(U_GROUP_MODERATOR))
{
@@ -286,7 +280,7 @@ class AjaxComment extends AjaxHandler
DB::Aowow()->query('UPDATE ?_comments SET flags = flags & ~?d WHERE id = ?d', CC_FLAG_STICKY, $this->_post['id'][0]);
}
protected function handleCommentOutOfDate()
protected function handleCommentOutOfDate() : string
{
$this->contentType = 'text/plain';
@@ -319,12 +313,12 @@ class AjaxComment extends AjaxHandler
return Lang::main('intError');
}
protected function handleCommentShowReplies()
protected function handleCommentShowReplies() : string
{
return Util::toJSON(!$this->_get['id'] ? [] : CommunityContent::getCommentReplies($this->_get['id']));
}
protected function handleReplyAdd()
protected function handleReplyAdd() : string
{
$this->contentType = 'text/plain';
@@ -347,7 +341,7 @@ class AjaxComment extends AjaxHandler
return Lang::main('intError');
}
protected function handleReplyEdit()
protected function handleReplyEdit() : string
{
$this->contentType = 'text/plain';
@@ -371,7 +365,7 @@ class AjaxComment extends AjaxHandler
return Lang::main('intError');
}
protected function handleReplyDetach()
protected function handleReplyDetach() : void
{
if (!$this->_post['id'] || !User::isInGroup(U_GROUP_MODERATOR))
{
@@ -382,7 +376,7 @@ class AjaxComment extends AjaxHandler
DB::Aowow()->query('UPDATE ?_comments c1, ?_comments c2 SET c1.replyTo = 0, c1.type = c2.type, c1.typeId = c2.typeId WHERE c1.replyTo = c2.id AND c1.id = ?d', $this->_post['id'][0]);
}
protected function handleReplyDelete()
protected function handleReplyDelete() : void
{
if (!User::$id || !$this->_post['id'])
{
@@ -396,7 +390,7 @@ class AjaxComment extends AjaxHandler
trigger_error('AjaxComment::handleReplyDelete - deleting comment #'.$this->_post['id'][0].' by user #'.User::$id.' from db failed', E_USER_ERROR);
}
protected function handleReplyFlag()
protected function handleReplyFlag() : void
{
if (!User::$id || !$this->_post['id'])
{
@@ -407,7 +401,7 @@ class AjaxComment extends AjaxHandler
Util::createReport(1, 19, $this->_post['id'][0], '[General Reply Report]');
}
protected function handleReplyUpvote()
protected function handleReplyUpvote() : void
{
if (!$this->_post['id'] || !User::canUpvote())
{
@@ -438,7 +432,7 @@ class AjaxComment extends AjaxHandler
trigger_error('AjaxComment::handleReplyUpvote - write to db failed', E_USER_ERROR);
}
protected function handleReplyDownvote()
protected function handleReplyDownvote() : void
{
if (!$this->_post['id'] || !User::canDownvote())
{
@@ -468,14 +462,6 @@ class AjaxComment extends AjaxHandler
else
trigger_error('AjaxComment::handleReplyDownvote - write to db failed', E_USER_ERROR);
}
protected function checkId($val)
{
// expecting id-list
if (preg_match('/\d+(,\d+)*/', $val))
return array_map('intVal', explode(',', $val));
return null;
}
}
?>

View File

@@ -33,7 +33,7 @@ class AjaxContactus extends AjaxHandler
7: already reported
$: prints response
*/
protected function handleContactUs()
protected function handleContactUs() : string
{
$mode = $this->_post['mode'];
$rsn = $this->_post['reason'];
@@ -89,3 +89,5 @@ class AjaxContactus extends AjaxHandler
return Lang::main('intError');
}
}
?>

View File

@@ -12,7 +12,7 @@ class AjaxCookie extends AjaxHandler
return;
$this->_get = array(
$params[0] => [FILTER_SANITIZE_STRING, 0xC], // FILTER_FLAG_STRIP_LOW | *_HIGH
$params[0] => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH],
);
// NOW we know, what to expect and sanitize
@@ -26,18 +26,20 @@ class AjaxCookie extends AjaxHandler
0: success
$: silent error
*/
protected function handleCookie()
protected function handleCookie() : string
{
if (User::$id && $this->params && $this->_get[$this->params[0]])
{
if (DB::Aowow()->query('REPLACE INTO ?_account_cookies VALUES (?d, ?, ?)', User::$id, $this->params[0], $this->_get[$this->params[0]]))
return 0;
return '0';
else
trigger_error('AjaxCookie::handleCookie - write to db failed', E_USER_ERROR);
}
else
trigger_error('AjaxCookie::handleCookie - malformed request received', E_USER_ERROR);
return null;
return '';
}
}
?>

View File

@@ -7,7 +7,7 @@ class AjaxData extends AjaxHandler
{
protected $_get = array(
'locale' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkLocale'] ],
't' => [FILTER_SANITIZE_STRING, 0xC], // FILTER_FLAG_STRIP_LOW | *_HIGH
't' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH],
'catg' => [FILTER_SANITIZE_NUMBER_INT, null ],
'skill' => [FILTER_CALLBACK, ['options' => 'AjaxData::checkSkill'] ],
'class' => [FILTER_SANITIZE_NUMBER_INT, null ],
@@ -28,7 +28,7 @@ class AjaxData extends AjaxHandler
/* responses
<string>
*/
protected function handleData()
protected function handleData() : string
{
$result = '';
@@ -117,17 +117,17 @@ class AjaxData extends AjaxHandler
return $result;
}
protected function checkSkill($val)
protected function checkSkill(string $val) : array
{
return array_intersect([171, 164, 333, 202, 182, 773, 755, 165, 186, 393, 197, 185, 129, 356], explode(',', $val));
}
protected function checkCallback($val)
protected function checkCallback(string $val) : bool
{
return substr($val, 0, 29) == '$WowheadProfiler.loadOnDemand';
return substr($val, 0, 29) === '$WowheadProfiler.loadOnDemand';
}
private function loadProfilerData($file, $catg = 'null')
private function loadProfilerData(string $file, string $catg = 'null') : string
{
$result = '';
if ($this->_get['callback'])

View File

@@ -84,7 +84,7 @@ class AjaxFilter extends AjaxHandler
$this->handler = 'handleFilter';
}
protected function handleFilter()
protected function handleFilter() : string
{
$url = '?'.$this->page;
@@ -106,5 +106,6 @@ class AjaxFilter extends AjaxHandler
// do get request
return $url;
}
}
?>

View File

@@ -21,17 +21,17 @@ class AjaxGotocomment extends AjaxHandler
/* responses
header()
*/
protected function handleGoToComment()
protected function handleGoToComment() : string
{
if (!$this->_get['id'])
exit; // just be blank
return '.'; // go home
if ($_ = DB::Aowow()->selectRow('SELECT IFNULL(c2.id, c1.id) AS id, IFNULL(c2.type, c1.type) AS type, IFNULL(c2.typeId, c1.typeId) AS typeId FROM ?_comments c1 LEFT JOIN ?_comments c2 ON c1.replyTo = c2.id WHERE c1.id = ?d', $this->_get['id']))
return '?'.Util::$typeStrings[$_['type']].'='.$_['typeId'].'#comments:id='.$_['id'].($_['id'] != $this->_get['id'] ? ':reply='.$this->_get['id'] : null);
else
trigger_error('AjaxGotocomment::handleGoToComment - could not find comment #'.$this->get['id'], E_USER_ERROR);
exit;
return '.';
}
}

View File

@@ -35,7 +35,7 @@ class AjaxGuild extends AjaxHandler
profile: <empty> [optional, also get related chars]
return: 1
*/
protected function handleResync()
protected function handleResync() : string
{
if ($guilds = DB::Aowow()->select('SELECT realm, realmGUID FROM ?_profiler_guild WHERE id IN (?a)', $this->_get['id']))
foreach ($guilds as $g)
@@ -72,7 +72,7 @@ class AjaxGuild extends AjaxHandler
1: char does not exist
2: armory gone
*/
protected function handleStatus()
protected function handleStatus() : string
{
$response = Profiler::resyncStatus(TYPE_GUILD, $this->_get['id']);
return Util::toJSON($response);

View File

@@ -21,7 +21,7 @@ class AjaxLocale extends AjaxHandler
/* responses
header()
*/
protected function handleLocale()
protected function handleLocale() : string
{
User::setLocale($this->_get['locale']);
User::save();

View File

@@ -11,7 +11,7 @@ class AjaxProfile extends AjaxHandler
protected $_get = array(
'id' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkIdList'] ],
'items' => [FILTER_CALLBACK, ['options' => 'AjaxProfile::checkItemList'] ],
'size' => [FILTER_SANITIZE_STRING, 0xC], // FILTER_FLAG_STRIP_LOW | *_HIGH
'size' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_LOW_HIGH],
'guild' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkEmptySet'] ],
'arena-team' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkEmptySet'] ],
'user' => [FILTER_CALLBACK, ['options' => 'AjaxProfile::checkUser'] ]
@@ -28,17 +28,17 @@ class AjaxProfile extends AjaxHandler
'talenttree2' => [FILTER_SANITIZE_NUMBER_INT, null ],
'talenttree3' => [FILTER_SANITIZE_NUMBER_INT, null ],
'activespec' => [FILTER_SANITIZE_NUMBER_INT, null ],
'talentbuild1' => [FILTER_SANITIZE_STRING, 0xC],// FILTER_FLAG_STRIP_LOW | *_HIGH
'glyphs1' => [FILTER_SANITIZE_STRING, 0xC],
'talentbuild2' => [FILTER_SANITIZE_STRING, 0xC],
'glyphs2' => [FILTER_SANITIZE_STRING, 0xC],
'icon' => [FILTER_SANITIZE_STRING, 0xC],
'talentbuild1' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_LOW_HIGH ],
'glyphs1' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_LOW_HIGH ],
'talentbuild2' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_LOW_HIGH ],
'glyphs2' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_LOW_HIGH ],
'icon' => [FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_LOW_HIGH ],
'description' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkFulltext'] ],
'source' => [FILTER_SANITIZE_NUMBER_INT, null ],
'copy' => [FILTER_SANITIZE_NUMBER_INT, null ],
'public' => [FILTER_SANITIZE_NUMBER_INT, null ],
'gearscore' => [FILTER_SANITIZE_NUMBER_INT, null ],
'inv' => [FILTER_CALLBACK, ['options' => 'AjaxProfile::checkItemString', 'flags' => FILTER_REQUIRE_ARRAY]],
'inv' => [FILTER_CALLBACK, ['options' => 'AjaxHandler::checkIdListUnsigned', 'flags' => FILTER_REQUIRE_ARRAY]],
);
public function __construct(array $params)
@@ -99,7 +99,7 @@ class AjaxProfile extends AjaxHandler
user: <string> [optional]
return: null
*/
protected function handleLink() // links char with account
protected function handleLink() : void // links char with account
{
if (!User::$id || empty($this->_get['id']))
{
@@ -139,7 +139,7 @@ class AjaxProfile extends AjaxHandler
user: <string> [optional]
return: null
*/
protected function handlePin() // (un)favorite
protected function handlePin() : void // (un)favorite
{
if (!User::$id || empty($this->_get['id'][0]))
{
@@ -169,7 +169,7 @@ class AjaxProfile extends AjaxHandler
user: <string> [optional]
return: null
*/
protected function handlePrivacy() // public visibility
protected function handlePrivacy() : void // public visibility
{
if (!User::$id || empty($this->_get['id'][0]))
{
@@ -204,7 +204,7 @@ class AjaxProfile extends AjaxHandler
size: <string> [optional]
return: image-header
*/
protected function handleAvatar() // image
protected function handleAvatar() : void // image
{
// something happened in the last years: those textures do not include tiny icons
$sizes = [/* 'tiny' => 15, */'small' => 18, 'medium' => 36, 'large' => 56];
@@ -246,8 +246,6 @@ class AjaxProfile extends AjaxHandler
imageGif($dest);
else
imageJpeg($dest);
return;
}
/* params
@@ -255,7 +253,7 @@ class AjaxProfile extends AjaxHandler
user: <string> [optional, not used]
return: 1
*/
protected function handleResync()
protected function handleResync() : string
{
if ($chars = DB::Aowow()->select('SELECT realm, realmGUID FROM ?_profiler_profiles WHERE id IN (?a)', $this->_get['id']))
{
@@ -291,7 +289,7 @@ class AjaxProfile extends AjaxHandler
1: char does not exist
2: armory gone
*/
protected function handleStatus()
protected function handleStatus() : string
{
// roster resync for this guild was requested -> get char list
if ($this->_get['guild'])
@@ -319,7 +317,7 @@ class AjaxProfile extends AjaxHandler
proileId [onSuccess]
-1 [onError]
*/
protected function handleSave() // unKill a profile
protected function handleSave() : string // unKill a profile
{
// todo (med): detail check this post-data
$cuProfile = array(
@@ -442,7 +440,7 @@ class AjaxProfile extends AjaxHandler
}
}
return $charId;
return (string)$charId;
}
/* params
@@ -450,7 +448,7 @@ class AjaxProfile extends AjaxHandler
return
null
*/
protected function handleDelete() // kill a profile
protected function handleDelete() : void // kill a profile
{
if (!User::$id || !$this->_get['id'])
{
@@ -475,7 +473,7 @@ class AjaxProfile extends AjaxHandler
return
lots...
*/
protected function handleLoad()
protected function handleLoad() : string
{
// titles, achievements, characterData, talents, pets
// and some onLoad-hook to .. load it registerProfile($data)
@@ -484,18 +482,18 @@ class AjaxProfile extends AjaxHandler
if (!$this->_get['id'])
{
trigger_error('AjaxProfile::handleLoad - profileId empty', E_USER_ERROR);
return;
return '';
}
$pBase = DB::Aowow()->selectRow('SELECT pg.name AS guildname, p.* FROM ?_profiler_profiles p LEFT JOIN ?_profiler_guild pg ON pg.id = p.guild WHERE p.id = ?d', $this->_get['id'][0]);
if (!$pBase)
{
trigger_error('Profiler::handleLoad - called with invalid profileId #'.$this->_get['id'][0], E_USER_WARNING);
return;
return '';
}
if (($pBase['cuFlags'] & PROFILER_CU_DELETED) && !User::isInGroup(U_GROUP_ADMIN | U_GROUP_BUREAU))
return;
return '';
$rData = [];
@@ -746,32 +744,23 @@ class AjaxProfile extends AjaxHandler
return
null
*/
protected function handlePurge() { } // removes completion data (as uploaded by the wowhead client) Just fail silently if someone triggers this manually
protected function handlePurge() : void { } // removes completion data (as uploaded by the wowhead client) Just fail silently if someone triggers this manually
protected function checkItemList($val)
protected function checkItemList($val) : array
{
// expecting item-list
if (preg_match('/\d+(:\d+)*/', $val))
return array_map('intval', explode(':', $val));
return array_map('intVal', explode(':', $val));
return null;
return [];
}
protected function checkItemString($val)
{
// expecting item-list
if (preg_match('/\d+(,\d+)*/', $val))
return array_map('intval', explode(',', $val));
return null;
}
protected function checkUser($val)
protected function checkUser(string $val) : string
{
if (User::isValidName($val))
return $val;
return null;
return '';
}
}

View File

@@ -294,7 +294,7 @@ abstract class BaseType
// reset on __construct
$this->reset();
while (list($id, $_) = each($this->templates))
foreach ($this->templates as $id => $__)
{
$this->id = $id;
$this->curTpl = &$this->templates[$id]; // do not use $tpl from each(), as we want to be referenceable
@@ -931,7 +931,7 @@ abstract class Filter
{
// doesn't need to set formData['form']; this happens in GET-step
foreach ($this->inputFields as $inp => list($type, $valid, $asArray))
foreach ($this->inputFields as $inp => [$type, $valid, $asArray])
{
if (!isset($_POST[$inp]) || $_POST[$inp] === '')
continue;
@@ -977,7 +977,7 @@ abstract class Filter
}
$cr = $crs = $crv = [];
foreach ($this->inputFields as $inp => list($type, $valid, $asArray))
foreach ($this->inputFields as $inp => [$type, $valid, $asArray])
{
if (!isset($post[$inp]) || $post[$inp] === '')
continue;

View File

@@ -221,7 +221,12 @@ if (!CLI)
session_set_cookie_params(15 * YEAR, '/', '', $secure, true);
session_cache_limiter('private');
session_start();
if (!session_start())
{
trigger_error('failed to start session', E_USER_ERROR);
exit;
}
if (!empty($AoWoWconf['aowow']) && User::init())
User::save(); // save user-variables in session

View File

@@ -159,9 +159,8 @@ class DbSimple_Connect
*
* @param string $query запрос
*/
public function addInit($query)
public function addInit(...$args)
{
$args = func_get_args();
if ($this->DbSimple !== null)
return call_user_func_array(array(&$this->DbSimple, 'query'), $args);
$this->init[] = $args;

View File

@@ -144,9 +144,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* mixed select(string $query [, $arg1] [,$arg2] ...)
* Execute query and return the result.
*/
public function select($query)
public function select(...$args)
{
$args = func_get_args();
$total = false;
return $this->_query($args, $total);
}
@@ -157,10 +156,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* Total number of found rows (independent to LIMIT) is returned in $total
* (in most cases second query is performed to calculate $total).
*/
public function selectPage(&$total, $query)
public function selectPage(&$total, ...$args)
{
$args = func_get_args();
array_shift($args);
$total = true;
return $this->_query($args, $total);
}
@@ -173,9 +170,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* because PHP DOES NOT generates notice on $row['abc'] if $row === null
* or $row === false (but, if $row is empty array, notice is generated).
*/
public function selectRow()
public function selectRow(...$args)
{
$args = func_get_args();
$total = false;
$rows = $this->_query($args, $total);
if (!is_array($rows)) return $rows;
@@ -188,9 +184,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* array selectCol(string $query [, $arg1] [,$arg2] ...)
* Return the first column of query result as array.
*/
public function selectCol()
public function selectCol(...$args)
{
$args = func_get_args();
$total = false;
$rows = $this->_query($args, $total);
if (!is_array($rows)) return $rows;
@@ -203,9 +198,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* Return the first cell of the first column of query result.
* If no one row selected, return null.
*/
public function selectCell()
public function selectCell(...$args)
{
$args = func_get_args();
$total = false;
$rows = $this->_query($args, $total);
if (!is_array($rows)) return $rows;
@@ -221,9 +215,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* mixed query(string $query [, $arg1] [,$arg2] ...)
* Alias for select(). May be used for INSERT or UPDATE queries.
*/
public function query()
public function query(...$args)
{
$args = func_get_args();
$total = false;
return $this->_query($args, $total);
}
@@ -246,9 +239,8 @@ abstract class DbSimple_Database extends DbSimple_LastError
* Нужно для сложных запросов, состоящих из кусков, которые полезно сохранить
*
*/
public function subquery()
public function subquery(...$args)
{
$args = func_get_args();
$this->_expandPlaceholders($args,$this->_placeholderNativeArgs !== null);
return new DbSimple_SubQuery($args);
}

View File

@@ -44,8 +44,8 @@ class Loot
{
reset($this->results);
while (list($k, $__) = each($this->results))
yield $k => $this->results[$k];
foreach ($this->results as $k => ['id' => $id])
yield $id => $this->results[$k];
}
public function getResult()
@@ -134,7 +134,7 @@ class Loot
// bandaid.. remove when propperly handling lootmodes
if (!in_array($entry['Reference'], $handledRefs))
{ // todo (high): find out, why i used this in the first place. (don't do drugs, kids)
list($data, $raw) = self::getByContainerRecursive(LOOT_REFERENCE, $entry['Reference'], $handledRefs, /*$entry['GroupId'],*/ 0, $entry['Chance'] / 100);
[$data, $raw] = self::getByContainerRecursive(LOOT_REFERENCE, $entry['Reference'], $handledRefs, /*$entry['GroupId'],*/ 0, $entry['Chance'] / 100);
$handledRefs[] = $entry['Reference'];

View File

@@ -454,7 +454,7 @@ class Profiler
if ($gemItems)
{
$gemScores = new ItemList(array(['id', array_column($gemItems, 0)]));
foreach ($gemItems as list($itemId, $mult))
foreach ($gemItems as [$itemId, $mult])
if (isset($gemScores->json[$itemId]['gearscore']))
$data['gearscore'] += $gemScores->json[$itemId]['gearscore'] * $mult;
}

View File

@@ -1,6 +1,6 @@
<?php
define('AOWOW_REVISION', 27);
define('AOWOW_REVISION', 28);
define('CLI', PHP_SAPI === 'cli');
@@ -10,8 +10,8 @@ foreach ($reqExt as $r)
if (!extension_loaded($r))
$error .= 'Required Extension <b>'.$r."</b> was not found. Please check if it should exist, using \"<i>php -m</i>\"\n\n";
if (version_compare(PHP_VERSION, '7.0.1') < 0)
$error .= 'PHP Version <b>7.0.1</b> or higher required! Your version is <b>'.PHP_VERSION."</b>.\nCore functions are unavailable!\n";
if (version_compare(PHP_VERSION, '7.1.0') < 0)
$error .= 'PHP Version <b>7.1</b> or higher required! Your version is <b>'.PHP_VERSION."</b>.\nCore functions are unavailable!\n";
if ($error)
{

View File

@@ -69,8 +69,8 @@ class SmartAI
if ($ts = $this->getTalkSource())
$this->getQuotes($ts);
list($evtBody, $evtFooter) = $this->event();
list($actBody, $actFooter) = $this->action();
[$evtBody, $evtFooter] = $this->event();
[$actBody, $actFooter] = $this->action();
if ($ef = $this->eventFlags())
{
@@ -174,9 +174,11 @@ class SmartAI
private function &iterate() : iterable
{
while (list($id, $_) = each($this->rawData))
reset($this->rawData);
foreach ($this->rawData as $k => $__)
{
$this->itr = &$this->rawData[$id];
$this->itr = &$this->rawData[$k];
yield $this->itr;
}

View File

@@ -559,7 +559,7 @@ class RemoteProfileList extends ProfileList
$curTpl['battlegroup'] = CFG_BATTLEGROUP;
// realm
list($r, $g) = explode(':', $guid);
[$r, $g] = explode(':', $guid);
if (!empty($realms[$r]))
{
$curTpl['realm'] = $r;
@@ -622,7 +622,7 @@ class RemoteProfileList extends ProfileList
$limit--;
}
list($r, $g) = explode(':', $guid);
[$r, $g] = explode(':', $guid);
// talent points post
$curTpl['talenttree1'] = 0;

View File

@@ -175,7 +175,7 @@ class QuestList extends BaseType
if (!(Game::sideByRaceMask($this->curTpl['reqRaceMask']) & $side))
continue;
list($series, $first) = DB::Aowow()->SelectRow(
[$series, $first] = DB::Aowow()->SelectRow(
'SELECT IF(prev.id OR cur.nextQuestIdChain, 1, 0) AS "0", IF(prev.id IS NULL AND cur.nextQuestIdChain, 1, 0) AS "1" FROM ?_quests cur LEFT JOIN ?_quests prev ON prev.nextQuestIdChain = cur.id WHERE cur.id = ?d',
$this->id
);

View File

@@ -684,7 +684,7 @@ class SpellList extends BaseType
$nModels = new CreatureList(array(['id', array_column($displays[TYPE_NPC], 1)]));
foreach ($nModels->iterate() as $nId => $__)
{
foreach ($displays[TYPE_NPC] as $srcId => list($indizes, $npcId))
foreach ($displays[TYPE_NPC] as $srcId => [$indizes, $npcId])
{
if ($npcId == $nId)
{
@@ -706,7 +706,7 @@ class SpellList extends BaseType
$oModels = new GameObjectList(array(['id', array_column($displays[TYPE_OBJECT], 1)]));
foreach ($oModels->iterate() as $oId => $__)
{
foreach ($displays[TYPE_OBJECT] as $srcId => list($indizes, $objId))
foreach ($displays[TYPE_OBJECT] as $srcId => [$indizes, $objId])
{
if ($objId == $oId)
{
@@ -1209,7 +1209,7 @@ class SpellList extends BaseType
break;
case 'o': // TotalAmount for periodic auras (with variance)
case 'O':
list($min, $max, $modStrMin, $modStrMax) = $this->calculateAmountForCurrent($effIdx, $srcSpell);
[$min, $max, $modStrMin, $modStrMax] = $this->calculateAmountForCurrent($effIdx, $srcSpell);
$periode = $srcSpell->getField('effect'.$effIdx.'Periode');
$duration = $srcSpell->getField('duration');
@@ -1261,7 +1261,7 @@ class SpellList extends BaseType
break;
case 's': // BasePoints (with variance)
case 'S':
list($min, $max, $modStrMin, $modStrMax) = $this->calculateAmountForCurrent($effIdx, $srcSpell);
[$min, $max, $modStrMin, $modStrMax] = $this->calculateAmountForCurrent($effIdx, $srcSpell);
$mv = $srcSpell->getField('effect'.$effIdx.'MiscValue');
$aura = $srcSpell->getField('effect'.$effIdx.'AuraId');
@@ -1381,7 +1381,7 @@ class SpellList extends BaseType
++$formCurPos; // for some odd reason the precision decimal survives if we dont increment further..
}
list($formOutStr, $fSuffix, $fRating) = $this->resolveFormulaString($formOutStr, $formPrecision, $scaling);
[$formOutStr, $fSuffix, $fRating] = $this->resolveFormulaString($formOutStr, $formPrecision, $scaling);
$formula = substr_replace($formula, $formOutStr, $formStartPos, ($formCurPos - $formStartPos));
}
@@ -1678,7 +1678,7 @@ class SpellList extends BaseType
$formPrecision = $data[$formCurPos + 1];
$formCurPos += 2;
}
list($formOutVal, $formOutStr, $ratingId) = $this->resolveFormulaString($formOutStr, $formPrecision ?: ($topLevel ? 0 : 10), $scaling);
[$formOutVal, $formOutStr, $ratingId] = $this->resolveFormulaString($formOutStr, $formPrecision ?: ($topLevel ? 0 : 10), $scaling);
if ($ratingId && Util::checkNumeric($formOutVal) && $this->interactive)
$resolved = sprintf($formOutStr, $ratingId, abs($formOutVal), sprintf(Util::$setRatingLevelString, $this->charLevel, $ratingId, abs($formOutVal), Util::setRatingLevel($this->charLevel, $ratingId, abs($formOutVal))));

View File

@@ -121,22 +121,14 @@ class CLI
flush();
}
public static function nicePath(/* $file = '', ...$pathParts */)
public static function nicePath(string $file, string ...$pathParts) : string
{
$path = '';
switch (func_num_args())
{
case 0:
return '';
case 1:
$path = func_get_arg(0);
break;
default:
$args = func_get_args();
$file = array_shift($args);
$path = implode(DIRECTORY_SEPARATOR, $args).DIRECTORY_SEPARATOR.$file;
}
if (!$pathParts)
return $file;
$path = implode(DIRECTORY_SEPARATOR, $pathParts).DIRECTORY_SEPARATOR.$file;
if (DIRECTORY_SEPARATOR == '/') // *nix
{
@@ -792,18 +784,13 @@ class Util
return false; // always false for passed arrays
}
public static function arraySumByKey(&$ref)
public static function arraySumByKey(array &$ref, array ...$adds) : void
{
$nArgs = func_num_args();
if (!is_array($ref) || $nArgs < 2)
if (!$adds)
return;
for ($i = 1; $i < $nArgs; $i++)
foreach ($adds as $arr)
{
$arr = func_get_arg($i);
if (!is_array($arr))
continue;
foreach ($arr as $k => $v)
{
if (!isset($ref[$k]))
@@ -853,18 +840,14 @@ class Util
return $hash;
}
public static function mergeJsGlobals(&$master)
public static function mergeJsGlobals(array &$master, array ...$adds) : bool
{
$args = func_get_args();
if (count($args) < 2) // insufficient args
if (!$adds) // insufficient args
return false;
if (!is_array($master))
$master = [];
for ($i = 1; $i < count($args); $i++) // skip first (master) entry
foreach ($adds as $arr)
{
foreach ($args[$i] as $type => $data)
foreach ($arr as $type => $data)
{
// bad data or empty
if (empty(Util::$typeStrings[$type]) || !is_array($data) || !$data)

View File

@@ -90,8 +90,10 @@ switch ($pageCall)
$cleanName = str_replace(['-', '_'], '', ucFirst($altClass ?: $pageCall));
try // can it be handled as ajax?
{
$out = '';
$class = 'Ajax'.$cleanName;
$ajax = new $class(explode('.', $pageParam));
if ($ajax->handle($out))
{
Util::sendNoCacheHeader();

View File

@@ -29,7 +29,7 @@ class AreaTriggerPage extends GenericPage
$this->subject = new AreaTriggerList(array(['id', $this->typeId]));
if ($this->subject->error)
$this->notFound(Util::ucFirst(Lang::game('areatrigger')), Lang::areatriger('notFound'));
$this->notFound(Util::ucFirst(Lang::game('areatrigger')), Lang::areatrigger('notFound'));
$this->name = $this->subject->getField('name') ?: 'AT #'.$this->typeId;
}

View File

@@ -87,7 +87,7 @@ class CurrencyPage extends GenericPage
{
$this->extendGlobalData($lootTabs->jsGlobals);
foreach ($lootTabs->iterate() as list($file, $tabData))
foreach ($lootTabs->iterate() as [$file, $tabData])
$this->lvTabs[] = [$file, $tabData];
}

View File

@@ -355,7 +355,7 @@ class EventPage extends GenericPage
$this->saveCache($tt);
}
list($start, $end) = $this->postCache();
[$start, $end] = $this->postCache();
header('Content-type: application/x-javascript; charset=utf-8');
die(sprintf($tt, $start, $end));

View File

@@ -392,6 +392,7 @@ class GenericPage
if (!empty($this->hasComContent)) // get comments, screenshots, videos
{
$jsGlobals = [];
$this->community = CommunityContent::getAll($this->type, $this->typeId, $jsGlobals);
$this->extendGlobalData($jsGlobals); // as comments are not cached, those globals cant be either
$this->applyGlobals();
@@ -746,6 +747,9 @@ class GenericPage
public function extendGlobalData($data, $extra = null) // add jsGlobals or typeIds (can be mixed in one array: TYPE => [mixeddata]) to display on the page
{
if ($data === null)
throw new ErrorException('ffffuuuu.....!');
foreach ($data as $type => $globals)
{
if (!is_array($globals) || !$globals)
@@ -975,7 +979,7 @@ class GenericPage
if (substr_count($cache[0], ' ') < 2)
return false;
list($time, $rev, $type) = explode(' ', $cache[0]);
[$time, $rev, $type] = explode(' ', $cache[0]);
if ($time + CFG_CACHE_DECAY <= time() || $rev != AOWOW_REVISION)
$cache = null;

View File

@@ -450,7 +450,7 @@ class ItemPage extends genericPage
{
$this->extendGlobalData($lootTabs->jsGlobals);
foreach ($lootTabs->iterate() as $idx => list($file, $tabData))
foreach ($lootTabs->iterate() as $idx => [$file, $tabData])
{
if (!$tabData['data'])
continue;

View File

@@ -184,7 +184,7 @@ class MorePage extends GenericPage
'copper' => 0
);
foreach ($tabs as list($t, $tabId, $tabName))
foreach ($tabs as [$t, $tabId, $tabName])
{
// stuff received
$res = DB::Aowow()->select('

View File

@@ -385,7 +385,7 @@ class QuestPage extends GenericPage
$this->extendGlobalData($olItemData->getJSGlobals(GLOBALINFO_SELF));
$providedRequired = false;
foreach ($olItems as $i => list($itemId, $qty, $provided))
foreach ($olItems as $i => [$itemId, $qty, $provided])
{
if (!$i || !$itemId || !in_array($itemId, $olItemData->getFoundIDs()))
continue;
@@ -568,11 +568,11 @@ class QuestPage extends GenericPage
*/
$nSources = 0;
foreach ($lootTabs->iterate() as list($type, $data))
foreach ($lootTabs->iterate() as [$type, $data])
if ($type == 'creature' || $type == 'object')
$nSources += count(array_filter($data['data'], function($val) { return $val['percent'] >= 1.0; }));
foreach ($lootTabs->iterate() as $idx => list($file, $tabData))
foreach ($lootTabs->iterate() as $idx => [$file, $tabData])
{
if (!$tabData['data'])
continue;
@@ -653,7 +653,7 @@ class QuestPage extends GenericPage
// POI objectives
// also map olItems to objectiveIdx so every container gets the same pin color
foreach ($olItems as $i => list($itemId, $qty, $provided))
foreach ($olItems as $i => [$itemId, $qty, $provided])
{
if (!$provided && $itemId)
{

View File

@@ -171,7 +171,7 @@ class SearchPage extends GenericPage
if ($this->searchMask & SEARCH_TYPE_REGULAR)
{
$foundTotal = 0;
foreach ($this->lvTabs as list($file, $tabData, $_, $osInfo))
foreach ($this->lvTabs as [$file, $tabData, , $osInfo])
$foundTotal += count($tabData['data']);
if ($foundTotal == 1) // only one match -> redirect to find
@@ -300,13 +300,13 @@ class SearchPage extends GenericPage
[], [], [], [], [], [], []
);
foreach ($this->lvTabs as list($_, $_, $_, $osInfo))
foreach ($this->lvTabs as [ , , , $osInfo])
$foundTotal += $osInfo[2];
if (!$foundTotal || $asError)
return '["'.Util::jsEscape($this->search).'", []]';
foreach ($this->lvTabs as list($_, $tabData, $_, $osInfo))
foreach ($this->lvTabs as [ , $tabData, , $osInfo])
{
$max = max(1, intVal($limit * $osInfo[2] / $foundTotal));
$limit -= $max;

View File

@@ -264,7 +264,7 @@ class UtilityPage extends GenericPage
{
$item = $channel->addChild('item');
foreach ($row as $key => list($isCData, $attrib, $text))
foreach ($row as $key => [$isCData, $attrib, $text])
{
if ($isCData && $text)
$child = $item->addChild($key)->addCData($text);

View File

@@ -72,7 +72,7 @@ switch ($cmd) // we accept only on
finish();
case 'update':
require_once 'setup/tools/clisetup/update.func.php';
list($s, $b) = update(); // return true if we do not rebuild stuff
[$s, $b] = update(); // return true if we do not rebuild stuff
if (!$s && !$b)
return;
case 'sync':

View File

@@ -27,7 +27,7 @@ function build($syncMe = null)
CLI::write();
// files with template
foreach (FileGen::$tplFiles as $name => list($file, $destPath, $deps))
foreach (FileGen::$tplFiles as $name => [$file, $destPath, $deps])
{
$reqDBC = [];

View File

@@ -30,7 +30,7 @@ function dbconfig()
$port = 0;
if (strstr($dbInfo['host'], ':'))
list($dbInfo['host'], $port) = explode(':', $dbInfo['host']);
[$dbInfo['host'], $port] = explode(':', $dbInfo['host']);
if ($dbInfo['host'])
{

View File

@@ -127,7 +127,7 @@ function firstrun()
$port = 0;
if (strstr($AoWoWconf[$what]['host'], ':'))
list($AoWoWconf[$what]['host'], $port) = explode(':', $AoWoWconf[$what]['host']);
[$AoWoWconf[$what]['host'], $port] = explode(':', $AoWoWconf[$what]['host']);
if ($link = @mysqli_connect($AoWoWconf[$what]['host'], $AoWoWconf[$what]['user'], $AoWoWconf[$what]['pass'], $AoWoWconf[$what]['db'], $port ?: $defPort))
mysqli_close($link);
@@ -175,7 +175,7 @@ function firstrun()
'static_host' => [$prot, $res['static_host'], '/css/aowow.css']
);
foreach ($cases as $conf => list($protocol, $host, $testFile))
foreach ($cases as $conf => [$protocol, $host, $testFile])
{
if ($host)
{

View File

@@ -13,7 +13,7 @@ if (!CLI)
function update()
{
list($date, $part) = array_values(DB::Aowow()->selectRow('SELECT `date`, `part` FROM ?_dbversion'));
[$date, $part] = array_values(DB::Aowow()->selectRow('SELECT `date`, `part` FROM ?_dbversion'));
CLI::write('checking sql updates');
@@ -21,7 +21,7 @@ function update()
foreach (glob('setup/updates/*.sql') as $file)
{
$pi = pathinfo($file);
list($fDate, $fPart) = explode('_', $pi['filename']);
[$fDate, $fPart] = explode('_', $pi['filename']);
$fData = intVal($fDate);
@@ -59,7 +59,7 @@ function update()
CLI::write($nFiles ? 'applied '.$nFiles.' update(s)' : 'db is already up to date', CLI::LOG_OK);
// fetch sql/build after applying updates, as they may contain sync-prompts
list($sql, $build) = array_values(DB::Aowow()->selectRow('SELECT `sql`, `build` FROM ?_dbversion'));
[$sql, $build] = array_values(DB::Aowow()->selectRow('SELECT `sql`, `build` FROM ?_dbversion'));
sleep(1);

View File

@@ -561,7 +561,7 @@ class DBC
if ($this->isGameTable)
$row[-1] = $i;
foreach ($this->fileRefs as $locId => list($handle, $fullPath, $header))
foreach ($this->fileRefs as $locId => [$handle, $fullPath, $header])
{
$rec = unpack($unpackStr, fread($handle, $header['recordSize']));

View File

@@ -157,10 +157,10 @@ class FileGen
self::$cliOpts[$opt] = true;
}
public static function hasOpt(/* ...$opt */)
public static function hasOpt(string ...$opts) : int
{
$result = 0x0;
foreach (func_get_args() as $idx => $arg)
foreach ($opts as $idx => $arg)
{
if (!is_string($arg))
continue;
@@ -204,7 +204,7 @@ class FileGen
if (!empty(self::$tplFiles[$key]))
{
list($file, $destPath, $deps) = self::$tplFiles[$key];
[$file, $destPath, $deps] = self::$tplFiles[$key];
if ($content = file_get_contents(FileGen::$tplPath.$file.'.in'))
{

View File

@@ -191,7 +191,7 @@ if (!CLI)
$checkSourceDirs = function($sub) use ($imgPath, &$paths, $modeMask)
{
$hasMissing = false;
foreach ($paths as $idx => list($subDir, $isLocalized, $realPath))
foreach ($paths as $idx => [$subDir, $isLocalized, $realPath])
{
if ($realPath && !$isLocalized)
continue;
@@ -236,7 +236,7 @@ if (!CLI)
$locList[] = $xp;
CLI::write('required resources overview:', CLI::LOG_INFO);
foreach ($paths as list($path, $isLocalized, $realPath))
foreach ($paths as [$path, $isLocalized, $realPath])
{
if (!$realPath)
CLI::write(CLI::red('MISSING').' - '.str_pad($path, 14).' @ '.sprintf($imgPath, '['.implode(',', $locList).']/').$path);

View File

@@ -193,7 +193,7 @@ if (!CLI)
$checkSourceDirs = function($sub) use ($imgPath, &$paths)
{
$hasMissing = false;
foreach ($paths as $pathIdx => list($subDir, , , , , $realPath))
foreach ($paths as $pathIdx => [$subDir, , , , , $realPath])
{
if ($realPath)
continue;
@@ -243,7 +243,7 @@ if (!CLI)
$locList[] = $xp;
CLI::write('required resources overview:', CLI::LOG_INFO);
foreach ($paths as list($path, , , , , $realPath))
foreach ($paths as [$path, , , , , $realPath])
{
if ($realPath)
CLI::write(CLI::green(' FOUND ').' - '.str_pad($path, 53).' @ '.$realPath);
@@ -310,7 +310,7 @@ if (!CLI)
$dbcEntries = array_intersect_key($dbcEntries, array_unique($dbcEntries));
$allPaths = [];
foreach ($paths as $i => list($inPath, $outInfo, $pattern, $isIcon, $tileSize, $path))
foreach ($paths as $i => [$inPath, $outInfo, $pattern, $isIcon, $tileSize, $path])
{
$search = $path.$pattern;
if ($pattern)
@@ -346,7 +346,7 @@ if (!CLI)
$nFiles = count($outInfo) * ($tileSize ? array_sum(array_map('count', $cuNames[$i])) : count($files));
foreach ($outInfo as list($dest, $ext, $srcSize, $destSize, $borderOffset))
foreach ($outInfo as [$dest, $ext, $srcSize, $destSize, $borderOffset])
{
if ($tileSize)
{

View File

@@ -19,7 +19,7 @@
<thead><th><?=Lang::privileges('privilege');?></th><th><?=Lang::privileges('requiredRep');?></th></thead>
<tbody>
<?php
foreach ($this->privileges as $id => list($earned, $name, $value)):
foreach ($this->privileges as $id => [$earned, $name, $value]):
echo ' <tr'.($earned ? ' class="wsa-earned"' : '').'><td><div class="wsa-check" style="float:left;margin:0 3px 0 0">&nbsp;</div><a href="?privilege='.$id.'">'.$name.'</a></td><td class="number-right"><span>'.Lang::nf($value)."</span></td></tr>\n";
endforeach;
?>