/** * Init scan process. * Solution for realtime output find on: http://stackoverflow.com/questions/1281140/run-process-with-realtime-output-in-php * Maybe ugly, but sometimes at 3AM it's only what is getting out of head ;-) */ public function initScan() { $view = new Views('templates/head.tpl.php'); $view->set('class', 'scanner'); print $view->render(); set_time_limit(0); $handle = popen(PHP . " scanner.php " . $this->project_id, "r"); if (ob_get_level() == 0) { ob_start(); } while (!feof($handle)) { $buffer = fgets($handle); $buffer = trim(htmlspecialchars($buffer)); $data = explode(';', $buffer); switch ($data[0]) { case 'FOUND': print "<div class=\"infobox\"><h3>Found something</h3><p><strong>Time:</strong> " . $data[1] . "<br><strong>Filter name:</strong> " . $data[2] . "<br><strong>Line:</strong> " . $data[3] . "<br><strong>File:</strong> " . $data[4] . "</p><a href=\"/report/" . $data[5] . "\" target=\"_blank\"><span class=\"button warning_button\" style=\"\">Show report</span></a></div>"; break; case 'NOT_FOUND': print "<div class=\"infobox\"><h3>WOW!</h3><p>Scanner didn't found anything. So your project is sooo secure. You are security mastah, or the filters are too weak ;-) Anyway, I recommend to do a manual code review, to be 100% sure ;-)</p></div>"; break; case 'SCANNED': print "<div class=\"infobox\"><h3>Hmmmm...</h3><p>Your project has been scanned before. Please go to project to check your reports. <br><a href=\"/show/" . $this->project_id . "\" target=\"_parent\"><span class=\"button\">Go to project page</span></a></p></div>"; break; } ob_flush(); flush(); time_nanosleep(0, 10000000); } pclose($handle); ob_end_flush(); }
/** * Sleeps for the given amount of milliseconds * * @param $ms */ public static function millisecond($ms) { if (($sec = (int) ($ms / 1000)) > 0) { $ms = $ms % 1000; } time_nanosleep($sec, $ms * 1000000); }
function QueryNominatim($query, $countryCodes = [], $searchLimit = "10", $boundingBox = []) { $curlString = self::NOMINATIM_URL_BASE . '/search?format=json'; $curlString .= '&limit=' . $searchLimit; $curlString .= '&email=' . self::NOMINATIM_EMAIL; $curlString .= '&addressdetails=1'; if ($countryCodes) { $curlString .= "&countrycodes=" . implode(',', $countryCodes); } if ($boundingBox) { $curlString .= "&viewbox=" . $boundingBox["west"]; $curlString .= "," . $boundingBox["north"]; $curlString .= "," . $boundingBox["east"]; $curlString .= "," . $boundingBox["south"]; $curlString .= "&bounded=1"; } $curlString .= '&q=' . $query; if (printOutput()) { echo "<br>Executing query: " . $curlString . "<br>"; } if (self::LIMIT_QUERIES) { while ($this->lastQueryTime + 1.0 > microtime(true)) { time_nanosleep(0, 10000); } } $this->lastQueryTime = microtime(true); return json_decode(Connectivity::runCurl($curlString), true); }
public function send($labels) { foreach ($labels as $label) { time_nanosleep(0, 100000000); $this->connector->send($label); } }
public function run($args) { while (1) { $this->_logger->log(__METHOD__ . ' ' . 'NEW CIRCULE'); $this->dataExchange(); time_nanosleep(0, 20000000); } }
/** * setUp test suite * * @return void */ public function setUp() { $options = new ConnectionOptions(); if (!self::$isGnatsd) { time_nanosleep(2, 0); $options->port = 4222; } $this->c = new Nats\Connection($options); $this->c->connect(); }
/** * setUp test suite * * @return void */ public function setUp() { $options = new ConnectionOptions(); if (!self::$isGnatsd) { time_nanosleep(1, 700000000); $options->setPort(4222); } $this->c = new Nats\Connection($options); $this->c->connect(); }
private static function isProcessRunning($pid) { try { $output = shell_exec("ps -p {$pid}"); if (count(preg_split("/\n/", $output)) > 2) { time_nanosleep(0, 500000); return true; } } catch (Exception $e) { } return false; }
function reserveRDaemon() { global $projectHome; for ($counter = 1; $counter <= 30; $counter++) { // wait up to 3 seconds $reservedRInstance = reserveRInstance(); if ($reservedRInstance != NULL) { return $reservedRInstance; } time_nanosleep(0, 100000000); } return null; }
public function testGetTime() { $timer = new Timer(); time_nanosleep(0, 200000000); $result1 = $timer->getTime(); time_nanosleep(0, 300000000); $result2 = $timer->getTime(true); time_nanosleep(0, 100000000); $result3 = $timer->getTime(); $this->assertTrue(0.2 <= $result1 && $result1 <= 0.205, $result1); $this->assertTrue(0.5 <= $result2 && $result2 <= 0.505, $result2); $this->assertTrue(0.1 <= $result3 && $result3 <= 0.105, $result3); }
public function __construct() { $this->filepath__ = Yii::app()->getBasePath() . DIRECTORY_SEPARATOR . 'nosqlvars' . DIRECTORY_SEPARATOR . $this->filename__; if (!file_exists($this->filepath__)) { $array = $this->initFieldsValues(); file_put_contents($this->filepath__, json_encode($array, true)); } $this->fileData__ = json_decode(file_get_contents($this->filepath__), true); while ($this->fileData__ == false) { time_nanosleep(0, 200000000); $this->fileData__ = json_decode(file_get_contents($this->filepath__), true); } $this->setValuesAsProperties(); }
/** * Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. * * @param int $timeout * @param TimeUnit|null $unit the timeunit of the given timeout * @return bool true if the count reached zero and false if the waiting time elapsed before the count reached zero */ public function await($timeout = 0, TimeUnit $unit = null) { if (null !== $unit) { $timeout = $unit->toMicros($timeout); } $timeoutAt = microtime(true) + $timeout / 1000000; while (0 != $this->count) { if ($timeout > 0 && microtime(true) > $timeoutAt) { return false; } time_nanosleep(0, 1); } return true; }
private function waitForLock($failSafe = false) { $wait_counter = 0; while (file_exists($this->email_file_loc . ".lock")) { $wait_counter++; if ($wait_counter > 100) { if (!$failSafe) { throw new Exception("Email time-out waiting for lock", 1); } else { return false; } } time_nanosleep(0, 100000000); //sleep for a 10th of a second. } return true; }
protected function uploadOrders($orders) { if (sizeof($orders)) { $orders = array_chunk($orders, $this->config['retailcrm_order_chunk_size']); foreach ($orders as $chunk) { try { $result = $this->crmClient->ordersUpload($chunk); if (!$result->isSuccessful()) { $this->writeLog('ordersUpload: ' . $result['errorMsg'] . (isset($result['errors']) ? ': ' . json_encode($result['errors']) : '')); } time_nanosleep(0, 200000000); } catch (\RetailCrm\Exception\CurlException $e) { $this->writeLog('ordersUpload: ' . $e, 'error'); } } return true; } else { return false; } }
function cache_get($url, $cache_file, $verbose = true, $update = false, $cache_life = 43200) { $message = ''; $content = ''; clearstatcache(); if ($url == '') { $message .= '[empty url]'; } else { if (file_exists($cache_file) && time() - filemtime($cache_file) <= $cache_life) { $message .= '[use cache]'; $content = @file_get_contents($cache_file); } else { $message .= '[update cache : '; if ($update && file_exists($cache_file) && curl_get_file_size($url) <= filesize($cache_file)) { $message .= 'cache file is already bigger'; $content = @file_get_contents($cache_file); } else { if (($content = curl_download($url)) !== false) { // @file_get_contents($url) rmkdir(dirname($cache_file)); if (($size = @file_put_contents($cache_file, $content)) === false) { $message .= 'not updatable (' . $cache_file . ')'; } else { $message .= 'updated (' . human_filesize($size) . ')'; } if (strpos($url, 'http://www.magic-ville.com') !== false) { time_nanosleep(0, 500000000); } // Avoid anti-leech mechanism on MV (30 queries every 15 sec) } else { $message .= 'not downloadable (' . $url . ')'; } } $message .= ']'; } } if ($verbose) { echo $message; } return $content; }
/** * Check for lock file and create new one * if no file exists. * * Other wise wait maximumg of $timeout * or force it if lockRunTime exceeded $maxRunTime * * @param string $filename Lock file * @param number $timeout In seconds * @param number $maxRunTime In seconds * @throws Exception * @return boolean */ public function acquireLock($filename, $timeout = 5, $maxRunTime = 3600) { if ($this->_filename) { throw new Exception('Lock already in place.'); } if (file_exists($filename)) { $data = unserialize(file_get_contents($filename)); // kill if process last touch exceeds max run time if ($data['last_touch'] + $maxRunTime < time()) { unlink($filename); } else { if ($timeout <= 0) { return false; } else { // wait till time out is reached $time = microtime(true); while (1) { time_nanosleep(0, 100000); if (!file_exists($filename)) { break; } else { if ($timeout < microtime(true) - $time) { return false; } } } } } } $this->_data = array('start' => time(), 'last_touch' => time(), 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null, 'uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null); //file_put_contents($filename, $data) $this->_fileHandle = fopen($filename, 'c+'); $this->_filename = realpath($filename); if (!$this->_filename) { throw new Exception('Failed to create lock, file could not be created.'); } // what ever happens, make sure to kill the current lock file register_shutdown_function(array('Mzax_Once', 'unlinkFile'), $this->_filename); $this->touch(); return true; }
function send_ipc_cmd($id, $cmd) { $socket = socket_create(AF_UNIX, SOCK_STREAM, 0); if (!@socket_connect($socket, "/tmp/IRC_" . $id . ".sock")) { echo "S_ERROR socket_connect"; return; } /*if (!socket_set_nonblock($socket)) { echo 'error stream_set_blocking'; return(1); }*/ $buf = $cmd . "\n"; $ret = socket_write($socket, $buf, strlen($buf)); $buf = ''; $sockarr = array($socket); while (1) { $in_buf = @socket_read($socket, 8192, PHP_NORMAL_READ); if (strlen(trim($in_buf)) == 0) time_nanosleep(0, 499999999); if ($in_buf === false || socket_last_error($socket) == 104) { // dead socket socket_close($socket); break; } if (trim($in_buf) == "EOR") break; $buf .= $in_buf; } socket_close($socket); return($buf); }
/** * Enforce the minimum execution time * * @param bool $log Should I log what I'm doing? Default is true. */ public function enforce_min_exec_time($log = true) { // Try to get a sane value for PHP's maximum_execution_time INI parameter if (@function_exists('ini_get')) { $php_max_exec = @ini_get("maximum_execution_time"); } else { $php_max_exec = 10; } if ($php_max_exec == "" || $php_max_exec == 0) { $php_max_exec = 10; } // Decrease $php_max_exec time by 500 msec we need (approx.) to tear down // the application, as well as another 500msec added for rounding // error purposes. Also make sure this is never gonna be less than 0. $php_max_exec = max($php_max_exec * 1000 - 1000, 0); // Get the "minimum execution time per step" Akeeba Backup configuration variable $configuration = AEFactory::getConfiguration(); $minexectime = $configuration->get('akeeba.tuning.min_exec_time', 0); if (!is_numeric($minexectime)) { $minexectime = 0; } // Make sure we are not over PHP's time limit! if ($minexectime > $php_max_exec) { $minexectime = $php_max_exec; } // Get current running time $elapsed_time = $this->getRunningTime() * 1000; // Only run a sleep delay if we haven't reached the minexectime execution time if ($minexectime > $elapsed_time && $elapsed_time > 0) { $sleep_msec = $minexectime - $elapsed_time; if (function_exists('usleep')) { if ($log) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Sleeping for {$sleep_msec} msec, using usleep()"); } usleep(1000 * $sleep_msec); } elseif (function_exists('time_nanosleep')) { if ($log) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Sleeping for {$sleep_msec} msec, using time_nanosleep()"); } $sleep_sec = floor($sleep_msec / 1000); $sleep_nsec = 1000000 * ($sleep_msec - $sleep_sec * 1000); time_nanosleep($sleep_sec, $sleep_nsec); } elseif (function_exists('time_sleep_until')) { if ($log) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Sleeping for {$sleep_msec} msec, using time_sleep_until()"); } $until_timestamp = time() + $sleep_msec / 1000; time_sleep_until($until_timestamp); } elseif (function_exists('sleep')) { $sleep_sec = ceil($sleep_msec / 1000); if ($log) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Sleeping for {$sleep_sec} seconds, using sleep()"); } sleep($sleep_sec); } } elseif ($elapsed_time > 0) { // No sleep required, even if user configured us to be able to do so. if ($log) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "No need to sleep; execution time: {$elapsed_time} msec; min. exec. time: {$minexectime} msec"); } } }
protected function wait($interval, $callback) { $seconds = floor($interval); $nanoseconds = ($interval - $seconds) * 1000000000; time_nanosleep($seconds, $nanoseconds); return $callback(); }
/** * Import weather data to data base * * @param InputInterface $input, OutputInterface $output */ protected function importWeather(InputInterface $input, OutputInterface $output) { $stationManager = $this->getContainer()->get('weather.guy.station.manager'); $infoManager = $this->getContainer()->get('weather.guy.information.manager'); $remoteAemet = $this->getContainer()->get('weather.guy.wunder.remote'); $result = $remoteAemet->stationList(); $output->writeln("<info>Processing ...</info>"); $count = 0; foreach ($result as $key => $onestation) { time_nanosleep('7', '10'); $count++; $autoFlush = $count % self::BATCH_SIZE === 0; // Check if station with name = $info['name'] exists. $station = $stationManager->findStationByName($onestation->name); if (null === $station) { $this->importStation($input, $output); } // Weather information Object $date = new \DateTime('now'); try { $weatherInfo = $infoManager->create($station, $date); } catch (\Exception $exc) { // Weather information for $station at $date exists. continue; } $info = $infoManager->findWeatherInformation($station, $date); if (null === $info) { $data = $remoteAemet->stationInfo($onestation->zmw); $avg_temp = floor(($data['weather_result'][0]->high->celsius + $data['weather_result'][0]->low->celsius) / 2); $weatherInfo->setMaxTemperature($this->getTemperatureOf($data['weather_result'][0]->high->celsius)); $weatherInfo->setMinTemperature($this->getTemperatureOf($data['weather_result'][0]->low->celsius)); $weatherInfo->setAvgTemperature($this->getTemperatureOf($avg_temp)); $weatherInfo->setPrecipitation($this->getPrecipitationOf($data['weather_result'][0]->qpf_allday->mm)); $weatherInfo->setSunshine($this->getSunshineOf($data['atronomy_result'])); $infoManager->save($weatherInfo, $autoFlush); $output->writeln("Weather information for station <info>'{$onestation->name}'</info> , at <info>{$date->format('d-m-Y')}</info> <comment>imported</comment>"); } } }
<?php /********************************************************* * Eworx S.A.- 2012 * @Author kp@eworx.gr * EFWEB-596 R Resources Management Layer (RRML) * File uses the stop and start RRML calls **********************************************************/ require_once "stop.php"; time_nanosleep(0, 200000000); //wait for 0.2 sec require_once "start.php";
$gap = 1000000000 / 5; $currentSpeed = 0; $currentTime = microtime(true); while (!feof($fh)) { $contents = fread($fh, 8192); $currentPosition += strlen($contents); $currentSpeed += strlen($contents); echo $contents; if ($currentSpeed >= $speed) { $diff = microtime(true) - $currentTime; $diff * 1000000000; $diff = floor($diff); error_log("{$currentSpeed} vs {$speed} on " . number_format($diff) . " vs " . number_format($gap) . ""); if ($diff < $gap) { $nanosleep = $gap - $diff; time_nanosleep(0, $nanosleep); } $currentSpeed = 0; $currentTime = microtime(true); } if (connection_status() != CONNECTION_NORMAL) { fclose($fh); error_log("End of connection"); exit; } error_log("Connection status : " . connection_status() . " @ " . $currentPosition); } fclose($fh); error_log("End"); // readfile($fullpath); }
<?php /* Codeine * @author bergstein@trickyplan.com * @description * @package Codeine * @version 8.x */ setFn('Do', function ($Call) { time_nanosleep($Call['Seconds'], $Call['Seconds'] - round($Call['Seconds']) * 1000000000); return $Call; });
function pcntl_sigtimedwait($signals, $siginfo, $sec, $nano) { pcntl_signal_dispatch(); if (time_nanosleep($sec, $nano) === TRUE) { return FALSE; } pcntl_signal_dispatch(); return TRUE; }
/** * UtilityTest::testTime() * * @covers ::returnElapsedTime * @return void */ public function testTime() { Utility::startClock(); time_nanosleep(0, 200000000); $res = Utility::returnElapsedTime(); $this->assertTrue(round($res, 1) === 0.2); time_nanosleep(0, 100000000); $res = Utility::returnElapsedTime(8, true); $this->assertTrue(round($res, 1) === 0.3); time_nanosleep(0, 100000000); $res = Utility::returnElapsedTime(); $this->assertTrue(round($res, 1) === 0.1); }
/** * Updates Magento products with data from GP. * * @param $data - data from GP. * @return bool */ public function _updateProductData($data, $gpSku = null) { /* Get downloadable tax class */ static $downloadableClass; if (is_null($downloadableClass)) { $classes = Mage::getModel('tax/class')->getCollection()->addFieldToFilter('class_name', array('eq' => 'Downloadable'))->load(); if ($classes->count()) { $downloadableClass = $classes->getFirstItem(); } else { $downloadableClass = Mage::getModel('tax/class'); $downloadableClass->setData(array('class_name' => 'Downloadable', 'class_type' => 'PRODUCT')); $downloadableClass->save(); } } // Mage::Log($data, Zend_Log::DEBUG, 'gp_product_cron.log'); /* * Check for empty data sets. If all are empty, return false for this sku. */ $gotData = false; $gotDescription = false; $gotWeight = false; $gotInventory = false; $gotTaxability = false; $gotTierPricing = false; if (isset($data->Description) && $data->Description != "") { $gotDescription = true; $gotData = true; } if (isset($data->Weight) && $data->Weight != "") { $gotWeight = true; $gotData = true; } if (isset($data->Inventory) && $data->Inventory != "") { $gotInventory = true; $gotData = true; } if (isset($data->Taxability) && $data->Taxability != "") { $gotTaxability = true; $gotData = true; } if (!empty($data->TierPricing) && is_object($data->TierPricing)) { $gotTierPricing = true; $gotData = true; } if (!$gotData) { $this->log("No data from GP for gp_sku = " . $gpSku); } else { $this->log("Data found from GP for gp_sku = " . $gpSku); } /* * Get the set of Magento products that have this GP_SKU */ $sku = empty($data->SKU) ? $gpSku : $data->SKU; $originalPrice = 0; $products = $this->getProductCollection(); $products = $products->addAttributeToFilter('gp_sku', $sku)->addAttributeToSelect('price')->addAttributeToSelect('visibility')->addTierPriceData()->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID); /* * Update product information for each product with this gp_sku */ foreach ($products as $product) { if ($gotData) { $this->numProdsWData++; } else { $this->numProdsNoData++; } $this->log("\tFound product with sku = " . $product->getSku()); /* * Process and update pricing from GP. */ $originalPrice = $product->getPrice(); if ($gotTierPricing) { $this->log("\t\tProcessing new tier prices"); $tierpricing = $data->TierPricing; $tierpricing = (array) $tierpricing; // Loop through GP tier pricing data and accumulate it in newTierPrices $newTierPrices = array(); foreach ($tierpricing as $group => $prices) { foreach ($prices->PriceTier as $gpPriceTier) { $gpPriceTier = (array) $gpPriceTier; $mageTiers = $this->processPrice($group, $gpPriceTier); foreach ($mageTiers as $singleTier) { $newTierPrices[] = $singleTier; // Iron Eyes Cody } } } // Mage::Log($newTierPrices, Zend_Log::DEBUG, 'gp_product_test.log'); // Set product's regular price to first tier that meets qualifications. // There should only be one anyhow. foreach ($newTierPrices as $tier) { if ($tier['price_qty'] == 1 && !$this->isCustGroupElevated($tier['cust_group'])) { $originalPrice = $tier['price']; break; } } /* * Retain existing tiers that are not part of the set of tiers that are updated from GP. */ $existingTierPrice = $product->getData('tier_price'); Mage::Log($existingTierPrice, Zend_Log::DEBUG, 'gp_product_test.log'); if ($existingTierPrice) { $this->log("\t\tHad existing tiers. Special values will be retained."); foreach ($existingTierPrice as $tp) { if (!$this->isCustGroupPricingUpdateFromGP($tp['cust_group'])) { $this->log("\t\tNot In group list - ALL,NOT LOGGED IN,General,Member,Reseller,HIDDEN_Reseller will not overwritten"); $newTierPrices[] = $tp; } else { //$this->log("\t\tIn group list - ALL,NOT LOGGED IN,General,Member,Reseller,HIDDEN_Reseller will overwritten"); $this->log("\t\tIn group list - ALL,NOT LOGGED IN,General,Member,Reseller,HIDDEN_Reseller will overwritten if such a tier already exists"); if (!$this->checkTierExists($tp, $newTierPrices)) { $newTierPrices[] = $tp; } } } Mage::Log($newTierPrices, Zend_Log::DEBUG, 'gp_product_test.log'); } } /* * Process and update weight * Ignores weights of 0 from GP. */ if ($gotWeight) { if ($data->Weight > 0) { $this->log("\t\tGot a new non-zero weight."); if ($product->getTypeId() == 'simple') { $product->setWeight($data->Weight); } } } /* ticket#2014112010000245 - only update inventory and taxability when product is not "virtual" and "event" */ $isEvent = $product->getData('type_id') == 'virtual' && $product->getData('attribute_set_id') == 11; /* * Process and update inventory */ $stockData = array(); if ($gotInventory && !$isEvent) { $this->log("\t\tSetting new inventory data"); $stockData['qty'] = $data->Inventory; // Set is_in_stock properly based on qty and (if necessary) backorderable // Note: if qty <= 0 and it is backorderable, we leave is_in_stock as is. if ($data->Inventory > 0) { $stockData['is_in_stock'] = 1; } else { $isBackorderable = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getBackorders(); if ($isBackorderable == "0") { $stockData['is_in_stock'] = 0; } } /* * * start. artem. gorilla. ticket 2012120710000352 ** */ //$product->setStockItem($stockData); $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product); $product->setStockItem($stockItem); $product->setStockData($stockData); /* * * end. artem. gorilla. ticket 2012120710000352 ** */ } else { $this->log("\t\tgotInventory -- " . $gotInventory . " --- isevent" . $isEvent); $stockData = $product->getStockItem(); if ($stockData->getUseConfigManageStokck() == 0) { $stockData->setData('qty', 0); $stockData->setData('is_in_stock', 1); $stockData->setData('manage_stock', 0); $stockData->setData('use_config_manage_stock', 0); // $stockData->save(); // This enough to save stock data. $product->setStockItem($stockData); } } /* * Process and update taxability */ if ($product->getTypeId() == 'downloadable') { $product->setTaxClassId($downloadableClass->getId()); } else { if ($gotTaxability && !$isEvent) { $this->log("\t\tSetting new tax data --- " . $data->Taxability); switch ($data->Taxability) { case "Basedoncustomer": case "BasedOnCustomer": $this->log("\t\tnew tax data -- 2"); $product->setTaxClassId(2); break; case "NonTaxable": case "Nontaxable": $this->log("\t\tnew tax data -- 0"); $product->setTaxClassId(0); break; default: $this->log("\t\tnew tax data -- 2"); $product->setTaxClassId(2); break; } } } /* * Update with time we ran this. */ $product->setLastGpUpdate($this->getScriptStartTime()); /** * Save the product. */ try { $this->log("\t\tSaving product"); $product->setPrice($originalPrice); // If we have new tier pricing data, there's a two step save process: // 1) first we unset the current tier price, then we save, // 2) then we set the new tier price, and then go with the regular save if ($gotTierPricing) { $this->log("\t\tGotTierPricing"); $product->setData(self::ATTRIBUTE_CODE, array()); $product->setData('tier_price_changed', 1); $this->log("\t\tbefore save 1"); $product->save(); $this->log("\t\tafter save 1"); time_nanosleep(0, 10000000); // this is 1/100th of a second. $this->log("\t\\after nano"); $product->setData(self::ATTRIBUTE_CODE, $newTierPrices); $this->log("\t\tafter setting new tiers"); } $product->save(); $this->log("\t\tSaved"); } catch (Exception $e) { $line = "Integrity constraint violation"; // We are supressing this error. if (strpos($e->getMessage(), $line) === false) { $this->log("Error saving product. Sku = " . $product->getSku . ". Error: " . $e->getMessage()); } } } return $gotData; }
public function processMessage($redis, $channel, $queue, $message) { $requestIdLength = 0; $message = json_decode($message, true); if ($this->_opts->getOption('show-request-id')) { echo "{$message['request']} "; $requestIdLength = strlen($message['request']) + 1; } $message = $message['data']; if ($queue == $this->getEndPoint()) { echo $message . "\n"; } else { if (strpos($queue, $this->getEndPoint('events')) === 0) { $this->_outputEvent($queue, $message, $requestIdLength); } else { if ($queue == $this->getEndPoint('pslogger_message')) { $this->_logMessage($message); } else { if ($queue == $this->getEndPoint('pslogger_sql')) { if ($this->_logSql($message)) { return; // bypass the delay if the regex doesn't match } } else { if ($queue == $this->getEndPoint('pslogger_sql_summary')) { $this->_logSqlSummary($message); } } } } } time_nanosleep(0, $this->_delay * 1000000); }
/** * Enforce the minimum execution time. Call this at the end of your long * processing to make sure that it doesn't take less time than the * minimum execution time. This is used to avoid being blocked by * overzealous server protection solutions. * * @return void */ public function enforce_min_exec_time() { // Try to get a sane value for PHP's maximum_execution_time INI parameter if (@function_exists('ini_get')) { $php_max_exec = @ini_get("maximum_execution_time"); } else { $php_max_exec = 10; } if ($php_max_exec == "" || $php_max_exec == 0) { $php_max_exec = 10; } // Decrease $php_max_exec time by 500 msec we need (approx.) to tear down // the application, as well as another 500msec added for rounding // error purposes. Also make sure this is never going to be less than 0. $php_max_exec = max($php_max_exec * 1000 - 1000, 0); // Get the "minimum execution time per step" Akeeba Backup configuration variable $minexectime = $this->min_exec_time; if (!is_numeric($minexectime)) { $minexectime = 0; } // Make sure we are not over PHP's time limit! if ($minexectime > $php_max_exec) { $minexectime = $php_max_exec; } // Get current running time $elapsed_time = $this->getRunningTime() * 1000; // Only run a sleep delay if we haven't reached the minexectime execution time if ($minexectime > $elapsed_time && $elapsed_time > 0) { $sleep_msec = $minexectime - $elapsed_time; if (function_exists('usleep')) { usleep(1000 * $sleep_msec); } elseif (function_exists('time_nanosleep')) { $sleep_sec = floor($sleep_msec / 1000); $sleep_nsec = 1000000 * ($sleep_msec - $sleep_sec * 1000); time_nanosleep($sleep_sec, $sleep_nsec); } elseif (function_exists('time_sleep_until')) { $until_timestamp = time() + $sleep_msec / 1000; time_sleep_until($until_timestamp); } elseif (function_exists('sleep')) { $sleep_sec = ceil($sleep_msec / 1000); sleep($sleep_sec); } } elseif ($elapsed_time > 0) { // No sleep required, even if user configured us to be able to do so. } }
/** * Edits fields associated with the response (action_plan, owner, release_progress, current_status). The model must * be initialized with a user_id before this function can be executed. * @param array $data An associative array containing the keys and values to be updated. * @return type True on successful update, false if otherwise. */ public function edit(array $data) { if (!$this->initialized) { return false; } if (!$this->Project_model->modify($this->user_id, $this->project_id)) { return false; } //filter excess data from array $keys = array('action_plan', 'owner', 'release_progress', 'date_of_plan', 'action', 'current_status', 'planned_closure', 'cost', 'post_response'); foreach ($data as $key => $val) { if (!in_array($key, $keys)) { unset($data[$key]); } } // $response_data = $this->get(); // $this->load->model('Risk_model'); // $send_risk_id = $response_data['risk_id']; // $send_user_id = $this->user_id; // $permission = $this->Risk_model->initialize($send_risk_id, $send_user_id); // if ($permission != "Admin" && $permission != "Owner" && $permission != "Write") { // return false; // } // $send_response_id = $this->response_id; // if ($this->Risk_model->update_adjusted_cost($send_response_id, $send_user_id, $send_risk_id) === false) // return false; // $this->Risk_model->close(); $data['date_of_update'] = date('Y-m-d'); if (isset($data['release_progress']) && $data['release_progress'] === 'Cancelled') { $data['post_response'] = 0; $data['cost'] = 0; } if (isset($data['cost'])) { $data['cost'] = $this->format_currency($data['cost']); } if (isset($data['post_response'])) { $data['post_response'] = $this->format_currency($data['post_response']); } // return $this->db->where('response_id', $this->response_id)->update('responses', $data); if ($this->db->where('response_id', $this->response_id)->update('responses', $data)) { // Just to make sure that the get doesn't fetch values from before the update time_nanosleep(0, 500000000); $response_data = $this->get(); $this->load->model('Risk_model'); $send_risk_id = $response_data['risk_id']; $send_user_id = $this->user_id; $permission = $this->Risk_model->initialize($send_risk_id, $send_user_id); if ($permission != "Admin" && $permission != "Owner" && $permission != "Write") { return false; } if ($this->Risk_model->update_adjusted_cost($send_user_id, $send_risk_id) === false) { return false; } $this->Risk_model->close(); return true; } else { return false; } }
/** Function to reach fixed execution time in order to mitigate timing attacks. * Because of doubts about the accurateness of microtime() and to hide system clock details * a random between 0 and randomSleepingNanosecondsMax nanoseconds is added. * Because the time <until> may in fact be in the past, sleeping will be * until next whole multitude of $seconds has passed. I.e. if $seconds is * 0.9 and one second has passed, sleeping will be until 1.8 * @param float $seconds since ::init until when to sleep */ public function sleepUntilSinceInit($seconds) { $passed = $this->getSecondsPassedSinceInit(); $multiplier = ceil($passed / $seconds); $multitude = $multiplier * $seconds; $toSleep = $multitude - $passed; $wholeSeconds = floor($toSleep); $nanoSeconds = round(($toSleep - $wholeSeconds) * 1000000000); // Add random nanoseconds sleeping time $nanoSeconds += mt_rand(0, $this->randomSleepingNanosecondsMax); if ($nanoSeconds > 1000000000) { $nanoSeconds -= 1000000000; $wholeSeconds++; } do { $result = time_nanosleep($wholeSeconds, $nanoSeconds); if (is_array($result)) { $wholeSeconds = $result['seconds']; $nanoSeconds = $result['nanoseconds']; } } while (is_array($result)); }