function GetUSRealms() { $cacheKey = 'extra:multirealm:realms2'; $realms = MCGet($cacheKey); if ($realms !== false) { return $realms; } $sql = 'select id, slug, name, house, canonical from tblRealm where region = \'US\' and locale is not null'; $db = DBConnect(); $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $realmList = DBMapArray($result); $stmt->close(); uasort($realmList, function ($a, $b) { return strcmp($a['name'], $b['name']); }); $realms = ['id' => $realmList, 'house' => []]; foreach ($realmList as $id => $row) { if (!is_null($row['canonical'])) { $realms['house'][$row['house']] = $id; } } MCSet($cacheKey, $realms, 86400); return $realms; }
function GetNextRealm() { global $db, $allRealms, $ownerRealms; $db->begin_transaction(); $stmt = $db->prepare('select * from tblRealm where canonical is not null and ifnull(lastfetch, \'2000-01-01\') < timestampadd(hour, -3, now()) order by lastfetch asc, id asc limit 1 for update'); $stmt->execute(); $result = $stmt->get_result(); $realm = DBMapArray($result, null); $stmt->close(); if (count($realm) == 0) { $db->rollback(); return false; } $realm = array_pop($realm); $stmt = $db->prepare('update tblRealm set lastfetch=now() where id = ?'); $stmt->bind_param('i', $realm['id']); $stmt->execute(); $stmt->close(); $db->commit(); $stmt = $db->prepare('select r.*, ifnull(r.ownerrealm, replace(name, \' \', \'\')) ownerrealm from tblRealm r where region = ?'); $stmt->bind_param('s', $realm['region']); $stmt->execute(); $result = $stmt->get_result(); $ownerRealms = DBMapArray($result, 'ownerrealm'); $stmt->close(); $stmt = $db->prepare('select r.*, ifnull(r.ownerrealm, replace(name, \' \', \'\')) ownerrealm from tblRealm r where r.region = ?'); $stmt->bind_param('s', $realm['region']); $stmt->execute(); $result = $stmt->get_result(); $allRealms = DBMapArray($result, 'name'); $stmt->close(); return $realm; }
function GetDataTables() { global $db, $argv; $sql = 'SELECT house from tblRealm where region=\'US\' and slug=\'medivh\''; $stmt = $db->prepare($sql); $stmt->execute(); $house = 0; $stmt->bind_result($house); $stmt->fetch(); $stmt->close(); $sql = 'SELECT id from tblRealm where house = ?'; $stmt = $db->prepare($sql); $stmt->bind_param('i', $house); $stmt->execute(); $result = $stmt->get_result(); $realms = DBMapArray($result, null); $stmt->close(); $sql = sprintf('SELECT id from tblSeller where realm in (%s) order by lastseen desc limit 20', implode(',', $realms)); $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $sellers = DBMapArray($result, null); $stmt->close(); $tables = ['tblAuction' => 'house=' . $house, 'tblAuctionExtra' => 'house=' . $house, 'tblAuctionPet' => 'house=' . $house, 'tblAuctionRare' => 'house=' . $house, 'tblBonusSet' => '1=1', 'tblHouseCheck' => '1=1', 'tblItemBonusesSeen' => '1=1', 'tblItemExpired' => 'house=' . $house, 'tblItemGlobal' => '1=1', 'tblItemHistoryDaily' => 'house=' . $house, 'tblItemHistoryHourly' => 'house=' . $house, 'tblItemHistoryMonthly' => 'item in (select id from tblDBCItem where auctionable=1) and house=' . $house, 'tblItemLevelsSeen' => '1=1', 'tblItemSummary' => 'house=' . $house, 'tblPet' => '1=1', 'tblPetHistoryHourly' => 'house=' . $house, 'tblPetSummary' => 'house=' . $house, 'tblRealm' => '1=1', 'tblRealmGuidHouse' => '1=1', 'tblSeller' => 'realm in (' . implode(',', $realms) . ')', 'tblSellerHistoryHourly' => 'seller in (' . implode(',', $sellers) . ')', 'tblSellerItemHistory' => 'seller in (' . implode(',', $sellers) . ')', 'tblSnapshot' => 'house=' . $house, 'tblWowToken' => '1=1']; if (count($argv) > 1) { $toRemove = array_diff(array_keys($tables), array_slice($argv, 1)); foreach ($toRemove as $tblName) { unset($tables[$tblName]); } } if (count($tables) == 0) { echo "No tables marked for export.\n"; exit(1); } $sqlFile = __DIR__ . '/../testdata.sql.gz'; if (!(touch($sqlFile) && ($sqlFile = realpath($sqlFile)))) { echo "Could not create testdata.sql\n"; exit(1); } $sqlResource = gzopen($sqlFile, 'w'); $tmpFile = tempnam('/tmp', 'testdata'); $cmd = 'mysqldump --verbose --allow-keywords --skip-opt --quick --create-options --add-drop-table --add-locks --extended-insert --no-autocommit --result-file=%s --user='******' --password='******' --where=%s ' . escapeshellarg(DATABASE_SCHEMA) . " %s\n"; foreach ($tables as $table => $where) { file_put_contents($tmpFile, ''); $trash = []; $ret = 0; exec(sprintf($cmd, escapeshellarg($tmpFile), escapeshellarg($where), escapeshellarg($table)), $trash, $ret); if ($ret != 0) { echo 'Error: ' . implode("\n", $trash); break; } gzwrite($sqlResource, file_get_contents($tmpFile)); } gzclose($sqlResource); unlink($tmpFile); }
function GetTradeSpells() { global $db; $stmt = $db->prepare('SELECT id, skillline, qtymade, crafteditem FROM `tblDBCSpell` WHERE crafteditem is not null'); $stmt->execute(); $result = $stmt->get_result(); $rows = DBMapArray($result); $stmt->close(); return $rows; }
function DataIntervalsData() { $cacheKey = 'dataintervalstable'; if (($tr = MCGet($cacheKey)) !== false) { return $tr; } $db = DBConnect(); $sql = <<<'EOF' select t.house, t.lastupdate, t.mindelta, modes.delta as modedelta, t.avgdelta, t.maxdelta, r.region, group_concat(r.name order by 1 separator ', ') nms from ( select deltas.house, max(deltas.updated) lastupdate, round(min(delta)/5)*5 mindelta, round(avg(delta)/5)*5 avgdelta, round(max(delta)/5)*5 maxdelta from ( select sn.updated, if(@prevhouse = sn.house and sn.updated > timestampadd(hour, -48, now()), unix_timestamp(sn.updated) - @prevdate, null) delta, @prevdate := unix_timestamp(sn.updated) updated_ts, @prevhouse := sn.house house from (select @prevhouse := null, @prevdate := null) setup, tblSnapshot sn order by sn.house, sn.updated) deltas group by deltas.house) t left join ( select house, delta from ( select if(@prev = house, @rownum := @rownum + 1, @rownum := 0) o, delta, (@prev := house) as house, c from ( select house, delta, count(*) c from ( select sn.updated, round(if(@prevh = sn.house, unix_timestamp(sn.updated) - @prevd, null)/5)*5 delta, @prevd := unix_timestamp(sn.updated) updated_ts, @prevh := sn.house house from (select @prevh := null, @prevd := null) setup, tblSnapshot sn where sn.updated > timestampadd(hour, -48, now()) order by sn.house, sn.updated) deltas where delta is not null group by house, delta order by house, c desc ) tosort, (select @rownum := 0, @prev := null) setup) filtered where o=0 ) modes on modes.house = t.house join tblRealm r on r.house = t.house and r.locale is not null group by r.house order by 4 asc, 3 asc, region asc, nms asc EOF; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $tr = DBMapArray($result, null); $stmt->close(); MCSet($cacheKey, $tr, 60); return $tr; }
function UpdateDataTables() { global $db; $sql = sprintf('SELECT table_name FROM information_schema.tables where table_name like \'tblDBC%%\' and table_schema=\'%s\'', DATABASE_SCHEMA); $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $tables = DBMapArray($result, null); $stmt->close(); $sqlFile = __DIR__ . '/datatables.sql'; if (!(touch($sqlFile) && ($sqlFile = realpath($sqlFile)))) { echo "Could not create datatables.sql\n"; exit(1); } $cmd = 'mysqldump --verbose --allow-keywords --result-file=' . escapeshellarg($sqlFile) . ' --user='******' --password='******' ' . escapeshellarg(DATABASE_SCHEMA); foreach ($tables as $table) { $cmd .= ' ' . escapeshellarg($table); } passthru($cmd); }
function SellerStats($house, $realm, $seller) { $seller = mb_ereg_replace(' ', '', $seller); $seller = mb_strtoupper(mb_substr($seller, 0, 1)) . mb_strtolower(mb_substr($seller, 1)); $key = 'seller_stats_' . $realm . '_' . $seller; if (($tr = MCGetHouse($house, $key)) !== false) { return $tr; } $db = DBConnect(); $sql = 'SELECT * FROM tblSeller s WHERE realm = ? AND name = ?'; $stmt = $db->prepare($sql); $stmt->bind_param('is', $realm, $seller); $stmt->execute(); $result = $stmt->get_result(); $tr = DBMapArray($result, null); if (count($tr)) { $tr = $tr[0]; } $stmt->close(); MCSetHouse($house, $key, $tr); return $tr; }
function BuildRealmGuidHouse() { global $db; $guids = GetRealmInfo(); $hardCoded = [1302 => 139, 1396 => 147]; $db->begin_transaction(); $stmt = $db->prepare('SELECT region, name, house FROM tblRealm'); $stmt->execute(); $result = $stmt->get_result(); $houses = DBMapArray($result, ['region', 'name']); $stmt->close(); $db->query('delete from tblRealmGuidHouse'); $stmt = $db->prepare('replace into tblRealmGuidHouse (realmguid, house) values (?, ?)'); $realmGuid = 0; $house = 0; $stmt->bind_param('ii', $realmGuid, $house); foreach ($guids as $guid => $realmInfo) { $found = false; for ($x = 1; $x < count($realmInfo); $x++) { if (isset($houses[$realmInfo[0]][$realmInfo[$x]])) { $found = true; unset($hardCoded[$guid]); $realmGuid = $guid; $house = $houses[$realmInfo[0]][$realmInfo[$x]]['house']; $stmt->execute(); } } if (!$found) { echo "Could not find house for " . implode(',', $realmInfo) . "\n"; } } foreach ($hardCoded as $guid => $forcedHouse) { $realmGuid = $guid; $house = $forcedHouse; $stmt->execute(); } $stmt->close(); $db->commit(); }
function GetRareWatches($loginState, $house = 0) { $userId = $loginState['id']; $house = intval($house, 10); $limit = SUBSCRIPTION_RARE_LIMIT_TOTAL; if ($house) { $allWatches = GetRareWatches($loginState); $otherHouseCount = 0; foreach ($allWatches['watches'] as $watch) { if ($watch['house'] != $house) { $otherHouseCount++; } } $limit = min(SUBSCRIPTION_RARE_LIMIT_HOUSE, SUBSCRIPTION_RARE_LIMIT_TOTAL - $otherHouseCount); } $cacheKey = SUBSCRIPTION_RARE_CACHEKEY . $userId . '_' . $house; $json = MCGet($cacheKey); if ($json !== false) { return ['maximum' => $limit, 'watches' => $json]; } $db = DBConnect(); $sql = 'SELECT seq, house, itemclass, minquality, minlevel, maxlevel, flags & 1 as includecrafted, flags & 2 as includevendor, days from tblUserRare where user = ?'; if ($house) { $sql .= ' and house = ?'; } $stmt = $db->prepare($sql); if ($house) { $stmt->bind_param('ii', $userId, $house); } else { $stmt->bind_param('i', $userId); } $stmt->execute(); $result = $stmt->get_result(); $json = DBMapArray($result); $stmt->close(); MCSet($cacheKey, $json); return ['maximum' => $limit, 'watches' => $json]; }
function TransmogGenericItemList($house, $params) { global $db, $canCache; $key = 'transmog_gi2_' . md5(json_encode($params)); if ($canCache && ($tr = MCGetHouse($house, $key)) !== false) { return $tr; } DBConnect(); if (is_array($params)) { $joins = isset($params['joins']) ? $params['joins'] : ''; $where = isset($params['where']) ? ' and ' . $params['where'] : ''; $group = isset($params['group']) ? array_merge($params['group'], [false]) : null; } else { $joins = ''; $group = null; $where = $params == '' ? '' : ' and ' . $params; } $sql = <<<EOF select ab.id, ab.display, ab.buy, ab.class, ab.subclass, ifnull(ab.type, -1 & ab.subclass) `type`, ab.subclassname from ( select aa.*, if(@previd = aa.display, 0, @previd := aa.display) previd from (select @previd := 0) aasetup, ( SELECT i.id, i.display, a.buy, i.class, i.subclass, i.type, concat_ws('-', i.class, i.subclass) subclassname FROM `tblDBCItem` i join tblAuction a on a.item=i.id {$joins} WHERE i.auctionable=1 and i.quality > 1 {$where} and i.display is not null and i.flags & 2 = 0 and a.house = ? and a.buy > 0 order by i.display, a.buy) aa ) ab where ab.previd > 0 EOF; $stmt = $db->prepare($sql); if (!$stmt) { DebugMessage("Bad SQL: \n" . $sql, E_USER_ERROR); } $stmt->bind_param('i', $house); $stmt->execute(); $result = $stmt->get_result(); $tr = DBMapArray($result, $group); $stmt->close(); MCSetHouse($house, $key, $tr); return $tr; }
function SendAndroidNotifications($regions) { global $db; global $timeZones, $timeLeftCodes, $regionNames; $sent = []; $AndroidEndpoint = 'https://android.googleapis.com/gcm/send'; foreach ($regions as $region) { $properRegion = strtoupper($region); if ($properRegion == 'US') { $properRegion = 'NA'; } $sql = 'select * from tblWowToken w where region = ? order by `when` desc limit 2'; $stmt = $db->prepare($sql); $stmt->bind_param('s', $region); $stmt->execute(); $result = $stmt->get_result(); $bothTokenData = DBMapArray($result, null); $tokenData = array_shift($bothTokenData); $prevTokenData = count($bothTokenData) ? array_shift($bothTokenData) : []; $stmt->close(); if (!$prevTokenData) { continue; } if ($tokenData['marketgold'] == $prevTokenData['marketgold']) { continue; } if ($tokenData['result'] != 1 || $tokenData['result'] != $prevTokenData['result']) { continue; } $d = new DateTime('now', timezone_open($timeZones[$region])); $d->setTimestamp(strtotime($tokenData['when'])); $formatted = ['BUY' => number_format($tokenData['marketgold']), 'TIMETOSELL' => isset($timeLeftCodes[$tokenData['timeleft']]) ? $timeLeftCodes[$tokenData['timeleft']] : $tokenData['timeleft'], 'UPDATED' => $d->format('M j g:ia T')]; $direction = $tokenData['marketgold'] > $prevTokenData['marketgold'] ? 'over' : 'under'; $sql = <<<EOF select s.endpoint, s.id, e.region, e.value from tblWowTokenSubs s join tblWowTokenEvents e on e.subid = s.id where s.lastfail is null and e.direction = '{$direction}' and e.region = '{$properRegion}' and s.endpoint like '{$AndroidEndpoint}%' EOF; if ($direction == 'over') { $sql .= ' and e.value >= ' . $prevTokenData['marketgold'] . ' and e.value < ' . $tokenData['marketgold']; } else { $sql .= ' and e.value <= ' . $prevTokenData['marketgold'] . ' and e.value > ' . $tokenData['marketgold']; } $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $rows = DBMapArray($result, ['id']); $stmt->close(); if (count($rows) == 0) { continue; } //sells in " . $formatted['TIMETOSELL'] . ' $message = $regionNames[$properRegion] . ' price %s: now ' . $formatted['BUY'] . "g, as of " . $formatted['UPDATED'] . '.'; $chunks = array_chunk($rows, 50, true); foreach ($chunks as $chunk) { $lookup = []; $toSend = []; $failed = []; $successful = []; foreach ($chunk as $id => $row) { $registrationId = substr($row['endpoint'], strlen($AndroidEndpoint) + 1); $msg = sprintf($message, $direction . ' ' . number_format($row['value'], 0) . 'g'); $key = md5($row['endpoint']); if (!isset($sent[$key])) { $lookup[] = $id; $toSend[] = $registrationId; $sent[$key] = $msg; } else { $sent[$key] .= " \n" . $msg; } MCSet('tokennotify-' . $key, $sent[$key], 8 * 60 * 60); } if (!count($toSend)) { continue; } $toSend = json_encode(['registration_ids' => $toSend, 'time_to_live' => 4 * 60 * 60]); $headers = ['Authorization: key=' . ANDROID_GCM_KEY, 'Content-Type: application/json']; $outHeaders = []; $ret = \Newsstand\HTTP::Post($AndroidEndpoint, $toSend, $headers, $outHeaders); $ret = json_decode($ret, true); if (json_last_error() != JSON_ERROR_NONE || !isset($ret['results'])) { if (count($lookup) == 1 && isset($outHeaders['responseCode']) && $outHeaders['responseCode'] == '404') { // only sent one, which failed, so mark it as failed $successful = []; $failed = $lookup; } else { // can only assume all went through DebugMessage("Bad response from {$AndroidEndpoint}\n" . print_r($headers, true) . $toSend . "\n" . print_r($outHeaders, true) . "\n{$ret}"); $successful = $lookup; $failed = []; } } else { for ($x = 0; $x < count($ret['results']); $x++) { if (isset($ret['results'][$x]['error'])) { $failed[] = $lookup[$x]; } else { $successful[] = $lookup[$x]; } } } $stmt = $db->prepare('update tblWowTokenEvents set lasttrigger=now() where subid in (' . implode(',', $lookup) . ') and region=\'' . $properRegion . '\' and direction=\'' . $direction . '\''); $stmt->execute(); $stmt->close(); if (count($successful)) { $stmt = $db->prepare('update tblWowTokenSubs set lastpush=now() where id in (' . implode(',', $successful) . ')'); $stmt->execute(); $stmt->close(); } if (count($failed)) { $stmt = $db->prepare('update tblWowTokenSubs set lastpush=now(), lastfail=now() where id in (' . implode(',', $failed) . ')'); $stmt->execute(); $stmt->close(); } DebugMessage('Sent ' . count($lookup) . ' messages to ' . $AndroidEndpoint . ' - ' . count($successful) . ' successful, ' . count($failed) . ' failed.'); } } }
function PetGlobalNow($region, $species) { global $db; $key = 'battlepet_globalnow2_' . $region . '_' . $species; if (($tr = MCGet($key)) !== false) { return $tr; } DBConnect(); $sql = <<<EOF SELECT i.breed, r.house, i.price, i.quantity, unix_timestamp(i.lastseen) as lastseen FROM `tblPetSummary` i join tblRealm r on i.house = r.house and r.region = ? WHERE i.species=? group by i.breed, r.house EOF; $stmt = $db->prepare($sql); $stmt->bind_param('si', $region, $species); $stmt->execute(); $result = $stmt->get_result(); $tr = DBMapArray($result, array('breed', null)); $stmt->close(); MCSet($key, $tr); return $tr; }
function GetSellerIds($region, &$sellerInfo, $snapshot, $afterInsert = false) { global $db, $ownerRealmCache, $maxPacketSize; $snapshotString = date('Y-m-d H:i:s', $snapshot); $workingRealms = array_keys($sellerInfo); $neededInserts = false; for ($r = 0; $r < count($workingRealms); $r++) { if (!isset($ownerRealmCache[$region][$workingRealms[$r]])) { continue; } $realmName = $workingRealms[$r]; $realmId = $ownerRealmCache[$region][$realmName]['id']; $sqlStart = "SELECT name, id FROM tblSeller WHERE realm = {$realmId} AND name IN ("; $sql = $sqlStart; $namesInQuery = 0; $names = array_keys($sellerInfo[$realmName]); $nameCount = count($names); $needInserts = false; for ($s = 0; $s < $nameCount; $s++) { if ($sellerInfo[$realmName][$names[$s]]['id'] != 0) { continue; } $nameEscaped = '\'' . $db->real_escape_string($names[$s]) . '\''; if (strlen($sql) + strlen($nameEscaped) + 5 > $maxPacketSize) { $sql .= ')'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $someIds = DBMapArray($result, null); $foundNames = 0; $lastSeenIds = array(); for ($n = 0; $n < count($someIds); $n++) { if (isset($sellerInfo[$realmName][$someIds[$n]['name']])) { $sellerInfo[$realmName][$someIds[$n]['name']]['id'] = $someIds[$n]['id']; $foundNames++; if ($sellerInfo[$realmName][$someIds[$n]['name']]['new'] > 0) { $lastSeenIds[] = $someIds[$n]['id']; } } } if (count($lastSeenIds) > 0 && !$afterInsert) { DBQueryWithError($db, sprintf('UPDATE tblSeller SET lastseen = \'%s\' WHERE id IN (%s)', $snapshotString, implode(',', $lastSeenIds))); } $needInserts |= $foundNames < $namesInQuery; $sql = $sqlStart; $namesInQuery = 0; } $sql .= ($namesInQuery++ > 0 ? ',' : '') . $nameEscaped; } if ($namesInQuery > 0) { $sql .= ')'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $someIds = DBMapArray($result, null); $foundNames = 0; $lastSeenIds = array(); for ($n = 0; $n < count($someIds); $n++) { if (isset($sellerInfo[$realmName][$someIds[$n]['name']])) { $sellerInfo[$realmName][$someIds[$n]['name']]['id'] = $someIds[$n]['id']; $foundNames++; if ($sellerInfo[$realmName][$someIds[$n]['name']]['new'] > 0) { $lastSeenIds[] = $someIds[$n]['id']; } } } if (count($lastSeenIds) > 0 && !$afterInsert) { DBQueryWithError($db, sprintf('UPDATE tblSeller SET lastseen = \'%s\' WHERE id IN (%s)', $snapshotString, implode(',', $lastSeenIds))); } $needInserts |= $foundNames < $namesInQuery; } if ($afterInsert || !$needInserts) { continue; } $neededInserts = true; $sqlStart = "INSERT IGNORE INTO tblSeller (realm, name, firstseen, lastseen) VALUES "; $sql = $sqlStart; $namesInQuery = 0; for ($s = 0; $s < $nameCount; $s++) { if ($sellerInfo[$realmName][$names[$s]]['id'] != 0) { continue; } $insertBit = sprintf('(%1$d,\'%2$s\',\'%3$s\',\'%3$s\')', $realmId, $db->real_escape_string($names[$s]), $snapshotString); if (strlen($sql) + strlen($insertBit) + 5 > $maxPacketSize) { DBQueryWithError($db, $sql); $sql = $sqlStart; $namesInQuery = 0; } $sql .= ($namesInQuery++ > 0 ? ',' : '') . $insertBit; } if ($namesInQuery > 0) { DBQueryWithError($db, $sql); } } if ($neededInserts) { GetSellerIds($region, $sellerInfo, $snapshot, true); } }
function DisableEmailAddress($address) { // Note: this is not permanent, a user can re-add it later $db = DBConnect(true); $stmt = $db->prepare('select id, locale from tblUser where email = ?'); $stmt->bind_param('s', $address); $stmt->execute(); $result = $stmt->get_result(); $ids = DBMapArray($result); $stmt->close(); $stmt = $db->prepare('update tblUser set email=null, emailverification=null where id = ?'); $userIdParam = 0; $stmt->bind_param('i', $userIdParam); foreach ($ids as $userId => $userRow) { $lang = GetLang($userRow['locale']); $userIdParam = $userId; $stmt->execute(); SendUserMessage($userId, 'Email', $lang['emailAddressRemoved'], sprintf($lang['emailAddressRemovedBounce'], htmlspecialchars($address, ENT_COMPAT | ENT_HTML5))); } $stmt->close(); $db->close(); return count($ids); }
function CaptchaDetails() { global $db; $cacheKey = 'captcha_' . $_SERVER['REMOTE_ADDR']; if (($details = MCGet($cacheKey)) !== false) { return $details['public']; } DBConnect(); $races = array('bloodelf' => 10, 'draenei' => 11, 'dwarf' => 3, 'gnome' => 7, 'goblin' => 9, 'human' => 1, 'nightelf' => 4, 'orc' => 2, 'tauren' => 6, 'troll' => 8, 'undead' => 5); $raceExclude = array($races['bloodelf'] => array($races['nightelf']), $races['nightelf'] => array($races['bloodelf'])); $keys = array_keys($races); $goodRace = $races[$keys[rand(0, count($keys) - 1)]]; $howMany = rand(2, 3); $sql = 'SELECT * FROM tblCaptcha WHERE race = ? AND helm = 0 ORDER BY rand() LIMIT ?'; $stmt = $db->prepare($sql); $stmt->bind_param('ii', $goodRace, $howMany); $stmt->execute(); $result = $stmt->get_result(); $goodRows = DBMapArray($result); $stmt->close(); $sql = 'SELECT * FROM tblCaptcha WHERE race NOT IN (%s) ORDER BY rand() LIMIT %d'; $exclude = array($goodRace); if (isset($raceExclude[$goodRace])) { $exclude = array_merge($exclude, $raceExclude[$goodRace]); } $sql = sprintf($sql, implode(',', $exclude), 12 - $howMany); $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $badRows = DBMapArray($result); $stmt->close(); $allRows = array_merge($goodRows, $badRows); shuffle($allRows); $details = array('answer' => '', 'public' => array('lookfor' => $goodRace, 'ids' => array())); for ($x = 0; $x < count($allRows); $x++) { if (isset($goodRows[$allRows[$x]['id']])) { $details['answer'] .= $x + 1; } $details['public']['ids'][] = $allRows[$x]['id']; } MCSet($cacheKey, $details); return $details['public']; }
function CategoryDealsItemListCached($house, $iidList, $flags) { if (count($iidList) == 0) { return array(); } $auctionIds = []; $sortBy = []; $sql = '('; foreach ($iidList as $row) { $sql .= (strlen($sql) == 1 ? '' : ' or ') . '(i.id = ' . $row['item'] . ' and s.bonusset = ' . $row['bonusset'] . ')'; $itemKey = $row['item'] . ':' . $row['bonusset']; $sortBy[] = $itemKey; if (isset($row['cheapestid'])) { $auctionIds[$itemKey] = $row['cheapestid']; } } $sql .= ')'; $sortBy = array_flip($sortBy); if ($flags & CATEGORY_FLAGS_WITH_BONUSES) { $tr = CategoryBonusItemList($house, ['where' => $sql, 'cols' => 'g.median globalmedian', 'outside' => 'r2.globalmedian']); } else { $tr = CategoryRegularItemList($house, ['where' => $sql, 'cols' => 'g.median globalmedian']); } usort($tr, function ($a, $b) use($sortBy) { return $sortBy[$a['id'] . ':' . $a['bonusset']] - $sortBy[$b['id'] . ':' . $b['bonusset']]; }); static $allRecentDates = []; if (isset($allRecentDates[$house])) { $recentDates = $allRecentDates[$house]; } else { $recentDates = MCGetHouse($house, 'category_disnapshots'); if ($recentDates === false) { $db = DBConnect(); $stmt = $db->stmt_init(); $stmt->prepare('SELECT unix_timestamp(updated) upd, maxid FROM `tblSnapshot` WHERE house=? and updated > timestampadd(hour, -60, now()) order by updated'); $stmt->bind_param('i', $house); $stmt->execute(); $result = $stmt->get_result(); $recentDates = DBMapArray($result, null); $stmt->close(); MCSetHouse($house, 'category_disnapshots', $recentDates); } $allRecentDates[$house] = $recentDates; } if (count($recentDates) < 2) { return $tr; } $rolloverBump = 0; if ($recentDates[count($recentDates) - 1]['maxid'] < $recentDates[0]['maxid']) { $rolloverBump = 0x80000000; } foreach ($tr as &$row) { $row['posted'] = null; $itemKey = $row['id'] . ':' . $row['bonusset']; if (!isset($auctionIds[$itemKey])) { continue; } $myId = $auctionIds[$itemKey]; if ($myId < 0x20000000) { $myId += $rolloverBump; } $x = count($recentDates) - 1; do { $maxId = $recentDates[$x]['maxid']; if ($maxId < 0x20000000) { $maxId += $rolloverBump; } if ($maxId < $myId) { break; } $row['posted'] = $recentDates[$x]['upd']; } while (--$x >= 0); } unset($row); return $tr; }
if (!DBConnect()) { DebugMessage('Cannot connect to db!', E_USER_ERROR); } if (APIMaintenance()) { DebugMessage('API Maintenance in progress, not reporting watches!', E_USER_NOTICE); exit; } $itemClassOrder = [2, 9, 6, 4, 7, 3, 14, 1, 15, 8, 16, 10, 12, 13, 17, 18, 5, 11]; $itemClassOrderSql = ''; foreach ($itemClassOrder as $idx => $classId) { $itemClassOrderSql .= "when {$classId} then {$idx} "; } $stmt = $db->prepare('SELECT house, group_concat(concat_ws(\' \', region, name) order by 1 separator \', \') names, min(region) region, min(slug) slug from tblRealm where locale is not null group by house'); $stmt->execute(); $result = $stmt->get_result(); $houseNameCache = DBMapArray($result); $stmt->close(); $loopStart = time(); $toSleep = 0; while (!$caughtKill && time() < $loopStart + 60 * 30 - 25) { heartbeat(); sleep(min($toSleep, 20)); if ($caughtKill || APIMaintenance()) { break; } ob_start(); $toSleep = CheckNextUser(); ob_end_flush(); if ($toSleep === false) { break; }
function NewPets($limit = 20) { global $db; $sql = <<<EOF select `is`.species from (select distinct species from tblPetSummary) `is` left join tblDBCPet i on i.id = `is`.species where i.id is null limit ? EOF; $stmt = $db->prepare($sql); $stmt->bind_param('i', $limit); $stmt->execute(); $result = $stmt->get_result(); $items = DBMapArray($result); $stmt->close(); return $items; }
when 'es_ES' then 'Spanish' when 'fr_FR' then 'French' when 'pt_BR' then 'Portuguese' when 'it_IT' then 'Italian' when 'ru_RU' then 'Russian' else 'Unknown' end) regionname, \tifnull(timezone, 'Unknown') timezonename \tfrom tblRealm r \twhere r.region = ? \torder by 1 EOF; $stmt = $db->prepare($sql); $stmt->bind_param('s', $region); $stmt->execute(); $result = $stmt->get_result(); $realms = DBMapArray($result); $stmt->close(); foreach ($realms as $realmId => $realmRow) { heartbeatsleep(15); heartbeat(); if ($caughtKill) { break; } $fn = strtolower($region) . '-' . $realmRow['slug']; DebugMessage("Making {$fn} " . round(memory_get_usage() / 1048576) . "MB"); $regionStats['realms'][$realmRow['slug']] = array('name' => $realmRow['name'], 'counts' => array('Alliance' => 0, 'Horde' => 0, 'Unknown' => 0, 'Neutral' => 0), 'stats' => array('pvp' => $realmRow['pvpname'], 'rp' => $realmRow['rpname'], 'region' => $realmRow['regionname'], 'timezone' => $realmRow['timezonename'])); if (!isset($regionStats['demographics'][$realmRow['pvpname']])) { $regionStats['demographics'][$realmRow['pvpname']] = array(); } if (!isset($regionStats['demographics'][$realmRow['pvpname']][$realmRow['rpname']])) { $regionStats['demographics'][$realmRow['pvpname']][$realmRow['rpname']] = array();
function ItemGlobalMonthly($region, $item) { global $db; $key = 'item_globalmonthly2_' . $region . '_' . $item; if (($tr = MCGet($key)) !== false) { return $tr; } DBConnect(); $sqlCols = ''; for ($x = 1; $x <= 31; $x++) { $padded = str_pad($x, 2, '0', STR_PAD_LEFT); $sqlCols .= ", round(avg(mktslvr{$padded})*100) mkt{$padded}, ifnull(sum(qty{$padded}),0) qty{$padded}"; } $sql = <<<EOF SELECT bonusset, month {$sqlCols} FROM `tblItemHistoryMonthly` ihm join tblRealm r on ihm.house = r.house and r.region = ? and r.canonical is not null WHERE ihm.item=? group by bonusset, month EOF; $stmt = $db->prepare($sql); $stmt->bind_param('si', $region, $item); $stmt->execute(); $result = $stmt->get_result(); $bonusRows = DBMapArray($result, array('bonusset', null)); $stmt->close(); $tr = array(); $today = strtotime(date('Y-m-d')); foreach ($bonusRows as $bonusSet => &$rows) { $prevPrice = 0; for ($x = 0; $x < count($rows); $x++) { $year = 2014 + floor(($rows[$x]['month'] - 1) / 12); $monthNum = $rows[$x]['month'] % 12; if ($monthNum == 0) { $monthNum = 12; } $month = ($monthNum < 10 ? '0' : '') . $monthNum; for ($dayNum = 1; $dayNum <= 31; $dayNum++) { $day = ($dayNum < 10 ? '0' : '') . $dayNum; if ($year == 2015 && $monthNum == 12 && ($dayNum >= 16 && $dayNum <= 22)) { continue; } if (!is_null($rows[$x]['mkt' . $day])) { $tr[$bonusSet][] = array('date' => "{$year}-{$month}-{$day}", 'silver' => round($rows[$x]['mkt' . $day] / 100, 2), 'quantity' => $rows[$x]['qty' . $day]); $prevPrice = round($rows[$x]['mkt' . $day] / 100, 2); } else { if (!checkdate($monthNum, $dayNum, $year)) { break; } if (strtotime("{$year}-{$month}-{$day}") >= $today) { break; } if ($prevPrice) { $tr[$bonusSet][] = array('date' => "{$year}-{$month}-{$day}", 'silver' => $prevPrice, 'quantity' => 0); } } } } } unset($rows); MCSet($key, $tr); return $tr; }
function IndexRegionDay($region, $timestamp) { global $db, $indexCategories, $caughtKill; heartbeat(); if ($caughtKill) { exit; } $indexValues = []; $total = 0; $when = date('Y-m-d', $timestamp); $month = (intval(date('Y', $timestamp), 10) - 2014) * 12 + intval(date('m', $timestamp), 10); $day = date('d', $timestamp); $dayPadded = str_pad($day, 2, '0', STR_PAD_LEFT); DebugMessage("Processing {$region} {$when}"); $sql = <<<'EOF' SELECT `mktslvr%1$s` FROM `tblItemHistoryMonthly` `ihm` JOIN `tblRealm` `r` ON `r`.`house` = `ihm`.`house` AND `r`.`canonical` IS NOT NULL WHERE `r`.`region` = ? AND `ihm`.`item` IN (%2$s) AND `ihm`.`bonusset` = 0 AND `ihm`.`month` = ? AND `mktslvr%1$s` IS NOT NULL ORDER BY 1 EOF; foreach ($indexCategories as $catName => $catItems) { heartbeat(); if ($caughtKill) { exit; } $stmt = $db->prepare(sprintf($sql, $dayPadded, implode(',', $catItems))); $stmt->bind_param('si', $region, $month); $stmt->execute(); $result = $stmt->get_result(); $prices = DBMapArray($result, null); $stmt->close(); $total += $indexValues[$catName] = MedianValue($prices); } $sql = 'REPLACE INTO `tblMarketIndex` (`region`, `when`, `total`'; $sqlVals = ') VALUES (?, ?, ?'; $types = 'ssi'; $valOrdered = [null, null]; $valOrdered[] =& $region; $valOrdered[] =& $when; $valOrdered[] =& $total; foreach (array_keys($indexValues) as $catName) { $sql .= ", `{$catName}`"; $sqlVals .= ", ?"; $valOrdered[] =& $indexValues[$catName]; $types .= 'i'; } $sql .= $sqlVals . ')'; $stmt = $db->prepare($sql); $valOrdered[0] =& $stmt; $valOrdered[1] =& $types; call_user_func_array('mysqli_stmt_bind_param', $valOrdered); if (!$stmt->execute()) { DebugMessage("Error saving {$region} {$when}\n{$sql}\n" . print_r($valOrdered, true)); } $stmt->close(); }
function ShowRealms() { echo '<h1>Realms</h1>'; global $db; $sql = <<<EOF SELECT r.house, r.region, r.canonical, sch.nextcheck scheduled, hc.nextcheck delayednext, sch.lastupdate, sch.mindelta, sch.avgdelta, sch.maxdelta FROM tblRealm r left join tblHouseCheck hc on hc.house = r.house left join ( select deltas.house, timestampadd(second, least(ifnull(min(delta)+15-120, 45*60), 150*60), max(deltas.updated)) nextcheck, max(deltas.updated) lastupdate, min(delta) mindelta, round(avg(delta)) avgdelta, max(delta) maxdelta from ( select sn.updated, if(@prevhouse = sn.house and sn.updated > timestampadd(hour, -72, now()), unix_timestamp(sn.updated) - @prevdate, null) delta, @prevdate := unix_timestamp(sn.updated) updated_ts, @prevhouse := sn.house house from (select @prevhouse := null, @prevdate := null) setup, tblSnapshot sn order by sn.house, sn.updated) deltas group by deltas.house ) sch on sch.house = r.house where r.canonical is not null order by unix_timestamp(ifnull(delayednext, scheduled)) - unix_timestamp(scheduled) desc, ifnull(delayednext, scheduled), sch.lastupdate, region, canonical EOF; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $rows = DBMapArray($result, null); echo '<table cellspacing="0"><tr><th>House</th><th>Region</th><th>Canonical</th><th>Updated</th><th>Scheduled</th><th>Min</th><th>Avg</th><th>Max</th></tr>'; foreach ($rows as &$row) { echo '<tr><td class="r">' . $row['house'] . '</td>'; echo '<td>' . $row['region'] . '</td>'; echo '<td><a href="?bnetget=' . $row['region'] . '-' . $row['canonical'] . '">' . $row['canonical'] . '</a></td>'; if (is_null($row['lastupdate'])) { echo '<td> </td>'; } else { $css = ''; $updateDelta = time() - strtotime($row['lastupdate']); if ($updateDelta > $row['maxdelta'] + 180) { $css = 'color: red'; } elseif ($updateDelta > $row['avgdelta'] + 60) { $css = 'color: #999900'; } echo '<td style="' . $css . '" class="r">' . TimeDiff(strtotime($row['lastupdate'])) . '</td>'; } if (is_null($row['scheduled'])) { echo '<td> </td>'; } elseif (is_null($row['delayednext'])) { echo '<td style="color: green" class="r">' . TimeDiff(strtotime($row['scheduled'])) . '</td>'; } else { echo '<td style="color: #999900" class="r">' . TimeDiff(strtotime($row['delayednext'])) . '</td>'; } echo '<td class="r">' . round(intval($row['mindelta'], 10) / 60) . ' min</td>'; echo '<td class="r">' . round(intval($row['avgdelta'], 10) / 60) . ' min</td>'; echo '<td class="r">' . round(intval($row['maxdelta'], 10) / 60) . ' min</td>'; echo '</tr>'; } unset($row); echo '</table>'; }
function cookhtml($realmset, $slug = '') { global $publicDir, $db; global $htmlheader, $htmlrealm, $htmlend, $htmlrealmset; $jsonfn = $publicDir . '/' . strtolower($realmset) . ($slug != '' ? '-' : '') . $slug . '.json'; $jsonsize = file_exists($jsonfn) ? filesize($jsonfn) : 0; if ($slug != '') { $html = $htmlheader . $htmlrealm . $htmlend; $realmset = substr(strtoupper($realmset), 0, 2); $realmslug = substr($slug, 0, 45); $sql = <<<EOF select r.*, if(r.region='US',if(locale='pt_BR', 'Brazil', if(locale='es_MX', 'Latin America', if(timezone like 'Australia/%', 'Oceanic', 'United States'))), case locale when 'de_DE' then 'German' when 'en_GB' then 'English' when 'es_ES' then 'Spanish' when 'fr_FR' then 'French' when 'pt_BR' then 'Portuguese' when 'it_IT' then 'Italian' when 'ru_RU' then 'Russian' else 'Unknown' end) regionname from tblRealm r where region = ? and slug = ? EOF; $stmt = $db->prepare($sql); $stmt->bind_param('ss', $realmset, $slug); $stmt->execute(); $result = $stmt->get_result(); $rows = DBMapArray($result, null); $stmt->close(); if (count($rows) == 0) { return ''; } $row = array_pop($rows); if ($realmslug != $row['slug']) { $realmslug = $row['slug']; } $realmbio = $row['region'] . ' ' . $row['name'] . ' is a ' . ($row['rp'] == '1' ? 'RP ' : 'Normal ') . ($row['pvp'] == '1' ? 'PvP' : 'PvE') . ' realm'; if (nvl($row['regionname'], '') != '') { $realmbio .= ' in the ' . $row['regionname'] . ' region'; } if (nvl($row['timezone'], '') != '') { $realmbio .= ' in the ' . $row['timezone'] . ' time zone'; } $realmbio .= '.'; //if (nvl($row['forumid'],'') != '') $realmbio .= ' <a href="http://'.strtolower($row['realmset']).'.battle.net/wow/ if (nvl($row['population'], '') != '') { $realmbio .= ' Blizzard calls it a ' . $row['population'] . ' population realm.'; } //header('Content-type: text/html; charset=utf8'); $sql = <<<EOF select concat_ws('-', lower(region), slug) as connslug, concat_ws(' ', region, name) as connname from tblRealm where house = ? and id != ? EOF; $stmt = $db->prepare($sql); $stmt->bind_param('ii', $row['house'], $row['id']); $stmt->execute(); $result = $stmt->get_result(); $connectedRows = DBMapArray($result, null); $stmt->close(); $connnames = ''; foreach ($connectedRows as $connrow) { $jsonsize += file_exists($publicDir . '/' . $connrow['connslug'] . '.json') ? filesize($publicDir . '/' . $connrow['connslug'] . '.json') : 0; $connnames .= ($connnames == '' ? '' : ', ') . $connrow['connname']; } if ($connnames != '') { $realmbio .= ' These statistics include its <a href="http://wowpedia.org/Connected_Realm">Connected Realm' . (strpos($connnames, ',') !== false ? 's' : '') . '</a>: ' . $connnames . '.'; } $html = str_replace('JSONSIZE', $jsonsize, str_replace('REALMSET', strtolower($realmset), str_replace('REALMBIO', $realmbio, str_replace('PRETTYREALM', $realmset . " " . $row['name'], str_replace('SLUG', $row['slug'], $html))))); return $html; } else { //$realmset = substr(strtoupper($_GET['realmset']),0,2); $realmset = strtoupper($realmset); switch ($realmset) { case 'US': case 'EU': break; default: return ''; } $html = $htmlheader . $htmlrealmset . $htmlend; $realmbio = ''; $html = str_replace('JSONSIZE', $jsonsize, str_replace('REALMSET', strtolower($realmset), str_replace('REALMBIO', $realmbio, str_replace('PRETTYREALM', $realmset, str_replace('SLUG', '', $html))))); return $html; } }
function CleanOldHouses() { global $db, $caughtKill; if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblAuction WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); $sql = 'DELETE FROM tblAuction WHERE house = %d LIMIT 2000'; foreach ($oldIds as $oldId) { if ($caughtKill) { return; } PrintImportantMessage('Clearing out auctions from old house ' . $oldId); while (!$caughtKill) { heartbeat(); $ok = $db->real_query(sprintf($sql, $oldId)); if (!$ok || $db->affected_rows == 0) { break; } } } if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblHouseCheck WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); if (count($oldIds)) { $db->real_query(sprintf('DELETE FROM tblHouseCheck WHERE house IN (%s)', implode(',', $oldIds))); } if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblItemHistoryHourly WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); $sql = 'DELETE FROM tblItemHistoryHourly WHERE house = %d LIMIT 2000'; foreach ($oldIds as $oldId) { if ($caughtKill) { return; } PrintImportantMessage('Clearing out item history from old house ' . $oldId); while (!$caughtKill) { heartbeat(); $ok = $db->real_query(sprintf($sql, $oldId)); if (!$ok || $db->affected_rows == 0) { break; } } } if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblItemSummary WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); $sql = 'DELETE FROM tblItemSummary WHERE house = %d LIMIT 2000'; foreach ($oldIds as $oldId) { if ($caughtKill) { return; } PrintImportantMessage('Clearing out item summary from old house ' . $oldId); while (!$caughtKill) { heartbeat(); $ok = $db->real_query(sprintf($sql, $oldId)); if (!$ok || $db->affected_rows == 0) { break; } } } if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblPetHistoryHourly WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); $sql = 'DELETE FROM tblPetHistoryHourly WHERE house = %d LIMIT 2000'; foreach ($oldIds as $oldId) { if ($caughtKill) { return; } PrintImportantMessage('Clearing out pet history from old house ' . $oldId); while (!$caughtKill) { heartbeat(); $ok = $db->real_query(sprintf($sql, $oldId)); if (!$ok || $db->affected_rows == 0) { break; } } } if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblPetSummary WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); $sql = 'DELETE FROM tblPetSummary WHERE house = %d LIMIT 2000'; foreach ($oldIds as $oldId) { if ($caughtKill) { return; } PrintImportantMessage('Clearing out pet summary from old house ' . $oldId); while (!$caughtKill) { heartbeat(); $ok = $db->real_query(sprintf($sql, $oldId)); if (!$ok || $db->affected_rows == 0) { break; } } } if ($caughtKill) { return; } $sql = 'SELECT DISTINCT house FROM tblSnapshot WHERE house NOT IN (SELECT DISTINCT house FROM tblRealm)'; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $oldIds = DBMapArray($result); $stmt->close(); $sql = 'DELETE FROM tblSnapshot WHERE house = %d LIMIT 2000'; foreach ($oldIds as $oldId) { if ($caughtKill) { return; } PrintImportantMessage('Clearing out snapshots from old house ' . $oldId); while (!$caughtKill) { heartbeat(); $ok = $db->real_query(sprintf($sql, $oldId)); if (!$ok || $db->affected_rows == 0) { break; } } } }
function UpdateGlobalDataJson() { global $caughtKill, $db; if ($caughtKill) { return; } heartbeat(); DebugMessage("Updating global data json"); $stmt = $db->prepare('SELECT item, floor(avg(median)) median FROM tblItemGlobal where bonusset=0 group by item'); $stmt->execute(); $result = $stmt->get_result(); $prices = DBMapArray($result, null); $stmt->close(); $json = []; foreach ($prices as $priceRow) { $json[$priceRow['item']] = $priceRow['median']; } file_put_contents(__DIR__ . '/../public/globalprices.json', json_encode($json, JSON_NUMERIC_CHECK | JSON_FORCE_OBJECT), LOCK_EX); }
$stmt->execute(); if ($db->affected_rows > 0) { $nextId++; } $stmt->reset(); } $stmt->close(); GetRussianOwnerRealms($region); if ($caughtKill) { break; } $stmt = $db->prepare('select slug, house, name, ifnull(ownerrealm, replace(name, \' \', \'\')) as ownerrealm from tblRealm where region = ?'); $stmt->bind_param('s', $region); $stmt->execute(); $result = $stmt->get_result(); $bySlug = DBMapArray($result); $stmt->close(); $canonicals = array(); $bySellerRealm = array(); $fallBack = array(); $candidates = array(); $winners = array(); foreach ($bySlug as $row) { heartbeat(); if ($caughtKill) { break 2; } $slug = $row['slug']; $bySellerRealm[$row['ownerrealm']] = $row['slug']; DebugMessage("Fetching {$region} {$slug}"); $url = GetBattleNetURL($region, "wow/auction/data/{$slug}");
function SearchItems($house, $search, $locale) { global $db; $suffixes = MCGet('search_itemsuffixes_' . $locale); if ($suffixes === false) { $sql = <<<EOF SELECT lower(suffix) FROM tblDBCItemRandomSuffix where locale='{$locale}' union select lower(ind.`desc_{$locale}`) from tblDBCItemBonus ib join tblDBCItemNameDescription ind on ind.id = ib.nameid where ind.`desc_{$locale}` is not null EOF; $stmt = $db->prepare($sql); $stmt->execute(); $result = $stmt->get_result(); $suffixes = DBMapArray($result, null); $stmt->close(); MCSet('search_itemsuffixes_' . $locale, $suffixes, 86400); } $terms = preg_replace('/\\s+/', '%', " {$search} "); $nameSearch = "i.name_{$locale} like ?"; $terms2 = ''; $barewords = trim(preg_replace('/ {2,}/', ' ', preg_replace('/[^ a-zA-Z0-9\'\\.]/', '', $search))); for ($x = 0; $x < count($suffixes); $x++) { if (substr($barewords, -1 * strlen($suffixes[$x])) == $suffixes[$x]) { $terms2 = '%' . str_replace(' ', '%', substr($barewords, 0, -1 * strlen($suffixes[$x]) - 1)) . '%'; $nameSearch = "(i.name_{$locale} like ? or i.name_{$locale} like ?)"; } } $sql = <<<EOF select results.*, (select round(avg(case hours.h when 0 then ihh.silver00 when 1 then ihh.silver01 when 2 then ihh.silver02 when 3 then ihh.silver03 when 4 then ihh.silver04 when 5 then ihh.silver05 when 6 then ihh.silver06 when 7 then ihh.silver07 when 8 then ihh.silver08 when 9 then ihh.silver09 when 10 then ihh.silver10 when 11 then ihh.silver11 when 12 then ihh.silver12 when 13 then ihh.silver13 when 14 then ihh.silver14 when 15 then ihh.silver15 when 16 then ihh.silver16 when 17 then ihh.silver17 when 18 then ihh.silver18 when 19 then ihh.silver19 when 20 then ihh.silver20 when 21 then ihh.silver21 when 22 then ihh.silver22 when 23 then ihh.silver23 else null end) * 100) from tblItemHistoryHourly ihh, (select 0 h union select 1 h union select 2 h union select 3 h union select 4 h union select 5 h union select 6 h union select 7 h union select 8 h union select 9 h union select 10 h union select 11 h union select 12 h union select 13 h union select 14 h union select 15 h union select 16 h union select 17 h union select 18 h union select 19 h union select 20 h union select 21 h union select 22 h union select 23 h) hours where ihh.house = ? and ihh.item = results.id and ihh.bonusset = results.bonusset) avgprice, ifnull(GROUP_CONCAT(bs.`tagid` ORDER BY 1 SEPARATOR '.'), '') tagurl, ifnull((select concat_ws(':', nullif(bonus1,0), nullif(bonus2,0), nullif(bonus3,0), nullif(bonus4,0)) FROM `tblItemBonusesSeen` ibs WHERE ibs.item=results.id and ibs.bonusset=results.bonusset order by ibs.observed desc limit 1),'') bonusurl from ( select i.id, i.quality, i.icon, i.class as classid, s.price, s.quantity, unix_timestamp(s.lastseen) lastseen, ifnull(s.bonusset,0) bonusset, i.level from tblDBCItem i left join tblItemSummary s on s.house=? and s.item=i.id where {$nameSearch} and (s.item is not null or ifnull(i.auctionable,1) = 1) group by i.id, ifnull(s.bonusset,0) limit ? ) results left join tblBonusSet bs on results.bonusset = bs.`set` group by results.id, results.bonusset EOF; $limit = 50 * strlen(preg_replace('/\\s/', '', $search)); $stmt = $db->prepare($sql); if ($terms2 == '') { $stmt->bind_param('iisi', $house, $house, $terms, $limit); } else { $stmt->bind_param('iissi', $house, $house, $terms, $terms2, $limit); } $stmt->execute(); $result = $stmt->get_result(); $tr = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); return $tr; }
function BuildAddonData($region) { global $db, $caughtKill; heartbeat(); if ($caughtKill) { return; } DebugMessage("Starting region {$region}"); $globalSpots = 3; // number of global prices in front of every string $stmt = $db->prepare('select distinct house from tblRealm where region = ? and canonical is not null order by 1'); $stmt->bind_param('s', $region); $stmt->execute(); $result = $stmt->get_result(); $houses = DBMapArray($result, null); $stmt->close(); $item_global = []; $item_avg = []; $item_stddev = []; $item_recent = []; $item_days = []; DebugMessage('Finding global prices'); $itemExcludeSql = <<<EOF and (i.quality > 0 or i.class in (2,4)) and not (i.class = 0 and i.subclass = 5 and 0 = (select count(*) from tblDBCItemReagents ir where ir.item = i.id) and i.quality < 2) EOF; $sql = <<<EOF SELECT g.item, g.bonusset, g.median, g.mean, g.stddev FROM tblItemGlobal g join tblDBCItem i on g.item=i.id where g.region = ? {$itemExcludeSql} EOF; $stmt = $db->prepare($sql); $stmt->bind_param('s', $region); $stmt->execute(); $result = $stmt->get_result(); while ($priceRow = $result->fetch_assoc()) { $item = '' . $priceRow['item'] . ($priceRow['bonusset'] != '0' ? 'x' . $priceRow['bonusset'] : ''); $item_global[$item] = pack('LLL', round($priceRow['median'] / 100), round($priceRow['mean'] / 100), round($priceRow['stddev'] / 100)); } $result->close(); $stmt->close(); $stmt = $db->prepare('SELECT species, breed, avg(price) `mean`, stddev(price) `stddev` FROM tblPetSummary group by species, breed'); $stmt->execute(); $result = $stmt->get_result(); while ($priceRow = $result->fetch_assoc()) { $item = '' . $priceRow['species'] . 'b' . $priceRow['breed']; $item_global[$item] = pack('LLL', 0, round($priceRow['mean'] / 100), round($priceRow['stddev'] / 100)); } $result->close(); $stmt->close(); $sql = <<<EOF SELECT tis.item, tis.bonusset, datediff(now(), tis.lastseen) since, round(ifnull(avg(case hours.h when 0 then ihh.silver00 when 1 then ihh.silver01 when 2 then ihh.silver02 when 3 then ihh.silver03 when 4 then ihh.silver04 when 5 then ihh.silver05 when 6 then ihh.silver06 when 7 then ihh.silver07 when 8 then ihh.silver08 when 9 then ihh.silver09 when 10 then ihh.silver10 when 11 then ihh.silver11 when 12 then ihh.silver12 when 13 then ihh.silver13 when 14 then ihh.silver14 when 15 then ihh.silver15 when 16 then ihh.silver16 when 17 then ihh.silver17 when 18 then ihh.silver18 when 19 then ihh.silver19 when 20 then ihh.silver20 when 21 then ihh.silver21 when 22 then ihh.silver22 when 23 then ihh.silver23 else null end), tis.price/100)) price, round(ifnull(avg(if(timestampadd(hour, 72 + hours.h, ihh.`when`) > now(), case hours.h when 0 then ihh.silver00 when 1 then ihh.silver01 when 2 then ihh.silver02 when 3 then ihh.silver03 when 4 then ihh.silver04 when 5 then ihh.silver05 when 6 then ihh.silver06 when 7 then ihh.silver07 when 8 then ihh.silver08 when 9 then ihh.silver09 when 10 then ihh.silver10 when 11 then ihh.silver11 when 12 then ihh.silver12 when 13 then ihh.silver13 when 14 then ihh.silver14 when 15 then ihh.silver15 when 16 then ihh.silver16 when 17 then ihh.silver17 when 18 then ihh.silver18 when 19 then ihh.silver19 when 20 then ihh.silver20 when 21 then ihh.silver21 when 22 then ihh.silver22 when 23 then ihh.silver23 else null end, null)), tis.price/100)) pricerecent, round(stddev(case hours.h when 0 then ihh.silver00 when 1 then ihh.silver01 when 2 then ihh.silver02 when 3 then ihh.silver03 when 4 then ihh.silver04 when 5 then ihh.silver05 when 6 then ihh.silver06 when 7 then ihh.silver07 when 8 then ihh.silver08 when 9 then ihh.silver09 when 10 then ihh.silver10 when 11 then ihh.silver11 when 12 then ihh.silver12 when 13 then ihh.silver13 when 14 then ihh.silver14 when 15 then ihh.silver15 when 16 then ihh.silver16 when 17 then ihh.silver17 when 18 then ihh.silver18 when 19 then ihh.silver19 when 20 then ihh.silver20 when 21 then ihh.silver21 when 22 then ihh.silver22 when 23 then ihh.silver23 else null end)) pricestddev, ceil(ivc.copper/100) vendorprice FROM tblItemSummary tis join tblDBCItem i on i.id = tis.item join (select 0 h union select 1 h union select 2 h union select 3 h union select 4 h union select 5 h union select 6 h union select 7 h union select 8 h union select 9 h union select 10 h union select 11 h union select 12 h union select 13 h union select 14 h union select 15 h union select 16 h union select 17 h union select 18 h union select 19 h union select 20 h union select 21 h union select 22 h union select 23 h) hours left join tblItemHistoryHourly ihh on ihh.item = tis.item and ihh.house = tis.house and ihh.bonusset = tis.bonusset left join tblDBCItemVendorCost ivc on ivc.item = i.id WHERE tis.house = ? {$itemExcludeSql} group by tis.item, tis.bonusset EOF; for ($hx = 0; $hx < count($houses); $hx++) { heartbeat(); if ($caughtKill) { return; } DebugMessage('Finding item prices in house ' . $houses[$hx] . ' (' . round($hx / count($houses) * 100) . '%) ' . round(memory_get_usage() / 1048576)); $stmt = $db->prepare($sql); $stmt->bind_param('i', $houses[$hx]); $stmt->execute(); $result = $stmt->get_result(); while ($priceRow = $result->fetch_assoc()) { $item = '' . $priceRow['item'] . ($priceRow['bonusset'] != '0' ? 'x' . $priceRow['bonusset'] : ''); if (!isset($item_avg[$item])) { $item_avg[$item] = ''; } if (!isset($item_stddev[$item])) { $item_stddev[$item] = ''; } if (!isset($item_recent[$item])) { $item_recent[$item] = ''; } if (!isset($item_days[$item])) { $item_days[$item] = ''; } $prc = intval($priceRow['price'], 10); $usingVendor = $priceRow['vendorprice'] && intval($priceRow['vendorprice'], 10) < $prc && $priceRow['bonusset'] == '0'; if ($usingVendor) { $prc = intval($priceRow['vendorprice'], 10); } $item_avg[$item] .= str_repeat(chr(0), 4 * $hx - strlen($item_avg[$item])) . pack('L', $prc); $item_stddev[$item] .= str_repeat(chr(0), 4 * $hx - strlen($item_stddev[$item])) . pack('L', !$usingVendor && $priceRow['pricestddev'] ? intval($priceRow['pricestddev'], 10) : 0); $item_recent[$item] .= str_repeat(chr(0), 4 * $hx - strlen($item_recent[$item])) . pack('L', !$usingVendor && $priceRow['pricerecent'] ? intval($priceRow['pricerecent'], 10) : $prc); $item_days[$item] .= str_repeat(chr(255), $hx - strlen($item_days[$item])) . chr($priceRow['vendorprice'] ? 252 : min(251, intval($priceRow['since'], 10))); } $result->close(); $stmt->close(); } $sql = <<<EOF SELECT tps.species, tps.breed, datediff(now(), tps.lastseen) since, round(ifnull(avg(case hours.h when 0 then phh.silver00 when 1 then phh.silver01 when 2 then phh.silver02 when 3 then phh.silver03 when 4 then phh.silver04 when 5 then phh.silver05 when 6 then phh.silver06 when 7 then phh.silver07 when 8 then phh.silver08 when 9 then phh.silver09 when 10 then phh.silver10 when 11 then phh.silver11 when 12 then phh.silver12 when 13 then phh.silver13 when 14 then phh.silver14 when 15 then phh.silver15 when 16 then phh.silver16 when 17 then phh.silver17 when 18 then phh.silver18 when 19 then phh.silver19 when 20 then phh.silver20 when 21 then phh.silver21 when 22 then phh.silver22 when 23 then phh.silver23 else null end), tps.price/100)) price, round(ifnull(avg(if(timestampadd(hour, 72 + hours.h, phh.`when`) > now(), case hours.h when 0 then phh.silver00 when 1 then phh.silver01 when 2 then phh.silver02 when 3 then phh.silver03 when 4 then phh.silver04 when 5 then phh.silver05 when 6 then phh.silver06 when 7 then phh.silver07 when 8 then phh.silver08 when 9 then phh.silver09 when 10 then phh.silver10 when 11 then phh.silver11 when 12 then phh.silver12 when 13 then phh.silver13 when 14 then phh.silver14 when 15 then phh.silver15 when 16 then phh.silver16 when 17 then phh.silver17 when 18 then phh.silver18 when 19 then phh.silver19 when 20 then phh.silver20 when 21 then phh.silver21 when 22 then phh.silver22 when 23 then phh.silver23 else null end, null)), tps.price/100)) pricerecent, round(stddev(case hours.h when 0 then phh.silver00 when 1 then phh.silver01 when 2 then phh.silver02 when 3 then phh.silver03 when 4 then phh.silver04 when 5 then phh.silver05 when 6 then phh.silver06 when 7 then phh.silver07 when 8 then phh.silver08 when 9 then phh.silver09 when 10 then phh.silver10 when 11 then phh.silver11 when 12 then phh.silver12 when 13 then phh.silver13 when 14 then phh.silver14 when 15 then phh.silver15 when 16 then phh.silver16 when 17 then phh.silver17 when 18 then phh.silver18 when 19 then phh.silver19 when 20 then phh.silver20 when 21 then phh.silver21 when 22 then phh.silver22 when 23 then phh.silver23 else null end)) pricestddev FROM tblPetSummary tps join (select 0 h union select 1 h union select 2 h union select 3 h union select 4 h union select 5 h union select 6 h union select 7 h union select 8 h union select 9 h union select 10 h union select 11 h union select 12 h union select 13 h union select 14 h union select 15 h union select 16 h union select 17 h union select 18 h union select 19 h union select 20 h union select 21 h union select 22 h union select 23 h) hours left join tblPetHistoryHourly phh on phh.species=tps.species and phh.house = tps.house and phh.breed=tps.breed WHERE tps.house = ? group by tps.species, tps.breed EOF; for ($hx = 0; $hx < count($houses); $hx++) { heartbeat(); if ($caughtKill) { return; } DebugMessage('Finding pet prices in house ' . $houses[$hx] . ' (' . round($hx / count($houses) * 100) . '%) ' . round(memory_get_usage() / 1048576)); $stmt = $db->prepare($sql); $stmt->bind_param('i', $houses[$hx]); $stmt->execute(); $result = $stmt->get_result(); while ($priceRow = $result->fetch_assoc()) { $item = '' . $priceRow['species'] . 'b' . $priceRow['breed']; if (!isset($item_avg[$item])) { $item_avg[$item] = ''; } if (!isset($item_stddev[$item])) { $item_stddev[$item] = ''; } if (!isset($item_recent[$item])) { $item_recent[$item] = ''; } if (!isset($item_days[$item])) { $item_days[$item] = ''; } $prc = intval($priceRow['price'], 10); $item_avg[$item] .= str_repeat(chr(0), 4 * $hx - strlen($item_avg[$item])) . pack('L', $prc); $item_stddev[$item] .= str_repeat(chr(0), 4 * $hx - strlen($item_stddev[$item])) . pack('L', $priceRow['pricestddev'] ? intval($priceRow['pricestddev'], 10) : 0); $item_recent[$item] .= str_repeat(chr(0), 4 * $hx - strlen($item_recent[$item])) . pack('L', $priceRow['pricerecent'] ? intval($priceRow['pricerecent'], 10) : $prc); $item_days[$item] .= str_repeat(chr(255), $hx - strlen($item_days[$item])) . chr(min(251, intval($priceRow['since'], 10))); } $result->close(); $stmt->close(); } heartbeat(); if ($caughtKill) { return; } DebugMessage('Making lua strings'); $priceLua = ''; $luaLines = 0; $dataFuncIndex = 0; foreach ($item_global as $item => $globalPriceList) { heartbeat(); if ($caughtKill) { return; } $globalPrices = array_values(unpack('L*', $globalPriceList)); $prices = isset($item_avg[$item]) ? array_values(unpack('L*', $item_avg[$item])) : []; $recents = isset($item_recent[$item]) ? array_values(unpack('L*', $item_recent[$item])) : []; $stddevs = isset($item_stddev[$item]) ? array_values(unpack('L*', $item_stddev[$item])) : []; $priceBytes = 0; for ($x = 0; $x < $globalSpots; $x++) { if (!isset($globalPrices[$x])) { $globalPrices[$x] = 0; continue; } for ($y = 4; $y >= $priceBytes; $y--) { if ($globalPrices[$x] >= pow(2, 8 * $y)) { $priceBytes = $y + 1; } } } for ($x = 0; $x < count($houses); $x++) { if (!isset($stddevs[$x])) { $stddevs[$x] = 0; } if (!isset($recents[$x])) { $recents[$x] = 0; } if (!isset($prices[$x])) { $prices[$x] = 0; continue; } for ($y = 4; $y >= $priceBytes; $y--) { if ($prices[$x] >= pow(2, 8 * $y)) { $priceBytes = $y + 1; } elseif ($stddevs[$x] >= pow(2, 8 * $y)) { $priceBytes = $y + 1; } elseif ($recents[$x] >= pow(2, 8 * $y)) { $priceBytes = $y + 1; } } } if ($priceBytes == 0) { continue; } $priceString = chr($priceBytes); for ($x = 0; $x < $globalSpots; $x++) { $priceBin = ''; $price = $globalPrices[$x]; for ($y = 0; $y < $priceBytes; $y++) { $priceBin = chr($price % 256) . $priceBin; $price = $price >> 8; } $priceString .= $priceBin; } for ($x = 0; $x < count($prices); $x++) { if (!isset($item_days[$item]) || ($thisPriceString = substr($item_days[$item], $x, 1)) === false) { $thisPriceString = chr(255); } $priceBin = ''; $price = $prices[$x]; for ($y = 0; $y < $priceBytes; $y++) { $priceBin = chr($price % 256) . $priceBin; $price = $price >> 8; } $thisPriceString .= $priceBin; $priceBin = ''; $price = $stddevs[$x]; for ($y = 0; $y < $priceBytes; $y++) { $priceBin = chr($price % 256) . $priceBin; $price = $price >> 8; } $thisPriceString .= $priceBin; $priceBin = ''; $price = $recents[$x]; for ($y = 0; $y < $priceBytes; $y++) { $priceBin = chr($price % 256) . $priceBin; $price = $price >> 8; } $thisPriceString .= $priceBin; $priceString .= $thisPriceString; } if ($luaLines == 0) { $dataFuncIndex++; $priceLua .= "dataFuncs[{$dataFuncIndex}] = function()\n"; } $priceLua .= sprintf("addonTable.marketData['%s']=crop(%d,%s)\n", $item, $priceBytes, luaQuote($priceString)); if (++$luaLines >= 2000) { $priceLua .= "end\n"; $luaLines = 0; } } unset($items); if ($luaLines > 0) { $priceLua .= "end\n"; } heartbeat(); if ($caughtKill) { return; } DebugMessage('Setting realm indexes'); $houseLookup = array_flip($houses); $stmt = $db->prepare('select rgh.realmguid, rgh.house from tblRealmGuidHouse rgh join tblRealm r on rgh.house = r.house and r.canonical is not null where r.region = ?'); $stmt->bind_param('s', $region); $stmt->execute(); $result = $stmt->get_result(); $guids = DBMapArray($result); $stmt->close(); $guidLua = ''; foreach ($guids as $guidRow) { if (isset($houseLookup[$guidRow['house']])) { $guidLua .= ($guidLua == '' ? '' : ',') . '[' . $guidRow['realmguid'] . ']=' . $houseLookup[$guidRow['house']]; } } heartbeat(); if ($caughtKill) { return; } DebugMessage('Building final lua'); $dataAge = time(); $lua = <<<EOF local addonName, addonTable = ... addonTable.dataLoads = addonTable.dataLoads or {} local realmIndex local dataFuncs = {} local tuj_substr = string.sub local tuj_concat = table.concat local function crop(priceSize, b) local headerSize = 1 + priceSize * 3 local recordSize = 1 + priceSize * 3 local offset = 1 + headerSize + recordSize * realmIndex return tuj_substr(b, 1, headerSize)..tuj_substr(b, offset, offset + recordSize - 1) end EOF; $luaEnd = <<<EOF local dataLoad = function(realmId) local realmGuids = {{$guidLua}} realmIndex = realmGuids[realmId] if not realmIndex then wipe(dataFuncs) return false end addonTable.marketData = {} addonTable.realmIndex = realmIndex addonTable.dataAge = {$dataAge} addonTable.region = "{$region}" for i=1,#dataFuncs,1 do dataFuncs[i]() dataFuncs[i]=nil end wipe(dataFuncs) return true end table.insert(addonTable.dataLoads, dataLoad) EOF; return pack('CCC', 239, 187, 191) . $lua . $priceLua . $luaEnd; }
define('ARRAY_INDEX_QUANTITY', 0); define('ARRAY_INDEX_AUCTIONS', 1); define('ARRAY_INDEX_MARKETPRICE', 2); define('ARRAY_INDEX_ALLBREEDS', -1); ini_set('memory_limit', '512M'); if (!DBConnect()) { DebugMessage('Cannot connect to db!', E_USER_ERROR); } if (APIMaintenance()) { DebugMessage('API Maintenance in progress, not parsing snapshots!', E_USER_NOTICE); exit; } $stmt = $db->prepare('SELECT house, region FROM tblRealm GROUP BY house'); $stmt->execute(); $result = $stmt->get_result(); $houseRegionCache = DBMapArray($result); $stmt->close(); $auctionExtraItemsCache = []; $stmt = $db->prepare('SELECT id FROM tblDBCItem WHERE `class` in (2,4) AND `auctionable` = 1'); $stmt->execute(); $z = null; $stmt->bind_result($z); while ($stmt->fetch()) { $auctionExtraItemsCache[$z] = $z; } $stmt->close(); $bonusTagIdCache = []; $stmt = $db->prepare('SELECT id, tagid FROM tblDBCItemBonus WHERE tagid IS NOT NULL ORDER BY 1'); $stmt->execute(); $id = $tagId = null; $stmt->bind_result($id, $tagId);