function connect($server, $db, $user, $password, $socketPath, $charset = null, $port = false) { $connection = false; if ($socketPath !== false) { ini_set("mysqli.default_socket", $socketPath); } if ($this->UsePersistentConnection == true) { // Only supported on PHP 5.3 (mysqlnd) if (version_compare(PHP_VERSION, '5.3') > 0) { $this->Server = 'p:' . $this->Server; } else { eZDebug::writeWarning('mysqli only supports persistent connections when using php 5.3 and higher', 'eZMySQLiDB::connect'); } } eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $connection = mysqli_connect($server, $user, $password, null, (int) $port, $socketPath); $dbErrorText = mysqli_connect_error(); eZPerfLogger::accumulatorStop('mysqli_connection'); $maxAttempts = $this->connectRetryCount(); $waitTime = $this->connectRetryWaitTime(); $numAttempts = 1; while (!$connection && $numAttempts <= $maxAttempts) { sleep($waitTime); eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $connection = mysqli_connect($this->Server, $this->User, $this->Password, null, (int) $this->Port, $this->SocketPath); eZPerfLogger::accumulatorStop('mysqli_connection'); $numAttempts++; } $this->setError(); $this->IsConnected = true; if (!$connection) { eZDebug::writeError("Connection error: Couldn't connect to database. Please try again later or inform the system administrator.\n{$dbErrorText}", __CLASS__); $this->IsConnected = false; throw new eZDBNoConnectionException($server); } if ($this->IsConnected && $db != null) { eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $ret = mysqli_select_db($connection, $db); eZPerfLogger::accumulatorStop('mysqli_connection'); if (!$ret) { //$this->setError(); eZDebug::writeError("Connection error: " . mysqli_errno($connection) . ": " . mysqli_error($connection), "eZMySQLiDB"); $this->IsConnected = false; } } if ($charset !== null) { $originalCharset = $charset; $charset = eZCharsetInfo::realCharsetCode($charset); } if ($this->IsConnected and $charset !== null) { eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $status = mysqli_set_charset($connection, eZMySQLCharset::mapTo($charset)); eZPerfLogger::accumulatorStop('mysqli_connection'); if (!$status) { $this->setError(); eZDebug::writeWarning("Connection warning: " . mysqli_errno($connection) . ": " . mysqli_error($connection), "eZMySQLiDB"); } } return $connection; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $realCacheDir = $this->getContainer()->getParameter('kernel.cache_dir'); $oldCacheDir = $realCacheDir . '_old'; $filesystem = $this->getContainer()->get('filesystem'); if (!is_writable($realCacheDir)) { throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $realCacheDir)); } if ($filesystem->exists($oldCacheDir)) { $filesystem->remove($oldCacheDir); } $kernel = $this->getContainer()->get('kernel'); $output->writeln(sprintf('Clearing the cache for the <info>%s</info> environment with debug <info>%s</info>', $kernel->getEnvironment(), var_export($kernel->isDebug(), true))); $this->getContainer()->get('cache_clearer')->clear($realCacheDir); if ($input->getOption('no-warmup')) { $filesystem->rename($realCacheDir, $oldCacheDir); } else { // the warmup cache dir name must have the same length than the real one // to avoid the many problems in serialized resources files $warmupDir = substr($realCacheDir, 0, -1) . '_'; if ($filesystem->exists($warmupDir)) { $filesystem->remove($warmupDir); } $this->warmup($warmupDir, $realCacheDir, !$input->getOption('no-optional-warmers')); $filesystem->rename($realCacheDir, $oldCacheDir); if (defined('PHP_WINDOWS_VERSION_BUILD')) { sleep(1); // workaround for windows php rename bug } $filesystem->rename($warmupDir, $realCacheDir); } $filesystem->remove($oldCacheDir); }
/** * 通知客户端 * Enter description here ... * @param unknown_type $operation * @param unknown_type $data */ protected function queueSend($start = 0) { $time = Windid::getTime(); $appids = $nids = array(); $logDs = $this->_getNotifyLogDs(); $queue = $logDs->getList(0, 0, 10, $start, 0); if (!$queue) { return false; } foreach ($queue as $v) { $appids[] = $v['appid']; $nids[] = $v['nid']; } $apps = $this->_getAppDs()->fetchApp(array_unique($appids)); $notifys = $this->_getNotifyDs()->fetchNotify(array_unique($nids)); $postData = $urls = array(); foreach ($queue as $k => $v) { $appid = $v['appid']; $nid = $v['nid']; $array = array('windidkey' => WindidUtility::appKey($v['appid'], $time, $apps[$appid]['secretkey']), 'operation' => $notifys[$nid]['operation'], 'uid' => (int) $notifys[$nid]['param'], 'clientid' => $v['appid'], 'time' => $time); $urls[$k] = WindidUtility::buildClientUrl($apps[$appid]['siteurl'], $apps[$appid]['apifile']) . http_build_query($array); } if (!$urls) { return false; } $result = WindidUtility::buildMultiRequest($urls); sleep(3); $this->logId = $this->logId + $result; $start += 10; $this->queueSend($start); }
function cron_verifyTiezi() { global $m; $set = unserialize(option::get('plugin_verifyTiezi')); $today = date("Y-m-d"); //准备:扫描verifyTiezi表中lastdo不是今天的,然后更新verifyTiezi_data表的remain $sy = $m->query("SELECT * FROM `" . DB_PREFIX . "verifyTiezi` WHERE `lastdo` != '{$today}';"); while ($sx = $m->fetch_array($sy)) { $m->query('UPDATE `' . DB_NAME . '`.`' . DB_PREFIX . 'verifyTiezi_data` SET `remain` = \'' . $sx['num'] . '\' WHERE `uid` = ' . $sx['uid']); $m->query('UPDATE `' . DB_NAME . '`.`' . DB_PREFIX . 'verifyTiezi` SET `lastdo` = \'' . $today . '\' WHERE `uid` = ' . $sx['uid']); } //开始:计划任务 $count = $m->once_fetch_array("SELECT COUNT(*) AS `c` FROM `" . DB_PREFIX . "verifyTiezi_data` WHERE `remain` > '0' LIMIT {$set['rem']};"); if ($count['c'] == $set['rem']) { $y = rand_row(DB_PREFIX . 'verifyTiezi_data', 'id', $set['rem'], "`remain` > '0'"); } else { $y = rand_row(DB_PREFIX . 'verifyTiezi_data', 'id', $count['c'], "`remain` > '0'"); } //如果只有一条记录的兼容方案 if (isset($y['url'])) { $y = array(0 => $y); } foreach ($y as $x) { if (!empty($x['pid']) && !empty($x['uid'])) { $u = $m->once_fetch_array("SELECT * FROM `" . DB_PREFIX . "verifyTiezi` WHERE `uid` = '{$x['uid']}'"); $cont = unserialize($u['cont']); $remain = $x['remain'] - 1; $res = verifyTiezi_send($x['uid'], $x['url'], $x['pid'], rand_array($cont), $set['device']); $m->query('UPDATE `' . DB_NAME . '`.`' . DB_PREFIX . 'verifyTiezi_data` SET `remain` = \'' . $remain . '\',`status` = \'' . $res['status'] . '\',`msg` = \'' . $res['msg'] . '\' WHERE `url` = \'' . $x['url'] . '\' AND `uid` = ' . $x['uid']); sleep($set['sleep']); } } }
function confirm($seconds) { sleep($seconds); $objResponse = new xajaxResponse(); $objResponse->append('outputDIV', 'innerHTML', '<br />confirmation from theFrame.php call'); return $objResponse; }
public function testGenerateTimestamp() { $idA = \Simpleflake\generate(null, 0, 0); sleep(1); $idB = \Simpleflake\generate(null, 0, 0); $this->assertNotEquals($idA, $idB); }
function get_profile_email($url) { global $g_acegi_cookie; global $g_session_cookie; global $g_delay; sleep($g_delay); // Create a stream // get cookie values using wget commands $cookie = sprintf("Cookie: ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE=%s; JSESSIONID=%s\r\n", $g_acegi_cookie, $g_session_cookie); $opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\n" . $cookie)); $context = stream_context_create($opts); @($html = file_get_contents($url, false, $context)); $doc = new \DOMDocument(); @$doc->loadHTML($html); $emailNode = $doc->getElementById("email1__ID__"); $nameNode = $doc->getElementById("name1__ID__"); $titleNode = $doc->getElementById("title1__ID__"); $companyNode = $doc->getElementById("company1__ID__"); if (!is_null($emailNode)) { $data = array(); $data["email"] = $emailNode->nodeValue; $data["name"] = is_null($nameNode) ? "" : $nameNode->nodeValue; $data["title"] = is_null($titleNode) ? "" : $titleNode->nodeValue; $data["company"] = is_null($companyNode) ? "" : $companyNode->nodeValue; return $data; } return NULL; }
public function testNoExpire() { $cache = $this->_getCacheDriver(); $cache->save('noexpire', 'value', 0); sleep(1); $this->assertTrue($cache->contains('noexpire'), 'Couchbase provider should support no-expire'); }
/** * A proxy curl implementation to get the content of the url. * * @param string $url * * @return string * @throws CurlException */ public function get($url) { $ch = curl_init($url); if (!ini_get('open_basedir')) { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); } if (self::$proxy) { curl_setopt($ch, CURLOPT_PROXY, self::$proxy); } curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent()); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 40); curl_setopt($ch, CURLOPT_REFERER, $this->getReferrer()); /*curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true);*/ sleep(mt_rand(10, 20)); $content = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this->connectedURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); if (404 === $code) { throw new CurlException('Content not found.'); } if ($content === false) { // there was a problem $error = curl_error($ch); throw new CurlException('Error retrieving "' . $url . '" (' . $error . ')'); } if (false !== strpos($content, 'Error 525')) { throw new CurlException('Error in a source site.'); } return $content; }
function exec_curl_request($handle) { $response = curl_exec($handle); if ($response === false) { $errno = curl_errno($handle); $error = curl_error($handle); error_log("Curl retornou um erro {$errno}: {$error}\n"); curl_close($handle); return false; } $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE)); curl_close($handle); if ($http_code >= 500) { // do not wat to DDOS server if something goes wrong sleep(10); return false; } else { if ($http_code != 200) { $response = json_decode($response, true); error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n"); if ($http_code == 401) { throw new Exception('Invalid access token provided'); } return false; } else { $response = json_decode($response, true); if (isset($response['description'])) { error_log("Request was successfull: {$response['description']}\n"); } $response = $response['result']; } } return $response; }
/** * Ensure that the automated cron run module is working. * * In these tests we do not use REQUEST_TIME to track start time, because we * need the exact time when cron is triggered. */ function testAutomatedCron() { // Test with a logged in user; anonymous users likely don't cause Drupal to // fully bootstrap, because of the internal page cache or an external // reverse proxy. Reuse this user for disabling cron later in the test. $admin_user = $this->drupalCreateUser(array('administer site configuration')); $this->drupalLogin($admin_user); // Ensure cron does not run when a non-zero cron interval is specified and // was not passed. $cron_last = time(); $cron_safe_interval = 100; \Drupal::state()->set('system.cron_last', $cron_last); $this->config('automated_cron.settings')->set('interval', $cron_safe_interval)->save(); $this->drupalGet(''); $this->assertTrue($cron_last == \Drupal::state()->get('system.cron_last'), 'Cron does not run when the cron interval is not passed.'); // Test if cron runs when the cron interval was passed. $cron_last = time() - 200; \Drupal::state()->set('system.cron_last', $cron_last); $this->drupalGet(''); sleep(1); $this->assertTrue($cron_last < \Drupal::state()->get('system.cron_last'), 'Cron runs when the cron interval is passed.'); // Disable cron through the interface by setting the interval to zero. $this->drupalPostForm('admin/config/system/cron', ['interval' => 0], t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); $this->drupalLogout(); // Test if cron does not run when the cron interval is set to zero. $cron_last = time() - 200; \Drupal::state()->set('system.cron_last', $cron_last); $this->drupalGet(''); $this->assertTrue($cron_last == \Drupal::state()->get('system.cron_last'), 'Cron does not run when the cron threshold is disabled.'); }
public function itemSealAction() { $LogType = $this->request->LogType; if ($LogType) { do { $S = time(); $AppId = intval($this->request->AppId); if ($AppId) { $ItemSeal = array(); $SealItem = $this->oSeal->getAll($AppId); foreach ($SealItem as $k => $v) { $ItemIds[$v['SealTimeType']][$v['SealTime']][$v['AppId']][] = $v['ItemId']; $ItemSeal[$v['ItemId']]['ItemSeal'] = $v['ItemSeal']; $ItemSeal[$v['ItemId']]['ItemName'] = $v['ItemName']; } foreach ($ItemIds as $k => $v) { switch ($k) { case "hh": $this->checkSeal($v, "Y-m-d H:00:00", 3600, $ItemSeal, $LogType, $k); break; case "dd": $this->checkSeal($v, "Y-m-d 00:00:00", 86400, $ItemSeal, $LogType, $k); break; } } } $E = time(); if ($E - $S < 900) { sleep(900 - ($E - $S)); } } while (true); } }
public function downloadAction() { $squadID = $this->params('id', 0); $squadRepo = $this->getEntityManager()->getRepository('Frontend\\Squads\\Entity\\Squad'); /** @var Squad $squadEntity */ $squadEntity = $squadRepo->findOneBy(array('user' => $this->identity(), 'id' => $squadID)); if (!$squadEntity) { $this->flashMessenger()->addErrorMessage('Squad not found'); return $this->redirect('frontend/user/squads'); } $fileName = 'squad_file_pack_armasquads_' . $squadID; $zipTmpPath = tempnam(ini_get('upload_tmp_dir'), $fileName); $zip = new \ZipArchive(); $zip->open($zipTmpPath, \ZipArchive::CHECKCONS); if (!$zip) { $this->flashMessenger()->addErrorMessage('Squad Package Download currently not possible'); return $this->redirect('frontend/user/squads'); } $zip->addFromString('squad.xml', file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $this->url()->fromRoute('frontend/user/squads/xml', array('id' => $squadEntity->getPrivateID())))); if ($squadEntity->getSquadLogoPaa()) { $zip->addFile(ROOT_PATH . $squadEntity->getSquadLogoPaa(), basename($squadEntity->getSquadLogoPaa())); } $zip->addFromString('squad.dtd', file_get_contents(realpath(__DIR__ . '/../../../../view/squads/xml/') . '/squad.dtd')); //$zip->addFromString('squad.xsl',file_get_contents(realpath(__DIR__ . '/../../../../view/squads/xml/').'/squad.xsl')); $zip->close(); header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . basename($fileName) . ".zip\""); readfile($zipTmpPath); sleep(1); @unlink($zipTmpPath); die; }
public function testMoveTaskAnotherSwimlane() { $tp = new TaskPosition($this->container); $tc = new TaskCreation($this->container); $p = new Project($this->container); $tf = new TaskFinder($this->container); $s = new Swimlane($this->container); $this->container['dispatcher'] = new EventDispatcher(); $this->container['dispatcher']->addSubscriber(new TaskMovedDateSubscriber($this->container)); $now = time(); $this->assertEquals(1, $p->create(array('name' => 'Project #1'))); $this->assertEquals(1, $s->create(array('project_id' => 1, 'name' => 'S1'))); $this->assertEquals(2, $s->create(array('project_id' => 1, 'name' => 'S2'))); $this->assertEquals(1, $tc->create(array('title' => 'Task #1', 'project_id' => 1))); $task = $tf->getById(1); $this->assertNotEmpty($task); $this->assertEquals($now, $task['date_moved'], '', 1); $this->assertEquals(1, $task['column_id']); $this->assertEquals(0, $task['swimlane_id']); sleep(1); $this->assertTrue($tp->movePosition(1, 1, 2, 1, 2)); $task = $tf->getById(1); $this->assertNotEmpty($task); $this->assertNotEquals($now, $task['date_moved']); $this->assertEquals(2, $task['column_id']); $this->assertEquals(2, $task['swimlane_id']); }
public function actionIndex() { while (1) { self::auto(); sleep(600); } }
/** * Create a daemon process. * * @return DaemonHttpApplication Return self to support chaining. */ public function execute() { // Create first child. if (pcntl_fork()) { // I'm the parent // Protect against Zombie children pcntl_wait($status); exit; } // Make first child as session leader. posix_setsid(); // Create second child. $pid = pcntl_fork(); if ($pid) { // If pid not 0, means this process is parent, close it. $this->processId = $pid; $this->storeProcessId(); exit; } $this->addLog('Daemonized'); fwrite(STDOUT, "Daemon Start\n-----------------------------------------\n"); $this->registerSignalHandler(); // Declare ticks to start signal monitoring. When you declare ticks, PCNTL will monitor // incoming signals after each tick and call the relevant signal handler automatically. declare (ticks=1); while (true) { $this->doExecute(); sleep(1); } return $this; }
/** * @dataProvider provideData */ public function testHandle($size, $duration, $data, $expectedPercent, $expectedRemaining, $expectedRate, $data2, $expectedPercent2, $expectedRemaining2, $expectedRate2, $currentPass, $totalPass) { $ffprobe = $this->getFFProbeMock(); $ffprobe->expects($this->once())->method('format')->with(__FILE__)->will($this->returnValue(new Format(array('size' => $size, 'duration' => $duration)))); $listener = new AudioProgressListener($ffprobe, __FILE__, $currentPass, $totalPass); $phpunit = $this; $n = 0; $listener->on('progress', function ($percent, $remaining, $rate) use(&$n, $phpunit, $expectedPercent, $expectedRemaining, $expectedRate, $expectedPercent2, $expectedRemaining2, $expectedRate2) { if (0 === $n) { $phpunit->assertEquals($expectedPercent, $percent); $phpunit->assertEquals($expectedRemaining, $remaining); $phpunit->assertEquals($expectedRate, $rate); } elseif (1 === $n) { $phpunit->assertEquals($expectedPercent2, $percent); $phpunit->assertEquals($expectedRemaining2, $remaining); $phpunit->assertLessThan($expectedRate2 + 3, $rate); $phpunit->assertGreaterThan($expectedRate2 - 3, $rate); } $n++; }); // first one does not trigger progress event $listener->handle('any-type' . mt_rand(), $data); sleep(1); $listener->handle('any-type' . mt_rand(), $data); sleep(1); $listener->handle('any-type' . mt_rand(), $data2); $this->assertEquals(2, $n); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $loggingIn = $request->is('api/v1/login') || $request->is('api/v1/register') || $request->is('api/v1/oauth_login'); $headers = Utils::getApiHeaders(); $hasApiSecret = false; if ($secret = env(API_SECRET)) { $requestSecret = Request::header('X-Ninja-Secret') ?: ($request->api_secret ?: ''); $hasApiSecret = hash_equals($requestSecret, $secret); } if ($loggingIn) { // check API secret if (!$hasApiSecret) { sleep(ERROR_DELAY); return Response::json('Invalid value for API_SECRET', 403, $headers); } } else { // check for a valid token $token = AccountToken::where('token', '=', Request::header('X-Ninja-Token'))->first(['id', 'user_id']); // check if user is archived if ($token && $token->user) { Auth::onceUsingId($token->user_id); Session::set('token_id', $token->id); } else { sleep(ERROR_DELAY); return Response::json('Invalid token', 403, $headers); } } if (!Utils::isNinja() && !$loggingIn) { return $next($request); } if (!Utils::hasFeature(FEATURE_API) && !$hasApiSecret) { return Response::json('API requires pro plan', 403, $headers); } else { $key = Auth::check() ? Auth::user()->account->id : $request->getClientIp(); // http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users $hour = 60 * 60; $hour_limit = 100; # users are limited to 100 requests/hour $hour_throttle = Cache::get("hour_throttle:{$key}", null); $last_api_request = Cache::get("last_api_request:{$key}", 0); $last_api_diff = time() - $last_api_request; if (is_null($hour_throttle)) { $new_hour_throttle = 0; } else { $new_hour_throttle = $hour_throttle - $last_api_diff; $new_hour_throttle = $new_hour_throttle < 0 ? 0 : $new_hour_throttle; $new_hour_throttle += $hour / $hour_limit; $hour_hits_remaining = floor(($hour - $new_hour_throttle) * $hour_limit / $hour); $hour_hits_remaining = $hour_hits_remaining >= 0 ? $hour_hits_remaining : 0; } if ($new_hour_throttle > $hour) { $wait = ceil($new_hour_throttle - $hour); sleep(1); return Response::json("Please wait {$wait} second(s)", 403, $headers); } Cache::put("hour_throttle:{$key}", $new_hour_throttle, 10); Cache::put("last_api_request:{$key}", time(), 10); } return $next($request); }
protected function tearDown() { // Restore output buffer. ob_end_clean(); // Sleep to avoid rate exceeded errors. sleep(5); }
function getNumAudience($code, $gender, $accessToken) { global $aux_num_intentos, $num_intentos, $data_acount_facebook, $data_acount_facebook_index; $numAudience = ""; $ban = 0; while ($ban == 0) { try { $datos = file_get_contents('https://graph.facebook.com/act_' . $data_acount_facebook[$data_acount_facebook_index]['accountId'] . '/reachestimate?endpoint=/act_' . $data_acount_facebook[$data_acount_facebook_index]['accountId'] . '/reachestimate&accountId=' . $data_acount_facebook[$data_acount_facebook_index]['accountId'] . '&locale=es_LA&targeting_spec={"genders":[' . $gender . '],"age_max":65,"age_min":13,"broad_age":true,"regions":[],"countries":["' . $code . '"],"cities":[],"zips":[],"radius":0,"keywords":[],"connections":[],"excluded_connections":[],"friends_of_connections":[],"relationship_statuses":null,"interested_in":[],"college_networks":[],"college_majors":[],"college_years":[],"education_statuses":[0],"locales":[],"work_networks":[],"user_adclusters":[]}&method=get&access_token=' . $accessToken); $datosarray2 = json_decode($datos, true); $numAudience = $datosarray2['users']; if ($numAudience != "" && is_numeric($numAudience)) { $ban = 1; } else { sleep(3); //Espera 3 minutos $accessToken = getAccessToken(); //Trata de obtener un nuevo access_token } } catch (Exception $e) { if ($aux_num_intentos++ > $num_intentos) { informarError(); } sleep(3); //Espera 3 minutos $accessToken = getAccessToken(); //Trata de obtener un nuevo access_token } } return $numAudience; }
function add_sites($array) { global $db, $spider; foreach ($array as $value) { $row = $db->get_one("select * from ve123_links where url='" . $value . "'"); if (empty($row)) { echo $value . "<br>"; $spider->url($value); $title = $spider->title; $fulltxt = $spider->fulltxt(800); $keywords = $spider->keywords; $description = $spider->description; $pagesize = $spider->pagesize; $htmlcode = $spider->htmlcode; $array = array('url' => $value, 'title' => $title, 'fulltxt' => $fulltxt, 'pagesize' => $pagesize, 'keywords' => $keywords, 'description' => $description, 'addtime' => time(), 'updatetime' => time()); //echo $fulltxt; $db->insert("ve123_links", $array); file_put_contents(PATH . "k/www/" . base64_encode($value), $htmlcode); //echo $htmlcode; } else { echo "已存在:" . $value . "<br>"; } ob_flush(); flush(); sleep(1); } }
/** * @group internet * @group slow */ public function test_recache() { global $conf; $conf['fetchsize'] = 500 * 1024; //500kb $local = media_get_from_URL('http://www.google.com/images/srpr/logo3w.png', 'png', 5); $this->assertTrue($local !== false); $this->assertFileExists($local); // remember time stamp $time = filemtime($local); clearstatcache(false, $local); sleep(1); // fetch again and make sure we got a cache file $local = media_get_from_URL('http://www.google.com/images/srpr/logo3w.png', 'png', 5); clearstatcache(false, $local); $this->assertTrue($local !== false); $this->assertFileExists($local); $this->assertEquals($time, filemtime($local)); clearstatcache(false, $local); sleep(6); // fetch again and make sure we got a new file $local = media_get_from_URL('http://www.google.com/images/srpr/logo3w.png', 'png', 5); clearstatcache(false, $local); $this->assertTrue($local !== false); $this->assertFileExists($local); $this->assertNotEquals($time, filemtime($local)); unlink($local); }
/** * @dataProvider getAcceptData */ public function testAccept($mode, $expected) { if (!is_callable($mode)) { switch ($mode) { case SortableIterator::SORT_BY_ACCESSED_TIME: file_get_contents(self::toAbsolute('.git')); sleep(1); file_get_contents(self::toAbsolute('.bar')); break; case SortableIterator::SORT_BY_CHANGED_TIME: file_put_contents(self::toAbsolute('test.php'), 'foo'); sleep(1); file_put_contents(self::toAbsolute('test.py'), 'foo'); break; case SortableIterator::SORT_BY_MODIFIED_TIME: file_put_contents(self::toAbsolute('test.php'), 'foo'); sleep(1); file_put_contents(self::toAbsolute('test.py'), 'foo'); break; } } $inner = new Iterator(self::$files); $iterator = new SortableIterator($inner, $mode); if ($mode === SortableIterator::SORT_BY_ACCESSED_TIME || $mode === SortableIterator::SORT_BY_CHANGED_TIME || $mode === SortableIterator::SORT_BY_MODIFIED_TIME) { $this->assertOrderedIteratorForGroups($expected, $iterator); } else { $this->assertOrderedIterator($expected, $iterator); } }
function getName($number, $pwd) { $TRY_TIMES = 10; S(array('prefix' => 'verify', 'expire' => 3 * $TRY_TIMES)); $verify_array = S('verify_array'); if (!$verify_array) { $verify_array = array(); } if (!in_array($number, $verify_array)) { array_push($verify_array, $number); } else { return false; } S('verify_' . $number, $pwd); S('verify_array', $verify_array); $i = 0; while ($i++ < $TRY_TIMES && S('verify_' . $number) == $pwd) { sleep(1); } $name = S('verify_' . $number); S(array('prefix' => '')); if ($i < $TRY_TIMES && $name != '0') { return $name; } else { return false; } }
public function __construct() { parent::__construct(); $oAffModel = new AffiliateModel(); $oSecurityModel = new SecurityModel(); $sEmail = $this->httpRequest->post('mail'); $sPassword = $this->httpRequest->post('password'); /** Check if the connection is not locked **/ $bIsLoginAttempt = (bool) DbConfig::getSetting('isAffiliateLoginAttempt'); $iMaxAttempts = (int) DbConfig::getSetting('maxAffiliateLoginAttempts'); $iTimeDelay = (int) DbConfig::getSetting('loginAffiliateAttemptTime'); if ($bIsLoginAttempt && !$oSecurityModel->checkLoginAttempt($iMaxAttempts, $iTimeDelay, $sEmail, $this->view, 'Affiliates')) { \PFBC\Form::setError('form_login_aff', Form::loginAttemptsExceededMsg($iTimeDelay)); return; // Stop execution of the method. } // Check Login $sLogin = $oAffModel->login($sEmail, $sPassword, 'Affiliates'); if ($sLogin === 'email_does_not_exist' || $sLogin === 'password_does_not_exist') { sleep(1); // Security against brute-force attack to avoid drowning the server and the database if ($sLogin === 'email_does_not_exist') { $this->session->set('captcha_enabled', 1); // Enable Captcha \PFBC\Form::setError('form_login_aff', t('Oops! "%0%" is not associated with any %site_name% account.', escape(substr($sEmail, 0, PH7_MAX_EMAIL_LENGTH)))); $oSecurityModel->addLoginLog($sEmail, 'Guest', 'No Password', 'Failed! Incorrect Username', 'Affiliates'); } elseif ($sLogin === 'password_does_not_exist') { $oSecurityModel->addLoginLog($sEmail, 'Guest', $sPassword, 'Failed! Incorrect Password', 'Affiliates'); if ($bIsLoginAttempt) { $oSecurityModel->addLoginAttempt('Affiliates'); } $this->session->set('captcha_enabled', 1); // Enable Captcha $sWrongPwdTxt = t('Oops! This password you entered is incorrect.') . '<br />'; $sWrongPwdTxt .= t('Please try again (make sure your caps lock is off).') . '<br />'; $sWrongPwdTxt .= t('Forgot your password? <a href="%0%">Request a new one</a>.', Uri::get('lost-password', 'main', 'forgot', 'affiliate')); \PFBC\Form::setError('form_login_aff', $sWrongPwdTxt); } } else { $oSecurityModel->clearLoginAttempts('Affiliates'); $this->session->remove('captcha_enabled'); $iId = $oAffModel->getId($sEmail, null, 'Affiliates'); $oAffData = $oAffModel->readProfile($iId, 'Affiliates'); if (true !== ($mStatus = (new AffiliateCore())->checkAccountStatus($oAffData))) { \PFBC\Form::setError('form_login_aff', $mStatus); } else { // Is disconnected if the user is logged on as "user" or "administrator". if (UserCore::auth() || AdminCore::auth()) { $this->session->destroy(); } // Regenerate the session ID to prevent the session fixation $this->session->regenerateId(); $aSessionData = ['affiliate_id' => $oAffData->profileId, 'affiliate_email' => $oAffData->email, 'affiliate_username' => $oAffData->username, 'affiliate_first_name' => $oAffData->firstName, 'affiliate_sex' => $oAffData->sex, 'affiliate_ip' => Ip::get(), 'affiliate_http_user_agent' => $this->browser->getUserAgent(), 'affiliate_token' => Various::genRnd($oAffData->email)]; $this->session->set($aSessionData); $oSecurityModel->addLoginLog($oAffData->email, $oAffData->username, '*****', 'Logged in!', 'Affiliates'); $oAffModel->setLastActivity($oAffData->profileId, 'Affiliates'); Header::redirect(Uri::get('affiliate', 'account', 'index'), t('You are successfully logged!')); } } }
function deactivate() { file_put_contents($this->config["incron"]["path"] . "/bittorrent.stop", "1"); do { sleep(1); } while ($this->isActive()); }
public function getGeocode($lon, $lat) { $result = ""; $result = json_decode(stripcslashes(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lon . '&sensor=false&language=ru'))); sleep(4); return $result; }
public function execute($url, $data = null) { if ($this->artificialDelay > 0) { sleep($this->artificialDelay); } return file_get_contents(__DIR__ . '/USPSResponse.xml'); }
/** * Stops scribe. Will check for termination if $pid is provided. * * @param string $scribe_ctrl_path scribe_ctrl path * @param int $port port * @param int $pid scribed process (optional) * * @return bool returns true on success * @author agiardullo */ function scribe_stop($scribe_ctrl_path, $port, $pid = 0) { $wait = 5; //seconds $scribe_ctrl = "{$scribe_ctrl_path}/scribe_ctrl"; $command = "{$scribe_ctrl} stop {$port} "; print "Stopping Scribed: {$command}\n"; // send stop command to scribe system($command, $error); echo "{$command} => {$error}\n"; if ($error == 0) { return true; } sleep($wait); if ($pid) { // kill if scribe process has not yet terminated system('kill -9 ' . $pid, $success); echo "kill -9 {$pid} => {$success}\n"; // If the kill failed if ($success == -1) { print "ERROR: scribed did not stop after {$wait} seconds.\n"; return false; } } return true; }