Exemplo n.º 1
0
 public function actionSave()
 {
     $this->_setJSONFormat(Yii::$app);
     $request = Yii::$app->request;
     $data = $request->post();
     $code = '1';
     if (!empty($data['_id'])) {
         $product = Product::findOne($data['_id']['$id']);
         $data['updatedAt'] = new \MongoDate();
         $code = '2';
     }
     if (empty($product)) {
         $product = new Product();
         $accessToken = Token::getToken();
         $user = User::findOne(['_id' => $accessToken->userId]);
         $data['accountId'] = $this->getAccountId();
         $data['creator'] = $user->name;
         $data['createdAt'] = new \MongoDate();
         $data['isDeleted'] = false;
     }
     if (!empty($product->accountId)) {
         unset($data['accountId']);
     }
     $product->attributes = $data;
     $product->save();
     return ['code' => $code];
 }
Exemplo n.º 2
0
 /**
  * This method is used to valide the user's authority with token in help desk chat system.
  * This method is invoked right before an action is executed.
  *
  * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  * will determine whether the action should continue to run.
  *
  * If you override this method, your code should look like the following:
  *
  * ```php
  * public function beforeAction($action)
  * {
  *     if (parent::beforeAction($action)) {
  *         // your custom code here
  *         return true;  // or false if needed
  *     } else {
  *         return false;
  *     }
  * }
  * ```
  * @param Action $action the action to be executed.
  * @return boolean whether the action should continue to run.
  * @author Harry Sun
  */
 public function beforeAction($action)
 {
     $route = $this->id . '/' . $action->id;
     //init i18n configuration from user agent
     Yii::$app->language = LanguageUtil::getBrowserLanguage();
     // the action ids without auth
     $noAuth = ['site/login', 'site/logout', 'conversation/state', 'conversation/message', 'setting/index', 'setting/self-helpdesk', 'site/send-reset-password-email', 'site/reset-password', 'help-desk/check-auth', 'conversation/user-state', 'issue/create-from-js-sdk', 'issue/remove-attachment'];
     if (in_array($route, $noAuth)) {
         return true;
     } else {
         $accessToken = $this->getQuery('accesstoken');
         $info = Token::getToken($accessToken);
         if (!empty($info) && isset($info->expireTime) && !MongodbUtil::isExpired($info->expireTime)) {
             Yii::$app->language = empty($info->language) ? LanguageUtil::DEFAULT_LANGUAGE : $info->language;
             $expireTime = new \MongoDate(time() + Token::EXPIRE_TIME);
             if ($info->expireTime < $expireTime) {
                 $info->expireTime = $expireTime;
             }
             $updateResult = $info->update();
             return true;
         }
         LogUtil::error(['accessToken' => $accessToken, 'message' => 'You have not logined']);
         throw new \yii\web\UnauthorizedHttpException('You have not logined');
     }
 }
Exemplo n.º 3
0
 /**
  * The first step of creating page
  * Use the createBasic scenario
  **/
 public function actionCreate()
 {
     $params = $this->getParams();
     $accesstoken = $this->getAccessToken();
     $token = Token::getToken($accesstoken);
     $page = new Page(['scenario' => 'createBasic']);
     $page->attributes = $params;
     $page->_id = new \MongoId();
     $page->accountId = $token->accountId;
     $userId = $token->userId;
     $user = User::findByPk($userId);
     $page->creator = ['id' => $userId, 'name' => $user->name];
     $page->url = Yii::$app->request->hostinfo . '/msite/page/' . $page->_id;
     $shortUrl = Yii::$app->urlService->shortenUrl($page->url);
     $page->shortUrl = $shortUrl['Short'];
     if ($page->validate()) {
         // all inputs are valid
         if ($page->save()) {
             return $page;
         } else {
             throw new ServerErrorHttpException(Yii::t('common', 'save_fail'));
         }
     } else {
         // valid fail, return errors
         $errors = array_keys($page->errors);
         throw new InvalidParameterException([$errors[0] => Yii::t("microSite", $errors[0] . '_field_not_empty')]);
     }
 }
Exemplo n.º 4
0
 public static function saveImportedCookbooks($datas, $accountId)
 {
     $results = [];
     $accessToken = Token::getToken();
     $userId = $accessToken->userId;
     $user = User::findOne(['_id' => $userId]);
     for ($i = 0; $i < sizeof($datas); $i++) {
         $results[] = self::_saveSingleCookbook($datas[$i], $user, $accountId);
     }
     return $results;
 }
Exemplo n.º 5
0
 /**
  * Get the account id according to the accessToken
  * @return MongoId | boolean, the PK for the account or false for no such account found
  */
 public function getAccountId()
 {
     $accountId = $this->getAccountIdFromCookies();
     if (!empty($accountId)) {
         return new MongoId($accountId);
     }
     $token = $this->getAccessToken();
     $tokenInfo = Token::getToken($token);
     if (empty($tokenInfo)) {
         return false;
     }
     return $tokenInfo->accountId;
 }
Exemplo n.º 6
0
 /**
  * Mobile to perfect personal info
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/member/member/personal<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for mobile to update personal info.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     memberId: string<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * </pre>
  */
 public function actionPersonal()
 {
     //this api is just for mobile user to perfect info, mobile user has no permission to update score and card
     $accesstoken = $this->getAccessToken();
     $token = Token::getToken($accesstoken);
     if (empty($token) || $token->role != User::ROLE_MOBILE_ENDUSER) {
         throw new \yii\web\ForbiddenHttpException(\Yii::t('common', 'no_permission'));
     }
     $params = $this->getParams();
     $memberId = new \MongoId($params['memberId']);
     $member = Member::findByPk($memberId);
     unset($params['memberId']);
     $properties = $member->properties;
     $member->load($params, '');
     $this->_validateProperty($member);
     $member->properties = $this->_mergeProperties($member, $properties);
     if ($member->save()) {
         $this->attachBehavior('MemberBehavior', new MemberBehavior());
         $this->updateItemByScoreRule($member);
         $member->_id .= '';
         return $member;
     } else {
         throw new ServerErrorHttpException('Fail to update personal information');
     }
 }
Exemplo n.º 7
0
 /**
  * Mark all messages as read or delete all read messages
  *
  * <b>Request Type</b>: PUT<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/common/message/update<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for mark all messages as read or delete all read messages
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     isRead: integer, the message read status
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     status: string, update result
  *     <br/><br/>
  *
  * <b>Request Example:</b><br/>
  * <pre>
  * {
  *     "isRead": 1
  * }
  * </pre>
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *     'status': 'ok'
  * }
  * </pre>
  */
 public function actionUpdate()
 {
     $token = $this->getAccessToken();
     $isRead = (bool) $this->getParams('isRead', false);
     $tokenInfo = Token::getToken($token);
     $accountId = $tokenInfo->accountId;
     $userId = $tokenInfo->userId;
     $condition = ['accountId' => $accountId, '$or' => [['to.target' => Message::TO_TARGET_ACCOUNT], ['to.target' => Message::TO_TARGET_USER, 'to.id' => $userId]], 'isRead' => $isRead];
     if ($isRead) {
         Message::deleteAll($condition);
     } else {
         Message::updateAll(['isRead' => true, 'readAt' => new \MongoDate()], $condition);
     }
     return ['status' => 'ok'];
 }
Exemplo n.º 8
0
 /**
  * Sync the stores data to wechat
  */
 public function actionPush()
 {
     $channelIds = $this->getParams('channelIds');
     $storeIds = $this->getParams('storeIds');
     $isAllStores = $this->getParams('isAllStores', false);
     if (empty($channelIds) || empty($storeIds) && !$isAllStores) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     $result = ['finished' => true];
     $token = Token::getToken();
     $accountId = $token->accountId;
     if ($isAllStores) {
         $stores = Store::find()->select(['_id'])->where(['accountId' => $accountId, 'isDeleted' => Store::NOT_DELETED])->all();
         if (!empty($stores)) {
             $storeIds = [];
             foreach ($stores as $store) {
                 $storeIds[] = (string) $store->_id;
             }
         }
     }
     $args = ['accountId' => (string) $accountId, 'channels' => $channelIds, 'storeIds' => $storeIds, 'userId' => (string) $token->userId, 'description' => 'Direct: Sync the stores data to wechat'];
     $token = Yii::$app->job->create('backend\\modules\\channel\\job\\StoreSync', $args);
     $result = ['finished' => false, 'token' => $token];
     return $result;
 }
Exemplo n.º 9
0
 /**
  * Get accountId and company when exchange
  * @param array $params
  * @return array
  */
 public function exchange($params)
 {
     $token = Token::getToken();
     \Yii::$app->language = empty($token->language) ? LanguageUtil::DEFAULT_LANGUAGE : $token->language;
     $this->checkCode($params);
     $accountId = $params['accountId'];
     $account = Account::findByPk($accountId);
     return ['accountId' => $accountId, 'company' => empty($account->company) ? null : $account->company];
 }
Exemplo n.º 10
0
 /**
  * validateUnique validates that the attribute value is unique with isDeleted in the specified database table.
  *
  * The following is an example of validation rules using this validator:
  *
  * ```php
  * // a1 needs to be unique
  * ['a1', 'validateUnique']
  * ```
  * @author Harry Sun
  */
 public function validateUnique($attribute)
 {
     $token = Token::getToken();
     $condition = [$attribute => $this->{$attribute}];
     if (!empty($token->accountId)) {
         $condition['accountId'] = $token->accountId;
     } else {
         if (!empty($this->accountId)) {
             $condition['accountId'] = $this->accountId;
         }
     }
     $model = self::findOne($condition);
     if (!empty($model) && $model->_id . '' !== $this->_id . '') {
         $this->addError($attribute, $this->{$attribute} . " has been used.");
     }
 }
 public function actionToCookbook()
 {
     sleep(2);
     Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     $request = Yii::$app->request;
     $fileB64 = $request->post('fileB64');
     $file = base64_decode(substr($fileB64, strpos($fileB64, ";base64,") + 8));
     $filePath = Yii::getAlias('@runtime') . '/cookbook' . date('his');
     file_put_contents($filePath, $file);
     $phpReader = new \PHPExcel_Reader_Excel2007();
     if (!$phpReader->canRead($filePath)) {
         $phpReader = new \PHPExcel_Reader_Excel5();
         if (!$phpReader->canRead($filePath)) {
             $phpReader = new \PHPExcel_Reader_CSV();
             if (!$phpReader->canRead($filePath)) {
                 unlink($filePath);
                 return ['fileError' => true];
             }
         }
     }
     $phpExcel = $phpReader->load($filePath);
     $sheets = $phpExcel->getAllSheets();
     $cookbookTitles = [];
     for ($si = 0; $si < sizeof($sheets); $si++) {
         $sheet = $sheets[$si];
         $rowTemp = [];
         $cowTemp = [];
         $ingredientFinished = false;
         $rowCount = $sheet->getHighestRow();
         $highestCol = $sheet->getHighestColumn();
         $colCount = ord($highestCol) - 65;
         $cookbook = [];
         //There has a bug
         //When the 'cuisineType' row does not exist, the $rowCount will be infinity
         //The code blow can avoid this bug
         $rowCount = $rowCount > 100 ? 100 : $rowCount;
         for ($row = 1; $row <= $rowCount; $row++) {
             for ($col = 0; $col <= $colCount; $col++) {
                 $val = $sheet->getCellByColumnAndRow($col, $row)->getValue();
                 $val = trim((string) $val);
                 if ($val === '') {
                     continue;
                 }
                 // Fill title and image
                 if (!isset($cookbook['title'])) {
                     $arr = explode('-', $val, 2);
                     if (empty($arr) || sizeof($arr) < 2) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: title is required');
                         return ['contentError' => true];
                     }
                     if (mb_strlen(trim(trim($arr[1])), 'utf-8') > 30) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: title should less than 30 words');
                         return ['titleLengthError' => true];
                     }
                     $cookbook['image'] = Yii::$app->qiniu->domain . '/' . trim($arr[0]) . '.jpg';
                     $cookbook['title'] = trim(trim($arr[1]));
                     unset($arr);
                     continue;
                 }
                 // Find category row
                 if (!isset($rowTemp['category'])) {
                     if (!preg_match('/^category$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: category is required');
                         return ['contentError' => true];
                     }
                     $rowTemp['category'] = $row;
                     continue;
                 }
                 // Fill category
                 if ($rowTemp['category'] === $row) {
                     //The first sheet's category row will leads to a bug
                     if ($si == 0) {
                         $firstCate = $val;
                     }
                     $arr = $this->_spiltByComma($val);
                     // $arr = preg_split('/[,,]/', $val);
                     $cookbook['category'] = [];
                     foreach ($arr as $v) {
                         $v = trim($v);
                         if ($v != '') {
                             $cookbook['category'][] = trim($v);
                         }
                     }
                     $row++;
                     $col = -1;
                     unset($arr);
                     continue;
                 }
                 // Find subCategory row
                 if (!isset($rowTemp['subCategory'])) {
                     if (!preg_match('/^sub[\\s\\n]*category$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: subCategory is required');
                         return ['contentError' => true];
                     }
                     $rowTemp['subCategory'] = $row;
                     continue;
                 }
                 // Fill subCategory
                 if ($rowTemp['subCategory'] === $row) {
                     // $arr = preg_split('/[,,]/', $val);
                     $arr = $this->_spiltByComma($val);
                     $cookbook['subCategory'] = [];
                     foreach ($arr as $v) {
                         $v = trim($v);
                         if ($v != '') {
                             $cookbook['subCategory'][] = trim($v);
                         }
                     }
                     $row++;
                     $col = -1;
                     unset($arr);
                     continue;
                 }
                 // Find cuisineType row
                 if (!isset($rowTemp['cuisineType'])) {
                     if (preg_match('/^cuisine[\\s\\n]*type$/i', $val)) {
                         $rowTemp['cuisineType'] = $row;
                         continue;
                     } else {
                         $rowTemp['cuisineType'] = '';
                     }
                 }
                 // Fill cuisineType
                 if ($rowTemp['cuisineType'] === $row) {
                     // $arr = preg_split('/[,,]/', $val);
                     $arr = $this->_spiltByComma($val);
                     $cookbook['cuisineType'] = [];
                     foreach ($arr as $v) {
                         $v = trim($v);
                         if ($v != '') {
                             $cookbook['cuisineType'][] = trim($v);
                         }
                     }
                     $row++;
                     $col = -1;
                     unset($arr);
                     continue;
                 }
                 // Find yield row
                 if (!isset($rowTemp['yield'])) {
                     if (!preg_match('/^yield$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: yield is required');
                         return ['contentError' => true];
                     }
                     $rowTemp['yield'] = $row;
                     continue;
                 }
                 // Fill yield
                 if ($rowTemp['yield'] === $row) {
                     if (!isset($cookbook['yield'])) {
                         $cookbook['yield'] = [];
                         $cookbook['yield']['Quantity'] = $val;
                     } else {
                         $cookbook['yield']['unit'] = $val;
                     }
                     continue;
                 }
                 // Find portionSize row
                 if (!isset($rowTemp['portionSize'])) {
                     if (!preg_match('/^portion[\\s\\n]*size$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: portionSize is required');
                         return ['contentError' => true];
                     }
                     $rowTemp['portionSize'] = $row;
                     continue;
                 }
                 // Fill portionSize
                 if ($rowTemp['portionSize'] === $row) {
                     $cookbook['portionSize'] = $val;
                     $row++;
                     $col = -1;
                     continue;
                 }
                 //Find ingredient quantity colume
                 if (!isset($colTemp['idtQuantity'])) {
                     if (!preg_match('/^quantity$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: ingredient quantity is required');
                         return ['contentError' => true];
                     }
                     $colTemp['idtQuantity'] = $col;
                     continue;
                 }
                 //Find ingredient unit colume
                 if (!isset($colTemp['idtUnit'])) {
                     if (!preg_match('/^unit$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: ingredient unit is required');
                         return ['contentError' => true];
                     }
                     $colTemp['idtUnit'] = $col;
                     continue;
                 }
                 //Find ingredient name colume
                 if (!isset($colTemp['idtName'])) {
                     if (!preg_match('/^ingredient[\\s\\n]*name$/i', $val)) {
                         unlink($filePath);
                         LogUtil::error(date('Y-m-d h:i:s') . ' ukkklp parse excel to cookbook error: ingredient name is required');
                         return ['contentError' => true];
                     }
                     $colTemp['idtName'] = $col;
                     continue;
                 }
                 //Fill ingredient
                 if (!isset($cookbook['ingredient'])) {
                     $cookbook['ingredient'] = [];
                 }
                 if (!$ingredientFinished) {
                     // Fill ingredient quantity
                     if ($col === $colTemp['idtQuantity']) {
                         $cookbook['ingredient'][$row]['quantity'] = $val;
                     }
                     // Fill ingredient unit
                     if ($col === $colTemp['idtUnit']) {
                         $cookbook['ingredient'][$row]['unit'] = $val;
                     }
                     // Fill ingredient name
                     if ($col === $colTemp['idtName']) {
                         $cookbook['ingredient'][$row]['name'] = $val;
                     }
                     $ingredientFinished = preg_match('/^preparation[\\s\\n]*method$/i', $val);
                     if ($ingredientFinished) {
                         array_pop($cookbook['ingredient']);
                     }
                     continue;
                 }
                 // Find preparation method description colume
                 if (!isset($colTemp['ptnDescription'])) {
                     if (preg_match('/^description$/i', $val)) {
                         $colTemp['ptnDescription'] = $col;
                     }
                     continue;
                 }
                 //Fill preparation method
                 if (!isset($cookbook['preparationMethod'])) {
                     $cookbook['preparationMethod'] = [];
                 }
                 // Fill preparation method description
                 if ($col === $colTemp['ptnDescription']) {
                     $cookbook['preparationMethod'][$row]['description'] = [];
                     $arr = preg_split('/靈感來源\\s*or\\s*貼心小提示/i', $val);
                     if (empty($arr) || sizeof($arr) !== 2) {
                         $cookbook['preparationMethod'][$row]['description']['step'] = $val;
                         $cookbook['preparationMethod'][$row]['description']['creativeExperience'] = '';
                     } else {
                         $cookbook['preparationMethod'][$row]['description']['step'] = trim($arr[0]);
                         $cookbook['preparationMethod'][$row]['description']['creativeExperience'] = trim($arr[1]);
                     }
                     unset($arr);
                 }
             }
         }
         if (!isset($cookbook['ingredient']) || !isset($cookbook['preparationMethod'])) {
             unlink($filePath);
             return ['contentError' => true];
         }
         $cookbook['ingredient'] = array_values($cookbook['ingredient']);
         $tmpInfo = $this->_findProductUrlAndSave($cookbook['ingredient']);
         $cookbook['ingredient'] = $tmpInfo['ingredients'];
         unset($tmpInfo);
         $cookbook['preparationMethod'] = array_values($cookbook['preparationMethod']);
         for ($i = 0; $i < sizeof($cookbook['ingredient']); $i++) {
             $cookbook['ingredient'][$i]['id'] = $this->_getRandomId();
         }
         $cookbook['content'] = $cookbook['preparationMethod'][0]['description']['step'];
         $cookbook['creativeExperience'] = $cookbook['preparationMethod'][0]['description']['creativeExperience'];
         $cookbooks[] = $cookbook;
         unset($rowTemp);
         unset($colTemp);
         unset($cookbook);
     }
     unlink($filePath);
     if (empty($cookbooks)) {
         return [];
     }
     $results = Cookbook::saveImportedCookbooks($cookbooks, $this->getAccountId());
     $cookbookBatch = new CookbookBatch();
     $accessToken = Token::getToken();
     $user = User::findOne(['_id' => $accessToken->userId]);
     $cookbookBatch->operator = $user->name;
     $cookbookBatch->cookbooks = $results;
     $cookbookBatch->hasImages = false;
     $cookbookBatch->accountId = $this->getAccountId();
     $cookbookBatch->createdTime = new \MongoDate();
     $cookbookBatch->insert();
     return sizeof($results);
 }
Exemplo n.º 12
0
 public function checkAuth($module, $token)
 {
     $baseId = Yii::$app->id;
     $moduleId = $module->id;
     //init i18n configuration from user agent
     Yii::$app->language = LanguageUtil::getBrowserLanguage();
     if ($baseId === $moduleId) {
         return true;
     }
     //accountId
     $accountId = $this->getAccountIdFromCookies();
     if (!empty($accountId) && $this->validateSignature()) {
         return true;
     }
     if (!empty($token)) {
         $info = Token::getToken($token);
         if (!empty($info)) {
             //set the language for i18n
             Yii::$app->language = empty($info->language) ? LanguageUtil::DEFAULT_LANGUAGE : $info->language;
             // If $module is a child module, use the parent module
             if (!empty($module->module->id) && $module->module->id !== $baseId) {
                 $module = $module->module;
                 $moduleId = $module->id;
             }
             if (isset($info->expireTime) && !MongodbUtil::isExpired($info->expireTime)) {
                 if (isset($module->roleAccess) && !empty($roleAccess = $module->roleAccess) && in_array($info->role, $roleAccess) && in_array($moduleId, $info->enabledMods)) {
                     //set the current user
                     $userId = $this->getUserId();
                     $controllerId = $this->owner->id;
                     $actionId = $this->owner->action->id;
                     // the current route
                     // change 'POST product/products' to 'product/product/create'
                     $route = "{$moduleId}/{$controllerId}/{$actionId}";
                     // find the sensitive operation with route
                     $condition = ['isActivated' => true, 'actions' => $route, 'accountId' => $info->accountId];
                     $option = SensitiveOperation::findOne($condition);
                     if (!empty($option)) {
                         // admin has all sensitive operation access authority
                         if ($info->role !== User::ROLE_ADMIN) {
                             if ($info->role !== User::ROLE_OPERATOR) {
                                 // other's role hasn't sensitive operation access authority
                                 throw new ForbiddenHttpException(Yii::t('common', 'no_permission'));
                             } else {
                                 if (empty($option->users) || !in_array($info->userId, $option->users)) {
                                     throw new ForbiddenHttpException(Yii::t('common', 'no_permission'));
                                 }
                             }
                         }
                     }
                     define('CURRENT_USER_ID', $userId);
                     $info->expireTime = new \MongoDate(time() + Token::EXPIRE_TIME);
                     $updateResult = $info->update();
                     $this->updateAccessTokenExpire();
                     LogUtil::info(['tokenId' => $info->_id, 'updateResult' => $updateResult]);
                     return true;
                 } else {
                     throw new ForbiddenHttpException(Yii::t('common', 'no_permission'));
                 }
             } else {
                 Yii::$app->language = LanguageUtil::getBrowserLanguage();
                 throw new UnauthorizedHttpException(Yii::t('common', 'login_timeout'));
             }
         }
     }
     throw new UnauthorizedHttpException(Yii::t('common', 'not_logined'));
 }
Exemplo n.º 13
0
 /**
  * Get account modules config
  *
  * <b>Request Type </b>:GET
  * <b>Request Endpoints </b>: http://{server-domain}/api/common/module/config
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used to get the account modules config.
  *
  * <b>Response Example</b>
  * {
  *     "menus": {
  *         "content": [
  *             {
  *                 "order": 1,
  *                 "title": "graphics_content",
  *                 "name": "graphics",
  *                 "state": "content-graphics"
  *             },
  *             {
  *                 "order": 2,
  *                 "title": "webpage_content",
  *                 "name": "webpage",
  *                 "state": "content-webpage"
  *             }
  *         ],
  *         "analytic": [
  *             {
  *                 "order": 1,
  *                 "title": "analytic_followers_growth",
  *                 "name": "growth",
  *                 "state": "analytic-growth"
  *             },
  *             {
  *                 "order": 2,
  *                 "title": "analytic_followers_property",
  *                 "name": "property",
  *                 "state": "analytic-property"
  *             },
  *             {
  *                 "order": 3,
  *                 "title": "analytic_content_spread",
  *                 "name": "content",
  *                 "state": "analytic-content"
  *             },
  *             {
  *                 "order": 4,
  *                 "title": "analytic_store",
  *                 "name": "store",
  *                 "state": "analytic-score"
  *             }
  *         ]
  *     },
  *     "mods": [
  *         {
  *             "name": "channel",
  *             "order": 1,
  *             "stateUrl": ""
  *         },
  *         {
  *             "name": "customer",
  *             "order": 2,
  *             "stateUrl": "/customer/follower"
  *         },
  *         {
  *             "name": "helpdesk",
  *             "order": 1,
  *             "stateUrl": "/helpdesk/helpdesk"
  *         }
  *     ],
  *     "forbiddenStates": [
  *         "member-score",
  *         "product-edit-product",
  *         "product-edit-product-{id}"
  *     ]
  * }
  **/
 public function actionConfig()
 {
     $accountId = $this->getAccountId();
     $account = Account::findByPk($accountId);
     $result = ['menus' => $account->menus, 'mods' => $account->mods];
     $token = Token::getToken();
     $forbiddenStates = [];
     if (empty($token->role) || $token->role !== User::ROLE_ADMIN) {
         $userId = empty($token->userId) ? '' : $token->userId;
         $forbiddenStates = SensitiveOperation::getForbiddenStates($userId, $accountId);
     }
     $menus =& $result['menus'];
     // Remove the forbidden menu
     foreach ($menus as &$menu) {
         foreach ($menu as $index => $subMenu) {
             if (!empty($subMenu['state']) && in_array($subMenu['state'], $forbiddenStates)) {
                 array_splice($menu, $index, 1);
             }
         }
     }
     $mods =& $result['mods'];
     foreach ($mods as $index => &$mod) {
         // Get the first menu's state in this mod
         if (!empty($menus[$mod['name']][0]['state'])) {
             // Use first menu's state to generate the mod's stateUrl
             $mod['stateUrl'] = $this->_state2Url($menus[$mod['name']][0]['state']);
         } else {
             // Remove the mod
             array_splice($mods, $index, 1);
         }
     }
     $result['forbiddenStates'] = $forbiddenStates;
     // Sort the menus and mods
     foreach ($result['menus'] as &$moduleItems) {
         ArrayHelper::multisort($moduleItems, 'order', SORT_ASC);
     }
     ArrayHelper::multisort($result['mods'], 'order', SORT_ASC);
     return $result;
 }
Exemplo n.º 14
0
 /**
  * Get account app key
  *
  * <b>Request Type</b>: GET<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/management/app-key/key<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for billing account to get account app key
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *     "accessKey": "j57yguwea3",
  *     "secretKey": "hddbb36a5agy1u4vwov1612svlp537c2bcvg8cnc",
  *     "keyCreatedAt": 1428479366
  * }
  * </pre>
  */
 public function actionKey()
 {
     $token = Token::getToken();
     $account = Account::findByPk($token->accountId);
     return $account->getKey();
 }
Exemplo n.º 15
0
 public static function saveByCookbook($cookbook, $accountId = null, $admin = null)
 {
     if ($accountId == null) {
         $accountId = Token::getAccountId();
     }
     if ($admin == null) {
         $accessToken = Token::getToken();
         $userId = $accessToken->userId;
         $admin = User::findOne(['_id' => $userId]);
     }
     $queryCookingtype = new Query();
     $queryCookingtype->from('uhkklpCookingtype')->where(['accountId' => $accountId]);
     $cookingTypes = $queryCookingtype->all();
     if (isset($cookbook['category'])) {
         for ($j = 0; $j < count($cookbook['category']); $j++) {
             if (self::checkExist($accountId, $cookbook['category'][$j])) {
                 $cookingType = new CookingType();
                 $cookingType->name = $cookbook['category'][$j];
                 $cookingType->category = '標簽';
                 $cookingType->operator = $admin['name'];
                 $cookingType->accountId = $accountId;
                 $cookingType->save();
             }
         }
     }
     /*if (isset($cookbook['restaurantName']) && $cookbook['restaurantName'] != '' && self::checkExist($accountId, $cookbook['restaurantName'])) {
           $cookingType = new CookingType();
           $cookingType->name = $cookbook['restaurantName'];
           $cookingType->category = '餐廳';
           $cookingType->operator = $admin['name'];
           $cookingType->accountId = $accountId;
           $cookingType->save();
       }*/
     if (isset($cookbook['subCategory'])) {
         for ($j = 0; $j < count($cookbook['subCategory']); $j++) {
             if (self::checkExist($accountId, $cookbook['subCategory'][$j])) {
                 $cookingType = new CookingType();
                 $cookingType->name = $cookbook['subCategory'][$j];
                 $cookingType->category = '標簽';
                 $cookingType->operator = $admin['name'];
                 $cookingType->accountId = $accountId;
                 $cookingType->save();
             }
         }
     }
     if (isset($cookbook['tag'])) {
         for ($j = 0; $j < count($cookbook['tag']); $j++) {
             if (self::checkExist($accountId, $cookbook['tag'][$j])) {
                 $cookingType = new CookingType();
                 $cookingType->name = $cookbook['tag'][$j];
                 $cookingType->category = '標簽';
                 $cookingType->operator = $admin['name'];
                 $cookingType->accountId = $accountId;
                 $cookingType->save();
             }
         }
     }
     if (isset($cookbook['cuisineType'])) {
         for ($j = 0; $j < count($cookbook['cuisineType']); $j++) {
             if (self::checkExist($accountId, $cookbook['cuisineType'][$j])) {
                 $cookingType = new CookingType();
                 $cookingType->name = $cookbook['cuisineType'][$j];
                 $cookingType->category = '標簽';
                 $cookingType->operator = $admin['name'];
                 $cookingType->accountId = $accountId;
                 $cookingType->save();
             }
         }
     }
     return ['code' => 200, 'msg' => 'Update types success!'];
 }
 /**
  * Create Questionnaire.
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/content/questionnaires<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for creating questionnaire.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     name: string<br/>
  *     startTime: string, startTime = "1429000112193"<br/>
  *     endTime: string, endTime = "1429000112193"<br/>
  *     description: string<br/>
  *     question:Array, question = [{"title": "math","type": "radio","order": 0,"options": [{"icon":
  *              "support","content": "A option" },{"icon": "support","content": "B option"}]},{"type":
  *              "input","order": 1,"title": "This is a problem"}]<br/>
  *     isPublished: boolean<br/>
  *
  * <b>Response Params:</b><br/>
  *     {
  *           "name": "name",
  *           "startTime": "1429000112193",
  *           "endTime": "1429000116193",
  *           "description": "good",
  *           "question": [
  *               {
  *                   "title": "math",
  *                   "type": "radio",
  *                   "order": 0,
  *                   "options": [
  *                       {
  *                           "icon": "support",
  *                           "content": "A option"
  *                       },
  *                       {
  *                           "icon": "support",
  *                           "content": "B option"
  *                       }
  *                   ]
  *               },
  *               {
  *                   "type": "input",
  *                   "order": 1,
  *                   "title": "This is a problem"
  *               }
  *           ],
  *           "isPublished": false
  *       }
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * {
  *     "message": "OK",
  *     "data": ""
  * }
  * <pre>
  * </pre>
  */
 public function actionCreate()
 {
     $params = $this->getParams();
     if (!isset($params['name']) || empty($params['startTime']) || empty($params['endTime']) || !isset($params['isPublished'])) {
         throw new InvalidParameterException(Yii::t('common', 'parameters_missing'));
     }
     Questionnaire::isNameExist($params['name']);
     $params['startTime'] = new \MongoDate(TimeUtil::ms2sTime($params['startTime']));
     $params['endTime'] = new \MongoDate(TimeUtil::ms2sTime($params['endTime']));
     $token = $this->getAccessToken();
     $tokenInfo = Token::getToken($token);
     $accountId = $tokenInfo['userId'];
     $params['accountId'] = $tokenInfo['accountId'];
     $condition = [];
     $question = [];
     $questionIds = [];
     $options = [];
     $questionTitles = [];
     if (!empty($params['question']) && count($params['question']) > 0) {
         foreach ($params['question'] as $questionInfo) {
             $questionId = new MongoId();
             $questionIds[] = $questionId;
             Question::checkTitle($questionInfo['title']);
             $question = ['_id' => $questionId, 'type' => $questionInfo['type'], 'title' => $questionInfo['title'], 'order' => $questionInfo['order'], 'createdAt' => new \MongoDate(), 'accountId' => $accountId];
             if (strcasecmp($questionInfo['type'], Question::TYPE_INPUT) != 0) {
                 if (is_array($questionInfo['options'])) {
                     if (Question::isQuestionOptionRepeat($questionInfo['options']) != null) {
                         $question['options'] = $questionInfo['options'];
                     }
                 }
             }
             if (in_array($question['title'], $questionTitles)) {
                 throw new InvalidParameterException(Yii::t('content', 'question_incorrect'));
             }
             $questionTitles[] = $question['title'];
             $condition[] = $question;
         }
         $isSaveQuestions = Question::saveQuestions($condition);
         if (!$isSaveQuestions) {
             throw new ServerErrorHttpException(Yii::t('common', 'save_fail'));
         }
     }
     $account = User::findOne(['_id' => new MongoId($accountId)]);
     $questionnaire = new Questionnaire();
     $questionnaire->name = $params['name'];
     $questionnaire->startTime = $params['startTime'];
     $questionnaire->endTime = $params['endTime'];
     $questionnaire->description = !isset($params['description']) ? '' : $params['description'];
     $questionnaire->creator = ['id' => $account['_id'], 'name' => !isset($account['name']) ? '' : $account['name']];
     $questionnaire->questions = $questionIds;
     $questionnaire->accountId = $params['accountId'];
     $questionnaire->isPublished = $params['isPublished'];
     $questionnaire->createdAt = new \MongoDate();
     if (!$questionnaire->save()) {
         throw new ServerErrorHttpException(Yii::t('common', 'save_fail'));
     } else {
         return ["message" => "OK", "data" => ""];
     }
 }
Exemplo n.º 17
0
 /**
  * Get tokenInfo from mongo
  *
  * <b>Request Type </b>:GET
  * <b>Request Endpoints </b>: http://{server-domain}/api/site/get-accesstoken
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for getting tokenInfo from mongo
  *
  * <b>Request Example </b>:
  * <pre>
  *  http://{server-domain}/api/site/get-accesstoken
  * </pre>
  *
  **/
 public function actionGetAccesstoken()
 {
     $token = $this->getAccessToken();
     $tokenInfo = Token::getToken($token);
     if (empty($tokenInfo)) {
         return ['tokenInfo' => null];
     } else {
         return ['tokenInfo' => $tokenInfo];
     }
 }