function Error($msg) { //erreur sur la classe FDPF, on la log avant d'arreter la génération... logMsg($msg); //Fatal error parent::Error($msg); }
protected function closed($user) { logMsg("user with id: " . $user->{"id"} . " disconnected from the server.", "userDisconnected"); // Do nothing: This is where cleanup would go, in case the user had any sort of // open files or other objects associated with them. This runs after the socket // has been closed, so there is no need to clean up the socket itself here. }
function loadClass($class, $param = NULL) { if (!is_string($class)) { logMsg(SL_ERROR, "参数错误!"); exit(-3); } static $commonClasses = array(); if (isset($commonClasses[$class]) && $commonClasses[$class] instanceof $class) { return $commonClasses[$class]; } $filePath = ''; foreach (array(INCLUDE_DIR, SRC_DIR) as $path) { if (file_exists($path . '/' . $class . '.php')) { $filePath = $path; break; } } if (!empty($filePath) && !isLoadFile($class) && class_exists($class, false) === FALSE) { require_once $filePath . '/' . $class . '.php'; } if (INCLUDE_DIR === $filePath) { $commonClasses[$class] = isset($param) ? new $class($param) : new $class(); return $commonClasses[$class]; } else { if (SRC_DIR == $filePath) { return isset($param) ? new $class($param) : new $class(); } } return FALSE; }
/** * Parses RSS feeds for new content */ private function parseFeeds() { foreach ($this->rssConfig as $feed) { if (!isset($this->lastCheck[$feed['url']]) || $this->lastCheck[$feed['url']] + $feed['pollInterval'] * 60 < time()) { $this->lastCheck[$feed['url']] = time(); logMsg("rssPlugin: Checking RSS: {$feed['url']}"); try { $content = file_get_contents($feed['url']); $x = new SimpleXmlElement($content); //RSS feed format if (isset($x->channel)) { foreach ($x->channel->item as $entry) { $this->saveEntry($feed['title'], $feed['channel'], $entry->title, $entry->link); } } else { //Atom feed format if (isset($x->entry)) { foreach ($x->entry as $entry) { $this->saveEntry($feed['title'], $feed['channel'], $entry->title, $entry->link->attributes()->href); } } } $content = null; $x = null; } catch (Exception $e) { logMsg($e->getMessage()); } } } }
/** * Reads all plugins in the plugins directory of the server root. * @return array */ public static function getPlugins($db = null) { if (!$db) { $db = Config::main()->getDBO(); } $result = array(); $path = DIAMONDMVC_ROOT . '/plugins'; $dir = opendir($path); while ($curr = readdir($dir)) { if ($curr === '.' or $curr === '..') { continue; } if (!is_dir("{$path}/{$curr}")) { logMsg('Plugin ist kein Ordner: $path/$curr', 5); continue; } if (!file_exists("{$path}/{$curr}/{$curr}.php")) { logMsg("Plugin-Hauptskript nicht gefunden: {$path}/{$curr}/{$curr}.php"); continue; } include_once "{$path}/{$curr}/{$curr}.php"; if (!class_exists("Plugin{$curr}")) { logMsg("Plugin-Hauptklasse nicht gefunden: {$curr}"); continue; } $className = "plugin{$curr}"; $result[] = new $className($db); } return $result; }
/** * Removes a mapping. * @param integer $type Unique field type to remove. */ public static function unregisterField($type) { if (isset(self::$fieldmap[$type])) { logMsg("FormBuilder: Removing field mapping {$type} -> " . self::$fieldmap[$type], 4); unset(self::$fieldmap[$type]); } else { logMsg("FormBuilder: Nothing to do. Field mapping {$type} not found.", 4); } }
public function addLog($iLevel, $sInfo, $sPath) { if (!$sInfo || !$sPath) { logMsg(SL_ERROR, 'Log param Error, now the sInfo is ' . $sInfo . ' sPath is ' . $sPath); return FALSE; } $strSql = "INSERT INTO {$this->dbName} (`sTime`,`iLevel`,`sInfo`,`sPath`) VALUES (NOW(),'{$iLevel}','{$sInfo}','{$sPath}')"; return $this->dbConnect->exec($strSql); }
/** * If the fallback method is used, this method invokes all registered autoloaders. */ public function invokeRegisteredAutoloaders($class) { foreach ($this->loaders as $loader) { try { call_user_func($loader, $class); } catch (Exception $ex) { logMsg('[CORE] Autoloader ' . (is_array($loader) ? $loader[1] : $loader) . ' threw an exception while loading class ' . $class); } } }
function dbConnect() { global $db, $dbFilename; $up = dirname(__FILE__) . '/../'; if ($db = new PDO('sqlite:' . $up . $dbFilename)) { logMsg('DB', 'Db opened ok'); } else { logMsg('ERROR', 'Db cannot be opened'); die; } }
public function exec($strSql) { try { $iResult = $this->dbConnect->exec($strSql); } catch (PDOException $e) { logMsg(SL_ERROR, "SQL failed : " . $e->getMessage()); echo $e->getMessage() . "\n"; exit(-3); } return $iResult; }
public function setConfig($key, $val) { if (!is_string($key) || !is_string($val)) { //记录日志 logMsg(SL_ERROR, "参数错误!"); return FALSE; } $this->arrConfig[$key] = $val; $content = json_encode($this->arrConfig); writeToFile(CONFIG_FILE, $content); return TRUE; }
/** * Reads the INI from the given path. * @param string $file Path to the INI file to read in. * @return IniGenerator This instance to enable method chaining. */ public function read($file) { if (!file_exists($file)) { logMsg('Failed to read ini file "' . $file . '": not found', 9, 5); } else { ob_start(); include $file; $contents = ob_get_contents(); ob_end_clean(); $this->data = parse_ini_string($contents, true); } return $this; }
public function execute() { // Försök rensa databasen if ($this->db->clear()) { // success $response = array("type" => "clearedList"); logMsg("Cleared the list.", "clearedList"); } else { // fail $resonse = array("type" => "error", "data" => "Det gick inte att rensa listan."); } return $response; }
/** * Lägger till den nya posten i databasen * @return $response En array som berättar om vad som skedde (eller inte skedde) */ public function execute() { // Försöka lägga till ny post if ($this->db->addItem($this->item)) { // success $response = array("type" => "addedItem", "data" => $this->item->getData(), "id" => $this->item->getId()); logMsg("Added new item: " . $response["data"] . " (" . $response["id"] . ")", "addedItem"); } else { // fail $response = array("type" => "error", "data" => "Det gick inte att lägga till: " . $this->item->getData() . " med id: " . $this->item->getId()); } return $response; }
public function execute() { // Försöka uppdatera post if ($this->db->updateItem($this->item)) { // success $response = array("type" => "updatedItem", "data" => $this->item->getData(), "id" => $this->item->getId(), "isMarked" => $this->item->isMarked()); logMsg("Updated item: (" . $response["id"] . ")" . " --> " . $response["data"], "updatedItem"); } else { // fail $response = array("type" => "warn", "data" => "Det gick inte att uppdatera post: " . $this->item->getId()); } return $response; }
public function execute() { // Försök ta bort posten if ($this->db->removeItem($this->item)) { // success $response = array("type" => "removedItem", "id" => $this->item->getId()); logMsg("Removed item: " . "(" . $response["id"] . ")", "removedItem"); } else { // fail $response = array("type" => "error", "data" => "Det gick inte att ta bort post: " . $this->item->getId()); } return $response; }
public function checkAnswerExist($iAnswerId, $sHashId) { if (!is_string($sHashId) || !$iAnswerId) { logMsg(SL_ERROR, "参数错误!"); echo "参数错误\n"; exit(-3); } $strSql = "SELECT iLocalAnswerId FROM tbAnswer WHERE iAnswerId={$iAnswerId} AND sHashId='{$sHashId}' LIMIT 1"; $result = $this->dbConnect->query($strSql); if (is_array($result) && isset($result[0]) && isset($result[0]['iLocalAnswerId'])) { return $result[0]['iLocalAnswerId']; } else { return FALSE; } }
public function run() { $dbModel = loadClass('DBModel'); $userPageParam = array(); while (1) { //若为空则尝试自动获取 if (count($userPageParam) <= 0 || !isset($userPageParam['url'])) { $userPageParam = $dbModel->getNext(); } if (is_array($userPageParam) && count($userPageParam) > 0) { logMsg(SL_DEBUG, "Start to handle user : " . json_encode($userPageParam)); loadClass('userPage', $userPageParam); $userPageParam = array(); } usleep(500); } }
public static function endSection() { if (Config::main()->get('DEBUG_MODE')) { $time = round(microtime(true)); if (empty(self::$sections)) { logMsg("--- No section to end ---", 1, 5); return $this; } $section = array_pop(self::$sections); $section['end'] = $time; $section['memEnd'] = round(memory_get_usage() / 1024); logMsg("- Section {$section['name']} end -", 1, false); logMsg("Start: {$section['start']}s", 1, false); logMsg("End: {$section['end']}s", 1, false); logMsg("Delta: " . ($section['end'] - $section['start']) . 's', 1, false); logMsg("Memory: {$section['memStart']} kiB - {$section['memEnd']} kiB", 1, false); logMsg("Median: " . ($section['memEnd'] + $section['memStart']) / 2 . ' kiB', 1, false); } }
/** * Checks if element references a specific platform * * @param string $platform Requested platform * @returns boolean TRUE if platform check succeeds * * @access private */ function supportedPlatform($platform = NULL) { $regex = '/^(\\w*\\|)*' . $this->db->databaseType . '(\\|\\w*)*$/'; if (!isset($platform) or preg_match($regex, $platform)) { logMsg("Platform {$platform} is supported"); return TRUE; } else { logMsg("Platform {$platform} is NOT supported"); return FALSE; } }
/** * Make sure the url isn't on our block list * * @param mixed $url */ function CheckUrl($url) { $ok = true; global $user; global $usingAPI; global $error; global $admin; $date = gmdate("Ymd"); if (strncasecmp($url, 'http:', 5) && strncasecmp($url, 'https:', 6)) { $url = 'http://' . $url; } if (!$usingAPI && !$admin) { $blockUrls = file('./settings/blockurl.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $blockHosts = file('./settings/blockdomains.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $blockAuto = file('./settings/blockdomainsauto.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if ($blockUrls !== false && count($blockUrls) || $blockHosts !== false && count($blockHosts) || $blockAuto !== false && count($blockAuto)) { // Follow redirects to see if they are obscuring the site being tested GetRedirect($url, $rhost, $rurl); foreach ($blockUrls as $block) { $block = trim($block); if (strlen($block) && preg_match("/{$block}/i", $url)) { logMsg("{$_SERVER['REMOTE_ADDR']}: url {$url} matched {$block}", "./log/{$date}-blocked.log", true); $ok = false; break; } elseif (strlen($block) && strlen($rurl) && preg_match("/{$block}/i", $rurl)) { logMsg("{$_SERVER['REMOTE_ADDR']}: url {$url} redirected to {$rurl} matched {$block}", "./log/{$date}-blocked.log", true); $ok = false; break; } } if ($ok) { $parts = parse_url($url); $host = trim($parts['host']); foreach ($blockHosts as $block) { $block = trim($block); if (strlen($block) && (!strcasecmp($host, $block) || !strcasecmp($host, "www.{$block}"))) { logMsg("{$_SERVER['REMOTE_ADDR']}: {$url} matched {$block}", "./log/{$date}-blocked.log", true); $ok = false; break; } elseif (strlen($block) && (!strcasecmp($rhost, $block) || !strcasecmp($rhost, "www.{$block}"))) { logMsg("{$_SERVER['REMOTE_ADDR']}: {$url} redirected to {$rhost} which matched {$block}", "./log/{$date}-blocked.log", true); $ok = false; break; } } } if ($ok) { $parts = parse_url($url); $host = trim($parts['host']); foreach ($blockAuto as $block) { $block = trim($block); if (strlen($block) && (!strcasecmp($host, $block) || !strcasecmp($host, "www.{$block}"))) { logMsg("{$_SERVER['REMOTE_ADDR']}: {$url} matched auto-block {$block}", "./log/{$date}-blocked.log", true); $ok = false; break; } } } } } if ($ok && !$admin && !$usingAPI) { $ok = SBL_Check($url, $message); if (!$ok) { $error = "<br>Sorry, your test was blocked because {$url} is suspected of being used for <a href=\"http://www.antiphishing.org/\">phishing</a> or <a href=\"http://www.stopbadware.org/\">hosting malware</a>.<br><br>Advisory provided by <a href=\"http://code.google.com/apis/safebrowsing/safebrowsing_faq.html#whyAdvisory\">Google</a>."; logMsg("{$_SERVER['REMOTE_ADDR']}: {$url} failed Safe Browsing check: {$message}", "./log/{$date}-blocked.log", true); } } return $ok; }
/** * Checks if element references a specific platform * * @param string $platform Requested platform * @returns boolean TRUE if platform check succeeds * * @access private */ function supportedPlatform($platform = NULL) { if (!empty($platform)) { $regex = '/(^|\\|)' . $this->db->databaseType . '(\\||$)/i'; if (preg_match('/^- /', $platform)) { if (preg_match($regex, substr($platform, 2))) { logMsg('Platform ' . $platform . ' is NOT supported'); return FALSE; } } else { if (!preg_match($regex, $platform)) { logMsg('Platform ' . $platform . ' is NOT supported'); return FALSE; } } } logMsg('Platform ' . $platform . ' is supported'); return TRUE; }
/** * Check the given test against our block list to see if the test bypassed our blocks. * If it did, add the domain to the automatic blocked domains list * */ function CheckForSpam() { global $testPath; global $id; global $runNumber; global $cacheWarmed; global $testInfo; global $testInfo_dirty; if (isset($testInfo) && !array_key_exists('spam', $testInfo) && strpos($id, '.') == false && !strlen($testInfo['user']) && !strlen($testInfo['key']) && is_file('./settings/blockurl.txt')) { $blocked = false; $blockUrls = file('./settings/blockurl.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if (count($blockUrls)) { if (!isset($runNumber)) { $runNumber = 1; } if (!isset($cacheWarmed)) { $cacheWarmed = 0; } $secure = false; $haveLocations = false; $requests = getRequests($id, $testPath, $runNumber, $cacheWarmed, $secure, $haveLocations, false); if (isset($requests) && is_array($requests) && count($requests)) { foreach ($requests as &$request) { if (array_key_exists('full_url', $request)) { $url = $request['full_url']; foreach ($blockUrls as $block) { $block = trim($block); if (strlen($block) && preg_match("/{$block}/i", $url)) { $date = gmdate("Ymd"); // add the top-level page domain to the block list $pageUrl = $requests[0]['full_url']; $host = ''; if (strlen($pageUrl)) { $parts = parse_url($pageUrl); $host = trim($parts['host']); if (strlen($host) && strcasecmp($host, 'www.google.com') && strcasecmp($host, 'google.com') && strcasecmp($host, 'www.youtube.com') && strcasecmp($host, 'youtube.com')) { // add it to the auto-block list if it isn't already there if (is_file('./settings/blockdomainsauto.txt')) { $autoBlock = file('./settings/blockdomainsauto.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); } if (!isset($autoBlock) || !is_array($autoBlock)) { $autoBlock = array(); } $found = false; foreach ($autoBlock as $entry) { if (!strcasecmp($entry, $host)) { $found = true; break; } } if (!$found) { $autoBlock[] = $host; file_put_contents('./settings/blockdomainsauto.txt', implode("\r\n", $autoBlock)); } } } logMsg("[{$id}] {$host}: {$pageUrl} referenced {$url} which matched {$block}", "./log/{$date}-auto_blocked.log", true); $blocked = true; break 2; } } } } } } if ($blocked) { $testInfo['spam'] = $blocked; $testInfo_dirty = true; } } }
/** * @return array Key is the file extension, value is the MIME type. * Unsorted. */ function loadMapFromUrl($url) { global $duplicateResolution; $map = array(); $lines = file($url); if ($lines === false) { logMsg('Error loading URL: ' . $url); exit(2); } foreach ($lines as $line) { if ($line[0] == '#') { continue; } $line = preg_replace("#\\s+#", ' ', trim($line)); $parts = explode(' ', $line); $type = array_shift($parts); $extensions = $parts; foreach ($extensions as $ext) { if (isset($map[$ext])) { if (isset($duplicateResolution[$ext])) { //force the type to our wishes $type = $duplicateResolution[$ext]; } else { logMsg(sprintf('Duplicate extension: %s for %s and %s', $ext, $map[$ext], $type)); logMsg('Add it to $duplicateResolution array'); exit(1); } } $map[$ext] = $type; } } return $map; }
/** * Generate aggregate metrics for the given test * * @param mixed $benchmark * @param mixed $state */ function AggregateResults($benchmark, &$state, $options) { global $logFile; if (!is_dir("./results/benchmarks/{$benchmark}/aggregate")) { mkdir("./results/benchmarks/{$benchmark}/aggregate", 0777, true); } if (is_file("./results/benchmarks/{$benchmark}/aggregate/info.json")) { $info = json_decode(file_get_contents("./results/benchmarks/{$benchmark}/aggregate/info.json"), true); } else { $info = array('runs' => array()); } if (!array_key_exists('runs', $info)) { $info['runs'] = array(); } // store a list of metrics that we aggregate in the info block $info['metrics'] = array('TTFB', 'basePageSSLTime', 'bytesOut', 'bytesOutDoc', 'bytesIn', 'bytesInDoc', 'connections', 'requests', 'requestsDoc', 'render', 'fullyLoaded', 'docTime', 'domTime', 'score_cache', 'score_cdn', 'score_gzip', 'score_keep-alive', 'score_compress', 'gzip_total', 'gzip_savings', 'image_total', 'image_savings', 'domElements', 'titleTime', 'loadEvent-Time', 'domContentLoadedEventStart', 'domContentLoadedEvent-Time', 'visualComplete', 'lastVisualChange', 'js_bytes', 'js_requests', 'css_bytes', 'css_requests', 'image_bytes', 'image_requests', 'flash_bytes', 'flash_requests', 'html_bytes', 'html_requests', 'text_bytes', 'text_requests', 'other_bytes', 'other_requests', 'SpeedIndex', 'responses_404', 'responses_other', 'browser_version', 'server_rtt', 'docCPUms'); require_once 'benchmarks/data.inc.php'; $bmSettings = GetBenchmarkInfo($benchmark); if (isset($bmSettings) && is_array($bmSettings) && array_key_exists('metrics', $bmSettings) && is_array($bmSettings['metrics'])) { foreach ($bmSettings['metrics'] as $metric => $label) { $info['metrics'][] = $metric; } } // loop through all of the runs and see which ones we don't have aggregates for $runs = array_reverse($state['runs']); foreach ($runs as $run_time) { if (!array_key_exists($run_time, $info['runs'])) { $file_name = "./results/benchmarks/{$benchmark}/data/" . gmdate('Ymd_Hi', $run_time) . '.json'; logMsg("Aggregating Results for {$file_name}", "./log/{$logFile}", true); if (gz_is_file($file_name)) { $data = json_decode(gz_file_get_contents($file_name), true); FilterRawData($data, $options); CreateAggregates($info, $data, $benchmark, $run_time, $options); unset($data); $info['runs'][$run_time] = 1; } else { logMsg("Missing data file - {$file_name}", "./log/{$logFile}", true); } } } file_put_contents("./results/benchmarks/{$benchmark}/aggregate/info.json", json_encode($info)); $state['needs_aggregation'] = false; logMsg("Agregation complete", "./log/{$logFile}", true); }
function error($m) { return logMsg('error', $m); }
require 'checklogin.php'; // Om man ej är inloggad if (!$_SESSION['id']) { header("Location: /login.php"); // Om man är inloggad } else { // Stänger if-else-konstruktionen } // Anslut till MySql-databasen require 'connect.php'; // Importera "items" från databasen "shoppinglist" try { // Förbered och exekvera statement $stmt = $con->prepare("SELECT * FROM items ORDER BY items.Id"); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $item = $row['Data']; $itemId = $row['Id']; $isMarked = $row['isMarked']; if ($isMarked) { echo '<div id=' . $itemId . ' class="marked">'; } else { echo '<div id=' . $itemId . '>'; } echo '<input class="itemBox" value=\'' . $item . '\' type="text" onblur="shoppinglist.updateItem({localOnly: true, id: \'' . $itemId . '\'});" name="myItems[]">'; echo '<button class="itemRemoveButton" tabindex="-1" type="button" onclick="shoppinglist.removeItem({localOnly: true, id: \'' . $itemId . '\'});">x</button>'; echo "</div>"; } } catch (PDOException $ex) { logMsg($ex->getMessage(), "error"); }
/** * Handle serious errors */ function errorHandler($errno, $errstr, $errfile, $errline) { switch ($errno) { //Serious error, like server disconnection. Take a little break before restarting case E_USER_WARNING: logMsg("Error detected, restarting the bot."); sleep(10); doRestart(); break; //PHP Warnings, like SSL errors //PHP Warnings, like SSL errors case E_WARNING: if (strstr($errstr, "OpenSSL Error messages") !== false) { logMsg("SSL error detected, restarting the bot. ({$errstr})"); sleep(10); doRestart(); } break; //PHP Notice, ignore it //PHP Notice, ignore it case E_NOTICE: break; //Default error handling, just log it //Default error handling, just log it default: logMsg("errorHandler: unhandled PHP error {$errno}, {$errstr} from {$errfile}:{$errline}"); break; } return false; }
function mergeTrialAccount($args) { $args; logMsg(0, "mergeTrialAccount"); throw new SoapFault('Client.LoginUnauthorized', l10n("MSG_SOAPFAULT_LOGIN_UNAUTHORIZED") . " (mergeTrialAccount)"); }
@ini_set("memory_limit", "1024M"); @ini_set("max_execution_time", "1200"); $up = dirname(__FILE__); $andreiDb = '../db/andrei.neculau@gmail.com-GoogleMail#database[1]'; $aronDb = '../db/aron.henriksson@gmail.com-GoogleMail#database'; dbChoose(); $thresholdUsernameSimilarity = 90; $thresholdNameSimilarity = 70; $weightMetaphone = 2 / 3; $weightLevenshtein = 2 / 3 * 1 / 3; $weightSoundex = 1 / 3 * 1 / 3; $thresholdWords = 50; $meanMultiplier = 4; $thresholdMean = 5; $thresholdSharedMessages = 3; #$logEcho = true; $logEcho = array('USER', 'MEMORY'); #$limitRecords = " LIMIT 0,100"; $filenameId = array_shift(explode('@', basename($dbFilename))) . '_' . date('YmdHis'); $logFilename = $up . '/logs/' . $filenameId . '.txt'; $log = fopen($logFilename, 'w'); if ($log) { logMsg('DEBUG', 'Log opened for writing'); } if (!$dbFilename) { logMsg('USER', 'Database missing'); die; } else { logMsg('USER', 'Chosen database: ' . array_shift(explode('@', basename($dbFilename)))); dbConnect(); }