public function run() { $params = array(); $criteria = new CDbCriteria(); // $criteria->select = array('id,username,fullname,phone,address,status'); $criteria->select = '*'; if (isset($this->team_lear_id) and $this->team_lear_id != '') { $criteria->addCondition('team_lear_id=' . $this->team_lear_id); } $criteria->params = $params; $total = ATrainingTeam::model()->count($criteria); $offset = $this->limit * ($this->page - 1); $criteria->limit = $this->limit; $criteria->offset = $offset; $data = ATrainingTeam::model()->findAll($criteria); $listTrainee = array(); if (!empty($data)) { foreach ($data as $item) { $listTrainee[] = CJSON::decode(CJSON::encode($item->pls_user)); } } $data = $listTrainee; $pages = new CPagination($total); $pages->pageSize = $this->limit; $pages->applyLimit($criteria); $this->render($this->view, array('data' => $data, 'pages' => $pages)); }
/** * Decodes JSON sting. * * @static * * @param string $data * @param bool $asArray get result as array instead of object * * @return mixed */ public static function decodeJson($data, $asArray = true) { if (self::$json === null) { self::$json = new CJSON(); } return self::$json->decode($data, $asArray); }
public function actions() { $formSettings = array('redirect' => $this->createUrl('admin'), 'forms' => array('id' => 'mainForm', 'varName' => 'cmsAlias', 'models' => 'CmsAlias', 'onAfterSave' => function ($event) { $model = $event->params['model']; if ($model->location != 'nochange') { $decode = CJSON::decode($_POST['CmsAlias']['location']); $to = CmsAlias::model()->findByPk((int) $decode['to']); $action = $decode['action']; switch ($action) { case 'child': $model->moveAsLast($to); break; case 'before': if ($to->isRoot()) { $model->moveAsRoot(); } else { $model->moveBefore($to); } break; case 'after': if ($to->isRoot()) { $model->moveAsRoot(); } else { $model->moveAfter($to); } break; } } }, 'forms' => array('id' => 'routesForm', 'models' => 'CmsAliasRoute', 'varName' => 'cmsAliasRoutes', 'parentIdAttribute' => 'alias_id'))); return array('create' => array('class' => 'application.components.actions.Create', 'formSettings' => $formSettings), 'update' => array('class' => 'application.components.actions.Update', 'formSettings' => $formSettings), 'delete' => array('class' => 'application.components.actions.Delete', 'modelClass' => 'CmsAlias'), 'admin' => array('class' => 'application.components.actions.Admin', 'modelClass' => 'CmsAlias')); }
public function runAction($action, $data) { $this->id = $data; $s = new CHttpSession(); $s->open(); $storedData = $s[$this->id]; $s->close(); $this->model = $storedData['model']; if ($action == 'listitems') { $parent_id = null; if (isset($_GET['id'])) { $parent_id = $_GET['id']; } return $this->model->eyuiformeditordb_listitems($_GET['item_type'], $parent_id); } if ($action == 'newitem') { $parent_id = null; if (isset($_GET['id'])) { $parent_id = $_GET['id']; } return $this->model->eyuiformeditordb_newitem($_GET['item_type'], self::t("New Item"), $parent_id); } if ($action == 'deleteitem') { if ($this->model->eyuiformeditordb_deleteitem($_GET['id'])) { return "OK"; } } if ($action == 'updateitem') { $obj = CJSON::decode(trim(file_get_contents('php://input'))); if ($this->model->eyuiformeditordb_updateitem($obj) == true) { return "OK"; } } }
public function actionEditCustomer($id) { $data = CJSON::decode(file_get_contents('php://input')); $customer = Customer::model()->findByPk($id); if (!$customer) { $response = array('success' => false, 'message' => 'Couldn\'t find customer with id = ' . $id); $this->renderJSON($response); } $orders = array(); if (isset($data['orders'])) { $orders = $data['orders']; unset($data['orders']); } $customer->attributes = $data; $customer->save(); if (count($orders)) { $ordersArray = array(); foreach ($orders as $order) { $order = array('customer_id' => $id, 'posted_at' => $order['postedAt'], 'amount' => $order['amount'], 'paid_at' => $order['paidAt']); $orderModel = new Order(); $orderModel->attributes = $order; $orderModel->save(); } } $response = array('success' => true); $this->renderJSON($response); }
/** * Returns all available updates for a given version * * @param type $version */ public static function getAvailableUpdate() { try { $url = Yii::app()->getModule('updater')->getApiUrl() . "getHumHubUpdates?version=" . urlencode(HVersion::VERSION) . "&updaterVersion=" . Yii::app()->getModule('updater')->getVersion(); $http = new Zend_Http_Client($url, array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => Yii::app()->getModule('updater')->getCurlOptions(), 'timeout' => 30)); $response = $http->request(); $body = $response->getBody(); if ($body == "") { return null; } $info = CJSON::decode($body); if (!isset($info['fromVersion'])) { return null; } $package = new UpdatePackage(); $package->versionFrom = $info['fromVersion']; $package->versionTo = $info['toVersion']; $package->fileName = $info['fileName']; $package->md5 = $info['md5']; $package->downloadUrl = $info['downloadUrl']; return $package; } catch (Exception $ex) { throw new CHttpException('500', Yii::t('UpdaterModule.base', 'Could not get update info online! (%error%)', array('%error%' => $ex->getMessage()))); } return null; }
public function authenticate() { $user = User::model()->findByAttributes(array('username' => $this->username)); if ($user === null) { $this->errorCode = self::ERROR_USERNAME_INVALID; } else { // check Auto or Not $password = $this->autoLogin == false ? MSecure::password($this->username . $this->password . $user->registered) : $this->password; if ($user->password !== $password) { $this->errorCode = self::ERROR_PASSWORD_INVALID; } else { $this->_id = $user->id; if ($user->lastvisited === NULL) { $lastLogin = new CDbExpression('NOW()'); } else { $lastLogin = $user->lastvisited; } // RBAC $roles = CJSON::decode($user->role); $auth = Yii::app()->authManager; foreach ($roles as $role) { if (!$auth->isAssigned($role, $this->_id)) { if ($auth->assign($role, $this->_id)) { Yii::app()->authManager->save(); } } } $this->setState('email', $user->email); $this->setState('lastvisited', $lastLogin); $this->errorCode = self::ERROR_NONE; } } return !$this->errorCode; }
public function actionIndex() { $shop_id = Yii::app()->request->getParam('shop_id'); if (!$shop_id) { Error::output(Error::ERR_NO_SHOPID); } //查询出改商店的一些详细信息 $shopData = Shops::model()->findByPk($shop_id); if (!$shopData) { Error::output(Error::ERR_NO_SHOPID); } $shopData = CJSON::decode(CJSON::encode($shopData)); //根据店铺id查询出该店铺的菜单 $menuData = Menus::model()->with('food_sort', 'image', 'shops')->findAll(array('condition' => 't.shop_id=:shop_id AND t.status=:status', 'params' => array(':shop_id' => $shop_id, ':status' => 2))); $data = array(); foreach ($menuData as $k => $v) { $data[$k] = $v->attributes; $data[$k]['index_pic'] = $v->index_pic ? Yii::app()->params['img_url'] . $v->image->filepath . $v->image->filename : ''; $data[$k]['sort_name'] = $v->food_sort->name; $data[$k]['shop_name'] = $v->shops->name; $data[$k]['create_time'] = Yii::app()->format->formatDate($v->create_time); $data[$k]['status'] = Yii::app()->params['menu_status'][$v->status]; $data[$k]['price'] = $v->price; } Out::jsonOutput(array('shop' => $shopData, 'menus' => $data)); }
public function beforeSave() { $ip = Yii::app()->request->userHostAddress; $key = 'ipInfo-' . $ip; $ipData = zmf::getCookie($key); if (!$ipData) { $url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=' . $ip; // 执行HTTP请求 $header = array('apikey:e5882e7ac4b03c5d6f332b6de4469e81'); $ch = curl_init(); // 添加apikey到header curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $res = curl_exec($ch); $res = CJSON::decode($res, true); $retData = array(); if ($res['errNum'] == 0) { $retData = $res['retData']; } $ipData = json_encode($retData); zmf::setCookie($key, $ipData, 2592000); } $this->ip = ip2long($ip); $this->ipInfo = $ipData; return true; }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { //read the post input (use this technique if you have no post variable name): $post = file_get_contents("php://input"); //decode json post input as php array: $data = CJSON::decode($post, true); //Event is a Yii model: $evento = new Evento(); //load json data into model: $evento->attributes = $data; //this is for responding to the client: $response = array(); //save model, if that fails, get its validation errors: if ($evento->save() == false) { $response['success'] = false; $response['errors'] = $evento->errors; } else { $response['success'] = true; //respond with the saved contact in case the model/db changed any values //$response['evento'] = $evento; } //respond with json content type: header('Content-type:application/json'); //encode the response as json: echo CJSON::encode($response); exit; }
public function actionAddnewaduan() { //read the post input (use this technique if you have no post variable name): $post = file_get_contents("php://input"); //decode json post input as php array: $data = CJSON::decode($post, true); echo $data; //read the post input (use this technique if you have no post variable name): // $post = file_get_contents("php://input"); //decode json post input as php array: // $data = CJSON::decode($post, true); // $showjson = json_decode($post); // $result = file_get_contents('php://input'); // echo $result; // $post = Yii::$app->request->post(); // $get = json_decode($result); // // Get data from object // $member = $get->member; // $judul = $get->judul; // $deskripsi = $get->deskripsi; // $category = $get->category; // $kecamatan = $get->kecamatan; // echo '<h1>Ngantuk</h1>'; // Your code..... // $model = new ModelAduan(); // // if ($model->load(Yii::$app->request->post())) { // $data = $model->AddNewUser($member, $judul, $deskripsi, $category, $kecamatan); // sukses // echo json_encode(array('data' => $result, 'status' => '1')); // }else{ // // gagal // echo json_encode(array('status' => '2')); // } // URL : http://back.end/index.php?r=api/addnewaduan }
/** * @test * @depends reLoginAndCheckToken * @param string $token */ public function logout($token) { $route = 'logout/'; $this->handlePost(401, null, $route); $response = \CJSON::decode($this->handlePost(200, array('access_token' => $token), $route)->getBody()->getContents()); $this->assertTrue(time() >= $response['expire']); }
private function complete() { $required = array('social_service' => true); $params = $this->controller->getParams($required); /** * @var Quest[] $socialQuests */ $socialQuests = Quest::model()->byUser($this->controller->identity->getId())->byType(QuestTypes::POST_TO_WALL)->byModel((new \ReflectionClass(ContestManager::getCurrentActive()))->getShortName(), ContestManager::getCurrentActive()->id)->findAll(); if (!in_array($params['social_service'], array('vk', 'ok', 'fb'))) { throw new InvalidParamsApiException(); } /** * @var CommentatorsContestParticipant $participant */ $participant = CommentatorsContestParticipant::model()->byContest(ContestManager::getCurrentActive()->id)->byUser($this->controller->identity->getId())->find(); foreach ($socialQuests as $quest) { if (\CJSON::decode($quest->settings)['social_service'] == $params['social_service']) { $quest->complete(); $this->controller->data = $quest; $participant->score += 25; $participant->update(array('score')); break; } } if (!$this->controller->data) { throw new NotFoundApiException(); } }
public function run() { $params = array(); $criteria = new CDbCriteria(); $criteria->select = array('lecture_name,training_minute,id,lecture_type'); if (isset($this->lecture_name) and $this->lecture_name != '') { $keyword = addcslashes($this->lecture_name, '%_'); $criteria->addCondition('lecture_name LIKE :keyword'); $params[':keyword'] = "%{$keyword}%"; } if (isset($this->lecture_cat) and $this->lecture_cat != '') { $criteria->addCondition('lecture_cat_id=' . $this->lecture_cat); } if (isset($this->trainer) and $this->trainer != '') { $criteria->addCondition('created_by=' . $this->trainer); } if (!empty(Yii::app()->user->id) and Yii::app()->session['group_id'] == 1) { $criteria->addCondition('created_by=' . Yii::app()->user->id); } $criteria->params = $params; $criteria->order = 'created_date DESC'; $total = Lecture::model()->count($criteria); $offset = $this->limit * ($this->page - 1); $criteria->limit = $this->limit; $criteria->offset = $offset; $data = Lecture::model()->findAll($criteria); if (!empty($data)) { $data = CJSON::decode(CJSON::encode($data)); } $pages = new CPagination($total); $pages->pageSize = $this->limit; $pages->applyLimit($criteria); $this->render($this->view, array('data' => $data, 'pages' => $pages)); }
public function actionSaveAnswer() { $request = CJSON::decode(file_get_contents('php://input')); if ($request) { echo CJSON::encode(Answers::saveAnswer($request)); } }
public function actionCreateJurnalUmum() { // return; if (!app()->request->isAjaxRequest) { return; } if (isset($_POST) && !empty($_POST)) { $status = false; $msg = 'Jurnal umum berhasil disimpan.'; $user = app()->user->getId(); $detils = CJSON::decode($_POST['detil']); $transaction = app()->db->beginTransaction(); try { $ref = new MtReferenceCom(); $docref = $ref->get_next_reference(JURNAL_UMUM); $jurnal_umum_id = Mt::get_max_type_no(JURNAL_UMUM); $jurnal_umum_id++; foreach ($detils as $detil) { $amount = $detil['debit'] > 0 ? $detil['debit'] : -$detil['kredit']; Mt::add_gl(JURNAL_UMUM, $jurnal_umum_id, $_POST['tran_date'], $docref, $detil['account'], "-", $amount, $user, $detil['id_mobil']); } $ref->save(JURNAL_UMUM, $jurnal_umum_id, $docref); $transaction->commit(); $status = true; } catch (Exception $ex) { $transaction->rollback(); $status = false; $msg = $ex; } echo CJSON::encode(array('success' => $status, 'id' => $docref, 'msg' => $msg)); app()->end(); } }
/** * Initializes the widget. */ public function init() { if (is_null($this->theme)) { $this->theme = 'default'; } // check if options parameter is a json string if (is_string($this->options)) { if (!($this->options = CJSON::decode($this->options))) { throw new CException('The options parameter is not valid JSON.'); } } // merge options with default values $defaultOptions = array(); $this->options = CMap::mergeArray($defaultOptions, $this->options); // merge options with Javascript events $normalizedEvents = array(); foreach ($this->events as $name => $handler) { $normalizedEvents[$name] = new CJavaScriptExpression($handler); } $this->options = CMap::mergeArray($normalizedEvents, $this->options); // set field initial value if (isset($this->options['formatSubmit'])) { if (!isset($this->htmlOptions['data-value']) && $this->hasModel()) { $this->htmlOptions['data-value'] = CHtml::resolveValue($this->model, $this->attribute); } } // prepend pickadate scripts to the begining of the additional js files array if (!empty($this->language)) { array_unshift($this->scripts, "translations/{$this->language}"); } array_unshift($this->scripts, 'picker.date'); array_unshift($this->scripts, $this->baseScript); }
public function actionGenerate() { $postdata = file_get_contents("php://input"); $post = CJSON::decode($postdata); $path = Yii::getPathOfAlias($post['path']); $file = $path . DIRECTORY_SEPARATOR . $post['name']; $result = ['status' => 'ok', 'path' => $path, 'file' => $file]; switch ($post['type']) { case "folder": if (!file_exists($path)) { mkdir($path, 0777, true); } break; case "index": case "form": case "relform": case "chooserelform": case "master": if (!file_exists($file) || !!@$post['overwrite']) { $this->generateAR($post, $result); } break; case "js": $this->generateJS($post, $result); break; case "controller": if (!file_exists($file) || !!@$post['overwrite']) { $this->generateController($post, $result); } break; default: break; } echo json_encode($result); }
/** * description: Hidrata el array $arguments con la informacion enviada desde el cliente dependiendo del * metodo que se trate. */ public function actionProcessRequest() { $hU = new HttpUtils(); $this->httpMethod = $hU->getHttpRequestMethod(); switch ($this->httpMethod) { case HttpUtils::METHOD_GET: $this->arguments = $_GET; $this->processGet(); break; case HttpUtils::METHOD_HEAD: $this->arguments = $_GET; $this->processHead(); break; case HttpUtils::METHOD_POST: $json = file_get_contents('php://input'); $this->arguments = CJSON::decode($json); if ($this->arguments == null) { $this->arguments = $_POST; } $this->processPost(); break; case HttpUtils::METHOD_PUT: $this->processPut(); break; case HttpUtils::METHOD_DELETE: parse_str(file_get_contents('php://input'), $this->arguments); $this->processDelete(); break; } }
public function actionUpdate($id) { if (null === ($model = User::model()->findByPk($id))) { throw new CHttpException(404); } $data = CJSON::decode(file_get_contents('php://input')); $model->fname = $data['fname']; $model->lname = $data['lname']; $model->email = $data['email']; $model->username = $data['username']; $model->role = $data['role']; $model->newPassword = $data['password']; if ($model->newPassword) { $model->password = $model->newPassword; } if (!$model->save()) { $errors = array(); foreach ($model->getErrors() as $e) { $errors = array_merge($errors, $e); } $this->sendResponse(500, implode("<br />", $errors)); } $model = User::model()->noPassword()->findByPk($model->id); $this->sendResponse(200, CJSON::encode($model)); }
public function actionSave() { $result = array(); if (Yii::app()->user->isGuest) { $result['status'] = "fail"; $result['reason'] = "You must log in to save search query"; } else { $criteriaStr = $_POST['criteria']; $criteria = CJSON::decode($criteriaStr, true); if (isset($criteria['keyword']) && strlen($criteria['keyword']) > 0) { $search = new SearchRecord(); $search->user_id = Yii::app()->user->_id; $search->name = $criteria['keyword']; $search->query = $_POST['criteria']; $search->result = $_POST['result']; if ($search->save()) { $result['status'] = "success"; } else { $result['status'] = "fail"; $result['reason'] = "Unknown Reason"; } } else { $result['status'] = "fail"; $result['reason'] = "Problem with search query, pls check"; } } echo json_encode($result); }
/** * Retrieves all of the themes from webroot.themes and returns them in an array group by type, each containing * the contents of theme.json. * * The themes are then cached for easy retrieval later. (I really hate unecessary DiskIO if something isn't changing...) * * @return array */ public function getThemes() { $themes = Yii::app()->cache->get('settings_themes'); if ($themes == false) { $themes = array(); $currentTheme = Cii::getConfig('theme'); $themePath = Yii::getPathOfAlias('base.themes') . DS; $directories = glob($themePath . "*", GLOB_ONLYDIR); // Pushes the current theme onto the top of the list foreach ($directories as $k => $dir) { if ($dir == Yii::getPathOfAlias('base.themes') . DS . $currentTheme) { unset($directories[$k]); break; } } array_unshift($directories, $themePath . $currentTheme); foreach ($directories as $dir) { $json = CJSON::decode(file_get_contents($dir . DIRECTORY_SEPARATOR . 'composer.json')); $name = $json['name']; $key = str_replace('ciims-themes/', '', $name); $themes[$key] = array('path' => $dir, 'name' => $name, 'hidden' => isset($json['hidden']) ? $json['hidden'] : false); } Yii::app()->cache->set('settings_themes', $themes); return $themes; } return $themes; }
public function actionOperation() { $post = file_get_contents("php://input"); $postData = CJSON::decode($post, true); $this->_device->ifaces[$postData['iface_id']]->saveAttributes(array('lastactivity' => $postData['start'])); $operation = new Operation(); $postData['alarm'] = $postData['alarm'] ? 1 : 0; $operation->attributes = $postData; $transaction = Yii::app()->db->beginTransaction(); try { $operation->save(); $operation_id = $operation->id; foreach ($postData['records'] as $record) { $record['operation_id'] = $operation_id; $recordModel = new Record(); $recordModel->attributes = $record; $recordModel->save(); } $transaction->commit(); $this->_sendResponse(200); } catch (Exception $e) { $transaction->rollBack(); $this->_sendResponse(400); } }
protected function validateAttribute($object, $attribute) { $serialized = $object->{$attribute}; if (!empty($serialized)) { $unserialized = CJSON::decode($serialized); if (json_last_error() != JSON_ERROR_NONE) { $message = Zurmo::t('EmailTemplatesModule', 'Unable to decode serializedData.'); $this->addError($object, $attribute, $message); return false; } if (empty($unserialized)) { return true; } if (count($unserialized) == 2 || count($unserialized) == 3 && isset($unserialized['baseTemplateId'], $unserialized['dom']) && is_array($unserialized['dom'])) { $firstElement = reset($unserialized['dom']); if (count($firstElement) == 3 && isset($firstElement['class'], $firstElement['properties'], $firstElement['content'])) { return true; } } $message = Zurmo::t('EmailTemplatesModule', 'serializedData contains invalid scheme.'); $this->addError($object, $attribute, $message); return false; } return true; }
public function cities($params = array()) { $cache = Yii::app()->cache; if ($city_all = $cache->hget('city', 'cities')) { $provices = CJSON::decode($city_all); } else { //获取全国省列表 $provice_obj = YhmCity::model()->findAll('class_parent_id=:id', array(':id' => '1')); $provices = array(); if ($provice_obj) { foreach ($provice_obj as $key => $val) { $provices[$val->class_id] = array('id' => $val->class_id, 'name' => $val->class_name); } } $obj = YhmCity::model()->findAll('class_parent_id >:id and class_type = :type', array(':id' => 1, ':type' => 2)); if ($obj) { foreach ($obj as $key => $val) { if ($val->class_parent_id > 1) { } $provices[$val->class_parent_id]['cites'][] = array('id' => $val->class_id, 'name' => $val->class_name); } $cache->hset('city', 'cities', json_encode($provices, JSON_UNESCAPED_UNICODE)); } } $result = array('cities' => $provices); return $this->notice('OK', 0, '成功', $result); }
public function actionIndex() { //取出公告数据 $notice = Announcement::model()->findAll(array('order' => 'create_time DESC', 'condition' => 'status=:status', 'params' => array(':status' => 2))); $notice = CJSON::decode(CJSON::encode($notice)); Out::jsonOutput($notice); }
/** * Generates a default layout from the desktop layout if available, or from the model's * fields otherwise. * @param string $type 'form' or 'view' * @param string $modelName * @return array */ public static function generateDefaultLayout($type, $modelName) { if ($type === 'form') { $layout = FormLayout::model()->findByAttributes(array('model' => ucfirst($modelName), 'defaultForm' => 1, 'scenario' => 'Default')); } else { $layout = FormLayout::model()->findByAttributes(array('model' => ucfirst($modelName), 'defaultView' => 1, 'scenario' => 'Default')); } $layoutData = array(); if ($layout) { $layout = CJSON::decode($layout->layout); if (isset($layout['sections'])) { foreach ($layout['sections'] as $section) { foreach ($section['rows'] as $row) { foreach ($row['cols'] as $col) { foreach ($col['items'] as $item) { if (isset($item['name'])) { $fieldName = preg_replace('/^formItem_/u', '', $item['name']); $layoutData[] = $fieldName; } } } } } } } elseif (is_subclass_of($modelName, 'X2Model')) { $layoutData = Yii::app()->db->createCommand()->select('fieldName')->from('x2_fields')->where('modelName=:modelName', array(':modelName' => $modelName))->andWhere($type === 'view' ? 'readOnly' : 'true')->queryColumn(); } return $layoutData; }
public function run() { $model = $this->controller->loadModel(); $this->_ext_oauth = Yii::getPathOfAlias('ext') . "/OAuth"; if (isset($_POST['OAuth'])) { $model->attributes = $_POST['OAuth']; switch ($model->id) { case 'qq': //配置QQ登录 $config = $this->configQQ(); break; case 'sinawb': //配置新浪微博登录 $config = $this->configSinaWb(); break; case 'weixin': //配置微信登录 $config = $this->configWeiXin(); break; case 'renren': //配置人人网登录 $config = $this->configRenren(); break; } $model->apiconfig = $config; if ($model->save()) { $this->controller->message('success', Yii::t('admin', 'Update Success'), $this->controller->createUrl('index')); } } //获取接口配置信息 $apiconfig = CJSON::decode($model->apiconfig); $this->controller->render('update', array('model' => $model, 'apiconfig' => $apiconfig)); }
/** * 获取汇率 * 雅虎YQL https://developer.yahoo.com/yql/console/ * 请求语句 select * from yahoo.finance.xchange where pair="CNYUSD,CNYHKD" * 示例 https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22CNYUSD%2CCNYHKD%22%0A%09%09&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback= */ public function actionExrates() { $units = tools::getUnits(); unset($units['CNY']); $arr = array(); foreach ($units as $k => $v) { $arr[] = 'CNY' . $k; } $str = join(',', $arr); $url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22{$str}%22%0A%09%09&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback="; $output = zmf::curlget($url); if (!$output) { exit('Failed'); } $rateArr = CJSON::decode($output); $rateArr = $rateArr['query']['results']['rate']; foreach ($rateArr as $val) { $_key = str_replace('CNY', '', $val['id']); $rates[$_key] = array('rate' => $val['Rate'], 'title' => tools::getUnits($_key)); } $detailDir = Yii::app()->basePath . '/runtime/rates/'; zmf::createUploadDir($detailDir); $dir = $detailDir . 'detail.log'; file_put_contents($dir, CJSON::encode($rates)); exit('well done'); }
/** * @param array $destinations * [Х][departure] - departure city iata code, * [Х][arrival] - arrival city iata code, * [Х][date] - departure date, * * @param int $adt amount of adults * @param int $chd amount of childs * @param int $inf amount of infanties */ public function actionBE(array $destinations, $adt = 1, $chd = 0, $inf = 0, $format = 'json') { $asyncExecutor = new AsyncCurl(); $this->addBusinessClassAsyncResponse($destinations, $adt, $chd, $inf, $asyncExecutor); $this->addEconomClassAsyncResponse($destinations, $adt, $chd, $inf, $asyncExecutor); $responses = $asyncExecutor->send(); $errors = array(); $variants = array(); foreach ($responses as $response) { if ($httpCode = $response->headers['http_code'] == 200) { $combined = CJSON::decode($response->body); $flights = $combined['flights']; $searchParams = $combined['searchParams']; $variants = CMap::mergeArray($variants, FlightManager::injectForBe($flights, $searchParams)); } else { $errors[] = 'Error ' . $httpCode; } } if (!empty($this->errors)) { $variants = array(); } $flightSearchParams = $this->buildSearchParams($destinations, $adt, $chd, $inf, 'A'); $this->results = $variants; $result['flights']['flightVoyages'] = $this->results; $result['searchParams'] = $flightSearchParams->getJsonObject(); $siblingsEconom = FlightManager::createSiblingsData($flightSearchParams); $result['siblings']['E'] = $siblingsEconom; $this->sendWithCorrectFormat($format, $result); }