/** Cacher::__construct() * @param string $name name for this instance of the cacher object * @param string $dataSource anything that would do for the fileParserClass * @see FileParser::__construct() */ public function __construct($name, $dataSource) { self::setName($name); # Decide on which object to use $type = (string) "Cache"; if (extension_loaded("mysql")) { $type .= "Mysql"; } elseif (extension_loaded("apc")) { $type .= "Apc"; } else { $type .= "File"; } print "<pre style='font-family:verdana;font-size:13'>"; print_r($type); print "</pre>"; require_once BASE . "basefunctions/baseapis/cache/mechanisms/" . $type . ".php"; self::setCache(new $type(self::getName())); if (($data = self::getCache()->load(self::getName())) === false) { require_once BASE . "basefunctions/baseapis/FileParser/FileParser.php"; $fileParser = new FileParser($dataSource); $data = $fileParser->parseFile(); if (self::getCache()->save($data) === false) { print "Something went wrong with the saving of the cache" . PHP_EOL; } } if ($data && is_array($data)) { self::setData($data); } }
/** fleetTruckLinkImporter::__construct() * Class constructor */ public function __construct() { $realPath = realpath(dirname(__FILE__)); $maxine = substr($realPath, 0, strrpos($realPath, DIRECTORY_SEPARATOR)); $rootaccess = substr($maxine, 0, strrpos($maxine, DIRECTORY_SEPARATOR) + 1); define("BASE", $rootaccess); include_once BASE . "basefunctions/baseapis/TableManager.php"; include_once BASE . "basefunctions/baseapis/FileParser/FileParser.php"; $manager = new TableManager("fleet_truck_count"); $apiurl = "https://t24.max.bwtsgroup.com/api_request/Report/export?report=73&responseFormat=csv"; // Live // $apiurl = "http://max.mobilize.biz/m4/2/api_request/Report/export?report=141&responseFormat=csv"; // Test $required_fleets = (array) array(27, 13, 20, 26, 24); $rows = (array) array(); foreach ($required_fleets as $fleetId) { $url = $apiurl . "&Fleet=" . $fleetId; $fileParser = new FileParser($url); $fileParser->setCurlFile("fleet_truck_count_" . $fleetId . ".csv"); $data = $fileParser->parseFile(); $cnt = count($data); $rows[] = array("fleet_id" => $fleetId, "count" => $cnt, "t24" => 1); unset($s); unset($cnt); } //: Delete rows where t24=1 $sql = (string) "DELETE FROM `fleet_truck_count` WHERE `t24`=1"; $manager->runSql($sql); $manager->insert($rows); }
/** * Retrieves the line the specified constant starts at. * * @param string $filename * @param string $name * * @return int|null */ protected function getStartLineIn($filename, $name) { if (!$filename) { return null; } $parser = new FileParser($filename); return $parser->getLineForRegex("/const\\s+{$name}/"); }
/** * Execute the command * @param array $args Arguments gived to the command * @return array Response */ public function execute($args = array()) { $fileExists = false; // If we specified a file if (count($args) > 0 && ($file = $args[0])) { if (file_exists(Config::get('indexClasses'))) { $index = json_decode(file_get_contents(Config::get('indexClasses')), true); // Invalid json (#24) if (false !== $index) { $fileExists = true; $found = false; $fileParser = new FileParser($file); $class = $fileParser->getFullClassName(null, $found); // if (false !== $class = array_search($file, $classMap)) { if ($found) { if (isset($index['mapping'][$class])) { unset($index['mapping'][$class]); } if (false !== ($key = array_search($class, $index['autocomplete']))) { unset($index['autocomplete'][$key]); $index['autocomplete'] = array_values($index['autocomplete']); } if ($value = $this->buildIndexClass($class)) { $index['mapping'][$class] = array('methods' => $value); $index['autocomplete'][] = $class; } } } } } // Otherwise, full index if (!$fileExists) { // Autoload classes foreach ($this->getClassMap(true) as $class => $filePath) { if ($value = $this->buildIndexClass($class)) { $index['mapping'][$class] = $value; $index['autocomplete'][] = $class; } } // Internal classes foreach (get_declared_classes() as $class) { $provider = new ClassProvider(); if ($value = $provider->execute(array($class, true))) { if (!empty($value)) { $index['mapping'][$class] = $value; $index['autocomplete'][] = $class; } } } } file_put_contents(Config::get('indexClasses'), json_encode($index)); return array(); }
public function execute() { $paths = $this->getFiles($this->sourceFilesDir); $prefixLength = strlen($this->sourceFilesDir); $modules = array(); $indexModule = null; for ($i = 0; $i < count($paths); $i++) { $path = $paths[$i]; $filename = trim(substr(substr($path, 0, -3), $prefixLength), "/\\."); $moduleName = str_replace(DS, '.', $filename); if (!empty($this->rootModuleName)) { $moduleName = $this->rootModuleName . '.' . $moduleName; } $skip = false; foreach ($this->excludes as $key => $value) { $len = strlen($value); if (substr($moduleName, 0, $len) == $value) { $skip = true; break; } } if ($skip) { continue; } $module = array('path' => $path, 'filename' => $filename, 'moduleName' => $moduleName, 'outputFilename' => strtolower($moduleName) . '.html'); if ($moduleName == $this->indexModuleName) { $module['outputFilename'] = 'index.html'; $indexModule = $module; } else { $modules[] = $module; } } usort($modules, array($this, 'compareTwoModule')); if (!$indexModule) { printf("\nnot found index module.\n"); return false; } array_unshift($modules, $indexModule); foreach ($modules as $module) { printf("create %s\n", $module['moduleName']); $parser = new FileParser($this->title, $module['moduleName'], $indexModule['outputFilename']); $parser->parse($module['path']); $outputPath = $this->outputDir . DS . $module['outputFilename']; file_put_contents($outputPath, $parser->html($modules)); // print("ok\n"); } $this->copyfile('luadocx-style.css'); $this->copyfile('luadocx-style-monokai.css'); $this->copyfile('luadocx-highlight.min.js'); print "copy assets file.\n"; print "\n"; return true; }
/** * @return Array */ public function provideParsedLines() { $parser = new FileParser(); $lines = array(); for ($i = 0; $i < $parser->getLines(); $i++) { $line = $parser->readLine($i); $blz = mb_substr($line, 0, 8, 'UTF-8'); $type = mb_substr($line, FileParser::TYPE_OFFSET, FileParser::TYPE_LENGTH, 'UTF-8'); $lines[] = array($blz, $type); } return $lines; }
/** * {@inheritDoc} */ public function execute(array $args = []) { $isSuccessful = true; $fileToReindex = array_shift($args); if (!$fileToReindex) { $index = []; foreach (get_declared_classes() as $class) { if (mb_strpos($class, 'PhpIntegrator') === 0) { continue; // Don't include our own classes. } if ($value = $this->fetchClassInfo($class, false)) { $index[$class] = $value; } } foreach ($this->buildClassMap() as $class => $filePath) { if ($value = $this->fetchClassInfo($class, true)) { $index[$class] = $value; } } } elseif (file_exists(Config::get('indexClasses'))) { $index = json_decode(file_get_contents(Config::get('indexClasses')), true); if ($index !== false) { $found = false; $fileParser = new FileParser($fileToReindex); $class = $fileParser->getFullClassName(null, $found); if ($found) { if (isset($index[$class])) { unset($index[$class]); } $value = $this->fetchClassInfo($class, true); if ($value) { $index[$class] = $value; } else { $isSuccessful = false; } } } } file_put_contents(Config::get('indexClasses'), json_encode($index)); return ['success' => $isSuccessful, 'result' => null]; }
/** * Validates a bundesbank file. * * @param string $file bundesbank file. * @throws FileValidatorException */ public function validate($file) { $parser = new FileParser($file); // file size is normally around 3 MB. Less than 1.5 is not valid $size = filesize($file); if ($size < self::FILESIZE) { throw new InvalidFilesizeException("Get updated BAV version:" . " file size should not be less than " . self::FILESIZE . " but was {$size}."); } // check line length $minLength = FileParser::SUCCESSOR_OFFSET + FileParser::SUCCESSOR_LENGTH; if ($parser->getLineLength() < $minLength) { throw new InvalidLineLengthException("Get updated BAV version:" . " Line length shouldn't be less than {$minLength} but was {$parser->getLineLength()}."); } // rough check that line length is constant. if ($size % $parser->getLineLength() != 0) { throw new InvalidLineLengthException("Get updated BAV version: Line length is not constant."); } $firstLine = $parser->readLine(0); if (!preg_match("/^100000001Bundesbank/", $firstLine)) { throw new FieldException("Get updated BAV version: first line has unexpected content: {$firstLine}"); } }
/** * Resolves and determiens the full return type (class name) for the return value of the specified item. * * @param array $info * @param string|null $currentClass The class that contains the method (either through inheritance or directly). * * @return string|null */ protected function determineFullReturnType(array $info, $currentClass = null) { if (!isset($info['return']['type']) || empty($info['return']['type'])) { return null; } $returnValue = $info['return']['type']; if ($returnValue == '$this' || $returnValue == 'self') { return isset($info['declaringClass']['name']) ? $info['declaringClass']['name'] : null; } elseif ($returnValue == 'static') { return $currentClass ?: null; } $soleClassName = $this->getSoleClassName($returnValue); if (!empty($soleClassName)) { if ($soleClassName[0] !== "\\") { $filename = isset($info['declaringStructure']['filename']) ? $info['declaringStructure']['filename'] : $info['filename']; $parser = new FileParser($filename); $completedClassName = $parser->getFullClassName($soleClassName, $useStatementFound); return $completedClassName; } return $soleClassName; } return $returnValue; }
/** * Parses a string * * @param $string * * @param $data * * @return mixed|null */ public static function Parse($string, $data) { FileParser::$defaults = FileParser::ReadDefaults(); /** * If we are still equal to null, fail */ if (FileParser::$defaults == null) { return null; } /** * Then, lets loop! */ foreach (FileParser::$defaults as $key => $value) { if (!FileParser::HasInstance($string, $key)) { continue; } $string = FileParser::ReplaceInstances($string, $key, FileParser::GetFunction($value['function'], $data[$value['array_index']])); } /** * Return that string */ return $string; }
function fetchRightDays() { // Preparation { require_once BASE . "basefunctions/baseapis/FileParser/FileParser.php"; if ($_POST["conf"]) { $conf = $_POST["conf"]; // Build date strings for CURL pull { $startday = substr($conf["startdate"], 0, 2); $startmonth = substr($conf["startdate"], 3, 2); $startyear = substr($conf["startdate"], 6, 4); $startstring = $startyear . "-" . $startmonth . "-" . $startday; $stopday = substr($conf["stopdate"], 0, 2); $stopmonth = substr($conf["stopdate"], 3, 2); $stopyear = substr($conf["stopdate"], 6, 4); $stopstring = $stopyear . "-" . $stopmonth . "-" . $stopday; // } // Fetch the report and it's results { $reporturl = "http://login.max.manline.co.za/m4/2/api_request/Report/export?report=26&responseFormat=csv&Start_Date=" . $startstring . "&Stop_Date=" . $stopstring . "&numberOfRowsPerPage=10000"; $fileParser = new FileParser($reporturl); $fileParser->setCurlFile("greenmiledays" . date("U") . ".csv"); $reportresults = $fileParser->parseFile(); if ($reportresults === false) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<br>"; } // } if ($reportresults) { // Create and process the start of the csv file { $destination = FIRSTBASE . "/displaycase/greenmiledays/"; $destname = $startstring . "-" . $stopstring; $destname = str_replace(".csv", "", $destname); $destname .= ".csv"; $desthandle = fopen($destination . $destname, "w"); foreach ($reportresults[1] as $header => $discard) { fwrite($desthandle, $header . ","); } fwrite($desthandle, "Load Diff,Offload Diff\r\n"); // } foreach ($reportresults as $reskey => $resval) { foreach ($resval as $column => $value) { fwrite($desthandle, $value . ","); } // Loading Difference { $loadplanned = $resval["Planned Loading Arrival"]; $loadactual = $resval["Loading Arrival"]; if ($loadactual != "(none)") { $plannedday = substr($loadplanned, 8, 2); $plannedmonth = substr($loadplanned, 5, 2); $plannedyear = substr($loadplanned, 0, 4); $actualday = substr($loadactual, 8, 2); $actualmonth = substr($loadactual, 5, 2); $actualyear = substr($loadactual, 0, 4); if ($plannedmonth < $actualmonth) { $monthdays = date("t", mktime(0, 0, 0, $plannedmonth, $plannedday, $plannedyear)); $loaddiff = $actualday + $monthdays - $plannedday; } else { if ($plannedmonth > $actualmonth) { $monthdays = date("t", mktime(0, 0, 0, $actualmonth, $actualday, $actualyear)); $loaddiff = $plannedday + $monthdays - $actualday; } else { if ($plannedday < $actualday) { $loaddiff = $actualday - $plannedday; } else { $loaddiff = $plannedday - $actualday; } } } $diffyear = $plannedyear - $actualyear; } else { $loaddiff = -1; } $reportresults[$reskey]["Load Diff"] = $loaddiff; // } // Offoading Difference { $offloadplanned = $resval["Planned Offloading Arrival"]; $offloadactual = $resval["Offloading Arrival"]; if ($offloadactual != "(none)") { $plannedday = substr($offloadplanned, 8, 2); $plannedmonth = substr($offloadplanned, 5, 2); $plannedyear = substr($offloadplanned, 0, 4); $actualday = substr($offloadactual, 8, 2); $actualmonth = substr($offloadactual, 5, 2); $actualyear = substr($offloadactual, 0, 4); if ($plannedmonth < $actualmonth) { $monthdays = date("t", mktime(0, 0, 0, $plannedmonth, $plannedday, $plannedyear)); $offloaddiff = $actualday + $monthdays - $plannedday; } else { if ($plannedmonth > $actualmonth) { $monthdays = date("t", mktime(0, 0, 0, $actualmonth, $actualday, $actualyear)); $offloaddiff = $plannedday + $monthdays - $actualday; } else { if ($plannedday < $actualday) { $offloaddiff = $actualday - $plannedday; } else { $offloaddiff = $plannedday - $actualday; } } } $diffyear = $plannedyear - $actualyear; } else { $offloaddiff = -1; } $reportresults[$reskey]["Offload Diff"] = $offloaddiff; // } fwrite($desthandle, $loaddiff . "," . $offloaddiff . "\r\n"); // Add details to csv } } fclose($desthandle); // close the csv } // } maxineTop("Header"); print "<form name='dayreportform' action='index.php?mode=maxine/index&action=fetchrightdays' method='post'>"; openHeader(1200); maxineButton("Submit", "dayreportform.submit();", 2); if ($reportresults) { maxineButton("Download", "goTo(\"" . BASE . "/basefunctions/downloadcsv.php?filename=" . $destname . "&filepath=" . $destination . "\");", 2); } maxineButton("Back", "goTo(\"index.php?mode=maxine/index&action=firstmenu\");", 2); closeHeader(); print "<div class='tray' style='width:1200px;'>"; // Date Select { openSubbar(500); print "Date Select"; closeSubbar(); print "<div class='standard content1' style='width:500px;'>"; print "<span style='width:50%; display:inline-block;'>"; print "Start Date"; print "<input name='conf[startdate]' id='startdate' value='" . $conf["startdate"] . "' readonly style='width: 110px; text-align: center;'>"; print "<img src='" . BASE . "/images/calendar.png' onClick='displayDatePicker(\"conf[startdate]\", this, \"dmy\", \"\");' />"; print "</span>"; print "<span style='width:50%; display:inline-block;'>"; print "Stop Date"; print "<input name='conf[stopdate]' id='stopdate' value='" . $conf["stopdate"] . "' readonly style='width: 110px; text-align: center;'>"; print "<img src='" . BASE . "/images/calendar.png' onClick='displayDatePicker(\"conf[stopdate]\", this, \"dmy\", \"\");' />"; print "</span>"; print "</div>"; // } if ($reportresults) { openSubbar(1200); print "Results"; closeSubbar(); print "<table class='standard' style='width:1200px;'>"; // Headers { print "<tr class='heading' style='font-size:10px;'>"; foreach ($reportresults[1] as $header => $discard) { print "<td>"; print $header; print "</td>"; } print "</tr>"; // } foreach ($reportresults as $reskey => $resval) { print "<tr class='content1' style='height:38px;'>"; foreach ($resval as $column => $value) { print "<td>"; print "<p class='standard' style='color:BLACK;'>" . $value . "</font>"; print "</td>"; } print "</tr>"; } print "</table>"; } print "</div>"; print "</form>"; maxineBottom(); }
/** * Loads and parses map files * stores the data in internal entityList property * * @param $fileName * @return QuakeMap */ public function load($fileName) { $parser = new FileParser($this); $parser->load($fileName); }
public function pullFleetDayT24($day, $range = 0) { $this->_day = $day; $this->_date = mktime(0, 0, 0, date("m"), $day, date("Y")); //: Create date strings for query $startmonth = date("m"); $startyear = date("Y"); $startday = date("d", mktime(0, 0, 0, $startmonth, $this->_day - $range, $startyear)); $startstring = $startyear . "-" . $startmonth . "-" . $startday; $stopdate = mktime(0, 0, 0, $startmonth, $this->_day + 1, $startyear); $stopday = date("d", $stopdate); $stopmonth = date("m", $stopdate); $stopyear = date("Y", $stopdate); $stopstring = $stopyear . "-" . $stopmonth . "-" . $stopday; print $startstring . " to " . $stopstring . PHP_EOL; //: End //: Content /** To DO * 1) Get all income for trucks * 2) loop through fleets to get list of trucks attached to each fleet * 3) sum data for each fleet * 4) save to maxinedb.fleet_scores */ $income = preg_replace("/login/", "t24", $this->_apiurl) . "report=79&responseFormat=csv&Date%20Start=" . $startstring . "&Date%20Stop=" . $stopstring; print $income . PHP_EOL; $fileParser = new FileParser($income); $fileParser->setCurlFile("income" . $startstring . ".csv"); $data = $fileParser->parseFile(); // print_r($data); if (is_array($data) === FALSE) { //: 404 return FALSE; } $trucksinafleet = $this->pullT24FleetData($startday); $fleetTrucks = (array) array(); foreach ($trucksinafleet as $truck) { $fleetTrucks[$truck["fleet_id"]][] = $truck; } $inc = (array) array(); foreach ($data as $row) { $inc[$row["Truck"]][] = $row; } $fleets = (array) array(); foreach ($fleetTrucks as $key => $row) { $t24Income = (array) array(); $t24Income["fleetid"] = $key; $t24Income["day"] = $this->_day; $t24Income["date"] = $this->_date; $t24Income["updated"] = date("U"); $t24Income["income"] = (double) 0; $t24Income["kms"] = (double) 0; foreach ($row as $val) { if (array_key_exists($val["Truck"], $inc)) { foreach ($inc[$val["Truck"]] as $trinc) { if (preg_match('/error\\:/', $trinc["Tripleg Income"])) { $t24Income["income"] += (double) 0.0; } else { $t24Income["income"] += (double) preg_replace("/\\,{0,}/", "", $trinc["Tripleg Income"]); } if (array_key_exists('Lead Kms', $trinc) && $trinc['Lead Kms'] != '(none)') { $t24Income['kms'] += floatval($trinc['Lead Kms']) * 2; } else { $t24Income['kms'] += floatval($trinc['Kms in Trip leg']) + floatval($trinc['Empty Kms']); } } } } $fleets[$key] = $t24Income; } return $fleets; }
public function __construct($rFilePath) { parent::__construct($rFilePath); }
/** * Execute the command. * * @param array $args Arguments gived to the command. * * @return array Response */ public function execute($args = array()) { $class = $args[0]; $name = $args[1]; if (strpos($class, '\\') === 0) { $class = substr($class, 1); } $isMethod = false; if (strpos($name, '()') !== false) { $isMethod = true; $name = str_replace('()', '', $name); } $relevantClass = null; $data = $this->getClassMetadata($class); if (isset($data['values'][$name])) { $memberInfo = $data['values'][$name]; if (!isset($data['values'][$name]['isMethod'])) { foreach ($data['values'][$name] as $value) { if ($value['isMethod'] && $isMethod) { $memberInfo = $value; } elseif (!$value['isMethod'] && !$isMethod) { $memberInfo = $value; } } } $returnValue = $memberInfo['args']['return']; if ($returnValue == '$this' || $returnValue == 'static') { $relevantClass = $class; } elseif ($returnValue === 'self') { $relevantClass = $memberInfo['declaringClass']['name']; } else { $soleClassName = $this->getSoleClassName($returnValue); if ($soleClassName) { // At this point, this could either be a class name relative to the current namespace or a full // class name without a leading slash. For example, Foo\Bar could also be relative (e.g. // My\Foo\Bar), in which case its absolute path is determined by the namespace and use statements // of the file containing it. $relevantClass = $soleClassName; if (!empty($soleClassName) && $soleClassName[0] !== "\\") { $parser = new FileParser($memberInfo['declaringStructure']['filename']); $useStatementFound = false; $completedClassName = $parser->getFullClassName($soleClassName, $useStatementFound); if ($useStatementFound) { $relevantClass = $completedClassName; } else { $isRelativeClass = true; // Try instantiating the class, e.g. My\Foo\Bar. try { $reflection = new \ReflectionClass($completedClassName); $relevantClass = $completedClassName; } catch (\Exception $e) { // The class, e.g. My\Foo\Bar, didn't exist. We can only assume its an absolute path, // using a namespace set up in composer.json, without a leading slash. } } } } } } // Minor optimization to avoid fetching the same data twice. return $relevantClass === $class ? $data : $this->getClassMetadata($relevantClass); }
/** * Tests readLine() * * @see FileParser::readLine() * @dataProvider provideTestReadLine */ public function testReadLine($file, $line, $expectedData) { $parser = new FileParser($file); $data = $parser->readLine($line); $this->assertEquals($expectedData, $data); }
$startstring = $startyear . "-" . $startmonth . "-" . $startday; //$stopdate = mktime(0, 0, 0, ($startmonth+1), 0, $startyear); $stopdate = mktime(0, 0, 0, $startmonth, date("d") + 1, $startyear); $stopday = date("d", $stopdate); $stopmonth = date("m", $stopdate); $stopyear = date("Y", $stopdate); $stopstring = $stopyear . "-" . $stopmonth . "-" . $stopday; //$startstring = "2010-08-01"; //$stopday = 14; //$stopstring = "2010-04-14"; // } $url = (string) "http://login.max.manline.co.za/m4/2/api_request/"; $url .= "Report/export?report=84&format=csv&Start_Date=" . $startstring . "&Stop_Date=" . $stopstring . "&Fleet=" . $fleets[$count]["id"]; //$url = (string)"http://max.mobilize.biz/m4/2/api_request/"; //$url .= "Report/export?report=87&format=csv&Start_Date=".$startstring."&Stop_Date=".$stopstring."&Fleet=".$fleets[$count]["id"]; $fileParser = new FileParser($url); if ($fileParser->getErrors()) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return false; } $mtddata = $fileParser->parseFile(); if ($mtddata === false) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<pre style='font-family:verdana;font-size:13'>errors"; print_r($fileParser->getErrors()); print "</pre>";
$mtddata = $fileParser->parseFile(); if ($mtddata === false) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<pre style='font-family:verdana;font-size:13'>errors"; print_r($fileParser->getErrors()); print "</pre>"; print "<br>"; } // } // Budgets { $budurl = (string) "http://login.max.manline.co.za/m4/2/api_request/"; $budurl .= "Report/export?report=85&format=csv&Start_Date=" . $startstring . "&Stop_Date=" . $stopstring . "&Fleet=" . $fleets[$count]["id"]; $fileParser = new FileParser($budurl); $buddata = $fileParser->parseFile(); if ($buddata === false) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<pre style='font-family:verdana;font-size:13'>errors"; print_r($fileParser->getErrors()); print "</pre>"; print "<br>"; } // } // Datawork { // Sort functions { function cmpCargoId($a, $b)
/** fleetTruckLinkImporter::__construct() * Class constructor */ public function __construct() { $realPath = realpath(dirname(__FILE__)); $maxine = substr($realPath, 0, strrpos($realPath, DIRECTORY_SEPARATOR)); $rootaccess = substr($maxine, 0, strrpos($maxine, DIRECTORY_SEPARATOR) + 1); defined("BASE") || define("BASE", $rootaccess); include_once BASE . "basefunctions/baseapis/TableManager.php"; include_once BASE . "basefunctions/baseapis/FileParser/FileParser.php"; $manager = new TableManager("fleet_truck_count"); //: Do a test to see if table includes subbie_trucks field $fields = $manager->describeTable(); if (in_array('subbie_count', array_keys($fields)) === FALSE) { $sql = (string) "ALTER TABLE `fleet_truck_count` ADD COLUMN `subbie_count` INT NOT NULL DEFAULT 0;"; if ($manager->runSql($sql) === FALSE) { print "Altering table failed" . PHP_EOL; return FALSE; } } //: End $subbietrucksurl = "https://login.max.bwtsgroup.com/api_request/Report/export?report=153&responseFormat=csv"; // Max $apiurl = "https://login.max.bwtsgroup.com/api_request/Report/export?report=145&responseFormat=csv"; // Max $t24apiurl = "https://t24.max.bwtsgroup.com/api_request/Report/export?report=73&responseFormat=csv"; // T24 // $apiurl = "http://max.mobilize.biz/m4/2/api_request/Report/export?report=141&responseFormat=csv"; // Test //: Get the list of subbie trucks $fileParser = new FileParser($subbietrucksurl); $fileParser->setCurlFile("subbie_trucks.csv"); $data = $fileParser->parseFile(); $subbieTrucks = (array) array(); foreach ($data as $val) { if (array_key_exists("Trucks", $val) === FALSE) { continue; } $trucks = preg_split("/\\,/", $val["Trucks"]); if (is_array($trucks) === FALSE) { continue; } foreach ($trucks as $trucklist) { $subbieTrucks[] = $trucklist; } } //print_r($subbieTrucks); unset($data); //return FALSE; //: End $fleetDayHandler = new fleetDayHandler(); $required_fleets = $fleetDayHandler->getIncomeFleets(); $rows = (array) array(); foreach ($required_fleets as $val) { if (array_key_exists('fleets', $val)) { $count = (int) 0; $subbie_count = (int) 0; foreach ($val['fleets'] as $subfleets) { $manager->setWhere($manager->quoteString('`fleet_id`=?', $subfleets[0])); $record = $manager->selectSingle(); $count += (int) $record['count']; $subbie_count += (int) $record['subbie_count']; } $rows[] = (array) array('fleet_id' => $val['id'], 'count' => isset($count) && $count ? $count : 0, 'subbie_count' => isset($subbie_count) && $subbie_count ? $subbie_count : 0); } else { $url = $apiurl . "&Fleet=" . $val["maxid"] . "&Start%20Date=" . date("Y-m-d") . "&Stop%20Date=" . date('Y-m-d', strtotime('+1 day')); if (array_key_exists('t24', $val)) { $url = $t24apiurl . "&Fleet=" . $val["maxid"] . "&Start%20Date=" . date("Y-m-d") . "&Stop%20Date=" . date('Y-m-d', strtotime('+1 day')); } print_r('url: ' . $url . PHP_EOL); $fileParser = new FileParser($url); $fileParser->setCurlFile("fleet_truck_count_" . $val["id"] . ".csv"); $data = $fileParser->parseFile(); // print_r($data); /*if ($fleetId == 75) { //: confirm a fleet is correct print("<pre>"); print_r($data); print("</pre>"); }*/ $sub_cnt = (int) 0; foreach ($data as $row) { if (in_array($row['Truck'], $subbieTrucks)) { $sub_cnt++; } } //print($sub_cnt.PHP_EOL); $record = (array) array('fleet_id' => $val['id'], 'count' => count($data), 'subbie_count' => $sub_cnt); if (array_key_exists('t24', $val)) { $record['t24'] = (int) 1; } $rows[] = $record; } } //: Loop through and update/insert records foreach ($rows as $row) { $where = (string) $manager->quoteString('`fleet_id`=?', $row['fleet_id']); if (array_key_exists('t24', $row) && $row['t24'] === 1) { $where .= $manager->quoteString(' AND `t24`=?', $row['t24']); } $manager->setWhere($where); $record = $manager->selectSingle(); if ($record) { print_r($record); print_r($row); $nDifference = (double) $row['count'] == 0 ? 100 : ($record['count'] - $row['count']) / $row['count'] * 100; print_r('diff: ' . $nDifference . PHP_EOL); if ($nDifference > 50 || $nDifference < -50) { continue; } $manager->setWhere($manager->quoteString('`id`=?', $record['id'])); $manager->update($row); } else { $manager->insert($row); } } }
/** * Retrieves the line the specified property starts at. * * @param string $filename * @param string $name * * @return int|null */ protected function getStartLineForPropertyIn($filename, $name) { if (!$filename) { return null; } $parser = new FileParser($filename); return $parser->getLineForRegex("/(?:protected|public|private|static)\\s+\\\${$name}/"); }
$nRand = rand(10, 20); $sMsg = sprintf("%s read %d bytes from file '%s' | pausing %d seconds.", __METHOD__, strlen($sContent), $sFileName, $nRand); Logger::getInstance()->info($sMsg); sleep($nRand); return TRUE; } } // Set up and run the daemon try { $oDaemon = NULL; // Initialize daemon class $nUIDToRunUnder = NULL; // Don't try to change UID $sPIDFilename = DAEMON_NAME . '.pid'; // PID file simply in current dir $oDaemon = new FileParser($nUIDToRunUnder, $sPIDFilename); // Now set some daemon options $oDaemon->setMaxChildren(2); // Only up to 2 child processes $oDaemon->setSendChildrenUNIXSignals(FALSE); // Don't forward signals $oDaemon->setIdleSleepTime(5 * 1000000); // Wait 5sec when no job avail. printf("Will run %d child process with PID file %s\n", $oDaemon->getMaxChildren(), $oDaemon->getPIDFile()); // Call our own custom init method $oDaemon->demoAppInit(); // Start daemon $oDaemon->daemonRun(); } catch (Exception $e) { if ($oDaemon == NULL) { $sErr = ': Daemon class failed to instantiate: ';
function getRightTimes($startstring, $stopstring) { // Fetch the report and it's results { $reporturl = "http://login.max.manline.co.za/m4/2/api_request/Report/export?report=26&responseFormat=csv&Start_Date=" . $startstring . "&Stop_Date=" . $stopstring . "&numberOfRowsPerPage=10000"; $fileParser = new FileParser($reporturl); $fileParser->setCurlFile("greenmiledays.csv"); $reportresults = $fileParser->parseFile(); if ($reportresults === false) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<br>"; } // } $loadcount = 0; $offloadcount = 0; $rightdayload = 0; $righthourload = 0; $rightdayoffload = 0; $righthouroffload = 0; foreach ($reportresults as $reskey => $resval) { // Loading Difference { $loadhourdiff = $resval["Loading Difference (hrs)"]; $loaddaydiff = calcDaysBetweenPlannedVsActual($resval["Planned Loading Arrival"], $resval["Loading Arrival"]); //print($resval["Planned Loading Arrival"]." ".$resval["Loading Arrival"]."<br>"); //print($loadhourdiff." ".$loaddaydiff.""); if ($loaddaydiff >= 0) { $loadcount++; if ($loadhourdiff < 4 && $loadhourdiff > -4) { //print(" Load Hour +"); $righthourload++; } if ($loaddaydiff == 0) { $rightdayload++; //print(" Load Day +"); } } // } // Offoading Difference { $offloadhourdiff = $resval["Offloading Difference (hrs)"]; $offloaddaydiff = calcDaysBetweenPlannedVsActual($resval["Planned Offloading Arrival"], $resval["Offloading Arrival"]); if ($offloaddaydiff >= 0) { $offloadcount++; if ($offloadhourdiff < 4 && $offloadhourdiff > -4) { $righthouroffload++; } if ($offloaddaydiff == 0) { $rightdayoffload++; } } // } } if ($loadcount > 0 && $offloadcount > 0) { $result["loadtime"] = round($righthourload / $loadcount * 100, 2); $result["loadday"] = round($rightdayload / $loadcount * 100, 2); $result["offloadtime"] = round($righthouroffload / $offloadcount * 100, 2); $result["offloadday"] = round($rightdayoffload / $offloadcount * 100, 2); } else { $result["loadday"] = 0; $result["loadtime"] = 0; $result["offloadday"] = 0; $result["offloadtime"] = 0; } return $result; }
/** fleetdayHandler::importBudget() * Import this months budget data * @author Feighen Oosterbroek * @author feighen@manlinegroup.com * @return FALSE on failure NULL otherwise */ public function importBudget() { for ($i = 1; $i <= date("t"); $i++) { foreach ($this->_incomefleets as $incfleetkey => $incfleetval) { $blackoutcount = (double) 0; $daybudget = (double) 0; $daybudkms = (double) 0; $daybudgetcontrib = (double) 0; //: Get the data $budgeturl = $this->_apiurl . "report=85&responseFormat=csv&Start_Date=" . date("Y-m-" . (strlen($i) === 1 ? "0" . $i : $i)) . "&Stop_Date=" . ($i == date("t") ? date("Y-" . date("m", strtotime("+1 month")) . "-01") : date("Y-m-" . (strlen($i) === 1 ? "0" . ($i + 1) : $i + 1))) . "&Fleet=" . $incfleetval["id"]; $fileParser = new FileParser($budgeturl); $fileParser->setCurlFile("budget" . $incfleetval["id"] . ".csv"); $budgetdata = $fileParser->parseFile(); if ($budgetdata === false) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<pre style='font-family:verdana;font-size:13'>errors"; print_r($fileParser->getErrors()); print "</pre>"; print "<br />"; } //: End //: Collate data foreach ($budgetdata as $budgetkey => $budgetval) { $truckbudget = isset($budgetval["Income"]) ? str_replace(",", "", $budgetval["Income"]) : ""; $truckbudget = str_replace("R", "", $truckbudget); $daybudget += $truckbudget; $truckbudgetcontrib = isset($budgetval["Contribution"]) ? str_replace(",", "", $budgetval["Contribution"]) : ""; $truckbudgetcontrib = str_replace("R", "", $truckbudgetcontrib); $daybudgetcontrib += $truckbudgetcontrib; $daybudkms += isset($budgetval["Kms"]) ? $budgetval["Kms"] : 0; // Calculate the number of trucks per fleet that have a budget and no trip if (isset($budgetval["Blackout Status"]) && ($budgetval["Blackout Status"] == "1" || $budgetval["Blackout Status"] == "Yes")) { if ($truckbudget > 0) { $blackoutcount++; } } } //: End //: Insert or update $fleetscore = (array) array(); $fleetscore["fleetid"] = $incfleetval["id"]; $fleetscore["budget"] = $daybudget; $fleetscore["budgetcontrib"] = $daybudgetcontrib; $fleetscore["budkms"] = $daybudkms; $fleetscore["day"] = $i; $fleetscore["date"] = strtotime(date("Y-m-" . (strlen($i) === 1 ? "0" . $i : $i))); $fleetscore["updated"] = date("U"); $fleetscore["blackouts"] = $blackoutcount; //: check to see if this data needs to be updated or if it can just be inserted $record = sqlPull(array("onerow" => TRUE, "table" => "fleet_scores", "where" => "`fleetid`=" . $fleetscore["fleetid"] . " AND `date`=" . $fleetscore["date"])); if (isset($record) && $record) { //: Update sqlCommit(array("table" => "fleet_scores", "where" => "id=" . $record["id"], "fields" => $fleetscore)); } else { //: Insert sqlCreate(array("table" => "fleet_scores", "fields" => $fleetscore)); } //: End } /* //: Testing if ($i > 1) { break; } //: End */ } }
$subfleets[54]["master"] = 77; $subfleets[54]["count"] = 0; $subfleets[35]["id"] = 35; $subfleets[35]["name"] = "XB Tris"; $subfleets[35]["master"] = 77; $subfleets[35]["count"] = 0; $subfleets[75]["id"] = 75; $subfleets[75]["name"] = "XB 711"; $subfleets[75]["master"] = 77; $subfleets[75]["count"] = 0; // } // } // Fetch the report and it's results { $reporturl = "http://login.max.manline.co.za/m4/2/api_request/Report/export?report=87&responseFormat=csv&numberOfRowsPerPage=10000"; print $reporturl . "<br>"; $fileParser = new FileParser($reporturl); $fileParser->setCurlFile("fleetPositions.csv"); $reportresults = $fileParser->parseFile(); if ($reportresults === false) { print "There was an error!"; print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return; print "<br>"; } // } $fleetlist = array(); foreach ($reportresults as $memberkey => $memberval) { $fleetid = $memberval["Fleet Id"]; $truckid = $memberval["Truck Id"];
/** refuel($test = FALSE) * get open and missing refuel data * @param BOOL $test is this a request for test platform? * @return TRUE on success. FALSE otherwise */ public function refuel($test = FALSE) { $fleets = $this->_incomefleets; $data = (array) array(); foreach ($fleets as $val) { $data[$val['maxid']]['fleet_id'] = $val['maxid']; if (array_key_exists('fleets', $val)) { $sql = (string) 'SELECT SUM(`fleet_count`) AS `fleet_count`, SUM(`missing_count`) AS `missing_count`, SUM(`open_count`) AS `open_count`, SUM(`total_open_count`) AS `total_open_count` '; $sql .= 'FROM `refuels` '; $fleetsToLoop = (array) array(); foreach ($val['fleets'] as $ook) { $fleetsToLoop[] = $ook[0]; } $sql .= 'WHERE `fleet_id` IN(' . implode($fleetsToLoop, ',') . ')'; $row = sqlQuery($sql); if ($row === FALSE) { continue; } $data[$val['maxid']]['fleet_count'] = $row[0]['fleet_count']; $data[$val['maxid']]['missing_count'] = $row[0]['missing_count']; $data[$val['maxid']]['open_count'] = $row[0]['open_count']; $data[$val['maxid']]['total_open_count'] = $row[0]['total_open_count']; } else { //: Get fleet count $trucks = $this->_apiurl . "report=145&responseFormat=csv&Fleet=" . $val['maxid'] . "&Start%20Date=" . date("Y-m-d") . "&Stop%20Date=" . date("Y-m-d", strtotime("+1 day")); if ($test === TRUE) { $trucks = preg_replace('/https\\:\\/\\/login\\.max\\.bwtsgroup\\.com/', 'http://max.mobilize.biz', $trucks); } $fileParser = new FileParser($trucks); $fileParser->setCurlFile("trucks." . $val['maxid'] . ".csv"); $trucks = $fileParser->parseFile(); if ($trucks === FALSE) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return FALSE; } if (is_array($trucks) === FALSE) { return FALSE; } $data[$val['maxid']]['fleet_count'] = count($trucks); //: End $refuels = $this->_apiurl . "report=175&responseFormat=csv&Fleet=" . $val['maxid'] . "&Start%20Date=" . date("Y-m-d", strtotime('-30 days')) . "&Stop%20Date=" . date("Y-m-01", strtotime("+1 month")); if ($test === TRUE) { $refuels = preg_replace('/https\\:\\/\\/login\\.max\\.bwtsgroup\\.com/', 'http://max.mobilize.biz', $refuels); } print $refuels . PHP_EOL; $fileParser = new FileParser($refuels); $fileParser->setCurlFile("missingrefuels" . $val['maxid'] . ".csv"); $missingrefuels = $fileParser->parseFile(); if ($missingrefuels === FALSE) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return FALSE; } if (is_array($missingrefuels) === FALSE) { return FALSE; } // print_r($missingrefuels); $i = (int) 0; //: Missing Refuels foreach ($missingrefuels as $key => $value) { //: Checks if ($val['maxid'] == 73) { print_r($value); } if ($value['Odometer'] === '(none)' || $value['Odometer'] === '') { continue; } if (substr($value['Variance'], 0, 1) !== '-') { continue; } //: End if ($value['Variance'] * -1 >= $val['kms_limit']) { $i++; } } $data[$val['maxid']]['missing_count'] = $i; //: End //: Open Refuels $refuels = $this->_apiurl . "report=174&responseFormat=csv&Fleet=" . $val['maxid'] . "&Start%20Date=" . date("Y-m-d", strtotime('-30 days')) . "&Stop%20Date=" . date("Y-m-01", strtotime("+1 month")); if ($test === TRUE) { $refuels = preg_replace('/https\\:\\/\\/login\\.max\\.bwtsgroup\\.com/', 'http://max.mobilize.biz', $refuels); } print $refuels . PHP_EOL; $fileParser = new FileParser($refuels); $fileParser->setCurlFile("openrefuels" . $val['maxid'] . ".csv"); $openrefuels = $fileParser->parseFile(); if ($openrefuels === FALSE) { print "<pre style='font-family:verdana;font-size:13'>"; print_r($fileParser->getErrors()); print "</pre>"; return FALSE; } if (is_array($openrefuels) === FALSE) { return FALSE; } // print_r($openrefuels); $cnt = (int) 0; foreach ($openrefuels as $key => $value) { //: Convert the refuel time difference into seconds $refuel_time = (int) 0; $split = preg_split('/\\s/', $value['Duration Open (Refuel Time)']); if (array_key_exists(0, $split)) { if (substr($split[0], -1, 1) === 'd') { //: Days $refuel_time += 24 * 60 * 60 * (int) $split[0]; } else { //: Hours $refuel_time += 60 * 60 * (int) $split[0]; } } if (array_key_exists(1, $split)) { //: Hours $refuel_time += 60 * 60 * (int) $split[0]; } // print('refuel time: '.$refuel_time.PHP_EOL); if ($refuel_time >= $val['open_time']) { $cnt++; } //: End } $data[$val['maxid']]['total_open_count'] = count($openrefuels); $data[$val['maxid']]['open_count'] = $cnt; //: End } } foreach ($data as $key => $val) { $record = sqlPull(array("table" => "refuels", "where" => "fleet_id=" . $key, "customkey" => "fleet_id")); if (array_key_exists($key, $record) && $record[$key]) { sqlCommit(array("table" => "refuels", "where" => "fleet_id=" . $key, "fields" => $val)); } else { sqlCreate(array("table" => "refuels", "fields" => $val)); } print '|'; } }
/** * Read all agencies from the bundesbank file. * * @return Agency[] */ private function provideAgencies() { $parser = new FileParser(); $databackend = new FileDataBackend($parser->getFile()); $agencies = array(); for ($line = 0; $line < $parser->getLines(); $line++) { $data = $parser->readLine($line); $bank = $parser->getBank($databackend, $data); $agency = $parser->getAgency($bank, $data); $agencies[$agency->getID()] = $agency; } return $agencies; }
/** * Renvoie les données contenues dans le fichier sous forme de tableau * Parse automatiquemen si cela n'a pas été fait * * Peut être appelé statiquement en passant le nom du fichier * NB : ne respecte pas le standard 'strict', il faudrait une autre méthode de type 'static' * * @return array les données sous forme de tableau * @access public */ function getData($file = null, $options = array()) { if (!isset($this)) { if (!$file) { trigger_error("En mode static, cette méthode doit disposer d'un paramètre {$file} valide", E_USER_ERROR); } $_this = new FileParser($file, $options); $data = $_this->getData(); $_this->close(); return $data; } return $this->Parser->getData(); }