function parse_output($output, $strkey) { $key = array_find($strkey, $output); if ($key !== false) { return substr($output[$key], 20); } else { return false; } }
public function testFindFailure() { // arrange $array = array(array('id' => 1, 'name' => 'foo'), array('id' => 2, 'name' => 'bar'), array('id' => 3, 'name' => 'baz '), array('id' => 4, 'name' => 'bar')); // act $result = array_find($array, function ($item) { return $item['name'] == 'qux'; }); // assert $this->assertNull($result); }
/** * コンストラクタ。 * コンシューマキー、及びコンシューマ秘密鍵はプロパティファイルに定義することも可能です。 * * config/global_properties.yml の設定例: * <code> * twitter: * # コンシューマキー。 * consumerKey: * * # コンシューマ秘密鍵。 * consumerSecret: * </code> * @see Mars_OAuthProvider::__construct() * @author Naomichi Yamakita <*****@*****.**> */ protected function __construct($consumerKey = NULL, $consumerSecret = NULL) { $config = Mars_Config::loadProperties('twitter'); if ($consumerKey === NULL) { $consumerKey = array_find($config, 'consumerKey'); } if ($consumerSecret === NULL) { $consumerSecret = array_find($config, 'consumerSecret'); } parent::__construct($consumerKey, $consumerSecret); }
/** * コンストラクタ。 * コンシューマキー、及びコンシューマ秘密鍵はプロパティファイルに定義することも可能です。 * * config/global_properties.yml の設定例: * <code> * mixiGraph: * # コンシューマキー。 * consumerKey: * * # コンシューマ秘密鍵。 * consumerSecret: * </code> * @see Mars_OAuthProvider::__construct() * @author Naomichi Yamakita <*****@*****.**> */ protected function __construct($consumerKey = NULL, $consumerSecret = NULL) { $config = Mars_Config::loadProperties('mixiGraph'); if ($consumerKey === NULL) { $consumerKey = array_find($config, 'consumerKey'); } if ($consumerSecret === NULL) { $consumerSecret = array_find($config, 'consumerSecret'); } $this->_userAgent = $this->request->getUserAgent(); parent::__construct($consumerKey, $consumerSecret); }
/** * コンストラクタ。 * コンシューマキー、及びコンシューマ秘密鍵はコンストラクタの引数、またはプロパティファイルに定義することが可能です。 * (プロパティファイルの設定例は {@link Mars_MixiMobileApp} クラスの API を参照) * * @param string $consumerKey コンシューマキー。 * @param string $consumerSecret コンシューマ秘密鍵。 * @author Naomichi Yamakita <*****@*****.**> */ protected function __construct($consumerKey = NULL, $consumerSecret = NULL) { $config = Mars_Config::loadProperties('mixi'); if ($consumerKey === NULL) { $consumerKey = array_find($config, 'consumerKey'); } if ($consumerSecret === NULL) { $consumerSecret = array_find($config, 'consumerSecret'); } parent::__construct($consumerKey, $consumerSecret); $this->_consumer = new OAuthConsumer($consumerKey, $consumerSecret); $this->_hasZlib = extension_loaded('zlib'); }
/** * Fetch common form data needed for subclass controllers * The 2 main items are the organization list participating in the specified CTA * and the specified church (either passed in URI or set in cookie by WP site) * * @return Array */ protected function getFormData($permalink = null, $withs = []) { $orgs = $this->getOrgsForDropdown($withs); \Log::debug('------------ QUERIES --------------'); \Log::debug(print_r(\DB::getQueryLog(), true)); // pass in the church to override, fall back to the cookie if it exists $churchId = 0; $churchUid = ''; if ($permalink === null) { // RT - cannot use Laravel Cookie b/c it's expecting encrypted junk $permalink = array_key_exists('church', $_COOKIE) ? $_COOKIE['church'] : null; if (empty($permalink)) { $permalink = null; } // just in case empty string } if ($permalink !== null) { $church = array_find($orgs, function ($o) use($permalink) { return $o->permalink == $permalink; }); if ($church) { $churchId = $church->id; $churchUid = $church->uid; } } $orgs4dropdown = ['0' => '-- Select Your Church --']; foreach ($orgs as $o) { $location = ''; if (!empty($o->effective_meeting_city)) { $location = $o->effective_meeting_city; } if (!empty(trim($o->effective_meeting_country)) && ($o->effective_meeting_country != 'US' && $o->effective_meeting_country != 'CA')) { $location .= ", " . $o->full_effective_meeting_country; } else { if (trim($o->effective_meeting_state)) { $location .= ", " . $o->effective_meeting_state; } } if (!empty(trim($location))) { $location = ": " . $location; } $orgs4dropdown[$o->id] = $o->name . $location; $o->dropdownLabel = $o->name . $location; } $orgs4dropdown[null] = 'Other'; return ['organizations' => $orgs, 'orgsDropdown' => $orgs4dropdown, 'churchId' => $churchId, 'churchUid' => $churchUid, 'permalink' => $permalink]; }
public function execute() { $arguments = $this->controller->getArguments(); $type = array_find($arguments, 'type', 'json'); $level = array_find($arguments, 'level', 'error'); $levels = array('trace', 'debug', 'info', 'warning', 'error', 'fatal'); if (!in_array($level, $levels)) { fputs(STDERR, sprintf('Invalid parameter [--level=%s]', $level)); exit; } $fp = fopen('php://stderr', 'r'); $buffer = NULL; $data = fread($fp, 4096); if ($type === 'json') { $separate = str_repeat('=', 74); $message = sprintf("%s\nSummary:\n%s\n%s\n" . "%s\n\$_SERVER:\n%s\n%s\n", $separate, $separate, json_string_format($data), $separate, $separate, var_export($_SERVER, TRUE)); } $array = json_decode($data, TRUE); $logger = Mars_Logger::getLogger(basename($array['path'])); $logger->{$level}($message); }
"contact" => "author_data", # in author_data ); $authorDataOrderBy = array( "affiliation" => "affiliation", "contact" => "name", ); if(isset($_REQUEST["sort"])) { $orderKey = $_REQUEST["sort"]; if(!array_key_exists($orderKey, $orderBy)) { # Invalid order key $orderKey = null; } } if(empty($orderKey)) $orderKey = "date"; $orderColumn = $orderBy[$orderKey]; if(!array_find($orderColumn, $cols, false, true)) { $cols[] = $orderColumn; } $list = $db->getQueryResults($search, $cols, 'AND', true, true, $orderColumn); $html = ''; $i = 0; $count = sizeof($list); $max = 25; $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; if ($page > 1) { $multiplier = $page - 1; $skip = $multiplier * $max; #echo "<!-- Skipping $skip on page $page with multiplier $multiplier for max $max for total results $count -->"; } else { $skip = 0; }
function editAccess($link, $deltas) { /*** * ***/ global $db, $login_status, $default_user_database, $default_sql_user, $default_sql_password, $sql_url, $default_user_table, $db_cols; try { $udb = new DBHelper($default_user_database, $default_sql_user, $default_sql_password, $sql_url, $default_user_table, $db_cols); $uid = $login_status['detail']['uid']; $pid = $db->sanitize($link); if (!$db->isEntry($pid, 'project_id', true)) { return array('status' => false, 'error' => 'INVALID_PROJECT', 'human_error' => 'No project #' . $pid . ' exists'); } $search = array('project_id' => $pid); $projectList = $db->getQueryResults($search, '*', 'AND', false, true); $project = $projectList[0]; $originalAccess = $project['access_data']; $authorizedStatus = checkProjectAuthorized($project, $uid); if (!$authorizedStatus['can_edit']) { return array('status' => false, 'error' => 'UNAUTHORIZED', 'human_error' => 'You have insufficient privileges to change user permissions on project #' . $pid); } if (!is_array($deltas)) { return array('status' => false, 'error' => 'BAD_DELTAS', 'human_error' => 'Your permission changes were malformed. Please correct them and try again.'); } $additions = $deltas['add']; $removals = $deltas['delete']; $changes = $deltas['changes']; $editList = $authorizedStatus['editors']; $viewList = $authorizedStatus['viewers']; $authorList = array($project['author']); $totalList = array_merge($editList, $viewList, $authorList); $notices = array(); $operations = array(); # Add users foreach ($additions as $newUid) { if (!$udb->isEntry($newUid, 'dblink')) { $notices[] = 'User ' . $user['uid'] . " doesn't exist"; continue; } if (in_array($newUid, $totalList)) { $notices[] = "{$newUid} is already given project permissions"; continue; } $viewList[] = $newUid; $operations[] = "Succesfully added {$newUid} as a viewer"; } # Remove users foreach ($removals as $user) { # Remove user from list after looping through each if (!is_array($user)) { $notices[] = "Couldn't remove user, permissions object malformed"; continue; } if (!$udb->isEntry($user['uid'], 'dblink')) { $notices[] = 'User ' . $user['uid'] . " doesn't exist"; continue; } $currentRole = strtolower($user['currentRole']); if ($currentRole == 'edit') { $observeList = 'editList'; } elseif ($currentRole == 'read') { $observeList = 'viewList'; } elseif ($currentRole == 'authorList') { # Check the lists for other author thing $observeList = 'authorList'; continue; } else { $notices[] = "Unrecognized current role '" . strotupper($currentRole) . "'"; continue; } $key = array_find($user['uid'], ${$observeList}); if ($key === false) { $notices[] = 'Invalid current role for ' . $user['uid']; continue; } $orig = ${$observeList}; unset(${$observeList}[$key]); $operations[] = 'User ' . $user['uid'] . " removed from role '" . strtoupper($currentRole) . "' in " . $observeList; } # Changes to existing users foreach ($changes as $user) { if (!is_array($user)) { $notices[] = "Couldn't change permissions, permissions object malformed"; continue; } if (!$udb->isEntry($user['uid'], 'dblink')) { $notices[] = 'User ' . $user['uid'] . " doesn't exist"; continue; } if (empty($user['currentRole']) || empty($user['newRole']) || empty($user['uid'])) { $notices[] = "Couldn't change permissions, missing one of newRole, uid, or currentRole for user"; continue; } # Match the roles $newRole = strtolower($user['newRole']); $currentRole = strtolower($user['currentRole']); if ($newRole == $currentRole) { $notices[] = 'User ' . $user['uid'] . " already has permissions '" . strtoupper($currentRole) . "'"; continue; } if ($currentRole == 'edit') { $observeList = 'editList'; } elseif ($currentRole == 'read') { $observeList = 'viewList'; } elseif ($currentRole == 'authorList') { $observeList = 'authorList'; } else { $notices[] = "Unrecognized current role '" . strtoupper($currentRole) . "'"; continue; } if ($newRole == 'edit') { $addToList = 'editList'; } elseif ($newRole == 'read') { $addToList = 'viewList'; } elseif ($newRole == 'authorList' || $newRole == "author") { # $addToList = 'authorList'; $addToList = 'editList'; } else { $notices[] = "Unrecognized new role '" . strtoupper($newRole) . "'"; continue; } $useAuthorQuery = false; if ($newRole == 'edit' || $newRole == 'read' || $newRole == "author") { $key = array_find($user['uid'], ${$observeList}); if ($key === false) { $notices[] = 'Invalid current role for ' . $user['uid']; continue; } if ($observeList == 'authorList') { # Someone else must be set as the author } else { unset(${$observeList}[$key]); } array_push(${$addToList}, $user['uid']); $operations[] = 'Removed ' . $user['uid'] . " from {$observeList} and added to {$addToList}"; if ($newRole == 'author') { # Need to do fanciness $useAuthorQuery = true; $authorQuery = 'UPDATE `' . $db->getTable() . "` SET `author`='" . $user['uid'] . "' WHERE `project_id`='" . $pid . "'"; $db->closeLink(); $r = mysqli_query($db->getLink(), $authorQuery); if ($r !== true) { throw new Exception(mysqli_error($db->getLink())); } $operations[] = "Changed project author to " . $user['uid']; } } else { $notices[] = 'Invalid role assignment for user ' . $user['uid']; } } # Write the new lists back out $newList = array(); $editListTracker = array(); $readListTracker = array(); foreach ($editList as $user) { if (array_key_exists($user, $editListTracker)) { continue; } $newList[] = $user . ':EDIT'; $editListTracker[$user] = true; } foreach ($viewList as $user) { if (array_key_exists($user, $readListTracker)) { continue; } $newList[] = $user . ':READ'; $readListTracker[$user] = true; } $newListString = implode(',', $newList); $newListString = $db->sanitize($newListString); $newEntry = array('access_data' => $newListString); $lookup = array('project_id' => $pid); $db->closeLink(); $query = 'UPDATE `' . $db->getTable() . "` SET `access_data`='" . $newListString . "' WHERE `project_id`='" . $pid . "'"; $r = mysqli_query($db->getLink(), $query); if ($r !== true) { throw new Exception(mysqli_error($db->getLink())); } $projectList = $db->getQueryResults($search, 'access_data', 'AND', false, true); $project = $projectList[0]; return array('status' => true, 'operations_status' => $operations, 'notices' => $notices, 'new_access_list' => $newList, 'deltas' => $deltas, 'new_access_saved' => $newListString, 'project_id' => $pid); } catch (Exception $e) { return array('status' => false, 'error' => $e->getMessage(), 'human_error' => 'Server error processing access changes'); } }
<?php } ?> </results> <?php } else { if ($_REQUEST['type'] == 'friends') { $matchedusers = array(); $searcharray = array(); $userpros = array(); foreach ($_SESSION['friends'] as $user) { $userpro = getminipro($user); $searcharray[$user] = $userpro['username']; $userpros[$user] = $userpro; } $matchedusers = array_find($_REQUEST['key'], $searcharray); ?> <users> <?php foreach ($matchedusers as $user) { $userpro = $userpros[$user]; ?> <user> <userid><?php echo $userpro['userid']; ?> </userid> <username><?php echo $userpro['username']; ?> </username> <propic><?php
function update_combat($planet_id = 0, $update_to = '') { $this->log[] = 'Update Combat'; if (empty($update_to)) { $update_to = $this->data->update_to(); } // ################################################## // Make sure any navy groups prior to now have landed { if (empty($planet_id)) { $this->sql->where(array(array('tasks', 'round_id', $_SESSION['round_id']), array('tasks', 'type', TASK_NAVY), array('tasks', 'completion', $update_to, '<='))); $this->sql->orderby(array(array('tasks', 'planet_id', 'asc'), array('tasks', 'completion', 'asc'))); $this->sql->limit(1); $db_result = $this->sql->execute(); while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) { $this->data->updater->task_navy($db_row); } } // } list($combat, $info, $blueprints) = $this->getAllInformation($planet_id, $update_to); if (empty($combat)) { return; } // ################################################## // Loop through all combat { foreach ($combat as $planet_id => $current) { $this->log[] = 'Combat: Updating ' . $planet_id; $reports = array(); $last_update = $update_to - $current['combat']['completion']; $time_left = $last_update % $info['round']['combattick']; $combat_updates = floor($last_update / $info['round']['combattick']) + 1; // ################################################## // Update however many times combat happened in this time { for ($i = 0; $i < $combat_updates; $i++) { // Start running combat $this->log[] = 'Combat: Update ' . $i; $combat_report = array(); $current['combat']['rounds']++; // If no kingdoms are present no battle. $fighting = false; $kingdoms = array_keys($current['sudo']['army']['kingdoms'] + $current['sudo']['navy']['kingdoms'] + array($info['planets'][$planet_id]['kingdom_id'] => true)); foreach ($kingdoms as $kingdom_id) { $variable = array_diff($kingdoms, array_keys($info['kingdoms'][$kingdom_id]['allies']) + array($kingdom_id)); if (!empty($variable)) { $fighting = true; break; } } if (!$fighting) { // nobody won // delete combat $db_query = "DELETE FROM `combat` WHERE `combat_id` = '" . $current['combat']['combat_id'] . "' LIMIT 1"; $db_result = mysql_query($db_query); $this->log[] = 'Combat: No combat'; // go to the next planet for combat continue 2; } $after_combat = $current; // Repeat for army and navy units foreach ($this->type_array as $type) { $this->log[] = 'Combat: Type: ' . $type; $storedCombatDamage = array(); foreach ($current['sudo'][$type]['kingdoms'] as $kingdom_id => $groups) { $kingdom = $info['kingdoms'][$kingdom_id]; $this->log[] = 'Combat: Kingdom: ' . $kingdom_id; $find = array('kingdom_id' => array_keys($kingdom['allies'])); $find['kingdom_id'][] = $kingdom_id; foreach ($groups as $group_id => $units) { $group = $info['groups'][$type][$group_id]; $this->log[] = 'Combat: Group: ' . $group_id; foreach ($units as $unit_id => $unit_count) { $unit = $blueprints[$type][$unit_id]; $this->log[] = 'Combat: Unit: ' . $unit_id; foreach ($unit['weapons'] as $weapon_id => $weapon_count) { $weapon = $blueprints['weapon'][$weapon_id]; $this->log[] = 'Combat: Weapon: ' . $weapon_id; // Filter remaining groups against kingdom allies $targets['groups'] = array_find($find, $after_combat['sudo'][$type]['groups'], true); if (empty($targets['groups'])) { $this->log[] = 'Combat: Empty Targets'; // This kingdom is out of targets // Continue with the next kingdom continue 4; } // Rate of Fire Spray: Weapons with a high rof should have decreased accuracy. $rof_spray = pow($weapon['rateoffire'], 0.9) / $weapon['rateoffire']; $ammo = $unit_count * $weapon_count * $weapon['rateoffire'] * $weapon['accuracy'] * $rof_spray / 100; $this->log[] = 'Combat: Ammo: ' . $ammo; $targets_left = true; if (isset($targeted)) { unset($targeted); } // Repeat combat until we're out of targets or ammo while ($ammo > 0 && $targets_left) { $targets['groups'] = array_find($find, $after_combat['sudo'][$type]['groups'], true); if (!empty($group['targets'][$weapon_id]) && empty($targeted['group'])) { $target_type = $group['targets'][$weapon_id]; $targeted['group'] = true; $this->log[] = 'Combat: Target: Group: ' . $target_type; } elseif (!empty($weapon['targets'][$weapon_id]) && empty($targeted['weapon'])) { $target_type = $weapon['targets'][$weapon_id]; $targeted['weapon'] = true; $this->log[] = 'Combat: Target: Weapon: ' . $target_type; } else { $targets['random'] = $targets['groups']; if (!empty($targets['random'])) { $target_type = array_rand($targets['random']); unset($targets['random'][$target_type]['kingdom_id']); $target_type = array_rand($targets['random'][$target_type]); } else { $targets_left = false; $target_type = 0; } $this->log[] = 'Combat: Target: Random: ' . $target_type; $targeted['random'] = true; } // Filters units $targets['active'] = array_find(array('array_find:key' => $target_type), $targets['groups']); if (empty($targets['active'])) { $this->log[] = 'Combat: No targets of that type.'; if (!empty($targeted['random'])) { continue 5; } else { continue; } } // Associated Shuffle (maintain keys while shuffling values) $targets['active'] = ashuffle($targets['active']); foreach ($targets['active'] as $target_group_id => $unit_types) { $target_kingdom_id = $unit_types['kingdom_id']; $target_kingdom = $info['kingdoms'][$target_kingdom_id]; unset($unit_types['kingdom_id']); $this->log[] = 'Combat: Target Kingdom: ' . $target_kingdom_id; $this->log[] = 'Combat: Target Group: ' . $target_group_id; foreach ($unit_types[$target_type] as $target_id => $target_count) { $target = $blueprints[$type][$target_id]; $this->log[] = 'Combat: Target Unit: ' . $target_id; // COMBAT CALCULATIONS START HERE! // combat calculations $rand = rand(15, 25) / 10; if (empty($info['round']['combat_engine'])) { $info['round']['combat_engine'] = 'xenocide'; } switch ($info['round']['combat_engine']) { case 'x^2': // Random here, random there $random_factor = rand(80, 120) / 100; /* * Attack vs Defense balance * Half of the shots will hit by default. * 1% to 99% are valid. 0% and 100% are not. * 1/100 = 2% * 10/100 = 26% * 10/90 = 27.1% * 20/80 = 35% * 30/70 = 41.2% * 40/60 = 45.7% * 50/50 (1/1) = 50% * 100/1 = 98% */ $combat_balance = log($unit['attack'] / $target['defense']) * 24 + 50; $combat_balance /= 100 / $random_factor; $hits = $ammo * $combat_balance; if ($hits < 0) { $hits = 0; } if ($weapon['power'] < $target['armor']) { // You just targeted a unit that has impenitrable armor; shots wasted. $damage = 0; $kills = 0; $ammo = 0; } else { // Single Shot Damage $damage = $weapon['damage'] * $this->calculate_ad_bonus($weapon['areadamage']); // We can't kill any more than we hit. rof_spray is already taken into account. $maxkills = $ammo; // if we can kill a single unit with one shot then we can kill as many as in our area. if ($damage > $target['hull']) { $maxkills *= $weapon['areadamage']; } $kills = $damage * $hits / $target['hull']; // If there are actually less targets than "killed", refund some unusd ammo. if ($kills > $target_count) { // Reverse calculate how much wasn't really fired, but only give half of that back. // (expended in the heat of battle). $ammo = floor(($kills - $target_count) * ($target['hull'] / $damage)); $hits -= $ammo; $ammo = floor($ammo / ($combat_balance / 0.5)); $kills = $target_count; } else { $ammo = 0; } // If we can't actually kill this many units (due to rof or ad)... if ($kills > $maxkills) { $kills = $maxkills; } else { if (floor($kills) != $kills) { if (!empty($storedCombatDamage[$target_kingdom_id][$target_id])) { $kills += $storedCombatDamage[$target_kingdom_id][$target_id]; } $leftover_kills = $kills - floor($kills); $chance_kill = rand(0, 10000); if ($leftover_kills > 0.5 && $chance_kill < $leftover_kills * 5000 || $chance_kill < pow($leftover_kills, 2) * 10000) { unset($storedCombatDamage[$target_kingdom_id][$target_id]); $kills = ceil($kills); } else { $storedCombatDamage[$target_kingdom_id][$target_id] = $leftover_kills; $kills = floor($kills); } } } $damage = $hits * $damage; } break; case 'toel': $modifier = 0.01; // porting over Ferret's areadamage calculation since ToeL doesn't account for it $damage = $weapon['damage'] * $this->calculate_ad_bonus($weapon['areadamage']); // $kills = 1 / $target['hull'] * $damage * $hits * $modifier * $weapon['power'] * sqrt(1 / ($weapon['damage'] * $target['armor']) * $weapon['power'] * $target['hull']); $hits2kill = ceil($target['hull'] / ($damage * $modifier * $weapon['power'] * sqrt($weapon['power'] * $target['hull'] / ($damage * $target['armor'])))); if ($hits2kill < 1 / $weapon['areadamage']) { $hits2kill = 1 / $weapon['areadamage']; } $kills = $ammo / $hits2kill; if ($kills > $target_count) { $kills = $target_count; } $hits = $kills * $hits2kill; $damage = $hits * $weapon['damage']; $ammo -= $hits; $remainder = $kills - floor($kills); if ($remainder > 0) { if (rand(0, 100) < $remainder) { $kills = ceil($kills); } else { $kills = floor($kills); } } break; case 'xenocide': default: if ($weapon['power'] < $target['armor']) { // You just tried to target a unit that has impenitrable armor; shots wasted. $hits = floor($ammo * ($unit['attack'] / $target['defense'] / $rand)); if ($hits > $ammo) { $hits = $ammo; } $damage = 0; $kills = 0; $ammo = 0; } else { $modifier = $weapon['power'] / $target['armor']; if ($weapon['power'] > $target['armor']) { $modifier = sqrt($modifier); } // New Area Damage Code $damage = $weapon['damage'] * $this->calculate_ad_bonus($weapon['areadamage']); // $weapon['damage'] replaced by $damage here for area damage. $hits2kill = $target['hull'] / ($damage * $modifier); $hits2kill = $hits2kill / ($unit['attack'] / $target['defense'] / $rand); // Area Damage cap on hits2kill if ($hits2kill < 1 / $weapon['areadamage']) { $hits2kill = 1 / $weapon['areadamage']; } $kills = $ammo / $hits2kill; if ($kills > $target_count) { $kills = $target_count; } $hits = $kills * $hits2kill; $damage = $hits * $weapon['damage']; $ammo -= $hits; $remainder = $kills - floor($kills); if ($remainder > 0) { if (rand(0, 100) < $remainder) { $kills = ceil($kills); } else { $kills = floor($kills); } } } } if (floor($kills) != $kills) { $kills = floor($kills); } $this->log[] = 'Combat: Hits: ' . $hits; $this->log[] = 'Combat: Damage: ' . $damage; $this->log[] = 'Combat: Killed: ' . $kills . ' / ' . $target_count; $this->log[] = 'Combat: Ammo Left: ' . $ammo; $score = $kills * $target['score']; if ($type == 'army') { $score *= 300; } $combat_report['details'][$kingdom_id][$type][$group_id][$unit_id][$weapon_id][] = array('target_unit_id' => $target_id, 'hits' => ceil($hits), 'damage' => ceil($damage), 'kills' => floor($kills)); if (empty($after_combat['combat']['scores'][$kingdom_id][$info['groups'][$type][$group_id]['player_id']])) { $after_combat['combat']['scores'][$kingdom_id][$info['groups'][$type][$group_id]['player_id']] = 0; } $after_combat['combat']['scores'][$kingdom_id][$info['groups'][$type][$group_id]['player_id']] += $score; $after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id] -= $kills; if (ceil($after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id]) != $after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id]) { $after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id] = ceil($after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id]); } if (empty($after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id])) { unset($after_combat['sudo'][$type]['groups'][$target_group_id][$target_type][$target_id]); } if (empty($after_combat['sudo'][$type]['groups'][$target_group_id][$target_type])) { unset($after_combat['sudo'][$type]['groups'][$target_group_id][$target_type]); } if (empty($after_combat['sudo'][$type]['groups'][$target_group_id]) || count($after_combat['sudo'][$type]['groups'][$target_group_id]) == 1) { unset($after_combat['sudo'][$type]['groups'][$target_group_id]); } $after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id][$target_group_id][$target_id] -= $kills; if (empty($after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id][$target_group_id][$target_id])) { unset($after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id][$target_group_id][$target_id]); } if (empty($after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id][$target_group_id])) { unset($after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id][$target_group_id]); } if (empty($after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id])) { unset($after_combat['sudo'][$type]['kingdoms'][$target_kingdom_id]); } $info['groups'][$type][$target_group_id]['units'][$target_id] -= $kills; if (empty($info['groups'][$type][$target_group_id]['units'][$target_id])) { unset($info['groups'][$type][$target_group_id]['units'][$target_id]); } $info['groups'][$type][$target_group_id]['size'] -= $blueprints[$type][$target_id]['size'] * $kills; if ($type == 'navy') { $info['groups'][$type][$target_group_id]['cargo_max'] -= $blueprints[$type][$target_id]['cargo'] * $kills; } // continue with the next weapon if ($ammo <= 0) { continue 4; } } } } } } } } // } // Going through each group it needs a way to see how many units of that kingdom were killed. // That would update the unit totals of the group but not any details. // // go through each kingdom's group. // what percent of the total units are in that group? // take that percent and multiply it by what the group did. // hits, damage, kills, etc // ################################################## // Build combat report { $this->log[] = 'Combat: Results'; foreach ($current['sudo'][$type]['kingdoms'] as $kingdom_id => $kingdom_groups) { $combat_report['names']['kingdoms'][$kingdom_id] = $info['kingdoms'][$kingdom_id]['name']; $combat_report['participants'][$kingdom_id][$type] = 0; foreach ($kingdom_groups as $group_id => $group_units) { $combat_report['names']['groups'][$type][$group_id] = $info['groups'][$type][$group_id]['name']; $combat_report['participants'][$kingdom_id][$type] += array_sum($group_units); foreach ($group_units as $unit_id => $unit_total) { $combat_report['names']['units'][$type][$unit_id] = $blueprints[$type][$unit_id]['name']; foreach ($blueprints[$type][$unit_id]['weapons'] as $weapon_id => $weapon_count) { $combat_report['names']['weapons'][$weapon_id] = $blueprints['weapon'][$weapon_id]['name']; } // How many were lost? $lost = $current['sudo'][$type]['kingdoms'][$kingdom_id][$group_id][$unit_id]; if (!empty($after_combat['sudo'][$type]['kingdoms'][$kingdom_id][$group_id][$unit_id])) { $lost -= $after_combat['sudo'][$type]['kingdoms'][$kingdom_id][$group_id][$unit_id]; } $remaining = 0; if (!empty($after_combat['sudo'][$type]['kingdoms'][$kingdom_id][$group_id][$unit_id])) { $remaining = $after_combat['sudo'][$type]['kingdoms'][$kingdom_id][$group_id][$unit_id]; } $combat_report['casualties'][$kingdom_id][$type][$group_id][$unit_id] = array('killed' => $lost, 'remaining' => $remaining); } } } // } } foreach ($combat_report['names']['kingdoms'] as $kingdom_id => $kingdomname) { if (empty($after_combat['sudo']['army']['kingdoms'][$kingdom_id]) && empty($after_combat['sudo']['navy']['kingdoms'][$kingdom_id])) { $combat_report['status'][$kingdom_id] = 2; } else { $combat_report['status'][$kingdom_id] = 0; } } $combat_report['header'] = array('defender' => $info['players'][$info['planets'][$planet_id]['player_id']]['name'], 'date' => $current['combat']['completion'], 'location' => array('name' => $info['planets'][$planet_id]['name'], 'planet_id' => $planet_id)); $current = $after_combat; // ################################################## // Check Victory Conditions { // victory conditions check $armies = count($current['sudo']['army']['kingdoms']); $navies = count($current['sudo']['navy']['kingdoms']); if ($armies == 0 && $navies == 0) { // nobody won // delete combat $db_query = "DELETE FROM `combat` WHERE `combat_id` = '" . $current['combat']['combat_id'] . "' LIMIT 1"; $db_result = mysql_query($db_query); $this->log[] = 'Combat: No groups on the planet'; // stop combat on this planet $reports[] = $combat_report; break; } else { // Check allies of all remaining kingdoms and calculate scores $fighting = false; $scores = array(); $kingdoms = array_keys($current['sudo']['army']['kingdoms'] + $current['sudo']['navy']['kingdoms']); foreach ($kingdoms as $kingdom_id) { $variable = array_keys($info['kingdoms'][$kingdom_id]['allies']); $variable[] = $kingdom_id; $variable = array_diff($kingdoms, $variable); if (!empty($variable)) { $fighting = true; break; } if (!empty($current['combat']['scores'][$kingdom_id])) { $scores[$kingdom_id] = array_sum($current['combat']['scores'][$kingdom_id]); } } if ($fighting) { $reports[] = $combat_report; $current['combat']['completion'] += $info['round']['combattick']; // still fighting. Next combat. continue; } if (!empty($scores)) { asort($scores); while ($winning_kingdom = array_pop($scores)) { if (empty($current['combat']['scores'][$winning_kingdom])) { continue; } asort($current['combat']['scores'][$winning_kingdom]); while ($winning_player = array_pop($current['combat']['scores'][$winning_kingdom])) { break; } } } if (empty($scores) || empty($winning_kingdom) || empty($winning_player)) { $winning_kingdom = $kingdoms[array_rand($kingdoms)]; if (empty($current['sudo']['navy']['kingdoms'][$winning_kingdom])) { $type = 'army'; } else { $type = 'navy'; } $winning_player = $info['groups'][$type][array_rand($current['sudo'][$type]['kingdoms'][$winning_kingdom])]['player_id']; } $combat_report['status'][$winning_kingdom] = 1; // Planet was lost if ($winning_kingdom != $info['planets'][$planet_id]['kingdom_id'] && !in_array($info['planets'][$planet_id]['kingdom_id'], $kingdoms)) { // ################################################## // TODO /* X Delete Combat X Figure out winning player_id X Set planet player_id, kingdom_id, & permissions = winner X Remove planet from players & kingdoms */ $this->data->updater->update_tasks($planet_id, $current['combat']['completion']); $this->data->updater->update_resources($planet_id, $current['combat']['completion']); $losing_player = $info['planets'][$planet_id]['player_id']; $losing_kingdom = $info['planets'][$planet_id]['kingdom_id']; $news = array('kingdom_id' => $winning_kingdom, 'kingdom_name' => $info['kingdoms'][$winning_kingdom]['name'], 'player_id' => $winning_player, 'player_name' => $info['players'][$winning_player]['name'], 'target_kingdom_id' => $losing_kingdom, 'target_kingdom_name' => $info['kingdoms'][$losing_kingdom]['name'], 'target_player_id' => $losing_player, 'target_player_name' => $info['players'][$losing_player]['name'], 'planet_id' => $planet_id, 'planet_name' => $info['planets'][$planet_id]['name'], 'posted' => $current['combat']['completion']); // ################################################## // Take score from losing player and kingdom. { $this->data->updater->update_score($planet_id, $info['planets'][$planet_id]['score'] * -1, SCORE_PLANET); // } // ################################################## // Delete combat now that it has been resolved. { $this->log[] = 'Combat: Combat winner: K#' . $winning_kingdom . ' P#' . $winning_player; $db_query = "DELETE FROM `combat` WHERE `combat_id` = '" . $current['combat']['combat_id'] . "' LIMIT 1"; $db_result = mysql_query($db_query); $db_query = "DELETE FROM `permissions` WHERE `id` = '" . $planet_id . "' AND `type` = '" . PERMISSION_PLANET . "'"; $db_result = mysql_query($db_query); //permissions_update_planets(); // } // ################################################## // Take planet from losing player and kingdom unset($info['players'][$losing_player]['planets'][$planet_id]); unset($info['kingdoms'][$losing_kingdom]['planets'][$planet_id]); // Give planet to winning player and kingdom $info['players'][$winning_player]['planets'][$planet_id] = true; $info['kingdoms'][$winning_kingdom]['planets'][$planet_id] = true; $info['planets'][$planet_id]['kingdom_id'] = $winning_kingdom; $info['planets'][$planet_id]['player_id'] = $winning_player; // } // ################################################## // Delete certain tasks on said planet { $db_query = "\n\t\t\t\t\t\t\tDELETE FROM `tasks`\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t`planet_id` = '" . $planet_id . "' AND\n\t\t\t\t\t\t\t\t`type` IN (" . TASK_RESEARCH . ", " . TASK_UPGRADE . ")"; $db_result = mysql_query($db_query); $db_query = "UPDATE `planets` SET `researching` = '0' WHERE `planet_id` = '" . $planet_id . "' LIMIT 1"; $db_result = mysql_query($db_query); // } // ################################################## // Remove warp time from planet { $info['planets'][$planet_id]['warptime_construction'] = 0; $info['planets'][$planet_id]['warptime_research'] = 0; // } // ################################################## // Take score from losing player and kingdom. { $this->data->updater->update_score($planet_id, $info['planets'][$planet_id]['score'], SCORE_PLANET); // } // ################################################## // If the player has no more planets left then // make them a prisoner of the winner { $loser_count = count($info['players'][$losing_player]['planets']); if ($loser_count == 0) { $db_query = "DELETE FROM `permissions` WHERE `id` = '" . $losing_player . "' AND `type` = '" . PERMISSION_PLAYER . "'"; $db_result = mysql_query($db_query); $info['players'][$losing_player]['kingdom_id'] = $winning_kingdom; $info['players'][$losing_player]['planets'] = array(); $info['players'][$losing_player]['rank'] = 0; unset($info['kingdoms'][$losing_kingdom]['members'][$losing_player]); $info['kingdoms'][$winning_kingdom]['members'][$losing_player] = true; $leftover_members = count($info['kingdoms'][$losing_kingdom]['members']); if ($leftover_members == 0) { $this->kingdom_defeated($losing_kingdom); add_news_entry(NEWS_KINGDOMDEFEATED, $news); } else { add_news_entry(NEWS_PLAYERCAPTURED, $news); } } else { add_news_entry(NEWS_PLANETCONQUERED, $news); } $reports[] = $combat_report; break; // } } elseif ($winning_kingdom == $info['planets'][$planet_id]['kingdom_id'] || in_array($info['planets'][$planet_id]['kingdom_id'], $kingdoms)) { // defender won // delete combat $db_query = "DELETE FROM `combat` WHERE `combat_id` = '" . $current['combat']['combat_id'] . "' LIMIT 1"; $db_result = mysql_query($db_query); $this->log[] = 'Combat: Winner is owner'; $reports[] = $combat_report; break; } } // } $current['combat']['completion'] += $info['round']['combattick']; $reports[] = $combat_report; // End running combat } // } // Store battle report(s) foreach ($reports as $value) { $insertreport = array(); $insertreport['round_id'] = $_SESSION['round_id']; $insertreport['report'] = $value; $insertreport['date'] = $value['header']['date']; $insertreport['planet_id'] = $planet_id; foreach ($value['status'] as $kingdom_id => $status) { $insertreport['kingdom_id'] = $kingdom_id; $insertreport['status'] = $status; $db_query = $this->sql->insert('combatreports', $insertreport); $db_result = mysql_query($db_query); } } $this->sql->set(array(array('combat', 'rounds', $current['combat']['rounds']), array('combat', 'completion', $current['combat']['completion']), array('combat', 'scores', serialize($current['combat']['scores'])), array('combat', 'beingupdated', 0))); $this->sql->where(array('combat', 'combat_id', $current['combat']['combat_id'])); $this->sql->limit(1); $db_result = $this->sql->execute(); // $db_query = "UPDATE `combat` SET `rounds` = `rounds` + '" . $combat_updates . "', `completion` = '" . $current['combat']['completion'] . "', `beingupdated` = '0' WHERE `combat_id` = '" . $current['combat']['combat_id'] . "' LIMIT 1"; // $db_result = mysql_query($db_query); // End updating planets } // } foreach ($this->type_array as $type) { foreach ($info['groups'][$type] as $group_id => $group) { if (empty($info['groups'][$type][$group_id]['units'])) { $info['groups'][$type][$group_id] = null; unset($info['groups'][$type][$group_id]); } } } }
foreach ($filelist as &$v) { if (isset($_SESSION['list'][$v['fid']])) { if ($_SESSION['list'][$v['fid']]['filename'] != $v['name']) { $fix->execute(array($v['name'], $v['fid'], $_SESSION['user_id'])); $check_result = '<td><font color="orange">数据库中的文件名错误,已经被自动修正。</font></td>'; } else { $check_result = '<td><font color="green">自动补档保护中</font></td>'; } $_SESSION['filecheck'][$v['fid']] = false; $check_result .= '<td><a href="' . $jumper . $_SESSION['list'][$v['fid']]['id'] . '" target="_blank">' . $jumper . $_SESSION['list'][$v['fid']]['id'] . '</a></td><td><a href="http://pan.baidu.com' . $_SESSION['list'][$v['fid']]['link'] . '">http://pan.baidu.com' . $_SESSION['list'][$v['fid']]['link'] . '</a></td>'; unset($_SESSION['list'][$v['fid']], $_SESSION['list_filenames'][$v['fid']]); } else { if (array_find($v['name'] . '/', $_SESSION['list_filenames']) !== false) { $check_result = '<td colspan="3"><font color="blue">文件夹内的文件被加入自动补档</font></td>'; $_SESSION['filecheck'][$v['fid']] = false; } elseif (array_find($v['name'], $_SESSION['list_filenames'], true) !== false) { $check_result = '<td colspan="3"><font color="blue">父文件夹被加入自动补档</font></td>'; $_SESSION['filecheck'][$v['fid']] = false; } else { $check_result = '<td colspan="3">本文件未加入自动补档</td>'; $_SESSION['filecheck'][$v['fid']] = true; } } if ($_SESSION['filecheck'][$v['fid']]) { ?> <tr><td><form method="post" action="add.php"><input type="hidden" name="fid" value="<?php echo $v['fid']; ?> " /><input type="hidden" name="filename" value="<?php echo $v['name']; ?>
/** * This function filters the content array * using it's details * * @global object $userquery * @param string $group * @param string $return * @return array */ function __filter_user_object_content($_group = null, $return = false, $cache = false) { if ($this->__get_filtered_content() && $cache === false) { return $this->__get_filtered_content(); } $groups = $this->___groups(); $group = $_group ? $_group : get('object_group'); if (!$this->__get_current_user()) { global $userquery; $user = $userquery->get_user_details(get('user'), false, true); $user = $this->__set_current_user($user); } else { $user = $this->__get_current_user(); } if (!$user) { return false; } if (!$group || !$groups[$group]) { $group = key($groups); } if ($groups[$group]) { foreach ($groups[$group] as $key => $value) { $info = $this->__extract_key_details($key); $section_disbaled = false; $is_private = false; $no_permission = false; $section_disbaled = $this->_confirm_section_enabled($value, $info); if (array_find('is_content', $info)) { $is_private = $this->_confirm_private($value, $key); $no_permission = $this->_confirm_permissions($value, $key); } else { foreach ($value as $type => $content) { $content_pri = $this->_confirm_private($content, $type); $content_per = $this->_confirm_permissions($content, $type); if ($content_pri && $content_per) { $remove_content[] = $content_pri; $remove_content[] = $content_per; } else { if ($content_pri) { $remove_content[] = $content_pri; } else { if ($content_per) { $remove_content[] = $content_per; } } } } } if ($section_disbaled || $is_private || $no_permission) { continue; } if (isset($remove_content)) { foreach ($remove_content as $rc) { if ($groups[$group][$key][$rc]) { unset($groups[$group][$key][$rc]); } } $value = $groups[$group][$key]; } unset($remove_content); if ($value) { $filtered_content[$key] = $value; } } return $return ? $filtered_content : $this->__set_filtered_content($filtered_content); } }
/** * @inheritdoc */ public function removeAddress($address) { unset($this->addresses[array_find($address)]); }
function array_compare($tax_rates) { $after = array(); foreach ($tax_rates as $key => $val) { $first_two = array("label" => $val['label'], "compound" => $val['compound'], 'rate' => $val['rate'], 'shipping' => $val['shipping'], 'is_all_states' => $val['is_all_states'], 'class' => $val['class']); $found = array_find($first_two, $after); if ($found !== false) { $combined = $after[$found]["state"]; $combined2 = $after[$found]["country"]; $combined = !is_array($combined) ? array($combined) : $combined; $combined2 = !is_array($combined2) ? array($combined2) : $combined2; $after[$found] = array_merge($first_two, array("state" => array_merge($combined, array($val['state'])), "country" => array_merge($combined2, array($val['country'])))); } else { $after = array_merge($after, array(array_merge($first_two, array("state" => $val['state'], "country" => $val['country'])))); } } return $after; }
continue; } ?> <h2><?php echo ucwords($tableName); ?> </h2> <table class="table table-striped table-hover users-table" style="margin: 0;"> <tbody target="<?php echo $tableName; ?> "> <?php foreach ($data as $index => $row) { $keys = array_keys($row); $key = array_find($search_text, $row); if ($key == FALSE) { continue; } if ($index == 0) { ?> <tr> <th class="text-center" style="border-right: 1px solid #ccc;color:#fff;">S.No</th> <th class="text-center" style="border-right: 1px solid #ccc;color:#fff;"><?php echo ucwords(str_replace("_", ' ', $key)); ?> </th> </tr> <?php } ?>
/** * FUNCTION USED TO GET THUMBNAIL * @param ARRAY video_details, or videoid will also work */ function get_thumb($vdetails, $num = 'default', $multi = false, $count = false, $return_full_path = true, $return_big = true, $size = false) { //echo $size; global $db, $Cbucket, $myquery; $num = $num ? $num : 'default'; #checking what kind of input we have if (is_array($vdetails)) { if (empty($vdetails['title'])) { #check for videoid if (empty($vdetails['videoid']) && empty($vdetails['vid']) && empty($vdetails['videokey'])) { if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } else { if (!empty($vdetails['videoid'])) { $vid = $vdetails['videoid']; } elseif (!empty($vdetails['vid'])) { $vid = $vdetails['vid']; } elseif (!empty($vdetails['videokey'])) { $vid = $vdetails['videokey']; } else { if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } } } } else { if (is_numeric($vdetails)) { $vid = $vdetails; } else { if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } } #checking if we have vid , so fetch the details if (!empty($vid)) { $vdetails = get_video_details($vid); } if (empty($vdetails['title'])) { if ($multi) { return default_thumb(); } return default_thumb(); } #Checking if there is any custom function for if (count($Cbucket->custom_get_thumb_funcs) > 0) { foreach ($Cbucket->custom_get_thumb_funcs as $funcs) { //Merging inputs $in_array = array('num' => $num, 'multi' => $multi, 'count' => $count, 'return_full_path' => $return_full_path, 'return_big' => $return_big, 'size' => $size); if (!empty($vdetails['files_thumbs_path']) && $funcs == 'server_thumb') { $funcs = "ms_server_thumb"; } if (function_exists($funcs)) { $func_returned = $funcs($vdetails, $in_array); if ($func_returned) { return $func_returned; } } } } // echo "hooooo"; #get all possible thumbs of video $thumbDir = isset($vdetails['file_directory']) && $vdetails['file_directory'] ? $vdetails['file_directory'] : ""; if (!isset($vdetails['file_directory'])) { $justDate = explode(" ", $vdetails['date_added']); $thumbDir = implode("/", explode("-", array_shift($justDate))); } if (substr($thumbDir, strlen($thumbDir) - 1) !== "/") { $thumbDir .= "/"; } //$justDate = explode(" ", $vdetails['date_added']); //$dateAdded = implode("/", explode("-", array_shift($justDate))); $file_dir = ""; if (isset($vdetails['file_name']) && $thumbDir) { $file_dir = "/" . $thumbDir; } $vid_thumbs = glob(THUMBS_DIR . "/" . $file_dir . $vdetails['file_name'] . "*"); #replace Dir with URL if (is_array($vid_thumbs)) { foreach ($vid_thumbs as $thumb) { if (file_exists($thumb) && filesize($thumb) > 0) { $thumb_parts = explode('/', $thumb); $thumb_file = $thumb_parts[count($thumb_parts) - 1]; if (!is_big($thumb_file) || $return_big) { if ($return_full_path) { $thumbs[] = THUMBS_URL . '/' . $thumbDir . $thumb_file; } else { $thumbs[] = $thumb_file; } } } elseif (file_exists($thumb)) { unlink($thumb); } } } if (count($thumbs) == 0) { if ($count) { return count($thumbs); } if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } else { if ($multi) { return $thumbs; } if ($count) { return count($thumbs); } //Now checking for thumb if ($num == 'default') { $num = $vdetails['default_thumb']; } if ($num == 'big' || $size == 'big') { $num = 'big-' . $vdetails['default_thumb']; if (!file_exists(THUMBS_DIR . '/' . $vdetails['file_name'] . '-' . $num . '.jpg')) { $num = 'big'; } } $default_thumb = array_find($vdetails['file_name'] . '-' . $num, $thumbs); if (!empty($default_thumb)) { return $default_thumb; } return $thumbs[0]; } }
function doAWebValidate($get) { /*** * ***/ $amphibiaWebListTarget = 'http://amphibiaweb.org/amphib_names.txt'; $localAWebTarget = dirname(__FILE__) . '/aweb_list.txt'; $dayOffset = 60 * 60 * 24; $response = array('status' => false, 'args_provided' => $get, 'notices' => array()); # We need, at minimum, genus and species if (empty($get['genus'])) { $response['error'] = 'MISSING_ARGUMENTS'; $response['human_error'] = 'You need to a genus and species to validate'; returnAjax($response); } if (empty($get['species'])) { $response["notices"][] = "No species provided. Using generic species"; $get["species"] = "sp"; } # How old is our copy? if (filemtime($localAWebTarget) + $dayOffset < time()) { # Fetch a new copy $aWebList = file_get_contents($amphibiaWebListTarget); $h = fopen($localAWebTarget, 'w+'); $bytes = fwrite($h, $aWebList); fclose($h); if ($bytes === false) { $response['notices'][] = "Couldn't write updated AmphibiaWeb list to {$localAWebTarget}"; } } $response['aweb_list_age'] = time() - filemtime($localAWebTarget); $response['aweb_list_max_age'] = $dayOffset; //$aWebList = file_get_contents($localAWebTarget); $aWebListArray = array_map('tsvHelper', file($localAWebTarget)); /* * For a given row, we have this numeric key to real id mapping: * * Object {0: "order", 1: "family", 2: "subfamily", 3: "genus", 4: "subgenus", 5: "species", 6: "common_name", 7: "gaa_name", 8: "synonymies", 9: "itis_names", 10: "iucn", 11: "isocc", 12: "intro_isocc", 13: "aweb_uid", 14: "uri/guid", 15: "taxon_notes_public"} */ $genusList = array(); $synonymList = array(); $synonymGenusList = array(); foreach ($aWebListArray as $k => $entry) { if ($k == 0) { continue; } # Prevent match on "genus" $genus = strtolower($entry[3]); $genusList[$genus] = $k; $gaaEntry = strtolower($entry[7]); if (!empty($gaaEntry)) { if (strpos($gaaEntry, ',') !== false) { $synon = explode(',', $gaaEntry); } else { $synon = array($gaaEntry); } foreach ($synon as $oldName) { $key = trim($oldName); $synonymList[$key] = $k; $oldGenus = explode(' ', $key); $oldGenus = $oldGenus[0]; $synonymGenusList[$oldGenus] = $k; } } $synonEntry = strtolower($entry[8]); if (!empty($synonEntry)) { if (strpos($synonEntry, ',') !== false) { $synon = explode(',', $synonEntry); } else { $synon = array($synonEntry); } foreach ($synon as $oldName) { $key = trim($oldName); $synonymList[$key] = $k; $oldGenus = explode(' ', $key); $oldGenus = $oldGenus[0]; $synonymGenusList[$oldGenus] = $k; } } $itisEntry = strtolower($entry[9]); if (!empty($itisEntry)) { if (strpos($itisEntry, ',') !== false) { $itis = explode(',', $itisEntry); } else { $itis = array($itisEntry); } foreach ($itis as $oldName) { $key = trim($oldName); $synonymList[$key] = $k; $oldGenus = explode(' ', $key); $oldGenus = $oldGenus[0]; $synonymGenusList[$oldGenus] = $k; } } } # First check: Does the genus exist? $providedGenus = strtolower($get['genus']); $providedSpecies = strtolower($get['species']); if (!array_key_exists($providedGenus, $genusList)) { # Are they using an old name? $testSpecies = $providedGenus . ' ' . $providedSpecies; if (!array_key_exists($testSpecies, $synonymList)) { # For 'nov. sp.', 'sp.' variants, and with following digits, # check genus only # See # http://regexr.com/3d1kb if (array_key_exists($providedGenus, $synonymGenusList) && preg_match('/^(nov[.]{0,1} ){0,1}(sp[.]{0,1}([ ]{0,1}\\d+){0,1})$/m', $providedSpecies)) { # OK, they were just looking for a genus anyway $row = $synonymGenusList[$providedGenus]; $aWebMatch = $aWebListArray[$row]; $aWebCols = $aWebListArray[0]; $aWebPretty = array(); $skipCols = array('species', 'gaa_name', 'common_name', 'synonymies', 'itis_names', 'iucn', 'isocc', 'intro_isocc'); foreach ($aWebMatch as $key => $val) { $prettyKey = $aWebCols[$key]; if (!in_array($prettyKey, $skipCols)) { $prettyKey = str_replace('/', '_or_', $prettyKey); if (strpos($val, ',') !== false) { $val = explode(',', $val); foreach ($val as $k => $v) { $val[$k] = trim($v); } } $aWebPretty[$prettyKey] = $val; } } # Pretty format the 'nov sp'/'sp'/etc $aWebPretty['species'] = preg_match('/^nov[.]{0,1} (sp[.]{0,1}([ ]{0,1}(\\d+)){0,1})$/m', $providedSpecies) ? trim(preg_replace('/^nov[.]{0,1} (sp[.]{0,1}([ ]{0,1}(\\d+)){0,1})$/m', 'nov. sp. $3', $providedSpecies)) : trim(preg_replace('/^sp[.]{0,1}([ ]{0,1}(\\d+)){0,1}$/m', 'sp. $2', $providedSpecies)); $response['status'] = true; $response['notices'][] = "Your genus '{$providedGenus}' was a synonym in the AmphibiaWeb database. It was automatically converted to the canonical genus."; $response['notices'][] = "You provided a generic species '" . $aWebPretty['species'] . "'. Only the genus has been validated."; $response['original_taxon'] = $providedGenus; # Note that Unicode characters may return escaped! eg, \u00e9. $response['validated_taxon'] = $aWebPretty; returnAjax($response); } # Nope, just failed $response['error'] = 'INVALID_GENUS'; $response['human_error'] = "'<span class='genus'>{$providedGenus}</span>' isn't a valid AmphibiaWeb genus (checked " . sizeof($genusList) . " genera), nor is '<span class='sciname'>{$testSpecies}</span>' a recognized synonym."; returnAjax($response); } # Ah, a synonym eh? $row = $synonymList[$testSpecies]; $aWebMatch = $aWebListArray[$row]; $aWebCols = $aWebListArray[0]; $aWebPretty = array(); foreach ($aWebMatch as $key => $val) { $prettyKey = $aWebCols[$key]; $prettyKey = str_replace('/', '_or_', $prettyKey); if (strpos($val, ',') !== false) { $val = explode(',', $val); foreach ($val as $k => $v) { $val[$k] = trim($v); } } $aWebPretty[$prettyKey] = $val; } if (empty($aWebPretty['subspecies']) && !empty($get['subspecies'])) { $aWebPretty['subspecies'] = $get['subspecies']; } $response['status'] = true; $response['notices'][] = "Your entry '{$testSpecies}' was a synonym in the AmphibiaWeb database. It was automatically converted to the canonical taxon."; $response['original_taxon'] = $testSpecies; # Note that Unicode characters may return escaped! eg, \u00e9. $response['validated_taxon'] = $aWebPretty; returnAjax($response); } # Cool, so the genus exists. $speciesList = array(); $speciesListComparative = array(); foreach ($aWebListArray as $row => $entry) { if ($row == 0) { continue; } # Prevent match on "species" $genus = strtolower($entry[3]); if ($genus == $providedGenus) { $species = $entry[5]; $speciesList[$species] = $row; $speciesListComparative[] = $species; } } if (!array_key_exists($providedSpecies, $speciesList)) { # Are they using an old name? $testSpecies = $providedGenus . ' ' . $providedSpecies; if (!array_key_exists($testSpecies, $synonymList)) { # For 'nov. sp.', 'sp.' variants, and with following digits, # check genus only # See # http://regexr.com/3d1kb if (preg_match('/^(nov[.]{0,1} ){0,1}(sp[.]{0,1}([ ]{0,1}\\d+){0,1})$/m', $providedSpecies)) { # OK, they were just looking for a genus anyway $row = $genusList[$providedGenus]; $aWebMatch = $aWebListArray[$row]; $aWebCols = $aWebListArray[0]; $aWebPretty = array(); $skipCols = array('species', 'gaa_name', 'common_name', 'synonymies', 'itis_names', 'iucn', 'isocc', 'intro_isocc'); foreach ($aWebMatch as $key => $val) { $prettyKey = $aWebCols[$key]; if (!in_array($prettyKey, $skipCols)) { $prettyKey = str_replace('/', '_or_', $prettyKey); if (strpos($val, ',') !== false) { $val = explode(',', $val); foreach ($val as $k => $v) { $val[$k] = trim($v); } } $aWebPretty[$prettyKey] = $val; } } # Pretty format the 'nov sp'/'sp'/etc $aWebPretty['species'] = preg_match('/^nov[.]{0,1} (sp[.]{0,1}([ ]{0,1}(\\d+)){0,1})$/m', $providedSpecies) ? trim(preg_replace('/^nov[.]{0,1} (sp[.]{0,1}([ ]{0,1}(\\d+)){0,1})$/m', 'nov. sp. $3', $providedSpecies)) : trim(preg_replace('/^sp[.]{0,1}([ ]{0,1}(\\d+)){0,1}$/m', 'sp. $2', $providedSpecies)); $response['notices'][] = "You provided a generic species '" . $aWebPretty['species'] . "'. Only the genus has been validated."; $response['status'] = true; # Note that Unicode characters may return escaped! eg, \u00e9. $response['validated_taxon'] = $aWebPretty; returnAjax($response); } # Gender? Latin sucks. # See: sylvaticus vs sylvatica if (strlen($providedSpecies) > 3) { $key = array_find(substr($providedSpecies, 0, -3), $speciesListComparative); } else { $key = false; } if ($key !== false) { $response['notices'][] = 'FUZZY_SPECIES_MATCH'; $response['notices'][] = "This is just a probable match for your entry '{$testSpecies}'. We ignored the species gender ending for you. If this isn't a match, your species is invalid"; $trueSpecies = $speciesListComparative[$key]; $aWebRow = $speciesList[$trueSpecies]; $aWebMatch = $aWebListArray[$aWebRow]; $aWebCols = $aWebListArray[0]; $aWebPretty = array(); foreach ($aWebMatch as $key => $val) { $prettyKey = $aWebCols[$key]; $prettyKey = str_replace('/', '_or_', $prettyKey); if (strpos($val, ',') !== false) { $val = explode(',', $val); foreach ($val as $k => $v) { $val[$k] = trim($v); } } $aWebPretty[$prettyKey] = $val; } if (empty($aWebPretty['subspecies']) && !empty($get['subspecies'])) { $aWebPretty['subspecies'] = $get['subspecies']; } $response['status'] = true; $response['original_taxon'] = $testSpecies; # Note that Unicode characters may return escaped! eg, \u00e9. $response['validated_taxon'] = $aWebPretty; returnAjax($response); } # Nope, just failed $response['error'] = 'INVALID_SPECIES'; $response['human_error'] = "'{$providedSpecies}' isn't a valid AmphibiaWeb species in the genus '{$providedGenus}', nor is '{$testSpecies}' a recognized synonym."; $response['human_error_html'] = "'<span class='species'>{$providedSpecies}</span>' isn't a valid AmphibiaWeb species in the genus '<span class='genus'>{$providedGenus}</span>', nor is '<span class='sciname'>{$testSpecies}</span>' a recognized synonym."; returnAjax($response); } # Let's play the synonym game again! $row = $synonymList[$testSpecies]; $aWebMatch = $aWebListArray[$row]; $aWebCols = $aWebListArray[0]; $aWebPretty = array(); foreach ($aWebMatch as $key => $val) { $prettyKey = $aWebCols[$key]; $prettyKey = str_replace('/', '_or_', $prettyKey); if (strpos($val, ',') !== false) { $val = explode(',', $val); foreach ($val as $k => $v) { $val[$k] = trim($v); } } $aWebPretty[$prettyKey] = $val; } if (empty($aWebPretty['subspecies']) && !empty($get['subspecies'])) { $aWebPretty['subspecies'] = $get['subspecies']; } $response['status'] = true; $response['notices'][] = "Your entry '{$testSpecies}' was a synonym in the AmphibiaWeb database. It was automatically converted to the canonical taxon."; $response['original_taxon'] = $testSpecies; # Note that Unicode characters may return escaped! eg, \u00e9. $response['validated_taxon'] = $aWebPretty; returnAjax($response); } # The genus and species is valid. # Prep for the user response $aWebRow = $speciesList[$providedSpecies]; $aWebMatch = $aWebListArray[$aWebRow]; $aWebCols = $aWebListArray[0]; $aWebPretty = array(); foreach ($aWebMatch as $key => $val) { $prettyKey = $aWebCols[$key]; $prettyKey = str_replace('/', '_or_', $prettyKey); if (strpos($val, ',') !== false) { $val = explode(',', $val); foreach ($val as $k => $v) { $val[$k] = trim($v); } } $aWebPretty[$prettyKey] = $val; } if (empty($aWebPretty['subspecies']) && !empty($get['subspecies'])) { $aWebPretty['subspecies'] = $get['subspecies']; } $response['status'] = true; # Note that Unicode characters may return escaped! eg, \u00e9. $response['validated_taxon'] = $aWebPretty; returnAjax($response); }
/** * Validate all modules in the database */ function acp_modules() { global $db, $user, $template, $phpEx, $phpbb_root_path; $this->_section_data['acp_modules'] = array('NAME' => 'ACP_MODULES_SETTINGS', 'TITLE' => 'ROWS'); $modules = $existing_modules = array(); get_acp_modules($this->db_cleaner->data->acp_modules, $modules); // Find extra modules $sql = 'SELECT * FROM ' . MODULES_TABLE; $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $existing_modules[] = $row['module_langname']; if (in_array($row['module_langname'], $modules)) { continue; } $module = $row['module_langname']; $module_id = $row['module_id']; $sql = 'SELECT * FROM ' . MODULES_TABLE . ' WHERE module_id = ' . $row['parent_id'] . ''; $res = $db->sql_query($sql); $row = $db->sql_fetchrow($res); $parent = $row['module_langname']; $class = $row['module_class']; $parent_id = $row['module_id']; if ($parent) { $link = append_sid("{$phpbb_root_path}adm/index.{$phpEx}", 'i=acp_modules&sid=' . $user->data['session_id'] . '&mode=' . $class . '&parent_id=' . $parent_id . ''); $module_mame = isset($user->lang[$parent]) ? '<b>' . $user->lang[$parent] . '</b>' : '<i>' . $user->lang['UNDEFINED'] . '</i>'; } else { $link = append_sid("{$phpbb_root_path}adm/index.{$phpEx}", 'i=acp_modules&sid=' . $user->data['session_id'] . '&mode=' . $class . ''); $module_mame = ''; } $db->sql_freeresult($res); $this->_section_data['acp_modules']['ITEMS'][] = array('NAME' => '' . $module . ' (' . $module_id . ')' . $user->lang['GO_TO_ACP'] . ' <a href="' . $link . '" target="_blank">' . $module_mame . '</a> [' . $parent . ' (' . $parent_id . ')]', 'FIELD_NAME' => $module_id, 'MISSING' => false, 'FIND' => append_sid("" . STK_ROOT_PATH . "finder." . PHP_EXT . "", 'm=' . $module . '')); if ($this->_has_changes === false) { $this->_has_changes = true; } } $db->sql_freeresult($result); //Find missing modules foreach ($modules as $module) { if (!in_array($module, $existing_modules)) { $key = array_find($this->db_cleaner->data->acp_modules, $module); if ($key) { $parent_key = array_find($this->db_cleaner->data->acp_modules, $key); } if (isset($parent_key)) { $cat_key = array_find($this->db_cleaner->data->acp_modules, $parent_key); } if ($cat_key) { $mode = $cat_key; } if (!$cat_key) { $cat_key = $key; $mode = $parent_key; } $sql = 'SELECT module_id FROM ' . MODULES_TABLE . ' WHERE module_langname = \'' . $key . '\''; $res = $db->sql_query($sql); $row = $db->sql_fetchrow($res); $parent_id = $row['module_id']; $db->sql_freeresult($result); // Link to ACP manage module $link = $parent_id ? '<a style="color:#70AED3;" href="' . append_sid("{$phpbb_root_path}adm/index.{$phpEx}", 'i=acp_modules&sid=' . $user->data['session_id'] . '&mode=' . $mode . '&parent_id=' . $parent_id . '') . '" " target="_blank">' : ''; $module_langname = $user->lang($module); $parent_module_langname = $user->lang($key); $this->_section_data['acp_modules']['ITEMS'][] = array('NAME' => '' . $module_langname . ' (' . $module . ')' . $user->lang['GO_TO_ACP'] . $link . '' . $parent_module_langname . '</a>', 'FIELD_NAME' => strtolower($module), 'MISSING' => true); } if ($this->_has_changes === false) { $this->_has_changes = true; } } $template->assign_vars(array('NO_CHANGES_TEXT' => $user->lang['SECTION_NOT_CHANGED_EXPLAIN'][$this->db_cleaner->step_to_action[$this->db_cleaner->step]], 'NO_CHANGES_TITLE' => $user->lang['SECTION_NOT_CHANGED_TITLE'][$this->db_cleaner->step_to_action[$this->db_cleaner->step]])); $this->success_message = 'DATABASE_ROLE_DATA_SUCCESS'; }
/** * Delete non standart and add native phpBB modules */ function acp_modules($error, $selected) { global $db, $user, $phpbb_root_path, $phpEx, $umil; if (sizeof($selected)) { if (!class_exists('acp_modules')) { include $phpbb_root_path . 'includes/acp/acp_modules.' . $phpEx; $acp_tools = new acp_modules(); } $module_ids = $class = array(); foreach (array_keys($selected) as $module_id) { $module_ids[] = $module_id; } $sql = 'SELECT module_class, module_id FROM ' . MODULES_TABLE . ' WHERE ' . $db->sql_in_set('module_id', $module_ids) . ' ORDER BY module_id ASC'; $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $class[$row['module_id']] = $row['module_class']; } $db->sql_freeresult($result); foreach (array_keys($selected) as $module_id) { if (is_numeric($module_id)) { // Delete module $this->delete_module($module_id, $acp_tools, $class[$module_id]); } else { // Add module $module_langname = strtoupper($module_id); $key = array_find($this->db_cleaner->data->acp_modules, $module_langname); if ($key) { $sql = 'SELECT module_class, module_id FROM ' . MODULES_TABLE . ' WHERE module_langname = \'' . $key . '\''; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $module_class = $row['module_class']; if (!$module_class) { $error[] = '' . $user->lang['MODULE_ADD'] . ' «' . $module_langname . '» ' . $user->lang['NO_PARENT'] . ''; continue; } $parent_id = $row['module_id']; $k_ary = explode('_', $key); $base_name = '' . $module_class . '_' . strtolower(array_pop(explode('_', $key))) . ''; if ($module_langname == 'ACP_SEARCH_INDEX') { $base_name = 'acp_search'; } $info_file = "{$module_class}/info/{$base_name}.{$phpEx}"; $module_mode = $module_auth = ''; if (file_exists($phpbb_root_path . 'includes/' . $info_file)) { include_once $phpbb_root_path . 'includes/' . $info_file; $classname = '' . $base_name . '_info'; $info = new $classname(); $module = $info->module(); unset($info); foreach ($module['modes'] as $key => $value) { if ($value['title'] == $module_langname) { $module_mode = $key; $module_auth = $value['auth']; } } } } $data = array('module_langname' => $module_langname, 'module_basename' => $base_name, 'module_mode' => $module_mode, 'module_auth' => $module_auth); $result = $umil->module_add($module_class, $parent_id, $data); $error[] = '«' . $user->lang[$module_langname] . '» ' . $result . ''; } } } return $error; }
function checkinstalldir() { $configfiles = scandir('config'); // Check the [array] config dir for a filename containing 'statsconfig' $statsconfig_exists = array_find('statsconfig', $configfiles); if (is_dir('install') && $statsconfig_exists) { echo '<html> <head> <title>XLRstats B3 - ERROR</title> <style type="text/css"> body{text-align: center; font-family:Arial, Helvetica, sans-serif; font-weight: bold} </style> </head> <body> <p>We found a valid configfile for XLRstats, seems you have finished installation.</p> <p>However, your installation directory is still at the default location!<br /> Before you can continue, you need to</p> <p style="font-size:1.5em; color: red"><i>Remove</i> or <i>Rename</i> your installation directory.</p> </body> </html>'; exit; } elseif (is_dir('install')) { // Not installed yet, forward to the install folder $install_loc = httplink() . 'install/'; header("Location: {$install_loc}"); } }
function get_server_img($params) { global $__resize_thumbs; if (!$__resize_thumbs) { return; } $w = DEFAULT_WIDTH; $h = DEFAULT_HEIGHT; global $baseurl; $timthumb_path = CB_SERVER_THUMB_URL . '/timthumb.php?src='; //var_dump($params); $details = $params['details']; $output = $params['output']; $size = $params['size']; $default = array('t', 'm', 'l', 'o'); $thumbs = array(); if (!$details) { //var_dump("get default 1"); return get_photo_default_thumb($size, $output); } if (!is_array($details)) { $photo = $cbphoto->get_photo($details, true); } else { $photo = $details; } if (empty($photo['photo_id']) or empty($photo['photo_key'])) { return get_photo_default_thumb($size, $output); } if (empty($photo['filename']) or empty($photo['ext'])) { return get_photo_default_thumb($size, $output); } $params['photo'] = $photo; $path = PHOTOS_DIR; $directory = get_photo_date_folder($photo); $with_path = $params['with_path'] = $params['with_path'] === false ? false : true; $with_original = $params['with_orig']; $size = (!in_array($size, $default) or !$size) ? 't' : $size; if ($size == 'l') { $w = 320; $h = 250; } else { if ($size == 'm') { $w = 160; $h = 90; } else { if ($size == 't') { $w = 120; $h = 60; } } } list($width, $height) = explode('x', $params['size']); if (isset($width) && is_numeric($width) && isset($height) && is_numeric($height)) { $w = $width; $h = $height; } $tim_postfix = '&type=photos&h=' . $h . '&w=' . $w . '&zc=1'; if ($directory) { $directory .= '/'; } $path .= '/' . $directory; $filename = $photo['filename'] . '%s.' . $photo['ext']; $files = glob($path . sprintf($filename, '*')); global $cbphoto; if (!empty($files)) { foreach ($files as $file) { $thumb_name = explode("/", $file); $thumb_name = end($thumb_name); $thumb_type = $cbphoto->get_image_type($thumb_name); if ($with_original) { //$thumbs[] = ( ( $with_path ) ? PHOTOS_URL.'/' : '' ) . $directory . $thumb_name; $thumbs[] = $timthumb_path . $thumb_name . '&directory=photos/' . $directory . $tim_postfix; } else { if (!empty($thumb_type)) { //$thumbs[] = ( ( $with_path ) ? PHOTOS_URL.'/' : '' ) . $directory . $thumb_name; $thumbs[] = $timthumb_path . $thumb_name . '&directory=photos/' . $directory . $tim_postfix; } } } if (empty($output) or $output == 'non_html') { if ($params['assign'] and $params['multi']) { assign($params['assign'], $thumbs); } else { if ($params['multi']) { return $thumbs; } else { $search_name = sprintf($filename, "_" . $size); $return_thumb = array_find($search_name, $thumbs); if (empty($return_thumb)) { return get_photo_default_thumb($size, $output); } else { if ($params['assign']) { assign($params['assign'], $return_thumb); } else { return $return_thumb; } } } } } if ($output == 'html') { $search_name = sprintf($filename, "_" . $size); $src = array_find($search_name, $thumbs); $src = empty($src) ? get_photo_default_thumb($size) : $src; $attrs = array('src' => $src); if (phpversion < '5.2.0') { global $json; } if ($json) { $image_details = $json->json_decode($photo['photo_details'], true); } else { $image_details = json_decode($photo['photo_details'], true); } if (empty($image_details) or empty($image_details[$size])) { $dem = getimagesize(str_replace(PHOTOS_URL, PHOTOS_DIR, $src)); $width = $dem[0]; $height = $dem[1]; /* UPDATEING IMAGE DETAILS */ $cbphoto->update_image_details($photo); } else { $width = $image_details[$size]['width']; $height = $image_details[$size]['height']; } if ($params['width'] and is_numeric($params['width']) and ($params['height'] and is_numeric($height))) { $width = $params['width']; $height = $params['height']; } else { if ($params['width'] and is_numeric($params['width'])) { $height = round($params['width'] / $width * $height); $width = $params['width']; } else { if ($params['height'] and is_numeric($height)) { $width = round($params['height'] * $width / $height); $height = $params['height']; } } } //$attrs[ 'width' ] = $width; //$attrs[ 'height' ] = $height; $attrs['id'] = ($params['id'] ? $params['id'] . '_' : 'photo_') . $photo['photo_id']; if ($params['class']) { $attrs['class'] = mysql_clean($params['class']); } if ($params['align']) { $attrs['align'] = mysql_clean($params['align']); } $attrs['title'] = $photo['photo_title']; if (isset($params['title']) and $params['title'] == '') { unset($attrs['title']); } $attrs['alt'] = TITLE . ' - ' . $photo['photo_title']; $anchor_p = array("place" => 'photo_thumb', "data" => $photo); $params['extra'] = ANCHOR($anchor_p); if ($params['style']) { $attrs['style'] = $params['style']; } if ($params['extra']) { $attrs['extra'] = $params['extra']; } $image = cb_create_html_tag('img', true, $attrs); if ($params['assign']) { assign($params['assign'], $image); } else { return $image; } } } else { return get_photo_default_thumb($size, $output); } }
/** * This will become a Smarty function. * I am writting this to eliminate the possiblitles * of distort pictures */ function getFileSmarty($p) { global $Cbucket; $details = $p['details']; $output = $p['output']; if (empty($details)) { return $this->default_thumb($size, $output); } else { //Calling Custom Functions if (count($Cbucket->custom_get_photo_funcs) > 0) { foreach ($Cbucket->custom_get_photo_funcs as $funcs) { if (function_exists($funcs)) { $func_returned = $funcs($p); if ($func_returned) { return $func_returned; } } } } if (empty($p['size'])) { $p['size'] = 't'; } if (!empty($p['code'])) { $p['size'] = $p['code']; } if ($details['is_mature'] == 'yes' && !userid()) { return get_mature_thumb($details, $size, $output); } if ($p['with_path'] === FALSE) { $p['with_path'] = FALSE; } else { $p['with_path'] = TRUE; } $with_path = $p['with_path']; $with_orig = $p['with_orig'] ? $p['with_orig'] : FALSE; if (!is_array($details)) { $photo = $this->get_photo($details); } else { $photo = $details; } if (empty($photo['photo_id']) || empty($photo['photo_key'])) { return $this->default_thumb($size, $output); } else { if (!empty($photo['filename']) && !empty($photo['ext'])) { /* Enhacing the code to work with date folder structure */ $date_dir = get_photo_date_folder($photo); if ($date_dir) { $date_dir .= '/'; } $files = glob(PHOTOS_DIR . "/" . $date_dir . $photo['filename'] . "*." . $photo['ext']); if (!empty($files) && is_array($files)) { foreach ($files as $file) { $file_parts = explode("/", $file); $thumb_name = $file_parts[count($file_parts) - 1]; $type = $this->get_image_type($thumb_name); if ($with_orig) { if ($with_path) { $thumbs[] = PHOTOS_URL . "/" . $date_dir . $thumb_name; } else { $thumbs[] = $thumb_name; } } elseif (!empty($type)) { if ($with_path) { $thumbs[] = PHOTOS_URL . "/" . $date_dir . $thumb_name; } else { $thumbs[] = $thumb_name; } } } if (!$thumbs) { return $this->default_thumb($size, $output); } if (empty($p['output']) || $p['output'] == 'non_html') { if ($p['assign'] && $p['multi']) { assign($p['assign'], $thumbs); } elseif (!$p['assign'] && $p['multi']) { return $thumbs; } else { $size = "_" . $p['size']; $return_thumb = array_find($photo['filename'] . $size, $thumbs); if (empty($return_thumb)) { $this->default_thumb($size, $output); } else { if ($p['assign'] != NULL) { assign($p['assign'], $return_thumb); } else { return $return_thumb; } } } } if ($p['output'] == 'html') { /* Creating output here is dropped. Now we'll create an array of * attributes and pass to cb_output_img_tag, that function will * create the actual HTML IMG tag */ $size = "_" . $p['size']; $src = array_find($photo['filename'] . $size, $thumbs); $attrs = array(); if (empty($src)) { return $this->default_thumb($size, $output); } else { $src = $src; } if (phpversion < '5.2.0') { global $json; $js = $json; } if (!empty($js)) { $imgDetails = $js->json_decode($photo['photo_details'], true); } else { $imgDetails = json_decode($photo['photo_details'], true); } if (empty($imgDetails) || empty($imgDetails[$p['size']])) { $dem = getimagesize(str_replace(PHOTOS_URL, PHOTOS_DIR, $src)); $width = $dem[0]; $height = $dem[1]; /* UPDATEING IMAGE DETAILS */ $this->update_image_details($details); } else { $width = $imgDetails[$p['size']]['width']; $height = $imgDetails[$p['size']]['height']; } if (USE_PHOTO_TAGGING && THIS_PAGE == 'view_item') { $id = $this->get_selector_id() . "_" . $photo['photo_id']; } else { if ($p['id']) { $id = mysql_clean($p['id']) . "_" . $photo['photo_id']; } else { $id = $this->get_selector_id() . "_" . $photo['photo_id']; } } $attrs['id'] = $id; if ($p['class']) { $attrs['class'] = mysql_clean($p['class']); } if ($p['align']) { $attrs['align'] = $p['align']; } if ($p['width'] && is_numeric($p['width']) && ($p['height'] && is_numeric($p['height']))) { $height = $p['height']; $width = $p['width']; } elseif ($p['width'] && is_numeric($p['width'])) { $height = round($p['width'] / $width * $height); $width = $p['width']; } elseif ($p['height'] && is_numeric($p['height'])) { $width = round($p['height'] * $width / $height); $height = $p['height']; } $attrs['width'] = $width; $attrs['height'] = $height; if ($p['title']) { $title = mysql_clean($p['title']); } else { $title = $photo['photo_title']; } $attrs['title'] = $title; if ($p['alt']) { $alt = mysql_clean($p['alt']); } else { $alt = mysql_clean(TITLE . ' - ' . $photo['photo_title']); } $attrs['alt'] = $alt; $anchor_p = array("place" => 'photo_thumb', "data" => $photo); ANCHOR($anchor_p); if ($p['style']) { $attrs['style'] = $p['style']; } if ($p['extra']) { $attrs['extra'] = $p['extra']; } $img = cb_output_img_tag($src, $attrs); if ($p['assign']) { assign($p['assign'], $img); } else { return $img; } } } else { return $this->default_thumb($size, $output); } } } } }
/** * Get thumbnails of a video * * This function will get all video thumbnails * and list them in array, you can either get single * thumb or number or size. This function has few limitations * that we will try to cover in upcoming updates. * * @since 2.x * @uses default_thumb(); * @uses MyQuery->get_video_details(); * * @param $vdetails ARRAY video details, array('videod','title'...) or it can be just STRING videoid * @param $num STRING number of thumb , if you want to get thumb-2 , you will set 2, default value is 'default' which return 1 * @param $multi BOOLEAN weather to return ALL thumbnails in array or just single thumb * @param $count BOOLEAN just count thumbs or not, if set to true, function will return number of thumb INT only * @param $return_full_path BOOLEAN if set to true, thumb will be return along with THUMBS_URL e.g http://cb/thumb/file-1.jpg * if set to false, it will return file-1.jpg * @param $return_big BOOLEAN weather to return BIG thumbnail or not, if set true, it will return file-big.jpg * * @since 2.6 * @param $size STRING dimension of thumb, it can be 120x90, 320x240, it was introduced in 2.6 to get more thumbs * using the same funcion. * @return STRING video thumbnail with/without path or ARRAY list of video thumbs or INT just number of thumbs * */ function get_thumb($vdetails, $num = 'default', $multi = false, $count = false, $return_full_path = true, $return_big = true, $size = NULL) { global $db, $Cbucket, $myquery, $cbvid; if (!is_array($vdetails)) { $vdetails = $myquery->get_video_details($vdetails); } $extras = $cbvid->get_video_extras($vdetails['videoid'], $vdetails['extras']); $thumbs = $extras['thumbs']; $vdetails['thumbs'] = $thumbs; if ($vdetails['thumbs']) { if ($return_full_path) { $folder = ''; $folder = $vdetails['file_directory']; if ($folder) { $folder .= '/'; } if (!isset($vdetails['files_thumbs_path'])) { $path = $vdetails['files_thumbs_path'] . '/' . $folder; } else { $path = THUMBS_URL . '/' . $folder; } } else { $path = ''; } if (!is_array($vdetails['thumbs'])) { $thumbs = json_decode($vdetails['thumbs'], true); } else { $thumbs = $vdetails['thumbs']; } $_thumbs = array(); if ($thumbs) { foreach ($thumbs as $the_size => $thumbs) { foreach ($thumbs as $thumb) { $_thumbs[$the_size][] = $path . $thumb; } } $thumbs = $_thumbs; } $thumb_size = get_size_by_name($size); if (!$thumb_size) { $thumb_size = $size; } if (!is_numeric($num) || $num < 1) { $num = 1; } $img = $thumbs[$thumb_size][$num - 1]; if (!$img) { $img = $thumbs[get_size_by_name('default')][0]; } if (!$img) { if (is_array($thumbs)) { foreach ($thumbs as $thumb) { $img = $thumb[0]; break; } } } if ($img) { if ($count) { return count($thumbs[$thumb_size]); } if ($multi) { if ($multi == 'all') { return $thumbs; } else { return $thumbs[$thumb_size]; } } return $img; } } $num = $num ? $num : 'default'; //checking what kind of input we have if (is_array($vdetails)) { if (empty($vdetails['title'])) { //check for videoid if (empty($vdetails['videoid']) && empty($vdetails['vid']) && empty($vdetails['videokey'])) { if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } else { if (!empty($vdetails['videoid'])) { $vid = $vdetails['videoid']; } elseif (!empty($vdetails['vid'])) { $vid = $vdetails['vid']; } elseif (!empty($vdetails['videokey'])) { $vid = $vdetails['videokey']; } else { if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } } } } else { if (is_numeric($vdetails)) { $vid = $vdetails; } else { if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } } //checking if we have vid , so fetch the details if (!empty($vid)) { $vdetails = $myquery->get_video_details($vid); } if (empty($vdetails['title'])) { if ($multi) { return default_thumb(); } return default_thumb(); } //Checking if there is any custom function for if (count($Cbucket->custom_get_thumb_funcs) > 0) { foreach ($Cbucket->custom_get_thumb_funcs as $funcs) { //Merging inputs $in_array = array('num' => $num, 'size' => $size, 'multi' => $multi, 'count' => $count, 'return_full_path' => $return_full_path, 'return_big' => $return_big); if (function_exists($funcs)) { $func_returned = $funcs($vdetails, $in_array); if ($func_returned) { return $func_returned; } } } } #get all possible thumbs of video if ($vdetails['file_name']) { $vid_thumbs = glob(THUMBS_DIR . "/" . $vdetails['file_name'] . "*"); } #replace Dir with URL if (is_array($vid_thumbs)) { foreach ($vid_thumbs as $thumb) { if (file_exists($thumb) && filesize($thumb) > 0) { $thumb_parts = explode('/', $thumb); $thumb_file = $thumb_parts[count($thumb_parts) - 1]; if (!is_big($thumb_file) || $return_big) { if ($return_full_path) { $thumbs[] = THUMBS_URL . '/' . $thumb_file; } else { $thumbs[] = $thumb_file; } } } elseif (file_exists($thumb)) { unlink($thumb); } } } if (count($thumbs) == 0) { if ($count) { return count($thumbs); } if ($multi) { return $dthumb[0] = default_thumb(); } return default_thumb(); } else { if ($multi) { return $thumbs; } if ($count) { return count($thumbs); } //Now checking for thumb if ($num == 'default') { $num = $vdetails['default_thumb']; } if ($num == 'big' || $size == 'big') { $num = 'big-' . $vdetails['default_thumb']; if (!file_exists(THUMBS_DIR . '/' . $vdetails['file_name'] . '-' . $num . '.jpg')) { $num = 'big'; } } $default_thumb = array_find($vdetails['file_name'] . '-' . $num, $thumbs); if (!empty($default_thumb)) { return $default_thumb; } return $thumbs[0]; } }
/** * @param array $array * @param $key * @param $value * * @return bool|int|string */ function array_find_key(array $array, $key, $value) { return array_find($array, function ($index, $element) use($key, $value) { return $element[$key] == $value; }); }
/** * This function returns the untouched/original file * of photo * * @global OBJECT $cbphoto * @param ARRAY $photo * @param BOOL $with_path * @return STRING */ function get_original_photo($photo, $with_path = false) { global $cbphoto; if (!is_array($photo)) { $ph = $cbphoto->get_photo($photo); } else { $ph = $photo; } if (is_array($ph)) { $files = $cbphoto->get_image_file($ph, 't', true, false, $with_path, true); $orig = $ph['filename'] . '.' . $ph['ext']; $file = array_find($orig, $files); return $file; } }
/** * マイミクをアプリに招待するためのフォームを生成します。 * * @param string $callback 招待状送信後にコールバックするパス。 * 指定可能なパスの書式は {@link Mars_RewriteRouter::buildRequestPath()} メソッドを参照。 * @param mixed $extra オプション属性。'キー=値;' 形式の文字列、または連想配列での指定が可能。 * - recipients: 初期選択状態とするユーザ ID。カンマ区切りの文字列、または配列形式で指定可能。 * - message: メッセージ本文。 * - image: メッセージに含める画像。{@link communicationFeedForm()} メソッドの 'mediaItem1' 属性を参照。 * - filterType: 対象とするユーザの種別。'joined'、'nod_joinded'、'both' のいずれかを指定。既定値は 'joined'。 * - appendURI: TRUE が指定された場合、招待状にアプリ起動のための URI を追加します。既定値は FALSE。 * - query: {@link communicationFeedForm()} メソッドの 'query' 属性を参照。 * 未指定の場合はスタート画面が表示される。 * - mobileQuery: {@link communicationFeedForm()} メソッドの 'mobileQuery' 属性を参照。 * 未指定の場合はスタート画面が表示される。 * - targetUsers: 友人の選択画面で表示するユーザのリスト。カンマ区切りの文字列、または配列形式で指定可能。 * - description: 友人の選択画面で表示する説明文。 * - excludeUsers: 友人の選択画面で非表示にするユーザのリスト。カンマ区切りの文字列、または配列形式で指定可能。 * - buttonLabel: 送信ボタンのラベル。 * @return string 生成したタグを返します。 * @link http://developer.mixi.co.jp/appli/spec/mob/for_partners/request_api リクエスト API について */ public function inviteForm($callback = NULL, $extra = array()) { $attributes = array(); $attributes['action'] = Mars_MixiMobileApp::buildCallbackActionPath($callback, 'invite:friends'); $attributes['method'] = 'post'; $extra = parent::constructParameters($extra); $hiddenBuffer = NULL; $recipients = array_find($extra, 'recipients'); $message = array_find($extra, 'message'); $image = array_find($extra, 'image'); $filterType = array_find($extra, 'filterType', 'joined'); $appendURI = array_find($extra, 'appendURI', FALSE); $query = array_find($extra, 'query', array()); $mobileQuery = array_find($extra, 'mobileQuery', array()); $targetUsers = array_find($extra, 'targetUsers'); $description = array_find($extra, 'description'); $excludeUsers = array_find($extra, 'excludeUsers'); $buttonLabel = array_find($extra, 'buttonLabel', '送信'); if ($recipients !== NULL) { if (is_array($recipients)) { $recipients = implode(',', $recipients); } $hiddenBuffer .= $this->inputHidden('recipients', array('value' => $recipients)); } if ($message !== NULL) { $hiddenBuffer .= $this->inputHidden('message', array('value' => $message)); } if (is_array($image)) { $value = sprintf('%s,%s', Mars_HTMLHelper::buildAssetPath($image[0], 'image', array('absolute' => TRUE)), $image[1]); $hiddenBuffer .= $this->inputHidden('image', array('value' => $value)); } if ($appendURI) { $uri = $this->buildLaunchURI(Mars_MixiApp::AGENT_TYPE_PC, $query); $hiddenBuffer .= $this->inputHidden('url', array('value' => $uri)); $mobileURI = $this->buildLaunchURI(Mars_MixiApp::AGENT_TYPE_MOBILE, $mobileQuery); $hiddenBuffer .= $this->inputHidden('mobile_url', array('value' => $mobileURI)); } if ($targetUsers !== NULL) { if (is_array($targetUsers)) { $targetUsers = implode(',', $targetUsers); } $hiddenBuffer .= $this->inputHidden('target_users', array('value' => $targetUsers)); } if ($description !== NULL) { $hiddenBuffer .= $this->inputHidden('description', array('value' => $description)); } if ($excludeUsers !== NULL) { if (is_array($excludeUsers)) { $excludeUsers = implode(',', $excludeUsers); } $hiddenBuffer .= $this->inputHidden('exclude_users', array('value' => $excludeUsers)); } $buffer = sprintf("<form%s>\n%s%s%s%s", parent::buildTagAttribute($attributes, FALSE), $this->inputHidden('filter_type', array('value' => 'joined')), $hiddenBuffer, $this->inputSubmit($buttonLabel), $this->close()); return $buffer; }
/** * This will become a Smarty function. * I am writting this to eliminate the possiblitles * of distort pictures */ function getFileSmarty($p) { global $Cbucket; $details = $p['details']; $output = $p['output']; if (empty($details)) { return $this->default_thumb($size, $output); } else { //Calling Custom Functions if (count($Cbucket->custom_get_photo_funcs) > 0) { foreach ($Cbucket->custom_get_photo_funcs as $funcs) { if (function_exists($funcs)) { $func_returned = $funcs($p); if ($func_returned) { return $func_returned; } } } } if ($p['size'] != 't' && $p['size'] != 'm' && $p['size'] != 'l' && $p['size'] != 'o' || empty($p['size'])) { $p['size'] = 't'; } if ($p['with_path'] === FALSE) { $p['with_path'] = FALSE; } else { $p['with_path'] = TRUE; } $with_path = $p['with_path']; $with_orig = $p['with_orig'] ? $p['with_orig'] : FALSE; if (!is_array($details)) { $photo = $this->get_photo($details); } else { $photo = $details; } if (empty($photo['photo_id']) || empty($photo['photo_key'])) { return $this->default_thumb($size, $output); } else { if (!empty($photo['filename']) && !empty($photo['ext'])) { $files = glob(PHOTOS_DIR . "/" . $photo['filename'] . "*." . $photo['ext']); if (!empty($files) && is_array($files)) { foreach ($files as $file) { $file_parts = explode("/", $file); $thumb_name = $file_parts[count($file_parts) - 1]; $type = $this->get_image_type($thumb_name); if ($with_orig) { if ($with_path) { $thumbs[] = PHOTOS_URL . "/" . $thumb_name; } else { $thumbs[] = $thumb_name; } } elseif (!empty($type)) { if ($with_path) { $thumbs[] = PHOTOS_URL . "/" . $thumb_name; } else { $thumbs[] = $thumb_name; } } } if (empty($p['output']) || $p['output'] == 'non_html') { if ($p['assign'] && $p['multi']) { assign($p['assign'], $thumbs); } elseif (!$p['assign'] && $p['multi']) { return $thumbs; } else { $size = "_" . $p['size']; $return_thumb = array_find($photo['filename'] . $size, $thumbs); if (empty($return_thumb)) { $this->default_thumb($size, $output); } else { if ($p['assign'] != NULL) { assign($p['assign'], $return_thumb); } else { return $return_thumb; } } } } if ($p['output'] == 'html') { $size = "_" . $p['size']; $src = array_find($photo['filename'] . $size, $thumbs); if (empty($src)) { $src = $this->default_thumb($size); } else { $src = $src; } if (phpversion < '5.2.0') { global $json; } $js = $json; if (!empty($js)) { $imgDetails = $js->json_decode($photo['photo_details'], true); } else { $imgDetails = json_decode($photo['photo_details'], true); } if (empty($imgDetails) || empty($imgDetails[$p['size']])) { $dem = getimagesize(str_replace(PHOTOS_URL, PHOTOS_DIR, $src)); $width = $dem[0]; $height = $dem[1]; /* UPDATEING IMAGE DETAILS */ $this->update_image_details($details); } else { $width = $imgDetails[$p['size']]['width']; $height = $imgDetails[$p['size']]['height']; } $img = "<img "; $img .= "src = '" . $src . "'"; if ($p['id']) { $img .= " id = '" . mysql_clean($p['id']) . "_" . $photo['photo_id'] . "'"; } if ($p['class']) { $img .= " class = '" . mysql_clean($p['class']) . "'"; } if ($p['align']) { $img .= " align = '" . $p['align'] . "'"; } if ($p['width'] && is_numeric($p['width']) && ($p['height'] && is_numeric($p['height']))) { $height = $p['height']; $width = $p['width']; } elseif ($p['width'] && is_numeric($p['width'])) { $height = round($p['width'] / $width * $height); $width = $p['width']; } elseif ($p['height'] && is_numeric($p['height'])) { $width = round($p['height'] * $width / $height); $height = $p['height']; } $img .= " width = '" . $width . "'"; $img .= " height = '" . $height . "'"; if ($p['title']) { $img .= " title = '" . mysql_clean($p['title']) . "'"; } else { $img .= " title = '" . $photo['photo_title'] . "'"; } if ($p['alt']) { $img .= " alt = '" . mysql_clean($p['alt']) . "'"; } else { $img .= " alt = '" . $photo['photo_title'] . "'"; } if ($p['anchor']) { $anchor_p = array("place" => $p['anchor'], "data" => $photo); ANCHOR($anchor_p); } if ($p['style']) { $img .= " style = '" . $p['style'] . "'"; } if ($p['extra']) { $img .= $p['extra']; } $img .= " />"; if ($p['assign']) { assign($p['assign'], $img); } else { return $img; } } } else { return $this->default_thumb($size, $output); } } } } }
if ($_GET['code'] == "favicon") { die; } if (strpos($_GET['code'], '/')) { $code = explode('/', $_GET['code']); $r = rand(0, count($code) - 1); $code = $code[$r]; } else { $code = $_GET['code']; } $code = substr($code, 0, 6); // cut off the file extension // Check if they're coming from a partner site if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) { $Host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); if (array_find($Host, $AllowedSites) === FALSE) { $DB->query("INSERT INTO access_unauth(Code,Browser,Referer,IP) VALUES('%s', '%s', '%s', %d)", $code, $_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_REFERER'], ip2long($_SERVER['REMOTE_ADDR'])); header("HTTP/1.0 403 Forbidden"); die; } } # 6/24 header("Cache-Control: private, max-age=1209600, pre-check=10800"); header("Pragma: private"); header("Expires: " . date(DATE_RFC822, strtotime(" 14 day"))); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { // if the browser has a cached version of this image, send 304 header('Last-Modified: ' . $_SERVER['HTTP_IF_MODIFIED_SINCE'], true, 304); exit; } $Size = -1;
die("Page not found"); } //$UrlizedTitle = urlencode(str_replace(" ","_", $Title)); if (!preg_match("/{$Title}/i", $Title, $Matches)) { die("Title not found in URL"); } $Page = get_contents("http://en.m.wikipedia.org{$WPUrl}"); $PageExp = explode("\n", $Page); // Sort of dirty, but let's play ball $Keys = array_find('<th scope="row" style="text-align:left;"><a href="/wiki/Music_genre" title="Music genre">Genre</a></th>', $PageExp); preg_match("/>(.*?)<\\/td>/i", $PageExp[$Keys + 1], $Tags); $Tags = explode(", ", $Tags[1]); $Tags = preg_replace("/<sup.+<\\/sup>/", "", $Tags); $Tags = preg_replace("/<a href=\".+\" title=\".+\">(.*?)<\\/a>/i", "\$1", $Tags); $Tags = array_map('format', $Tags); $Keys2 = array_find('<th scope="row" style="text-align:left;">Released</th>', $PageExp); if (!preg_match("/>.+ (\\d{4})/i", $PageExp[$Keys2 + 1], $Year)) { preg_match("/>(\\d{4})/i", $PageExp[$Keys2 + 1], $Year); } $Year = $Year[1]; // Get full image link (hax, sorta) preg_match_all("%<img .+ src=\"(.*?)\"%i", $Page, $PageImages); $Image = ''; foreach ($PageImages[1] as $VtrImage) { if (strpos($VtrImage, ".svg") || strpos($VtrImage, "Ambox_content.png")) { continue; } if (preg_match("%upload\\.wikimedia\\.org\\/wikipedia/[a-z]+\\/[a-z]+\\/[a-z0-9]\\/[a-z0-9]{2}\\/%i", $VtrImage)) { $Image = $VtrImage; break; }