/** * @param string $parentPath * @return void */ public function process($parentPath = '') { $this->loadManifest(); if ($this->namespace === '' || $this->namespace === null) { $this->namespace = 'unknown'; } if (empty($this->name)) { $this->name = $this->id; } if (empty($this->name)) { $this->name = basename($this->getFsLocation()); } $this->fullPath = $this->namespace . '.' . $this->id; $groupsDirectories = $this->getChildrenDirectories(); $this->groups = []; foreach ($groupsDirectories as $directory) { $group = $this->newChild($directory); try { $group->process($this->fullPath); if ($group->id === null) { Yii::error("Group for path {$directory} is in unknown format(no id or bad manifest)" . " - bundle: {$this->id}"); unset($group); continue; } $this->groups[$group->id] = $group; } catch (\RuntimeException $e) { Yii::warning($e); } } }
/** * Выполнить запрос * @param $command - команда * @param array $params - параметры команды * @return NssResponse */ public function request($command, array $params = []) { if (empty($this->ip)) { throw new InvalidParamException('IP not defined.'); } if (empty($this->port)) { throw new InvalidParamException('Port not defined.'); } $ch = curl_init($this->ip); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => 1, CURLOPT_PROXY => false, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_CONNECTTIMEOUT => $this->connectTimeout, CURLOPT_PORT => $this->port, CURLOPT_POSTFIELDS => $this->createBody($command, $params)]); $this->answer = @curl_exec($ch); if (curl_errno($ch) || empty($this->answer)) { $this->answer = new NssResponse(); $this->answer->error = 'По техническим причинам функция недоступна. Попробуйте позже.'; Yii::error(curl_error($ch), 'nss-direct'); } else { $this->answer = @simplexml_load_string($this->answer); if ($this->answer === false) { $this->answer = new NssResponse(); $this->answer->error = 'От сервера пришел неверный ответ.'; } } curl_close($ch); return $this->answer; }
/** * @inheritdoc */ public function process($files, $output) { foreach ($files as $i => $file) { $files[$i] = escapeshellarg($file); } $cmd = $this->libPath . ' ' . implode(' ', $files) . ' -o ' . escapeshellarg($output); if ($this->sourceMap) { $prefix = (int) substr_count(\Yii::getAlias('@webroot'), '/'); $mapFile = escapeshellarg($output . '.map'); $mapRoot = escapeshellarg(rtrim(\Yii::getAlias('@web'), '/') . '/'); $mapUrl = escapeshellarg(basename($output) . '.map'); $cmd .= " -p {$prefix} --source-map {$mapFile} --source-map-root {$mapRoot} --source-map-url {$mapUrl}"; } if ($this->compress) { $cmd .= ' --compress'; } if ($this->mangle) { $cmd .= ' --mangle'; } if ($this->options) { $cmd .= ' ' . $this->options; } shell_exec($cmd); if (!file_exists($output)) { \Yii::error("Failed to process JS files by UglifyJs with command: {$cmd}", __METHOD__); return false; } return true; }
/** * @return string */ public function actionCheckout() { $this->view->title = \Yii::t('skeeks/shop/app', 'Checkout') . ' | ' . \Yii::t('skeeks/shop/app', 'Shop'); $v3toysOrder = V3toysOrder::createCurrent(); $v3toysOrder->loadDefaultValues(); $rr = new RequestResponse(); if ($rr->isRequestAjaxPost()) { if ($v3toysOrder->load(\Yii::$app->request->post()) && $v3toysOrder->save()) { foreach (\Yii::$app->shop->shopFuser->shopBaskets as $shopBasket) { $shopBasket->delete(); } try { \Yii::$app->mailer->view->theme->pathMap['@app/mail'][] = '@v3toys/skeeks/mail'; \Yii::$app->mailer->compose('create-order', ['model' => $v3toysOrder])->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName . ''])->setTo($v3toysOrder->email)->setSubject(\Yii::$app->cms->appName . ': новый заказ #' . $v3toysOrder->id)->send(); if (\Yii::$app->v3toysSettings->notifyEmails) { foreach (\Yii::$app->v3toysSettings->notifyEmails as $email) { \Yii::$app->mailer->view->theme->pathMap['@app/mail'][] = '@v3toys/skeeks/mail'; \Yii::$app->mailer->compose('create-order', ['model' => $v3toysOrder])->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName . ''])->setTo($email)->setSubject(\Yii::$app->cms->appName . ': новый заказ #' . $v3toysOrder->id)->send(); } } } catch (\Exception $e) { \Yii::error('Email submit error: ' . $e->getMessage()); } $rr->message = 'Заказ успешно создан'; $rr->success = true; $rr->redirect = Url::to(['/v3toys/cart/finish', 'key' => $v3toysOrder->key]); } else { $rr->message = 'Проверьте правильность заполнения полей'; $rr->success = false; } return $rr; } return $this->render($this->action->id, ['model' => $v3toysOrder]); }
public function actionIndex() { $w = new \GearmanWorker(); $w->addServers($this->module->gman_server); $w->addFunction('kepco_file_download', function ($job) { $workload = Json::decode($job->workload()); $bidid = $workload['bidid']; $attchd_lnk = $workload['attchd_lnk']; $this->stdout("한전파일> {$bidid} \n", Console::FG_GREEN); try { $saveDir = "/home/info21c/data/kepco/" . substr($bidid, 0, 4) . "/{$bidid}"; @mkdir($saveDir, 0777, true); $cookie = $this->module->redis_get('kepco.cookie'); $token = $this->module->redis_get('kepco.token'); $downinfo = explode('|', $attchd_lnk); foreach ($downinfo as $info) { $this->stdout(" > {$info}\n"); list($name, $url) = explode('#', $info); $savePath = $saveDir . '/' . $name; $cmd = "wget -q -T 30 --header 'Cookie: {$cookie}' --header \"X-CSRF-TOKEN: {$token}\" --header 'Accept-Encoding: gzip' -O - '{$url}' | gunzip > \"{$savePath}\""; //echo $cmd,PHP_EOL; $res = exec($cmd); } $this->gman_fileconv->doBackground('fileconv', $bidid); } catch (\Exception $e) { $this->stdout("{$e}\n", Console::FG_RED); \Yii::error($e, 'kepco'); } $this->stdout(sprintf("[%s] Peak memory usage: %s Mb\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024), Console::FG_GREY); sleep(1); }); while ($w->work()) { } }
/** * Initialization * * @param array $config * @return \phantomd\filedaemon\FileProcessing Object * @throws InvalidParamException */ public static function init($config) { if (empty($config)) { $message = 'Component error: Could not be empty `config`!'; \Yii::error($message, __METHOD__ . '(' . __LINE__ . ')'); throw new InvalidParamException($message); } $class = null; if (false === empty($config['component'])) { if (class_exists($config['component'])) { $class = $config['component']; } else { $class = __NAMESPACE__ . '\\' . ucfirst(strtolower((string) $config['component'])) . 'Processing'; } } if ($class) { if (false === class_exists($class)) { $message = "Component error: Not exist - `{$class}`"; \Yii::error($message, __METHOD__ . '(' . __LINE__ . ')'); throw new InvalidParamException($message); } $params = ['class' => $class, 'config' => $config]; $object = \Yii::createObject($params); if ($object instanceof FileProcessing) { return $object; } else { $message = "Component error: `{$class}` must be instance of class `FileProcessing`!"; \Yii::error($message, __METHOD__ . '(' . __LINE__ . ')'); throw new InvalidParamException($message); } } return null; }
/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { /** * @var User $user */ $userClassName = \Yii::$app->user->identityClass; $user = new $userClassName(); if ($this->scenario == self::SCENARION_FULLINFO) { $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); $user->save(); return $user; } else { if ($this->scenario == self::SCENARION_ONLYEMAIL) { $password = \Yii::$app->security->generateRandomString(6); $user->generateUsername(); $user->setPassword($password); $user->email = $this->email; $user->generateAuthKey(); if ($user->save()) { \Yii::$app->mailer->view->theme->pathMap = ArrayHelper::merge(\Yii::$app->mailer->view->theme->pathMap, ['@app/mail' => ['@skeeks/cms/mail-templates']]); \Yii::$app->mailer->compose('@app/mail/register-by-email', ['user' => $user, 'password' => $password])->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName . ''])->setTo($user->email)->setSubject(\Yii::t('skeeks/cms', 'Sign up at site') . \Yii::$app->cms->appName)->send(); return $user; } else { \Yii::error("User rgister by email error: {$user->username} " . Json::encode($user->getFirstErrors()), 'RegisterError'); return null; } } } } return null; }
public function save() { $transaction = \Yii::$app->getDb()->beginTransaction(); try { $customers = new Customers(); $customers->c_name = $this->c_name; $customers->c_phone = $this->c_phone; $customers->save(); $orders = new Orders(); $orders->customer_id = $customers->id; $orders->save(); foreach ($this->products as $product) { $orderProducts = new OrderProducts(); $orderProducts->order_id = $orders->id; $orderProducts->product_id = $product['id']; $orderProducts->product_amount = $product['amount']; $orderProducts->save(); } $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); \Yii::error($e->getMessage()); throw $e; } }
public function create() { $rr = new RequestResponse(); $modelClass = $this->modelClassName; $model = new $modelClass(); $model->loadDefaultValues(); if ($post = \Yii::$app->request->post()) { $model->load($post); } $handler = $model->handler; if ($handler) { if ($post = \Yii::$app->request->post()) { $handler->load($post); } } if ($rr->isRequestPjaxPost()) { if (!\Yii::$app->request->post($this->notSubmitParam)) { $model->component_settings = $handler->toArray(); $handler->load(\Yii::$app->request->post()); if ($model->load(\Yii::$app->request->post()) && $model->validate() && $handler->validate()) { $model->save(); \Yii::$app->getSession()->setFlash('success', \Yii::t('skeeks/cms', 'Saved')); return $this->redirect(UrlHelper::constructCurrent()->setCurrentRef()->enableAdmin()->setRoute($this->modelDefaultAction)->normalizeCurrentRoute()->addData([$this->requestPkParamName => $model->{$this->modelPkAttribute}])->toString()); } else { \Yii::error(Json::encode($model->errors), self::className()); \Yii::$app->getSession()->setFlash('error', \Yii::t('skeeks/cms', 'Could not save')); } } } return $this->render('_form', ['model' => $model, 'handler' => $handler]); }
/** * @param array $data * @param string $method * * @return ApiResponseOk|ApiResponseError */ private function _send(array $data, $method = 'post') { $client = new Client(['requestConfig' => ['format' => Client::FORMAT_JSON]]); $response = $client->createRequest()->setMethod($method)->setUrl($this->url)->addHeaders(['Content-type' => 'application/json'])->addHeaders(['user-agent' => 'JSON-RPC PHP Client'])->setData($data)->setOptions(['timeout' => $this->timeout])->send(); //Нам сказали это всегда json. А... нет, все мы люди, бывает и не json ) try { $dataResponse = (array) Json::decode($response->content); } catch (\Exception $e) { \Yii::error("Json api response error: " . $e->getMessage() . ". Response: \n{$response->content}", self::className()); //Лайф хак, вдруг разработчики апи оставили var dump if ($pos = strpos($response->content, "{")) { $content = StringHelper::substr($response->content, $pos, StringHelper::strlen($response->content)); try { $dataResponse = (array) Json::decode($content); } catch (\Exception $e) { \Yii::error("Api response error: " . $response->content, self::className()); } } } if (!$response->isOk) { \Yii::error($response->content, self::className()); $responseObject = new ApiResponseError($dataResponse); } else { $responseObject = new ApiResponseOk($dataResponse); } $responseObject->statusCode = $response->statusCode; return $responseObject; }
public function actionNotify() { \Yii::info("POST: " . Json::encode(\Yii::$app->request->post()), self::className()); try { if (!\Yii::$app->request->post('OrderId')) { throw new Exception('Некорректны запрос от банка.'); } /** * @var $shopOrder ShopOrder */ if (!($shopOrder = ShopOrder::findOne(\Yii::$app->request->post('OrderId')))) { throw new Exception('Заказ не найден в базе.'); } if ($shopOrder->id != \Yii::$app->request->post('OrderId')) { throw new Exception('Не совпадает номер заказа.'); } if ($shopOrder->money->getAmount() != \Yii::$app->request->post('Amount')) { throw new Exception('Не совпадает сумма заказа.'); } if (\Yii::$app->request->post('Status') == "CONFIRMED") { \Yii::info("Успешный платеж", self::className()); $shopOrder->processNotePayment(); } } catch (\Exception $e) { \Yii::error($e->getMessage(), self::className()); } $this->layout = false; return "OK"; }
public function actionIndex() { $model = new ExampleModel(); echo '<br>'; echo '<br>'; echo '<br>'; echo '<br>'; echo '<br>'; echo '<br>'; dump($_REQUEST); // $request = \Yii::$app->getRequest(); // if ($request->isPost && $request->post('ajax') !== null) // { // $model->load(\Yii::$app->request->post()); // app()->response->format = Response::FORMAT_JSON; // $result = ActiveForm::validate($model); // return $result; // } if ($model->load(app()->request->post())) { if (!$model->validate()) { \Yii::error('Validation errors: ' . print_r($model->getErrors(), true)); } } return $this->render('/test/test', ['model' => $model]); }
/** * @param array $data * @return bool */ public function processResult($data) { // required parameters if (!array_key_exists('m_operation_id', $data) || !array_key_exists('m_sign', $data)) { return false; } // we process only succeeded payments if (ArrayHelper::getValue($data, 'm_status') != 'success') { return false; } if (!$this->checkSign($data)) { return false; } $event = new GatewayEvent(['gatewayData' => $data]); $transaction = \Yii::$app->getDb()->beginTransaction(); try { $this->trigger(GatewayEvent::EVENT_PAYMENT_REQUEST, $event); if (!$event->handled) { throw new \Exception(); } $this->trigger(GatewayEvent::EVENT_PAYMENT_SUCCESS, $event); $transaction->commit(); } catch (\Exception $e) { $transaction->rollback(); \Yii::error('Payment processing error: ' . $e->getMessage(), 'Payeer'); return false; } return true; }
public static function getModelByMobile($mobile) { $model = null; if (\Yii::$app->mutex->acquire(self::tableName(), self::SCENE_LOCK_WAIT_TIME_SECOND)) { $model = self::findOne(['mobile' => $mobile]); if (empty($model)) { $model = new self(); $model->mobile = $mobile; $model->created_at = time(); $model->save(false); } \Yii::$app->mutex->release(self::tableName()); if ($model->updated_at + $model->expire_seconds < time()) { $gh_id = MGh::GH_XIANGYANGUNICOM; \Yii::$app->wx->setGhId($gh_id); $scene_id = $model->scene_id + 100000; $arr = \Yii::$app->wx->WxgetQRCode($scene_id, 0, 300); $model->updated_at = time(); $model->ticket = $arr['ticket']; $model->expire_seconds = $arr['expire_seconds']; $model->url = $arr['url']; $qr_url = \Yii::$app->wx->WxGetQRUrl($arr['ticket']); $log_file_path = \Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qr' . DIRECTORY_SEPARATOR . "{$gh_id}_{$scene_id}.jpg"; Wechat::downloadFile($qr_url, $log_file_path); $model->qr_url = \Yii::$app->getRequest()->baseUrl . "/../runtime/qr/{$gh_id}_{$scene_id}.jpg"; $model->save(false); } } else { \Yii::error('acquire lock error'); } return $model; }
public function start($taskData) { $worker = $this->getWorker($taskData['worker']); if (!$worker) { \Yii::error('Worker ' . $taskData['worker'] . ' not found'); } $worker->start($taskData['task']); }
/** * 记录日志写入异常 * @param type $errorInfo */ public static function log($errorInfo) { try { self::getLogDb()->createCommand()->insert('log_exception', ['msg' => $errorInfo])->execute(); } catch (\Exception $ex) { \Yii::error($ex->getMessage(), 'Api-log'); } }
function setHost($host) { $this->host = $host; try { $this->data = geoip_record_by_name($this->host); } catch (\yii\base\ErrorException $E) { \Yii::error($E->getMessage(), __METHOD__); } }
/** * Sends the specified message. * * @param Message $message the message to be sent * @return boolean whether the message is sent successfully */ protected function sendMessage($message) { try { return $message->send(); } catch (\Exception $e) { \Yii::error('A queue error occurred: ' . get_class($e) . ' - ' . $e->getMessage(), self::LOG_ERROR); return false; } }
public function storeMessage(array $params) { try { Yii::$app->getDb()->createCommand()->insert(self::tableName(), $params)->execute(); } catch (Exception $e) { Yii::error($e->getMessage()); return false; } return true; }
/** * Returns the JS code * @return string */ function __toString() { try { $code = $this->getCode(); return $code ?: ''; } catch (\Exception $e) { \Yii::error($e->getMessage()); return ''; } }
/** * Sends message immediately using default transport * * @param string $to * @param string $text * @param null|string $transport * @return bool */ public function send($to, $text, $transport = null) { try { $result = $this->getTransport($transport)->send($to, $text); } catch (\Exception $e) { \Yii::error("Message to {$to} sending failure: " . $e->getMessage()); $result = false; } return $result; }
public function run() { try { return parent::run(); } catch (Exception $exc) { Yii::error(print_r('RUN LOG:' . $exc, true)); \app\helpers\Flash::setUndisplayError($exc->getMessage()); header("location:/site/oooops"); } }
/** * Attempt to use Verify first, but if network not supported or fails, attempt SMS * @param string $phoneNumber The mobile or landline phone number to verify. Unless you are setting country * explicitly, this number must be in E.164 format. For example, 4478342080934. * @param string $code This is ignored in Nexmo Verify implementation * @return string The verification code used, or another identifier to be used with self::verify() later * @throws \Exception */ public function send($phoneNumber, $code) { if (empty($code)) { throw new \Exception('Code cannot be empty', 1469712310); } elseif (empty($this->apiKey)) { throw new \Exception('API Key required for Nexmo', 1469712301); } elseif (empty($this->apiSecret)) { throw new \Exception('API Secret required for Nexmo', 1469712311); } elseif (empty($this->brand)) { throw new \Exception('Brand required for Nexmo', 1469712312); } elseif (empty($this->from)) { throw new \Exception('From is required for Nexmo', 1469712313); } $verify = $this->getVerifyClient(); try { /* * Returns the Verify ID if successful */ return $verify->send($phoneNumber, $code); } catch (\Exception $e) { if ($e instanceof NexmoException) { /* * If concurrent request, throw exception letting users know to check phone */ if (strval($e->getCode()) === '10') { throw new BadRequestHttpException('Verification currently in progress, please check your phone.', 1470317050); } } /* * Don't log error if Nexmo code in list: * 15 - The destination number is not in a supported network * 16 - The code inserted does not match the expected value * 17 - A wrong code was provided too many times */ if (!in_array(strval($e->getCode()), ['15', '16', '17'])) { \Yii::error(['action' => 'phone verification', 'type' => 'verify', 'status' => 'error', 'error' => $e->getMessage(), 'code' => $e->getCode()]); } } /* * Don't send Verify ID as verification code */ if (strlen($code) !== $this->codeLength) { \Yii::error(['action' => 'verify phone', 'status' => 'error', 'error' => 'Call to Nexmo Verify failed, $code is a Verify ID so not falling back to SMS', 'code' => $code]); throw new ServerErrorHttpException('There was an internal problem verifying your number. Please wait a minute and try again.', 1470317786); } $sms = $this->getSmsClient(); try { return $sms->send($phoneNumber, $code); } catch (\Exception $e) { /* * SMS also failed, just throw the exception back */ throw $e; } }
/** * @param string $commandId * @return boolean */ private function isAlreadyRunning($commandId) { $pidFile = $this->getPidFile($commandId); if (false === ($pid = file_get_contents($pidFile))) { \Yii::error('Can\'t read pid from ' . $pidFile); \Yii::$app->end(1); } $command = sprintf('ps -p%s -o pid=', escapeshellarg($pid)); $is = exec($command); return (bool) $is; }
public function close() { \Yii::info(__METHOD__); if ($this->getIsActive()) { @session_write_close(); $error = error_get_last(); if ($error) { \Yii::error(json_encode($error), __METHOD__); } } }
public function publishAssets() { /** @var Repository $repository */ $repository = Yii::$app->get('monsterRepository'); $group = $repository->group($this->fullPath); if ($group !== null) { $group->publishAssets(); } else { Yii::error("Can't find group for material {$this->fullPath}. That's weird"); } $this->publishEntityAssets(); }
/** * * @param array $params * @throws Exception * @return \conquer\oauth2\models\AuthorizationCode */ public static function createAuthorizationCode(array $params) { static::deleteAll(['<', 'expires', time()]); $params['authorization_code'] = \Yii::$app->security->generateRandomString(40); $authCode = new static($params); if ($authCode->save()) { return $authCode; } else { \Yii::error(__CLASS__ . ' validation error: ' . VarDumper::dumpAsString($authCode->errors)); } throw new Exception('Unable to create authorization code', Exception::SERVER_ERROR); }
/** * @param array $attributes * @throws Exception * @return \conquer\oauth2\models\AccessToken */ public static function createAccessToken(array $attributes) { static::deleteAll(['<', 'expires', time()]); $attributes['access_token'] = \Yii::$app->security->generateRandomString(40); $accessToken = new static($attributes); if ($accessToken->save()) { return $accessToken; } else { \Yii::error(__CLASS__ . ' validation error:' . VarDumper::dumpAsString($accessToken->errors)); } throw new Exception('Unable to create access token', Exception::INTERNAL_ERROR); }
/** * @return \Aerospike * @throws Exception */ public function getConnection() { if (is_null($this->connection)) { // Init connection $this->connection = new \Aerospike($this->config, $this->persistent_connection, $this->options); if ($this->connection->errorno() != 0) { \Yii::error("Failed to open aerospike DB connection: " . $this->connection->errorno() . " - " . $this->connection->error(), __CLASS__); throw new Exception('Failed to open aerospike DB connection', $this->connection->error(), (int) $this->connection->errorno()); } } return $this->connection; }
public function create() { /** @var CardRecord $card */ $card = \Yii::createObject(CardRecord::className()); $card->HardID = $this->HardID; if ($card->save()) { \Yii::info('Зарегистрирована новая карта - ' . $card->HardID . ' ID:' . $card->id, 'info'); } else { \Yii::error('Не удалось зарегистрировать новую карту: ' . $card->getFirstError('HardID'), 'info'); } return $card; }