public function run() { $captcha = new \WakePHP\Utils\CaptchaDraw(); $captcha->setText($this->args[1]); $captcha->show($file = tempnam(sys_get_temp_dir(), 'php')); $this->parent->captcha->uploadImage($this->args[0], file_get_contents($file), function ($lastError) { Daemon::log(Debug::dump($lastError)); $this->sendResult(true); }); }
public function redirect() { if (!$this->checkReferer($this->appInstance->config->domain->value)) { $this->req->setResult(['error' => 'Wrong referer']); return; } $code = Request::getString($_GET['code']); if ($code === '') { Daemon::log('Authentication failed'); $this->req->status(401); $this->req->setResult(['error' => 'Authenticaion failed']); return; } $this->appInstance->httpclient->get($get = ['https://api.vk.com/oauth/access_token', 'client_id' => $this->cmp->config->vk_app_key->value, 'redirect_uri' => HTTPClient::buildUrl([$this->req->getBaseUrl() . '/component/Account/ExternalAuthRedirect/json', 'agent' => 'VK', 'backurl' => $this->getBackurl(true)]), 'client_secret' => $this->cmp->config->vk_app_secret->value, 'code' => $code], function ($conn, $success) use(&$get) { if (!$success) { $this->req->status(400); $this->req->setResult(['error' => 'request declined']); return; } Daemon::log(Debug::dump($get)); Daemon::log(Debug::dump($conn->body)); $response = json_decode(rtrim($conn->body), true); $user_id = isset($response['user_id']) ? (int) $response['user_id'] : 0; $access_token = Request::getString($response['access_token']); if ($user_id === 0 || $access_token === '') { $this->req->status(403); $this->req->setResult(['error' => 'no access token or user id']); return; } $this->appInstance->httpclient->get(['https://api.vk.com/method/users.get', 'uids' => $user_id, 'fields' => 'screen_name', 'access_token' => $access_token], function ($conn, $success) use($user_id) { $response = json_decode($conn->body, true); if (!$success || !is_array($response) || empty($user_id)) { $this->req->redirectTo($this->req->getBaseUrl(), false); $this->req->setResult(['error' => 'Unrecognized response']); return; } $data = []; if (isset($response['screen_name'])) { $data['username'] = Request::getString($response['screen_name']); } $this->req->components->account->acceptUserAuthentication('VK', $user_id, $data, [$this, 'finalRedirect']); }); }); }
public static function checkJob($req, $invalidate = true) { $token = Request::getString($req->attrs->request['captcha_token']); $text = Request::getString($req->attrs->request['captcha_text']); return function ($jobname, $job) use($token, $text, $req, $invalidate) { Daemon::log(Debug::dump([$token, $text, $invalidate])); if ($token === '') { $job->setResult($jobname, ['captcha' => 'need']); return; } $req->appInstance->captcha->check($token, $text, $invalidate, function ($result) use($jobname, $job) { $errors = []; if ($result !== 'ok') { $errors['captcha'] = $result; } $job->setResult($jobname, $errors); }); }; }
public function updateAllServers() { gc_collect_cycles(); $app = $this; $amount = 1000 - sizeof($this->jobMap); \PHPDaemon\Core\Daemon::log('amount: ' . $amount); if ($amount <= 0) { return; } $this->servers->find(function ($cursor) use($app, $amount) { if (isset($cursor->items[0]['$err'])) { \PHPDaemon\Core\Daemon::log(\PHPDaemon\Core\Debug::dump($cursor->items)); return; } foreach ($cursor->items as $server) { $app->updateServer($server); } $cursor->destroy(); }, ['where' => ['$or' => [['atime' => ['$lte' => time() - 30], 'latency' => ['$ne' => false]], ['atime' => ['$lte' => time() - 120], 'latency' => false], ['atime' => null]]], 'limit' => -max($amount, 100), 'sort' => ['atime' => 1]]); }
/** * Send message to log. * @param mixed ...$args Arguments * @return string message */ public static function log() { $args = func_get_args(); if (sizeof($args) == 1) { $msg = is_scalar($args[0]) ? $args[0] : Debug::dump($args[0]); } else { $msg = Debug::dump($args); } $mt = explode(' ', microtime()); //$msg = substr($msg, 0, 1024) . Debug::backtrace(); if (is_resource(STDERR)) { fwrite(STDERR, '[PHPD] ' . $msg . "\n"); } $msg = str_replace("", $msg, date(strtr(Daemon::$config->logformat->value, ['%msg%' => "", '\\u' => '\\u', 'u' => sprintf('%06d', $mt[0] * 1000000)]))) . "\n"; if (Daemon::$logpointerAsync) { Daemon::$logpointerAsync->write($msg); } elseif (Daemon::$logpointer) { fwrite(Daemon::$logpointer, $msg); } }
/** * Initializes slave session. * @param object Object. * @param \MongoTimestamp $point * @return void */ public function initSlave($point) { $this->db->{'local.oplog.$main'}->find(function ($cursor) { $this->cursor = $cursor; $cursor->state = 1; $cursor->lastOpId = NULL; foreach ($cursor->items as $k => &$item) { if (\PHPDaemon\Core\Daemon::$config->logevents->value) { \PHPDaemon\Core\Daemon::log(get_class($this) . ': caught oplog-record with ts = (' . \PHPDaemon\Core\Debug::dump($item['ts']) . ')'); } $cursor->lastOpId = $item['ts']; if ($item['op'] === 'i') { $this->cacheObject($item['o']); } elseif ($item['op'] === 'd') { $this->deleteObject($item['o']); } elseif ($item['op'] === 'u') { if (isset($item['b']) && $item['b'] === FALSE) { $item['o']['_id'] = $item['o2']['_id']; $this->cacheObject($item['o']); } else { $cursor->appInstance->{$item['ns']}->findOne(function ($item) { $this->cacheObject($item); }, ['where' => ['_id' => $item['o2']['_id']]]); } } unset($cursor->items[$k]); } }, ['tailable' => TRUE, 'sort' => ['$natural' => 1], 'snapshot' => 1, 'where' => ['ts' => ['$gt' => $point], '$exists' => ['_key' => TRUE]], 'parse_oplog' => TRUE]); }
public function run() { Daemon::log(Debug::dump($this->args)); $this->sendResult(call_user_func_array('mail', $this->args)); }
public function setResult($result = null, $multi = false) { if ($this->dataType === 'json') { try { $this->header('Content-Type: text/json'); } catch (RequestHeadersAlreadySent $e) { } $this->out(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ($multi ? "\n" : '')); } elseif ($this->dataType === 'jsonp') { try { $this->header('Content-Type: text/plain'); } catch (RequestHeadersAlreadySent $e) { } $this->out(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . ($multi ? "\n" : '')); } elseif ($this->dataType === 'xml') { $converter = new Array2XML(); $converter->setRootName($this->xmlRootName); try { $this->header('Content-Type: text/xml'); } catch (RequestHeadersAlreadySent $e) { } $this->out($converter->convert($result)); } elseif ($this->dataType === 'bson') { try { $this->header('Content-Type: application/octet-stream'); } catch (RequestHeadersAlreadySent $e) { } $this->out(bson_encode($result)); } elseif ($this->dataType === 'dump') { try { $this->header('Content-Type: text/plain'); } catch (RequestHeadersAlreadySent $e) { } $this->out(Debug::dump($result)); } else { $this->header('Content-Type: application/x-javascript'); $this->out(json_encode(['errmsg' => 'Unsupported data-type.'])); } if (!$multi) { $this->finish(); } }
/** * Shutdown this worker * @param boolean Hard? If hard, we shouldn't wait for graceful shutdown of the running applications. * @return boolean|null Ready? */ protected function shutdown($hard = false) { $error = error_get_last(); if ($error) { if ($error['type'] === E_ERROR) { Daemon::log('W#' . $this->pid . ' crashed by error \'' . $error['message'] . '\' at ' . $error['file'] . ':' . $error['line']); } } if (Daemon::$config->logevents->value) { $this->log('event shutdown(' . ($hard ? 'HARD' : '') . ') invoked.'); } if (Daemon::$config->throwexceptiononshutdown->value) { throw new \Exception('event shutdown'); } @ob_flush(); if ($this->terminated === true) { if ($hard) { exit(0); } return; } $this->terminated = true; if ($hard) { $this->setState(Daemon::WSTATE_SHUTDOWN); exit(0); } $this->reloadReady = $this->appInstancesReloadReady(); if ($this->reload && $this->graceful) { $this->reloadReady = $this->reloadReady && microtime(TRUE) > $this->reloadTime; } if (Daemon::$config->logevents->value) { $this->log('reloadReady = ' . Debug::dump($this->reloadReady)); } Timer::remove('breakMainLoopCheck'); Timer::add(function ($event) { $self = Daemon::$process; $self->reloadReady = $self->appInstancesReloadReady(); if ($self->reload === TRUE) { $self->reloadReady = $self->reloadReady && microtime(TRUE) > $self->reloadTime; } if (!$self->reloadReady) { $event->timeout(); } else { $self->eventBase->exit(); } }, 1000000.0, 'checkReloadReady'); while (!$this->reloadReady) { $this->eventBase->loop(); } FileSystem::waitAllEvents(); // ensure that all I/O events completed before suicide exit(0); // R.I.P. }
/** * Called when socket is bound * @return boolean Success */ protected function onBound() { if (!$this->ev) { Daemon::log(get_class($this) . '::' . __METHOD__ . ': Couldn\'t set event on bound socket: ' . Debug::dump($this->fd)); return false; } return true; }
function D(...$args) { \PHPDaemon\Core\Daemon::log(\PHPDaemon\Core\Debug::dump(...$args)); //\PHPDaemon\Core\Daemon::log(\PHPDaemon\Core\Debug::backtrace()); }
public function debug($point = null) { $msg = "\n--------------------------\n"; $msg .= "TYPE: " . get_class($this) . "\n"; $msg .= "NEW: " . ($this->new ? 'YES' : 'NO') . "\n"; $msg .= "POINT: " . Debug::dump($point) . "\n"; $msg .= "COND: " . Debug::dump($this->cond) . "\n"; $msg .= "OBJ: " . Debug::dump($this->obj) . "\n"; $msg .= "UPDATE: " . Debug::dump($this->update) . "\n"; $msg .= "lastError: " . Debug::dump($this->lastError) . "\n"; $msg .= "--------------------------"; Daemon::log($msg); return $this; }
public function perform() { $this->cmp->onAuth(function ($result) { if (!in_array('Superusers', $this->req->account['aclgroups'], true)) { $this->req->setResult(['success' => false, 'goLoginPage' => true]); return; } static $fields = ['email' => 1, 'username' => 1, 'regdate' => 1, 'ip' => 1, 'firstname' => 1, 'lastname' => 1, 'location' => 1, 'aclgroups' => 1, '_id' => 1]; $fieldNames = array_keys($fields); $field = function ($n) use($fieldNames) { if (!isset($fieldNames[$n])) { return null; } return $fieldNames[$n]; }; $action = Request::getString($_REQUEST['action']); if ($action === 'EditColumn') { $column = $field(Request::getInteger($_REQUEST['column'])); if ($column === null) { $this->req->setResult(['success' => false, 'error' => 'Column not found.']); return; } /** @noinspection PhpIllegalArrayKeyTypeInspection */ $this->req->appInstance->accounts->getAccount()->condSetId(Request::getString($_REQUEST['id']))->attr($column, $value = Request::getString($_REQUEST['value']))->save(function ($o) use($value) { Daemon::log(Debug::dump($o->lastError())); if ($o->lastError(true)) { $this->req->setResult(['success' => true, 'value' => $value]); } else { $this->req->setResult(['success' => false, 'error' => 'Account not found.']); } }); return; } $where = []; $sort = []; $sortDir = []; foreach ($_REQUEST as $k => $value) { list($type, $index) = explode('_', $k . '_'); if ($type === 'iSortCol') { /** @noinspection PhpIllegalArrayKeyTypeInspection */ $sort[$field($value)] = Request::getString($_REQUEST['sSortDir_' . $index]) == 'asc' ? 1 : -1; } } unset($sort[null]); $offset = Request::getInteger($_REQUEST['iDisplayStart']); $limit = Request::getInteger($_REQUEST['iDisplayLength']); $job = $this->req->job = new ComplexJob(function ($job) { $this->req->setResult(['success' => true, 'sEcho' => (int) Request::getString($_REQUEST['sEcho']), 'iTotalRecords' => $job->results['countTotal'], 'iTotalDisplayRecords' => $job->results['countFiltered'], 'aaData' => $job->results['find']]); }); $job('countTotal', function ($jobname, $job) { $this->req->appInstance->accounts->countAccount(function ($o, $n) use($job, $jobname) { /** @var ComplexJob $job */ $job->setResult($jobname, $n); }); }); $job('countFiltered', function ($jobname, $job) use($where, $limit) { /** @var ComplexJob $job */ /** @var WakePHPRequest $job->req */ $this->req->appInstance->accounts->countAccount(function ($o, $n) use($job, $jobname, $where) { /** @var ComplexJob $job */ $job->setResult($jobname, $n); }, $where); }); $job('find', function ($jobname, $job) use($where, $sort, $fields, $fieldNames, $field, $offset, $limit) { $this->req->appInstance->accounts->findAccounts(function ($cursor) use($jobname, $job, $fieldNames, $offset, $limit) { /** @var Cursor $cursor */ /** @var ComplexJob $job */ $accounts = []; foreach ($cursor as $item) { $account = []; foreach ($fieldNames as $k) { if (!isset($item[$k])) { $val = null; } else { $val = $item[$k]; if ($k === 'regdate') { $val = $val != 0 ? date('r', $val) : ''; } elseif ($k === '_id') { $val = (string) $val; } else { if ($k === 'aclgroups') { $val = (string) implode(', ', $val); } $val = htmlspecialchars($val); } } $account[] = $val; } $accounts[] = $account; } $cursor->destroy(); $job->setResult($jobname, $accounts); }, ['fields' => $fields, 'sort' => $sort, 'offset' => $offset, 'limit' => -abs($limit)]); }); $job(); }); }
/** * @param $names * @param callable $cb */ public function check($token, $text, $invalidate = true, $cb) { $e = static::decodeToken($token); if ($e === false) { call_user_func($cb, 'badToken'); return; } list($id, $rnd) = $e; $this->captcha->findOne(function ($t) use($cb, $id, $text, $invalidate) { if (!$t) { call_user_func($cb, 'expired'); return; } Daemon::log(Debug::dump([$invalidate])); if (!$invalidate) { if (strtolower($t['text']) === strtolower($text)) { call_user_func($cb, 'ok'); return; } } $this->captcha->remove(['_id' => new \MongoId($id)], function ($lastError) use($t, $text, $cb) { if ($lastError['n'] !== 1) { call_user_func($cb, 'expired'); return; } if (strtolower($t['text']) !== strtolower($text)) { call_user_func($cb, 'incorrect'); return; } call_user_func($cb, 'ok'); }); }, ['where' => ['_id' => $id, 'rnd' => $rnd, 'ctime' => ['$gt' => time() - 3600]]]); }