/** * @param $username * @param $password * @return array Success { * @var string AccessId * @var string SecretKey * @var string UserId * @var string EmployeeId * } * @throws MPAuthException */ public function authenticate($username, $password) { $data = ['Login' => $username, 'Password' => md5($password)]; $this->prepareRequest($data); try { $response = $this->curl->post($this->url . $this->authRelativeUrl, true); try { $decodedResponse = Json::decode($response, true); switch ($decodedResponse['status']['code']) { case 'ok': break; case 'error': throw new MPAuthException('Invalid username or password.'); break; default: throw new MPAuthException('Unknown response status.'); } return $decodedResponse['data']; } catch (InvalidParamException $e) { throw new MPAuthException('Error decoding server response. Raw response: ' . var_export($response, true)); } } catch (Exception $e) { throw new MPAuthException('Error requesting host:' . $e->getMessage() . $e->getCode()); } }
public function callback(AMQPMessage $msg) { $routingKey = $msg->get('routing_key'); $method = 'read' . Inflector::camelize($routingKey); $interpreter = isset($this->interpreters[$this->exchange]) ? $this->interpreters[$this->exchange] : (isset($this->interpreters['*']) ? $this->interpreters['*'] : null); if ($interpreter === null) { $interpreter = $this; } else { if (class_exists($interpreter)) { $interpreter = new $interpreter(); if (!$interpreter instanceof AmqpInterpreter) { throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $interpreter)); } } else { throw new Exception(sprintf("Interpreter class '%s' was not found.", $interpreter)); } } if (method_exists($interpreter, $method) || is_callable([$interpreter, $method])) { $info = ['exchange' => $this->exchange, 'routing_key' => $routingKey, 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null, 'delivery_tag' => $msg->get('delivery_tag')]; try { $body = Json::decode($msg->body, true); } catch (\Exception $e) { $body = $msg->body; } $interpreter->{$method}($body, $info, $this->amqp->channel); } else { if (!$interpreter instanceof AmqpInterpreter) { $interpreter = new AmqpInterpreter(); } $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR); // debug the message $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO); } }
public function callback(AMQPMessage $msg) { $routingKey = $msg->delivery_info['routing_key']; $method = 'read' . Inflector::camelize($routingKey); if (!isset($this->interpreters[$this->exchange])) { $interpreter = $this; } elseif (class_exists($this->interpreters[$this->exchange])) { $interpreter = new $this->interpreters[$this->exchange](); if (!$interpreter instanceof AmqpInterpreter) { throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->exchange])); } } else { throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->exchange])); } if (method_exists($interpreter, $method)) { $info = ['exchange' => $msg->get('exchange'), 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null]; $interpreter->{$method}(Json::decode($msg->body, true), $info); } else { if (!isset($this->interpreters[$this->exchange])) { $interpreter = new AmqpInterpreter(); } $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR); // debug the message $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO); } }
/** * Download the exported file * * @return mixed */ public function actionDownload() { $request = Yii::$app->request; $type = $request->post('export_filetype', 'html'); $name = $request->post('export_filename', Yii::t('kvgrid', 'export')); $content = $request->post('export_content', Yii::t('kvgrid', 'No data found')); $mime = $request->post('export_mime', 'text/plain'); $encoding = $request->post('export_encoding', 'utf-8'); $bom = $request->post('export_bom', true); $config = $request->post('export_config', '{}'); if ($type == GridView::PDF) { $config = Json::decode($config); $this->generatePDF($content, "{$name}.pdf", $config); /** @noinspection PhpInconsistentReturnPointsInspection */ return; } elseif ($type == GridView::HTML) { $content = HtmlPurifier::process($content); } elseif ($type == GridView::CSV || $type == GridView::TEXT) { if ($encoding != 'utf-8') { $content = mb_convert_encoding($content, $encoding, 'utf-8'); } elseif ($bom) { $content = chr(239) . chr(187) . chr(191) . $content; // add BOM } } $this->setHttpHeaders($type, $name, $mime, $encoding); return $content; }
public function actionLog() { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $data = \yii\helpers\Json::decode(\Yii::$app->request->post('data')); $entry = null; if (isset($data['auditEntry'])) { $entry = models\AuditEntry::findOne($data['auditEntry']); } else { return ['result' => 'error', 'message' => 'No audit entry to attach to']; } // Convert data into the loggable object $javascript = new models\AuditJavascript(); $map = ['auditEntry' => 'audit_id', 'message' => 'message', 'type' => 'type', 'file' => 'origin', 'line' => function ($value) use($javascript) { $javascript->origin .= ':' . $value; }, 'col' => function ($value) use($javascript) { $javascript->origin .= ':' . $value; }, 'data' => function ($value) use($javascript) { if (count($value)) { $javascript->data = $value; } }]; foreach ($map as $key => $target) { if (isset($data[$key])) { if (is_callable($target)) { $target($data[$key]); } else { $javascript->{$target} = $data[$key]; } } } if ($javascript->save()) { return ['result' => 'ok']; } return ['result' => 'error', 'errors' => $javascript->getErrors()]; }
/** * Resets password. * @return boolean if password was reset */ public function resetPassword() { $bag = Yii::$app->request->get(); $url = Yii::$app->params['api_url'] . '/clientSetPassword?' . http_build_query(['client' => $bag['login'], 'new_password' => $this->password, 'confirm_data' => $bag]); $res = Json::decode(file_get_contents($url)); return !isset($res['_error']); }
public static function decode($json, $asArray = true, $isQuoted = true) { if (!$isQuoted) { $json = "{\"" . str_replace(array(":", ","), array("\":\"", "\",\""), $json) . "\"}"; } return parent::decode($json, $asArray); }
public function getArticles() { if (!($articles = $this->getAttribute('articles'))) { return []; } return Json::decode($articles); }
/** * Validates, runs Action and returns result in JSON-RPC 2.0 format * @param string $id the ID of the action to be executed. * @param array $params the parameters (name-value pairs) to be passed to the action. * @throws \Exception * @throws \yii\web\HttpException * @return mixed the result of the action. * @see createAction() */ public function runAction($id, $params = []) { $this->initRequest($id); try { $requestObject = Json::decode(file_get_contents('php://input'), false); } catch (InvalidParamException $e) { $requestObject = null; } $isBatch = is_array($requestObject); $requests = $isBatch ? $requestObject : [$requestObject]; $resultData = null; if (empty($requests)) { $isBatch = false; $resultData = [Helper::formatResponse(null, new Exception("Invalid Request", Exception::INVALID_REQUEST))]; } else { foreach ($requests as $request) { if ($response = $this->getActionResponse($request)) { $resultData[] = $response; } } } $response = Yii::$app->getResponse(); $response->format = Response::FORMAT_JSON; $response->data = $isBatch || null === $resultData ? $resultData : current($resultData); return $response; }
public function init() { self::$modelSetting = new GoogleFeed(); self::$modelSetting->loadConfig(); $this->handlers = Json::decode(self::$modelSetting->feed_handlers); foreach ($this->handlers as $handler) { if (is_subclass_of($handler, ModificationDataInterface::class)) { $this->on(self::MODIFICATION_DATA, [$handler, 'processData']); } } parent::init(); if ($this->mainCurrency === null) { $this->mainCurrency = Currency::findOne(['iso_code' => self::$modelSetting->shop_main_currency]); } if ($this->host === null) { $this->host = self::$modelSetting->shop_host; } if ($this->title === null) { $this->title = self::$modelSetting->shop_name; } if ($this->description === null) { $this->description = self::$modelSetting->shop_description; } if ($this->fileName === null) { $this->fileName = self::$modelSetting->feed_file_name; } }
public function json_post($uri, array $options = []) { $res = $this->client->request('POST', $uri, $options); $body = $res->getBody(); $json = Json::decode($body); return $json; }
private function processProductInfoData($header, $filePath, $classFunction, $params = []) { LogUtil::info(['message' => 'Begin to read csv file', 'fileName' => $filePath], 'resque'); $fileInfos = fopen($filePath, "r"); $newFilePath = ExcelUtil::getDownloadFile($filePath); $productNames = $infos = []; while (!feof($fileInfos)) { $fileInfo = Json::decode(fgets($fileInfos), true); if (!empty($fileInfo)) { if (in_array($fileInfo['productName'], $productNames) || empty($productNames)) { $infos[] = $fileInfo; $productNames[] = $fileInfo['productName']; } else { $args = [$infos, $params]; self::writeCsv($classFunction, $args, $header, $newFilePath); unset($infos, $productNames); $productNames[] = $fileInfo['productName']; $infos[] = $fileInfo; } } } if (!empty($infos)) { $args = [$infos, $params]; self::writeCsv($classFunction, $args, $header, $newFilePath); unset($productNames, $infos); } fclose($fileInfos); LogUtil::info(['message' => 'End to read csv file and end to write file', 'fileName' => $filePath], 'resque'); }
/** * @param string $json * @return static */ public static function createByJson($json) { $model = new static(); $attributes = Json::decode($json); $model->load($attributes, ''); return $model; }
/** * @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; }
/** * 创建快递跟踪信息 * @method send * @since 0.0.1 * @param {string} $company 快递公司代码 * @param {string} $number 快递单号 * @return {boolean} * @example \Yii::$app->express->send($company, $number); */ public function send($company, $number) { $eid = 0; if ($express = Express::findOne(['company' => $company, 'number' => $number])) { $eid = $express->id; } else { $express = new Express(); $express->company = $company; $express->number = $number; $express->generateAuthKey(); if ($express->save()) { $result = $this->debug ? ['returnCode' => 200] : Json::decode(Kd100::sdk($this->key)->poll($company, $number, $this->getUrl($express->id), $express->auth_key, $this->resultv2)); if (isset($result['returnCode'])) { switch ($result['returnCode']) { case 200: $express->status = '提交成功'; $eid = $express->id; break; case 501: $express->status = '重复订阅'; break; } $express->save(); } } } return $eid; }
/** * @inheritdoc */ public function setSetting($section, $key, $value, $type = null) { $model = static::findOne(['section' => $section, 'key' => $key]); if ($model === null) { $model = new static(); $model->active = 1; } $model->section = $section; $model->key = $key; $model->value = strval($value); if ($type !== null) { $model->type = $type; } else { $t = gettype($value); if ($t == 'string') { $error = false; try { Json::decode($value); } catch (InvalidParamException $e) { $error = true; } if (!$error) { $t = 'object'; } } $model->type = $t; } return $model->save(); }
public function getToken() { $url = $this->tokenUrl . '?user='******'&password='******'data'])) { return null; } if (!isset($json['data']['token'])) { return null; } return $json['data']['token']; }
public function actionImport($params = null) { try { $params = Json::decode($params); } catch (InvalidParamException $e) { echo 'Wrong input parameters.'; return 1; } if (empty($params['files'])) { return 1; } $ts = microtime(true); $files = []; foreach ($params['files'] as $file) { $xmlReader = new XmlFileReader($file); if (XmlFileReader::FILETYPE_IMPORT === $xmlReader->fileType()) { array_unshift($files, $file); } else { $files[] = $file; } unset($xmlReader); } foreach ($files as $file) { $xmlReader = new XmlFileReader($file); $xmlReader->parse(); unset($xmlReader); unlink($file); } echo sprintf('Task working time: %s', microtime(true) - $ts); return 0; }
public function actionIndex() { $data = Json::decode(Yii::$app->request->rawBody); if (is_array($data) === true) { // sort by event name $eventsNames = array_keys(array_reduce($data, function ($carry, $item) { if (isset($item['eventName'])) { $carry[$item['eventName']] = 1; } return $carry; }, [])); // preload all events into identity map Events::findByNames($eventsNames); // now we can handle it all foreach ($data as $eventItem) { if (isset($eventItem['eventName'], $eventItem['event'], $eventItem['timestamp']) === true) { $eventModel = Events::findByName($eventItem['eventName']); if ($eventModel !== null) { $className = $eventModel->event_class_name; $specialEvent = new $className($eventItem['event']); EventTriggeringHelper::triggerSpecialEvent($specialEvent); } } } } }
/** * Verify install */ public function actionIndex() { try { $installFile = 'install.json'; $path = $this->prompt('Enter path to module install file:'); $path = Yii::getAlias($path); if (!file_exists($path . '/' . $installFile)) { throw new InvalidParamException($path . '/' . $installFile . ' file not exist'); } $install = @file_get_contents($path . '/' . $installFile); $install = Json::decode($install); if (!isset($install['name'])) { throw new InvalidConfigException('Install config `name` not found'); } if (!isset($install['type'])) { throw new InvalidConfigException('Install config `type` not found'); } if (!isset($install['copy'])) { throw new InvalidConfigException('Install config `copy` not found'); } if (!is_array($install['copy'])) { throw new InvalidConfigException('Install config `copy` must be array'); } if (!isset($install['settings'])) { throw new InvalidConfigException('Install config `settings` not found'); } if (!is_array($install['settings'])) { throw new InvalidConfigException('Install config `settings` must be array'); } $this->_install = $install; $this->set(); } catch (\Exception $e) { $this->stdout($e->getMessage() . PHP_EOL, Console::FG_RED); } }
/** * @inheritdoc */ public function run() { if (!empty($_GET['contextData'])) { $contextData = Json::decode($_GET['contextData']); if (!empty($contextData[$this->clientIdGetParamName])) { $clientId = $contextData[$this->clientIdGetParamName]; /* @var $collection \yii\authclient\Collection */ $collection = Yii::$app->get($this->clientCollection); if (!$collection->hasClient($clientId)) { throw new UnauthorizedHttpException("Unknown auth client '{$clientId}'"); } /** @var OAuth2 $client */ $client = $collection->getClient($clientId); $client->contextData = Json::encode($contextData); if (!empty($_GET['sid'])) { $client->sessionId = $_GET['sid']; } try { return $this->auth($client); } catch (\Exception $e) { throw new UnauthorizedHttpException($e->getMessage(), $e->getCode(), $e->getPrevious()); } } } return parent::run(); }
/** * @inheritdoc */ public function pop($queue) { $job = $this->beanstalk->watch($queue)->ignore('default')->reserve(); $data = $job->getData(); $data = Json::decode($data); return ['id' => $data['id'], 'body' => $data['body'], 'queue' => $queue, 'message' => $job]; }
public function actionNotify($id) { $response = ['result' => 'false', 'returnCode' => '500', 'message' => '失败']; $express = Express::findOne($id); if ($express && isset($_POST['param'])) { $param = Json::decode($_POST['param']); if (isset($param['lastResult']) && $express->company == $param['lastResult']['com'] && $express->number == $param['lastResult']['nu'] && (empty($express->auth_key) || isset($_POST['sign']) && $this->module->manager->verify($_POST['sign'], $_POST['param'], $express->auth_key))) { $express->status = $this->module->manager->getStatus($param['lastResult']['state']); $express->details = Json::encode($param['lastResult']['data']); if ($param['lastResult']['ischeck'] == 1 && $param['lastResult']['state'] == 3) { $express->receipted_at = strtotime($param['lastResult']['data'][0]['time']); } if ($express->save()) { $response['result'] = 'true'; $response['returnCode'] = '200'; $response['message'] = '成功'; if ($notifyClass = $this->module->notifyClass) { $notifyClass::receipted($id); } } } } \Yii::$app->response->format = 'json'; return $response; }
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()) { } }
/** * HumHub API * * @param string $action * @param array $params * @return array */ public static function request($action, $params = []) { if (!Yii::$app->params['humhub']['apiEnabled']) { return []; } $url = Yii::$app->params['humhub']['apiUrl'] . '/' . $action; $params['version'] = urlencode(Yii::$app->version); $params['installId'] = Setting::Get('installationId', 'admin'); $url .= '?'; foreach ($params as $name => $value) { $url .= urlencode($name) . '=' . urlencode($value) . "&"; } try { $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => CURLHelper::getOptions(), 'timeout' => 30)); $response = $http->send(); $json = $response->getBody(); } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $ex) { Yii::error('Could not connect to HumHub API! ' . $ex->getMessage()); return []; } catch (Exception $ex) { Yii::error('Could not get HumHub API response! ' . $ex->getMessage()); return []; } try { return Json::decode($json); } catch (\yii\base\InvalidParamException $ex) { Yii::error('Could not parse HumHub API response! ' . $ex->getMessage()); return []; } }
public function setConstantsId() { $array_user_permission = $array_rol_permission = $array_group_permission = []; try { $sql = "SELECT (CASE \n WHEN g.name = 'companies' \n THEN c.name \n ELSE ((a.profile->>'first_name') || ' ' || (a.profile->>'first_surname')) \n END) as name_identity,\n ac.permission as user_permission,\n r.id as rol_id, r.name as rol_name, r.permission as rol_permission,\n c.id as company_id, c.name as company_name, \n g.id as group_id, g.name as group_name, g.permission as group_permission\n FROM sys_users u\n LEFT JOIN sys_access_control ac ON u.id = ac.users_id\n INNER JOIN sys_account a ON a.id = u.account_id\n INNER JOIN sys_company c ON c.id = a.company_id\n LEFT JOIN sys_rol r ON ac.rol_id = r.id\n LEFT JOIN sys_group g ON r.group_id = g.id AND g.type = 'user'\n WHERE u.id = " . Yii::$app->user->identity->id . ";"; $model = AccessControl::findBySql($sql)->one(); if ($model != NULL) { Yii::$app->session->set('user.group_id', $model->group_id); Yii::$app->session->set('user.group_name', $model->group_name); Yii::$app->session->set('user.company_id', $model->company_id); Yii::$app->session->set('user.company_name', $model->company_id); Yii::$app->session->set('user.rol_id', $model->rol_id); Yii::$app->session->set('user.rol_name', $model->rol_id); Yii::$app->session->set('user.name_identity', $model->name_identity); if ($model->group_permission != NULL || $model->group_permission != '""') { $array_group_permission = Json::decode($model->group_permission); } if ($model->rol_permission != NULL || $model->rol_permission != '""') { $array_rol_permission = Json::decode($model->rol_permission); } if ($model->user_permission != NULL || $model->user_permission != '""') { $array_user_permission = Json::decode($model->user_permission); } $permissions = $array_user_permission + $array_rol_permission + $array_user_permission; Yii::$app->session->set('user.permissions', $permissions); return true; } else { return false; } } catch (Exception $exc) { echo $exc->getTraceAsString(); } }
/** * @return array */ public function actionIndex() { Yii::$app->response->format = Response::FORMAT_JSON; $data = Json::decode(Yii::$app->request->post('data')); if (!isset($data['auditEntry'])) { $entry = Audit::getInstance()->getEntry(true); $data['auditEntry'] = $entry->id; } // Convert data into the loggable object $javascript = new models\AuditJavascript(); $map = ['auditEntry' => 'entry_id', 'message' => 'message', 'type' => 'type', 'file' => 'origin', 'line' => function ($value) use($javascript) { $javascript->origin .= ':' . $value; }, 'col' => function ($value) use($javascript) { $javascript->origin .= ':' . $value; }, 'data' => function ($value) use($javascript) { if (count($value)) { $javascript->data = $value; } }]; foreach ($map as $key => $target) { if (isset($data[$key])) { if (is_callable($target)) { $target($data[$key]); } else { $javascript->{$target} = $data[$key]; } } } if ($javascript->save()) { return ['result' => 'ok', 'entry' => $data['auditEntry']]; } return ['result' => 'error', 'errors' => $javascript->getErrors()]; }
protected function addToCart($data) { if (empty($data['product_ids'])) { return false; } $store = $this->owner; $options = $store->getOptionsByName(); if (!empty($options['add_to_cart_counter_statistics'])) { $option = $options['add_to_cart_counter_statistics']; } else { $option = new Option(); $option->name = 'add_to_cart_counter_statistics'; $option->link('store', $store); } $stats = []; if ($option->value) { $stats = Json::decode($option->value); } foreach ($data['product_ids'] as $product_id) { if (empty($stats[$product_id])) { $stats[$product_id] = 0; } $stats[$product_id]++; } $option->value = Json::encode($stats); $option->save(); }
public function run() { $this->genButton = Html::a(Icon::show('edit') . Yii::t('app', 'Generate'), '#', ['class' => 'btn btn-success', 'id' => 'btn-generate']); $parent_id = $this->model->main_category_id; $owner_id = $this->model->id; $this->addButton = Html::a(Icon::show('plus') . Yii::t('app', 'Add'), Url::toRoute(['/shop/backend-product/edit', 'parent_id' => $parent_id, 'owner_id' => $owner_id, 'returnUrl' => \app\backend\components\Helper::getReturnUrl()]), ['class' => 'btn btn-success', 'id' => 'btn-add']); if (!empty($this->footer)) { $this->footer = Html::tag('div', $this->addButton . ' ' . $this->genButton, ['class' => 'widget-footer']); } $this->object = Object::getForClass(get_class($this->model)); $rest_pg = (new Query())->select('id, name')->from(PropertyGroup::tableName())->where(['object_id' => $this->object->id])->orderBy('sort_order')->all(); $this->property_groups_to_add = []; foreach ($rest_pg as $row) { $this->property_groups_to_add[$row['id']] = $row['name']; } $optionGenerate = Json::decode($this->model->option_generate); if (null === PropertyGroup::findOne($optionGenerate['group'])) { $this->model->option_generate = $optionGenerate = null; } $groupModel = null; if (isset($optionGenerate['group'])) { $groupModel = PropertyGroup::findOne($optionGenerate['group']); $properties = Property::getForGroupId($optionGenerate['group']); } else { $group_ids = array_keys($this->property_groups_to_add); $group_id = array_shift($group_ids); $groupModel = PropertyGroup::findOne($group_id); $properties = Property::getForGroupId($group_id); } if (is_null($groupModel)) { $groupModel = new PropertyGroup(); } return $this->render($this->viewFile, ['model' => $this->model, 'form' => $this->form, 'groups' => $this->property_groups_to_add, 'groupModel' => $groupModel, 'properties' => $properties, 'optionGenerate' => $optionGenerate, 'footer' => $this->footer]); }
public function actionIndex() { $conversationId = $this->getQuery('conversationId'); if (empty($conversationId)) { throw new BadRequestHttpException("Missing conversationId"); } $query = ChatMessage::find(); if ($orderBy = $this->getQuery('orderBy', 'createdAt')) { if (StringUtil::isJson($orderBy)) { $orderBy = Json::decode($orderBy, true); foreach ($orderBy as $key => $value) { if ($value === 'asc' || $value === 'ASC') { $orderBy[$key] = SORT_ASC; } else { $orderBy[$key] = SORT_DESC; } } } else { $orderBy = [$orderBy => SORT_DESC]; } $query->orderBy($orderBy); } $query->where(['isDeleted' => false, 'conversationId' => new \MongoId($this->getQuery('conversationId'))]); return new ActiveDataProvider(['query' => $query]); }