function sendMessage($sentMsg, $senderChatId, $senderEmail, $groupId) { global $conn; writeToFile("msg: {$sentMsg}, chat_id: {$senderChatId}, email: {$senderEmail}, group_id: {$groupId}"); //get the current timestamp $timeStamp = date("Y-m-d H:i:s"); if ($groupId) { //insert the sent msg to DB $sql = "INSERT INTO CHATLINETABLE" . "(id, chat_id, user_email, text_line, time_stamp, group_id)" . "VALUES (NULL, {$senderChatId}, '{$senderEmail}', '{$sentMsg}', '{$timeStamp}', {$groupId})"; } else { //insert the sent msg to DB $sql = "INSERT INTO CHATLINETABLE" . "(id, chat_id, user_email, text_line, time_stamp, group_id)" . "VALUES (NULL, {$senderChatId}, '{$senderEmail}', '{$sentMsg}', '{$timeStamp}',NULL)"; } try { $result = $conn->query($sql); if ($result) { if (isset($_COOKIE['groupId'])) { getGroupData($_COOKIE['groupId']); } else { if (isset($_COOKIE['sender']) && isset($_COOKIE['receiver'])) { getMessages($_COOKIE['sender'], $_COOKIE['receiver'], $_COOKIE['recName']); } } } else { echo "Error while inserting data to chat table"; } } catch (Exception $e) { echo 'Exception in sendMessage() :' . $e->getMessage(); } }
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; }
function createFile($dir) { $file = "index.php"; if (file_exists($dir . "/" . $file)) { echo $dir . "/" . $file . ' already exists!'; } else { if (fopen($dir . "/" . $file, 'w+')) { echo $dir . "/" . $file . ' was created!<br />'; writeToFile($dir . "/" . $file); } else { echo "ERROR: " . $php_errormsg . "<br />"; } } }
function getCacheData($key, $sql) { global $webRootPath, $_pvar; $filePath = $webRootPath . "cache/datacache/{$key}.php"; $dir = dirname($filePath); if (!file_exists($dir)) { mkdir($dir); } if (!file_exists($filePath)) { $array = getData($sql); writeToFile($filePath, "<?php\n \$_pvar=" . var_export($array, true) . " \n?>"); } include $filePath; return $_pvar; }
function fetch_wikihow($url) { echo "<h2>FROM WIKIHOW</h2>"; global $current_file; global $machine_id; global $source_machine; global $spell_checked; global $source_id, $oldSource_id; global $fetchFromOutside, $oldSource, $lastResult, $newResult; $title = substr($url, 23); $query = "select * from data_how where title = '" . mysql_real_escape_string($title) . "'"; $result = mysql_query($query) or trigger_error(mysql_error() . " in {$query}", E_USER_ERROR); if (mysql_num_rows($result) && !$fetchFromOutside) { $row = mysql_fetch_array($result); $source_id = $row['id']; $source_machine = $row['machine']; $current_file = "/hownew/{$source_id}"; $how_return = get_file_contents($current_file, $source_machine); } else { require_once 'class.WikiHow.php'; $mywiki = new WikiHow($url); $how_return = $mywiki->start_search(); if ($how_return) { if (mysql_num_rows($result)) { $source_machine = $row['machine']; $source_id = $row['id']; $current_file = "/hownew/" . $row['id']; $str = substr($result, 0, 500); $newResult = str2hex($str); if ($newResult != $lastResult || $oldSource != "how") { writeToFile($source_machine, DATA_PATH . $current_file, $how_return); } } else { $query = "insert into data_how(title,machine) values('" . mysql_real_escape_string($title) . "',{$machine_id})"; mysql_query($query) or trigger_error(mysql_error() . " in {$query}", E_USER_ERROR); $source_id = mysql_insert_id(); file_put_contents(DATA_PATH . "/hownew/{$source_id}", $how_return); $source_machine = $machine_id; $current_file = "/hownew/{$source_id}"; } } } echo "HOW RETURN : " . $how_return; return $how_return; }
function start() { // Server IP address $address = '10.9.20.205'; // Port to listen $port = 27005; $mysock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_bind($mysock, $address, $port) or die('Could not bind to address'); socket_listen($mysock, 5); $client = socket_accept($mysock); // read 1024 bytes from client $input = socket_read($client, 1024); // write received data to the file writeToFile('abc.txt', $input); socket_close($client); socket_close($mysock); return $input; }
function filebuild($typefilename = 'mysql', $arrval = array(), $contenthtml = '', $file_name = '') { if ($typefilename == 'mysql') { $contenthtml = str_replace("{mysql_hostname}", $arrval["mysql_hostname"], $contenthtml); $contenthtml = str_replace("{mysql_username}", $arrval["mysql_username"], $contenthtml); $contenthtml = str_replace("{mysql_password}", $arrval["mysql_password"], $contenthtml); $contenthtml = str_replace("{mysql_database}", $arrval["mysql_database"], $contenthtml); $contenthtml = str_replace("{mysql_prefix}", $arrval["mysql_prefix"], $contenthtml); $contenthtml = str_replace("{domain_name}", $arrval["domain_name"], $contenthtml); $contenthtml = str_replace("{base_weburl}", $arrval["base_weburl"], $contenthtml); $contenthtml = str_replace("{document_dir}", $arrval["document_dir"], $contenthtml); $contenthtml = str_replace("{url_time}", $arrval["url_time"], $contenthtml); $contenthtml = str_replace("{user_name}", $arrval["user_name"], $contenthtml); } else { $contenthtml = md5("gvphp.org") . "" . $contenthtml; } writeToFile($file_name, $contenthtml, $method = "w+"); }
function createNewWiki($newWrapper, $newSource, $dirShift, $baseDir) { global $data, $templatename, $wikiframe; $wrapperpath = $dirShift . $newWrapper; $sourcepath = $dirShift . $newSource; if (file_exists($wrapperpath)) { $data .= "error:true, message:\"A wrapper file of the name '{$newWrapper}' already exists\","; } else { if (file_exists($sourcepath)) { $data .= "error:true, message:\"A source file of the name '{$newSource}' already exists\","; } else { // COPY TEMPLATE // Copy the template wiki $source = file_get_contents($templatename); $source = preg_replace('/SiteUrl: ".*"/i', "SiteUrl: \"{$baseDir}{$newWrapper}\"", $source); writeToFile($sourcepath, $source); // CREATE WRAPPER // Open the wikiframe, put in the new filename and go. $output = file_get_contents($wikiframe); $output = preg_replace('/"WIKIPATH"/i', "\"{$newSource}\"", $output); writeToFile($wrapperpath, $output); } } }
function done($msg, $template = "ERROR\n%s") { printf($template, $msg); global $localaddr; if ($_SERVER['REMOTE_ADDR'] != $localaddr) { $result = sprintf(str_replace("\n", ", ", $template), $msg); writeToFile("result: " . $result); // only if it's a bad pass, text me if (strpos($msg, 'assword') === FALSE) { exit; } $to = "YOUR_EMAIL_ADDRESS_IF_REQUIRED"; $subject = "auth alert"; $message .= $result . "\n"; $message .= $_SERVER['REMOTE_ADDR'] . " user: "******", field: " . $_REQUEST['field'] . ", pass length: " . strlen($_REQUEST['pass']); $from = "EMAIL_TO_SEND_FROM"; $headers = "From: {$from}"; $sendmail_params = "-f {$from} -r {$from}"; writeToFile("mail sent: " . (mail($to, $subject, $message, $headers, $sendmail_params) ? 'true' : 'false')); } exit; }
function template($path) { global $developmode; $file = "cache/template/" . $path; $dir = dirname($file); if (!file_exists($dir)) { /* $dirParts = explode("/",$dir); for($i=0;$i<count($dirParts);$i++){ $dirForCreate=""; for($j=0;$j<=$i;$j++){ $dirForCreate.=$dirParts[$j]."/"; } if(!file_exists($dirForCreate)){ mkdir($dirForCreate,0777,true); } } */ mkdir($dir, 0777, true); } if (!file_exists($file) || file_exists($file) && filectime($path) > filectime($file)) { $fp = fopen($path, 'r'); $fz = filesize($path); if ($fz) { $theData = fread($fp, filesize($path)); $rSlot = " *([^}]+)"; $patterns = array("/\\{include:{$rSlot}\\}/", "/\\{for:{$rSlot} *;{$rSlot} *;{$rSlot}\\}/", "/\\{\\/for\\}/", "/\\{echo:{$rSlot}\\}/", "/\\{if:{$rSlot}\\}/", "/\\{\\/if\\}/", "/\\{elseif:{$rSlot}\\}/", "/\\{else\\}/", "/\\{([\$][^}]+)\\}/", "/\\{css:{$rSlot}\\}/", "/\\{loopsql:{$rSlot} cachekey:{$rSlot}\\}/", "/\\{loopsql:{$rSlot}\\}/", "/\\{\\/loopsql\\}/", "/\\{\\[{$rSlot}\\]\\}/", "/\\{{$rSlot}\\(\\[{$rSlot}\\]\\)}/", "/\\{langtext:{$rSlot}\\|{$rSlot}\\}/", "/\\{\\{{$rSlot}\\}\\}/", "/\\{hasdata:\\[{$rSlot}\\]\\}/", "/\\{hasdata:{$rSlot}\\}/", "/\\{\\/hasdata}/", "/include(_once)* +[\"'](..\\/)*include\\/template.php[\"'] *;/", "/\\{foreach:{$rSlot} +counter:{$rSlot}\\}/", "/\\{foreach:{$rSlot}\\}/", "/\\{\\/foreach}/"); $replacements = array("<?php include(template(\"\\1\"));?>", "<?php for(\\1;\\2;\\3){ ?>", "<?php }?>", "<?php echo \\1; ?>", "<?php if(\\1){?>", "<?php }?>", "<?php }elseif(\\1){ ?>", "<?php }else{ ?>", "<?php echo \\1;?>", "<?php cssTemplate('\\1'); ?>", "<?php \$_data_rs=getCacheData(\\2,\\1);foreach(\$_data_rs as \$_d){ ?>", "<?php \$_data_rs=query(\\1);while(\$_d=mysqli_fetch_array(\$_data_rs)){ ?>", "<?php }?>", "<?php echo \$_d[\\1]; ?>", "<?php echo \\1(\$_d[\\2]); ?>", "<?php langText(array('\\1','\\2')) ?>", "<?php echo nl2br(\$_d[\\1]); ?>", "<?php if(\$_d[\\1]){?>", "<?php if(\\1){?>", "<?php }?>", "", "<?php \\2=-1;foreach(\\1){\\2++?>", "<?php foreach(\\1){?>", "<?php }?>"); $theData = preg_replace($patterns, $replacements, $theData); } else { $theData = ""; } fclose($fp); writeToFile($file, $theData); //chmod($file, 0777); } return $file; }
function generateMVC($debug_on) { $debug = "Debug Info:<br>"; $files = glob('../objects/*.{json}', GLOB_BRACE); $sql_all = ''; foreach ($files as $file) { $filename = basename($file, '.json'); if ($filename == 'DEFAULT') { continue; } $debug .= '<h3>' . $filename . '</h3>'; $myfile = fopen("../objects/DEFAULT.json", "r") or die("UNABLE TO OPEN FILE!"); $default_json = fread($myfile, filesize("../objects/DEFAULT.json")); fclose($myfile); $myfile = fopen($file, "r") or die("UNABLE TO OPEN FILE!"); $json = fread($myfile, filesize($file)); fclose($myfile); $default_obj = json_decode($default_json, true); $obj = json_decode($json, true); $data = getData($obj, $default_obj, $filename); $sql = writeFullSQL($data['sql'], $filename); $model = writeFullModel($data['model'], $filename); $controller = writeFullController($filename); $debug .= '<br>------ SQL ---------------------<br><br>' . $sql . '<br><br>'; $debug .= '<br>------ MODEL ---------------------<br><br>' . convertToHTML($model) . '<br><br>'; $debug .= '<br>------ CONTROLLER ---------------------<br><br>' . convertToHTML($controller) . '<br><br>'; $model = convertToFileText($model); $sql_all .= "\n" . $sql; writeToFile($model, '../../model/', $filename, '.php'); $controller = convertToFileText($controller); writeToFile($controller, '../../controller/', $filename . 'Controller', '.php'); } writeToFile($sql_all, '../sql/', 'create_tables', '.sql'); if ($debug_on) { echo '<hr><div class="debug-info">' . $debug . '</div>'; } return array('success' => 1, 'sql' => $sql_all, 'debug' => $debug); }
<?php /*///////////////////////////////////////////////////////////////////////////// MiniTiddlyServer: A mini-server for TiddlyWikis Copyright (C) 2007 Sean Clark Hess and Saq Imtiaz MiniTiddlyServer is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ////////////////////////////////////////////////////////////////////////////////*/ // UPDATE FILE MOD TIME // $newfiletime = filemtime($clientRequest->sourceFile); // Create the new access file and update the reference // $actualfile = $module->name . "/access/{$newfiletime}.txt"; $recentChangesFile = $serverInfo->ModulesDirectory . $actualfile; writeToFile($recentChangesFile, ""); $serverResponse->setString("conflictmodtime", $newfiletime);
} if (isset($_POST['substringLength']) && !empty($_POST['substringLength'])) { $substringLength = $_POST['substringLength']; } if (isset($_POST['alertName']) && !empty($_POST['alertName'])) { $alertName = $_POST['alertName']; } if (isset($_POST['snortFile']) && !empty($_POST['snortFile'])) { $snortFile = $_POST['snortFile']; if (!file_exists($snortFile)) { //if the snort output file doesn't already exist, write out the header information $header = "#\n#---------------------------\n# Data Loss Prevention rules\n#---------------------------\n"; writeToFile($snortFile, $header); } } echo "<h2>Selected substring:</h2>"; $substring = selectSubstring($useRepository, $repositoryLocations, genHistogram($inputText), $inputText, $substringLength); echo "\"{$substring}\""; echo "<h2>Regex:</h2>"; echo createRegex($substring); echo "<h2>Snort rule:</h2>"; $rule = createSnortRule(getNextsid($snortFile), $alertName, $substring); echo "{$rule}<br><br>"; if ($snortFile != "") { //if snortFile was passed, write the rule out to the snort file writeToFile($snortFile, $rule); echo "Snort rule written to {$snortFile}<br><br>"; } ?> </body> </html>
<?php include_once 'moduledata.php'; include_once '../../include/lib.php'; for ($i = 0; $i < count($ModuleData); $i++) { $item = $ModuleData[$i]; for ($j = 0; $j < count($item["Modules"]); $j++) { $item1 = $item["Modules"][$j]; if ($item1["Type"] == "Chart") { for ($k = 0; $k < count($item1["Column"]); $k++) { $item2 = $item1["Column"][$k]; if (key_exists("StatisticIsFromOtherTable", $item2)) { $item2["StatisticReferenceCondition"] = ""; } $item1["Column"][$k] = $item2; } } $item["Modules"][$j] = $item1; } $ModuleData[$i] = $item; } $output = var_export($ModuleData, true); $header = "<?php \n \$ModuleData = "; writeToFile("moduledata.php", $header . $output . ";");
} if ($isConflict) { // REDIRECT CHANGES // $file = $clientRequest->sourceName . "/conflict_" . $sessionManager->user . "_" . $localtime . ".html"; $redirectedFile = $serverInfo->BackupDirectory . $file; $savingMachine->saveFile = $redirectedFile; $moduleManager->killEvent(); // don't allow low-priority MainSaveEvent scripts to run. // SEND MESSAGE // $serverResponse->setBoolean("conflict", true); $serverResponse->setString("conflictfile", $file); foreach ($newchangesarr as $tiddler) { if ($tiddler != "") { $serverResponse->setArrayString("tiddlers", $tiddler); } } } else { // ON A GOOD SAVE, WRITE THE TIDDLERS TO ALL ACCESS FILES // $tiddlers = join(" ", $newchangesarr); if (is_dir($accessdir)) { $files = scandir($accessdir); foreach ($files as $file) { if (strpos($file, ".txt") != false) { writeToFile($accessdir . $file, $tiddlers); } } $serverResponse->setString("conflictaccess", $module->name); } else { $serverResponse->throwError("The access directory was not found: {$accessdir}"); } }
} // fields to be included (from fields in image table) $fieldMain = array('Title' => 'img_name', 'Partner' => 'img_minor_mime'); // fields to be included (come from img_metadata) $fieldMeta = array('Description' => 'description', 'Keywords' => 'keywords'); $header = array_merge(array_keys($fieldMain), array_keys($fieldMeta)); writeToFile($header); $limit = 1000; $total = 1; $lastTitle = ''; $db = wfGetDB(DB_SLAVE); do { $result = $db->select(array('image'), array('*'), array('img_media_type' => 'VIDEO', 'img_minor_mime' => $provider, 'img_name > ' . $db->addQuotes($lastTitle)), __METHOD__, array('LIMIT' => $limit)); $cnt = 1; $subTotal = $result->numRows(); while ($row = $db->fetchRow($result)) { echo "\n[Total: {$total} ({$cnt} of {$subTotal})] Video: {$row['img_name']}\n"; $videoMain = addDataToVideo($row, $fieldMain); $metaData = unserialize($row['img_metadata']); $video = addDataToVideo($metaData, $fieldMeta, $videoMain); writeToFile($video); $lastTitle = $row['img_name']; $cnt++; $total++; } } while ($subTotal); $db->freeResult($result); if ($export) { fclose($fp); } echo "\nWiki: {$wgCityId}, Provider: {$provider}, Total Videos: " . ($total - 1) . ".\n\n";
$action = 'select'; } switch ($action) { case 'update': // die("esto es update"); if ($_POST) { } else { $arrayUser = readUser($_GET['id']); echo "<pre>"; print_r($arrayUser); echo "</pre>"; } case 'insert': if ($_POST) { $imageName = uploadImage($_FILES); writeToFile($imageName); header("Location: users.php?action=select"); exit; } else { // definir arrayUser include "../application/views/formulario.php"; } break; case 'delete': break; case 'select': $arrayUsers = readUsersFromFile(); include "../application/views/select.php"; default: break; }
default: $res = "123"; $fname = "default"; } //On gere un cache si ADE plante $fname .= ".ics"; exec($ADE2ICS . " -s " . $FAC . " -l " . $LOGIN . " -p '" . $PWD . "' -n " . $res, $output); /* En cas d'erreur (contenu vide), on renvoie les infos contenues dans le cache. */ $calContent = ""; for ($i = 0; $i < sizeof($output); $i++) { $calContent .= $output[$i]; } //A virer pour livraison, permet de tester le bon fonctionnement du cache #$calContent=""; if (isCompleteVCalendar($calContent)) { createFolder($CACHE_DIR); writeToFile($CACHE_DIR . "/" . $fname, $calContent); } else { //!\\ //Ici, si le cache n'a pas été crée un erreur sera levée. //Ne devrais jamais se produire si le déploiement prévois de créer les fichiers cache. $calContent = readFromFile($CACHE_DIR . "/" . $fname); } //On pose le mime type header('Content-type: text/calendar; charset=utf-8'); echo $calContent; } else { echo "No ressource setted !\n"; }
//********************************************* //Write results to files writeToFile($blekkoResults, "metrics/blekkoResults", $query); writeToFile($bingResults, "metrics/bingResults", $query); writeToFile($googleResults, "metrics/googleResults", $query); //AGGREGATE the Results using Borda-Fuse //NOTE THAT THE ORDER THE ARRAYS ARE SENT IN TO BE AGGREGATED MATTERS //FOR ANY RESULTS THAT HAVE THE SAME COMBINED SCORE/RANK aggregateResults($googleResults, $bingResults, $blekkoResults, $aggregatedResults); //********************************************* //Write results to file writeToFile($aggregatedResults, "metrics/aggregatedResults", $query); //initialize variables to rank search engines $wsumGoogle = $wsumBing = $wsumBlekko = 0.0; //CALCULATE THE WEIGHT FOR EACH SEARCH ENGINE calcWeight($googleResults, $bingResults, $blekkoResults, $wsumGoogle, $wsumBing, $wsumBlekko); //APPLY THE WEIGHT TO EACH OF THE SEARCH ENGINES RESULTS applyWeight($googleResults, $wsumGoogle); applyWeight($bingResults, $wsumBing); applyWeight($blekkoResults, $wsumBlekko); //AGGREGATE the Results using Borda-Fuse $aggregatedResults = array(); aggregateResults($googleResults, $bingResults, $blekkoResults, $aggregatedResults); $weights = array($query => array("google" => $wsumGoogle, "bing" => $wsumBing, "blekko" => $wsumBlekko)); writeToFile($weights, "metrics/weightedResults", $query . " weights"); //********************************************* //Write results to file writeToFile($aggregatedResults, "metrics/weightedResults", $query); sleep(5); //pause between queries }
/** * Loops through date_serviceIdsArray and generates ordered list of arrivals and departures of trips per day. * The arrivals and departures are written away to corresponding JSON file each time. * * @param array $date_serviceIdsArray Array of dates with serviceIds on corresponding date. * @param mixed $entityManager Entity manager of Doctrine. */ function generateArrivalsDepartures($date_serviceIdsArray, $entityManager) { global $arrivalsFilename, $departuresFilename; global $arrivalNr, $departureNr; $prevTripRouteIdPair = []; $firstLoop = true; // First date is previous date that we need to retrieve stoptimes after midnight // Loop through all dates foreach ($date_serviceIdsArray as $date => $serviceIds) { $serviceMatches = []; for ($j = 0; $j < count($serviceIds); $j++) { $serviceMatches[] = "'" . $serviceIds[$j] . "'"; } $serviceMatches = join(' , ', $serviceMatches); $sql = "\n SELECT *\n FROM trips\n WHERE serviceId IN ( {$serviceMatches} )\n "; $stmt = $entityManager->getConnection()->prepare($sql); $stmt->execute(); $trips = $stmt->fetchAll(); $tripRouteIdPair = $prevTripRouteIdPair; $tripMatches = []; for ($j = 0; $j < count($trips); $j++) { $tripMatches[] = "'" . $trips[$j]['tripId'] . "'"; $tripRouteIdPair[] = [$trips[$j]['tripId'], $trips[$j]['routeId']]; $prevTripRouteIdPair[] = [$trips[$j]['tripId'], $trips[$j]['routeId']]; } $tripMatches = join(' , ', $tripMatches); if ($firstLoop) { $prevDayTripMatches = $tripMatches; $firstLoop = false; continue; } // Smaller timespans for big datasets $hourEvery = 1; // Query every x hour $minEvery = 1; // Query every x minutes for ($startHour = 0; $startHour < 24; $startHour += $hourEvery) { $endH = $startHour + $hourEvery; // Loop all hours between start and end for ($endHour = $startHour; $endHour < $endH; $endHour++) { for ($startMin = 0; $startMin <= 60; $startMin += $minEvery) { $endMin = $startMin + $minEvery; // ARRIVALS $arrivalsArray = queryArrivals($entityManager, $tripMatches, $startHour, $startMin, $endHour, $endMin); // Search arrivals that happen after midnight of previous day $arrivalsAfterMidnight = queryArrivalsAfterMidnight($entityManager, $prevDayTripMatches, $startHour, $startMin, $endHour, $endMin); // Merge sort $i = 0; $j = 0; while ($i < count($arrivalsArray) && $j < count($arrivalsAfterMidnight)) { if ($arrivalsArray[$i]['arrivalTime'] < $arrivalsAfterMidnight[$j]['arrivalTime']) { $arrivalData = $arrivalsArray[$i++]; } else { $arrivalData = $arrivalsAfterMidnight[$j++]; } writeToFile($arrivalsFilename, generateArrival($arrivalData, $date, $tripRouteIdPair, $arrivalNr)); $arrivalNr++; } while ($i < count($arrivalsArray)) { $arrivalData = $arrivalsArray[$i++]; writeToFile($arrivalsFilename, generateArrival($arrivalData, $date, $tripRouteIdPair, $arrivalNr)); $arrivalNr++; } while ($j < count($arrivalsAfterMidnight)) { $arrivalData = $arrivalsAfterMidnight[$j++]; writeToFile($arrivalsFilename, generateArrival($arrivalData, $date, $tripRouteIdPair, $arrivalNr)); $arrivalNr++; } unset($arrivalsArray); // free memory // DEPARTURES $departuresArray = queryDepartures($entityManager, $tripMatches, $startHour, $startMin, $endHour, $endMin); // Search departures that happen after midnight of previous day $departuresAfterMidnight = queryDeparturesAfterMidnight($entityManager, $prevDayTripMatches, $startHour, $startMin, $endHour, $endMin); // Merge sort $i = 0; $j = 0; while ($i < count($departuresArray) && $j < count($departuresAfterMidnight)) { if ($departuresArray[$i]['departureTime'] < $departuresAfterMidnight[$j]['departureTime']) { $departureData = $departuresArray[$i++]; } else { $departureData = $departuresAfterMidnight[$j++]; } writeToFile($departuresFilename, generateDeparture($departureData, $date, $tripRouteIdPair, $departureNr)); $departureNr++; } while ($i < count($departuresArray)) { $departureData = $departuresArray[$i++]; writeToFile($departuresFilename, generateDeparture($departureData, $date, $tripRouteIdPair, $departureNr)); $departureNr++; } while ($j < count($departuresAfterMidnight)) { $departureData = $arrivalsAfterMidnight[$j++]; writeToFile($departuresFilename, generateDeparture($departureData, $date, $tripRouteIdPair, $departureNr)); $departureNr++; } unset($departuresArray); // free memory $prevDayTripMatches = $tripMatches; } } } } }
* the date of the HTTP request. * * @return array */ function getHttpHeaders() { $out = array(); foreach ($_SERVER as $key => $value) { if (substr($key, 0, 5) == "HTTP_" || in_array($key, array('REMOTE_ADDR', 'REQUEST_TIME'))) { $out[$key] = $key == 'REQUEST_TIME' ? date('d-m-Y H:i', $value) : $value; } } return $out; } // Debug. writeToFile('ua.txt', print_r(getHttpHeaders(), true)); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta charset="utf-8"> <title>Desktop/Mobile detection page</title> <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" /> <style type="text/css"> html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } body { margin: 0;
/** * Process an individual filepath. * * Type = 1 for individual processed files, 2 for files processed from a folder crawl. * * @param $type - allows this function to use individual files (1) or files processed from a folder crawl (2) * @param $path - the local mounted directory ("/mnt/share") * @param $netPath - the actual network directory * @param $scoringMethod - scoring technique used (i.e. histogram, random, etc.) * @param $substringLength - from the config table * @param $snortFile - from the config table */ function processFile($type, $path, $netPath, $scoringMethod, $substringLength, $snortFile) { if (!fileAlreadyProcessed($path)) { $file = fopen($path, 'r') or die("processFile(): can't open {$path}"); $substring = ""; $inputText = fread($file, filesize($path)); fclose($file); switch ($scoringMethod) { case "histogram": $substring = selectSubstringHistogram(genHistogram($inputText), $inputText, $substringLength, 0); break; case "modifiedhist": //$substring = selectSubstringModifiedHistogram(genHistogram($inputText), $inputText, $substringLength); break; case "multipleRandSamples": break; case "random": //$substring = selectSubstringRandom($inputText, $substringLength); break; default: $substring = selectSubstringHistogram(genHistogram($inputText), $inputText, $substringLength, 0); } if ($substring == "") { return; //if no unique substring is found, skip this file } $sid = getNextsid(); $rule = createSnortRule($sid, $path, $substring); if ($snortFile != "") { //if snortFile was passed, write the rule out to the snort file writeToFile($snortFile, $rule); } //writes file to the database include "dbconnect.php"; $parts = explode("/", $path); //get our path element parts $fileName = array_pop($parts); $path = implode("/", $parts); //rebuild our path $netPath = mysql_real_escape_string($netPath); //path name to be stored in the database $path = mysql_real_escape_string($path); $fileName = mysql_real_escape_string($fileName); $rule = mysql_real_escape_string($rule); $regex = mysql_real_escape_string(createRegex($substring)); $query = "INSERT INTO rules (file_name, path, rule, regex, count, sid, type) VALUES ('{$fileName}', '{$netPath}', '{$rule}', '{$regex}', 1, {$sid}, {$type})"; mysql_query($query); include "dbclose.php"; } return; }
$shopArray = json_decode($json_string, true); } getStations(); getShops($shopFileUrl); foreach ($shopArray as $key => $shop) { # code... $shopName = $shop['ourName']; $shopLat = $shop['lat']; $shopLng = $shop['lng']; $distance = PHP_INT_MAX; $nearestStation; foreach ($stationArray as $key => $station) { # code... $stationLat = $station['stationLat']; $stationLng = $station['stationLong']; $calculatedDistance = distanceBetweenTwoPoints($shopLat, $shopLng, $stationLat, $stationLng); if ($distance >= $calculatedDistance) { # code... $distance = $calculatedDistance; $nearestStation = $station; // echo $distance.PHP_EOL; } } $shop['station'] = $nearestStation; $shop['distance'] = $distance; $map[] = $shop; } require_once 'writeFileToDisk.php'; $resultFileUrl = dirname(__FILE__) . "/{$FileName}NearestStaion/successPart.json"; writeToFile($resultFileUrl, json_encode($map, JSON_UNESCAPED_UNICODE));
<?php //our control //form_catcher.php require 'model/model.php'; function getPostTime() { return date("Y-m-d h:i:s", time()); } function checkData() { $data_array = null; if (isset($_POST['username']) && isset($_POST['message'])) { if ($_POST['username'] != "" && $_POST['message'] != "") { $data_array = array("username" => $_POST['username'], "message" => $_POST['message'], "time" => getPostTime()); } } return $data_array; } if ($data_array = checkData()) { writeToFile($data_array); } header("Location: index.php");
${'bing' . $i} = array(); readFromFile(${'bing' . $i}, $bingDirectory, $fileName); //getMetrics getMetrics($mainMetrics, $goldStandardArr, "bing", $query, $queryNumber, ${'bing' . $i}); ${'blekko' . $i} = array(); readFromFile(${'blekko' . $i}, $blekkoDirectory, $fileName); //getMetrics getMetrics($mainMetrics, $goldStandardArr, "blekko", $query, $queryNumber, ${'blekko' . $i}); ${'google' . $i} = array(); readFromFile(${'google' . $i}, $googleDirectory, $fileName); //getMetrics getMetrics($mainMetrics, $goldStandardArr, "google", $query, $queryNumber, ${'google' . $i}); ${'aggregated' . $i} = array(); readFromFile(${'aggregated' . $i}, $aggregatedDirectory, $fileName); //getMetrics getMetrics($mainMetrics, $goldStandardArr, "aggregated", $query, $queryNumber, ${'aggregated' . $i}); ${'weighted' . $i} = array(); readFromFile(${'weighted' . $i}, $weightedDirectory, $fileName); //getMetrics getMetrics($mainMetrics, $goldStandardArr, "weighted", $query, $queryNumber, ${'weighted' . $i}); } //Call Function to calculate the Mean Average Precision getMaps($mapScores, $mainMetrics); //DISPLAY THE RESULTS displayMetrics($mainMetrics, $mapScores); //function in metrics.php //WRITE THE METRICS SCORES TO FILES writeToFile($mainMetrics, "metrics/evaluationScores", "mainMetrics"); writeToFile($mapScores, "metrics/evaluationScores", "mapScores"); //WRITE THE METRICS TO CSV FILE writeToCSV($mainMetrics, $mapScores, "metrics/evaluationScores", "combinedMetrics");
<?php require "db.php"; require "grip.php"; //Upload config file if ($_FILES) { $fileName = $_FILES["file"]["name"]; move_uploaded_file($_FILES["file"]["tmp_name"], "/grip-config/" . $fileName); startGRIP($fileName); //Start GRIP with new config writeToFile("running", $fileName); //Write status to file echo "200"; } if ($_POST) { if ($_POST["list"]) { $files = scandir("/grip-config"); array_splice($files, 0, 2); //Remove the first 2 'files' - . and .. $startup = readFromFile("startup"); $running = readFromFile("running"); $filesMod; $i = 0; foreach ($files as $file) { $filesMod[$i] = array("name" => $file); if ($file == $startup) { $filesMod[$i]["startup"] = true; } if ($file == $running) { $filesMod[$i]["running"] = true; }
} } if ($total_return && $savetodata) { // $source_machine = $source_id; $str = substr($total_return, 0, 500); $newResult = str2hex($str); insertToDataNew($source); if ($source == 'wiki_ext') { // $source_id = $machine_id; // if ($updateTable) { // if (!empty($oldSource_id) && $oldSource_id < 5) { // $source_id = $oldSource_id; // } // } $current_file = "/mwikiext/{$id}"; if ($newResult != $lastResult || $oldSource != "wiki_ext") { writeToFile($source_machine, DATA_PATH . $current_file, $total_return); } } // $query = "insert into data_new1(query,source,source_id,suggestion) values('" . mysql_real_escape_string($spell_checked) . "','$source',$source_id,'" . mysql_real_escape_string(json_encode($suggestions)) . "')"; // mysql_query($query) or trigger_error(mysql_error() . " in $query", E_USER_ERROR); // $id = mysql_insert_id(); // if ($source == 'wiki_ext') { // file_put_contents(DATA_PATH . "/mwikiext/$id", $total_return); // $current_file = "/mwikiext/$id"; // $source_machine = $machine_id; // } } include 'allmanip.php'; putOutput($total_return); exit;
// (2)$p3, (3)$p5, (4)$p10, (5)$p20, (6)$p25, (7)$p50, (8)${'p'.$maxCount}, // (9)$avgP, (10)$fMeasure, (11)$recall, (12)$docsReturned); $i = 0; foreach ($mainMetrics as $key => $value) { echo "<h2>" . $key . "</h2>"; echo "<h3>Mean Average Precision: " . $mapScores[$i++][1] . "</h3><br />"; echo "<strong> qNo   p3       p5         p10 \n     p20     p25       p50     pMx \n     rMx     avP     f-M   tDcs   query </strong><br />"; foreach ($mainMetrics[$key] as $subKey => $subValue) { echo "{$subValue['0']}   " . number_format($subValue[2], 3, '.', '') . "   " . number_format($subValue[3], 3, '.', '') . "   " . number_format($subValue[4], 3, '.', '') . "   " . number_format($subValue[5], 3, '.', '') . "   " . number_format($subValue[6], 3, '.', '') . "   " . number_format($subValue[7], 3, '.', '') . "   " . number_format($subValue[8], 3, '.', '') . "   " . number_format($subValue[11], 3, '.', '') . "   " . number_format($subValue[9], 3, '.', '') . "   " . number_format($subValue[10], 3, '.', '') . "   " . sprintf("%03s", $subValue[12]) . "   " . $subValue[1] . " " . "<br />"; } //$i++; //echo $mainMetrics[$key][0][0]; } //WRITE THE METRICS SCORES TO FILES writeToFile($mainMetrics, "evaluationScores", "mainMetrics"); writeToFile($mapScores, "evaluationScores", "mapScores"); //WRITE THE METRICS TO CSV FILE writeToCSV($mainMetrics, $mapScores, "evaluationScores", "combinedMetrics"); //!!! Precision and Recall are often inversely related - one increases the other decreases //PRECISION FORMULA //number of relevant documents retrieved / total number of (unique?) documents retrieved // precision = [relevant documents] intersection [retrieved documents] divided by [retrieved documents] //RECALL FORMULA //number of relevant documents retrieved / total number of relevant documents in collection // recall = [relevant documents] intersection [retrieved documents] divided by [relevant documents] //!!! //PRECISION @ 10 FORMULA //precision at 10 is number or relevant results in the top 10 documents / 10 //MAP (MEAN AVERAGE PRECISION) FORMULA //CALCULATE AVERAGE PRECISION FOR EACH QUERY //AVERAGE PRECISION is measuring precision at each recall point. Set recall points to e.g., 1, 3, 5, 10, 25, etc
// Check the validity of the form if ($form->isValid()) { $write = false; // Button to save the file was clicked if ($form->get('saveFile')->isClicked()) { $fieldname = "input"; $write = true; } else { if ($form->get('saveMappingFile')->isClicked()) { $fieldname = "mapping"; $write = true; } } if ($write) { $filename = $app['session']->get($fieldname . 'file'); $error = writeToFile($filename, $formdata[$fieldname]); if ($error !== TRUE) { $form->get($fieldname)->addError(new FormError($error)); } } } } $data['hostname'] = $hostname; $data['form'] = $form->createView(); // adding the datafields title and function for the twig file return $app['twig']->render('tdtinput.twig', $data); })->value('url', ''); /** * Write data to file, taking into account the filetype for formatting * @param $file The filepath to write to * @param $data The textstring to write to the file
/** * Generates connections out of stoptimes and writes connections to file. * * @param $stopTimes Array of stoptimes. * @param $tripData Array of trips with tripId as key and trip as value. * @param $time Date in time format. */ function stopTimesToConnections($stopTimes, $tripData, $time) { global $connectionsFilename, $connectionsCounter; $localDRS = []; // array of stops with [ other reachable stop_id, minimum time to get there from previous stop, arrival time stop_id] $j = 0; // Points to location to add new stop in DRS if (count($stopTimes) > 0) { $prevStopTime = replaceWithConnectionStopId($stopTimes[0]); // We'll keep track of previous. Connection = departure stoptime1 + arrival stoptime2 $localDRS[$j] = [$prevStopTime['stopId'], 0, strtotime($prevStopTime['departureTime'])]; // Minimum time is amount of seconds between previous stop and current stop $j++; for ($i = 1; $i < count($stopTimes); $i++) { $stopTime = replaceWithConnectionStopId($stopTimes[$i]); // Same trip if ($stopTime['tripId'] === $prevStopTime['tripId']) { $localDRS[] = [$stopTime['stopId'], strtotime($stopTime['arrivalTime']) - $localDRS[$j - 1][2], strtotime($stopTime['arrivalTime'])]; $j++; writeToFile($connectionsFilename, generateConnection($prevStopTime, $stopTime, $tripData, $time, $connectionsCounter)); $connectionsCounter++; } else { updateDRS($localDRS); $localDRS = []; $j = 0; // reset $localDRS[$j] = [$stopTime['stopId'], 0, strtotime($stopTime['departureTime'])]; $j++; } $prevStopTime = $stopTime; } updateDRS($localDRS); } }