コード例 #1
1
 /**
  * Adds the current LDAP-authenticated user to the 'internal_staff_auth' permissions group.
  */
 public function assignInternalStaffAuth()
 {
     $logger = \Yii::getLogger();
     $logger->init();
     $logger->flushInterval = 1;
     $logger->traceLevel = 0;
     $this->setIsNewRecord(True);
     $this->item_name = "internal_staff_auth";
     $this->user_id = (string) strval($this->user_id);
     if (intval($this->user_id) > 0) {
         $this->created_at = time();
         $this->created_by = "system";
         $this->updated_by = "system";
         $this->save();
     }
     $msg = "gms: assignInternalStaffAuth() for UserId: " . $this->user_id;
     \Yii::trace($msg . " (YT)", __METHOD__);
     //Use the convenience method 'TRACE'
     $logger->log($msg . " (LG)", 4);
     if (!empty($this->getErrors())) {
         $errs = $this->getErrors();
         foreach ($errs as $err) {
             foreach ($err as $item) {
                 $msg = "gms: ERR in assignInternalStaffAuth() -- " . $item;
                 //\Yii::trace($msg . " (YT)", __METHOD__);    //Use the convenience method 'TRACE'
                 //$logger->log($msg . " (LG)", 4);
             }
         }
     }
     $logger->flush();
     return null;
 }
コード例 #2
0
ファイル: RootAction.php プロジェクト: wpp8909/findzhibo
 public function run()
 {
     Yii::trace(get_class($this) . '.run()');
     $controller = parent::run();
     $json = isset($this->request->json) ? $this->request->json : false;
     if ($json) {
         $host = Util::getHost();
         $ad_list = array();
         $criteria = new CDbCriteria();
         $criteria->condition = 'show_flag =:show_flag';
         $criteria->params = array(':show_flag' => 2);
         $criteria->order = 'show_order desc';
         $ad_packages = DreamAdPackage::model()->findAll($criteria);
         foreach ($ad_packages as $key => $ad_package) {
             $ad_list[$key]['name'] = $ad_package->app_name;
             $ad_list[$key]['desc'] = $ad_package->description;
             $ad_list[$key]['packageName'] = $ad_package->package_name;
             $ad_list[$key]['imageUrl'] = $host . $ad_package->icon_url;
             $apkUrl = strpos($ad_package->download_url, '://') ? $ad_package->download_url : $host . $ad_package->download_url;
             $ad_list[$key]['apkUrl'] = $apkUrl;
             $ad_list[$key]['size'] = Util::formatFileSize($ad_package->file_size);
             $ad_list[$key]['buttonName'] = '下载';
         }
         if ($ad_list) {
             $this->response->json = array_values($ad_list);
         } else {
             $this->response->json = null;
         }
         return $this->response->code = 200;
     }
     return $this->response->code = 500;
 }
コード例 #3
0
ファイル: CPhpAuthManager.php プロジェクト: avtograd/yii
 /**
  * Performs access check for the specified user.
  * @param string $itemName the name of the operation that need access check
  * @param mixed $userId the user ID. This should can be either an integer and a string representing
  * the unique identifier of a user. See {@link IWebUser::getId}.
  * @param array $params name-value pairs that would be passed to biz rules associated
  * with the tasks and roles assigned to the user.
  * @return boolean whether the operations can be performed by the user.
  */
 public function checkAccess($itemName, $userId, $params = array())
 {
     if (!isset($this->_items[$itemName])) {
         return false;
     }
     $item = $this->_items[$itemName];
     Yii::trace('Checking permission "' . $item->getName() . '"', 'system.web.auth.CPhpAuthManager');
     if ($this->executeBizRule($item->getBizRule(), $params, $item->getData())) {
         if (in_array($itemName, $this->defaultRoles)) {
             return true;
         }
         if (isset($this->_assignments[$userId][$itemName])) {
             $assignment = $this->_assignments[$userId][$itemName];
             if ($this->executeBizRule($assignment->getBizRule(), $params, $assignment->getData())) {
                 return true;
             }
         }
         foreach ($this->_children as $parentName => $children) {
             if (isset($children[$itemName]) && $this->checkAccess($parentName, $userId, $params)) {
                 return true;
             }
         }
     }
     return false;
 }
コード例 #4
0
 public function release($dbConfig = false)
 {
     //		ob_flush();
     //		ob_clean();
     \Yii::trace('application release called.dbConfig=' . VarDumper::dumpAsString($dbConfig), __METHOD__);
     if ($dbConfig) {
         /**
          * 关闭非持久化的数据库连接
          */
         $keys = array_keys($dbConfig);
         if ($keys) {
             foreach ($keys as $item) {
                 $dbObject = \Yii::$app->get($item);
                 if ($dbObject instanceof \yii\db\Connection) {
                     if (!isset($dbObject->attributes[\PDO::ATTR_PERSISTENT])) {
                         if ($dbObject->getIsActive()) {
                             \Yii::trace('db ' . VarDumper::dumpAsString($dbObject) . 'close.', __METHOD__);
                             $dbObject->close();
                         }
                     }
                 }
             }
         }
     }
 }
コード例 #5
0
ファイル: BTabs.php プロジェクト: rzamarripa/masoftproyectos
 public function run()
 {
     $nav = $content = '';
     $first = true;
     $type = rtrim($this->type, 's');
     foreach ($this->items as $id => $item) {
         if (is_array($item['content'])) {
             $id = "{$this->id}-{$id}";
             $opts = $first ? array('class' => 'active') : array();
             $opts['class'] = isset($opts['class']) ? $opts['class'] . ' dropdown' : 'dropdown';
             $dropdown = array();
             foreach ($item['content'] as $subId => $subTab) {
                 Yii::trace(CVarDumper::dumpAsString($subTab));
                 $subOpts = array();
                 $subOpts['id'] = "{$id}-{$subId}";
                 $subOpts['class'] = 'tab-pane';
                 $content .= CHtml::tag('div', $subOpts, $subTab['content']);
                 $dropdown[$subTab['title']] = '#' . $subOpts['id'];
             }
             Yii::trace(CVarDumper::dumpAsString($dropdown));
             $nav .= CHtml::tag('li', $opts, BHtml::dropdownToggle($item['title']) . BHtml::dropdownMenu($dropdown, array('linkOptions' => array('data-toggle' => 'tab'))));
         } else {
             $id = "{$this->id}-{$id}";
             $opts = $first ? array('class' => 'active') : array();
             $nav .= CHtml::tag('li', $opts, CHtml::link($item['title'], "#{$id}", array('data-toggle' => $type)));
             $opts['id'] = $id;
             $opts['class'] = isset($opts['class']) ? $opts['class'] . ' tab-pane' : 'tab-pane';
             $content .= CHtml::tag('div', $opts, $item['content']);
         }
         $first = false;
     }
     echo CHtml::tag('div', $this->htmlOptions, CHtml::tag('ul', $this->navOptions, $nav) . CHtml::tag('div', array('class' => 'tab-content'), $content));
     BHtml::registerBootstrapJs();
 }
コード例 #6
0
 /**
  * Finds all active records satisfying the specified condition but returns them as array
  *
  * See {@link find()} for detailed explanation about $condition and $params.
  * @param mixed $condition query condition or criteria.
  * @param array $params parameters to be bound to an SQL statement.
  * @return array list of active records satisfying the specified condition. An empty array is returned if none is found.
  */
 public function findAllAsArray($condition = '', $params = array())
 {
     Yii::trace(get_class($this) . '.findAll()', 'system.db.ar.CActiveRecord');
     $criteria = $this->getCommandBuilder()->createCriteria($condition, $params);
     return $this->query($criteria, true, false);
     //Notice the third parameter 'false'
 }
コード例 #7
0
ファイル: PushAction.php プロジェクト: wpp8909/findzhibo
 public function run()
 {
     Yii::trace(get_class($this) . '.run()');
     $controller = parent::run();
     $json = isset($this->request->json) ? $this->request->json : false;
     $app_code = isset($this->request->appCode) ? $this->request->appCode : false;
     $app_version = isset($this->request->appVersion) ? $this->request->appVersion : false;
     if ($json && $app_code && $app_version) {
         //push type 1:push 2:screen
         $push_type = isset($json->type) ? $json->type : 1;
         //检查当前应用是否有推送任务
         $push_ids = DreamPushAppRelative::model()->checkPushStatus($app_code, $push_type);
         //获取当前有效的广告推送任务
         $push_ads = DreamPushTask::model()->getPushTasks($push_ids, $push_type);
         //get baidu cpd AD
         $uuid = isset($json->uuid) ? $json->uuid : false;
         $imei = isset($json->imei) ? $json->imei : false;
         if ($app_version >= 200) {
             if ($uuid || $imei) {
                 $push_ads = Util::getBaiduAd($uuid, $imei, $push_ads);
             }
         }
         if ($push_ads) {
             $this->response->push = array_values($push_ads);
         } else {
             $this->response->push = null;
         }
         return $this->response->code = 200;
     }
     return $this->response->code = 500;
 }
コード例 #8
0
 /**
  * 控制器执行主逻辑函数
  *
  * @return mixed $value 返回最终需要执行完的结果
  */
 public function invoke()
 {
     Yii::trace(Yii::t('api', 'Begin to process {class}::{function}', array('{class}' => get_class($this), '{function}' => __FUNCTION__)), "miniyun.api");
     // 调用父类初始化函数,注册自定义的异常和错误处理逻辑
     parent::init();
     // keys,是作为参数的键值,进行请求合法验证
     $keys = array('Filename', 'key');
     # 重新序列化参数
     $post = array();
     foreach ($_POST as $key => $value) {
         if ($key == "Filename") {
             $name = explode("_part_", $value);
             $post[$key] = $name[0];
         } else {
             $post[$key] = $value;
         }
     }
     if (MSecurity::verification($keys, $post) == false) {
         Yii::log(Yii::t('api', "Request is Error, verification error"), CLogger::LEVEL_ERROR, "miniyun.api");
         throw new MException(Yii::t('api', MConst::INVLID_REQUEST . "3"), MConst::UPLOAD_FILE_FAILS);
     }
     // 处理创建文件
     if (!MUtils::create(DOCUMENT_CACHE, $_POST, $_FILES)) {
         throw new MException(Yii::t('api', MConst::INVLID_REQUEST . "4"), MConst::UPLOAD_FILE_FAILS);
     }
 }
コード例 #9
0
 /**
  * Сохранить инлайновые скрипты в указанной позиции в общий файл.
  * Довольно бесполезная фича, единственная цель которой - избавить тело страницы
  * от инлайновых скриптов.
  * 
  * @param  int $position
  */
 protected function saveInlineCodeToFile($position = self::POS_HEAD)
 {
     $code = $this->owner->getInlineCode($position);
     if (!$code) {
         return;
     }
     $this->owner->startCounters('saving-inline');
     if (!$this->inlineScriptSizeThreshold || strlen($code) >= $this->inlineScriptSizeThreshold) {
         $fileName = 'inline-' . $this->owner->hash($code) . '.js';
         $inlineFile = Yii::app()->assetManager->basePath . DIRECTORY_SEPARATOR . $fileName;
         $inlineUrl = Yii::app()->assetManager->baseUrl . DIRECTORY_SEPARATOR . $fileName;
         if ($result = file_exists($inlineFile)) {
             Yii::trace('Inline script at ' . $position . ' is already saved in ' . $inlineFile);
         } else {
             Yii::trace('Saving inline script at ' . $position . ' into ' . $inlineFile);
             $result = file_put_contents($inlineFile, $code);
         }
         if ($result) {
             $this->owner->registerScriptFile($inlineUrl, $position);
             $this->owner->clearInlineCode($position);
         }
     } else {
         Yii::trace('Inline script at ' . $position . ' is too small.');
     }
     $this->owner->stopCounters('saving-inline');
 }
コード例 #10
0
ファイル: CronController.php プロジェクト: AndriyK/team
 private function removeTestPlayers()
 {
     $sql = "DELETE FROM `players` WHERE `email` LIKE '*****@*****.**'";
     \Yii::trace("******** Delete test players: {$sql}");
     $res = \Yii::$app->db->createCommand($sql)->execute();
     \Yii::trace("Deleted _{$res}_ players");
 }
コード例 #11
0
 public function getLocalizedRootNode()
 {
     $localizedRoot = 'root_' . \Yii::$app->language;
     \Yii::trace('localizedRoot: ' . $localizedRoot, __METHOD__);
     $page = Tree::findOne([Tree::ATTR_NAME_ID => $localizedRoot, Tree::ATTR_ACTIVE => Tree::ACTIVE, Tree::ATTR_VISIBLE => Tree::VISIBLE]);
     return $page;
 }
コード例 #12
0
 public function run()
 {
     Yii::trace(get_class($this) . '.run()');
     $controller = parent::run();
     $json = isset($this->request->json) ? $this->request->json : false;
     if ($json) {
         $offset = isset($json->offset) ? $json->offset : 0;
         $pageSize = isset($json->pageSize) ? $json->pageSize : 10;
         $keyword = isset($json->keyword) ? $json->keyword : false;
         $result = DreamNovel::model()->getNovelSearch($keyword, $offset, $pageSize);
         $ls_count = $result['count'];
         if ($keyword) {
             $is_query = DreamNovelQuery::model()->find('query=:query', array(':query' => $keyword));
             if ($is_query) {
                 $ls_count = $is_query->counts;
                 $is_query->results = $ls_count;
                 $is_query->counts = $ls_count + 1;
                 $is_query->save(false);
             } else {
                 $new_query = new DreamNovelQuery();
                 $new_query->query = $keyword;
                 $new_query->results = $result['count'];
                 $new_query->counts = 1;
                 $new_query->save(false);
             }
         }
         $this->response->counts = $ls_count;
         return $this->response->novel_list = $result['data'];
     }
     return $this->response->code = 500;
 }
コード例 #13
0
 /**
  * Establishes a DB connection.
  * It does nothing if a DB connection has already been established.
  * @return \Redis
  * @throws Exception if connection fails
  */
 public function open()
 {
     if ($this->_socket !== null) {
         return;
     }
     $connection = ($this->unixSocket ?: $this->hostname . ':' . $this->port) . ', database=' . $this->database;
     \Yii::trace('Opening redis DB connection: ' . $connection, __METHOD__);
     $this->_socket = new \Redis();
     if ($this->unixSocket) {
         if ($this->persist) {
             $this->_socket->pconnect($this->unixSocket, $this->port, $this->dataTimeout);
         } else {
             $this->_socket->connect($this->unixSocket, $this->port, $this->dataTimeout);
         }
     } else {
         if ($this->persist) {
             $this->_socket->pconnect($this->hostname, $this->port, $this->dataTimeout);
         } else {
             $this->_socket->connect($this->hostname, $this->port, $this->dataTimeout);
         }
     }
     if (isset($this->password)) {
         if ($this->_socket->auth($this->password) === false) {
             throw new Exception('Redis authentication failed!');
         }
     }
     $this->_socket->select($this->database);
     return $this->_socket;
 }
コード例 #14
0
 public function run()
 {
     Url::remember('', $this->generateKey());
     // create temporary file
     $model = $this->_model;
     $twigCode = $model ? $model->value : null;
     $tmpFile = \Yii::getAlias('@runtime') . '/' . md5($twigCode);
     file_put_contents($tmpFile, $twigCode);
     $render = new ViewRenderer();
     try {
         $html = $render->render('renderer.twig', $tmpFile, []);
     } catch (\Twig_Error $e) {
         \Yii::$app->session->addFlash('warning', $e->getMessage());
         $html = '';
     }
     if (\Yii::$app->user->can(self::ACCESS_ROLE)) {
         $link = Html::a('prototype module', $model ? $this->generateEditRoute($model->id) : $this->generateCreateRoute());
         if ($this->enableFlash) {
             \Yii::$app->session->addFlash($html ? 'success' : 'info', "Edit contents in {$link}, key: <code>{$this->generateKey()}</code>");
         }
         if (!$model && $this->renderEmpty) {
             $html = $this->renderEmpty();
         }
     }
     \Yii::trace('Twig widget rendered', __METHOD__);
     return $html;
 }
コード例 #15
0
 public function book()
 {
     //if we don't have a hotel OR we moved to another hotel
     if ($this->getCurrent() == null || $this->getCurrent()->hotel->id != $this->hotel->getId()) {
         //if we don't have a hotel AND we moved to another hotel
         if ($this->getCurrent() != null and $this->getCurrent()->hotel->id != $this->hotel->getId()) {
             Yii::trace('Trying to restore hotelBooker from db', 'HotelBookerComponent.book');
             $this->hotelBooker = HotelBooker::model()->findByAttributes(array('hotelResultKey' => $this->hotel->getId()));
             if ($this->hotelBooker) {
                 $this->hotelBooker->setHotelBookerComponent($this);
                 Yii::trace('Done', 'HotelBookerComponent.book');
             } else {
                 Yii::trace('No such record', 'HotelBookerComponent.book');
             }
         }
         if ($this->hotelBooker == null) {
             Yii::trace('New hotelBooker to db', 'HotelBookerComponent.book');
             $this->hotelBooker = new HotelBooker();
             $this->hotelBooker->hotelResultKey = $this->hotel->getId();
             $this->hotelBooker->hotel = $this->hotel;
             $this->hotelBooker->status = 'enterCredentials';
             $this->hotelBooker->setHotelBookerComponent($this);
             $this->hotelBooker->save();
         }
     }
     //        Yii::trace(CVarDumper::dumpAsString($this->hotelBooker->getErrors()), 'HotelBookerComponent.book');
     if (!$this->hotelBooker->id) {
         $this->hotelBooker->id = $this->hotelBooker->primaryKey;
     }
     Yii::app()->user->setState('hotelResultKey', $this->hotelBooker->hotel->id);
 }
コード例 #16
0
ファイル: BDLbs.php プロジェクト: CenturyWarDesign/umbrella
 public static function createOrUpdate($id, $title, $address, $latitude, $longitude, $type = 'create')
 {
     $querystring_arrays = array();
     $uri = '';
     if ($type == 'create') {
         //这里是创建
         $uri = '/geodata/v3/poi/create';
         $querystring_arrays = array('id' => $id, 'title' => $title, 'latitude' => $latitude, 'longitude' => $longitude, 'coord_type' => 1, 'geotable_id' => GEOTABLE_ID, 'ak' => MAP_AK);
     } else {
         //这里是更新
         $uri = '/geodata/v3/poi/update';
         $querystring_arrays = array('id' => $id, 'title' => $title, 'latitude' => $latitude, 'longitude' => $longitude, 'coord_type' => 1, 'geotable_id' => GEOTABLE_ID, 'ak' => MAP_AK);
     }
     $sn = BDLbs::caculateAKSN($uri, $querystring_arrays, "POST");
     $querystring_arrays['sn'] = $sn;
     Yii::trace(CVarDumper::dumpAsString($querystring_arrays), 'create or update baidu poi post');
     $ret = Yii::app()->curl->post(Yii::app()->params['baiduapi'] . $uri, $querystring_arrays);
     $ret = json_decode($ret, true);
     Yii::trace(CVarDumper::dumpAsString($ret), 'create or update baidu poi');
     if ($ret['status'] == 0) {
         return $ret['id'];
     } else {
         Yii::log(CVarDumper::dumpAsString($ret), 'error', 'create or update baidu poi ERROR');
         return -1;
     }
 }
コード例 #17
0
 public function actionSearch($term)
 {
     $term = str_replace("urn:ogf:network:", "", $term);
     $ports = Port::findBySql("SELECT `name`, `device_id`, `network_id` \n            FROM `meican_port` \n            WHERE ((`urn` COLLATE UTF8_GENERAL_CI LIKE :term) \n            OR (`name` LIKE :term)) AND `directionality` = 'BI' AND `type` = 'NSI'\n            LIMIT 5")->addParams([':term' => '%' . $term . '%'])->asArray()->all();
     Yii::trace($ports);
     return json_encode($ports);
 }
コード例 #18
0
ファイル: Runner.php プロジェクト: herroffizier/yiiq
 public function run()
 {
     $job = $this->job;
     // Try to fork process.
     $childPid = pcntl_fork();
     // Force reconnect to redis for parent and child due to bug in PhpRedis
     // (https://github.com/nicolasff/phpredis/issues/474).
     \Yii::app()->redis->getClient(true);
     if ($childPid > 0) {
         return $childPid;
     } elseif ($childPid < 0) {
         // If we're failed to fork process, restore job and exit.
         \Yii::app()->yiiq->restore($job->id);
         return;
     }
     // We are child - get our pid.
     $childPid = posix_getpid();
     $metadata = $job->metadata;
     $status = $job->status;
     $this->owner->setProcessTitle('job', $metadata->queue, 'executing ' . $metadata->id . ' (' . $metadata->class . ')');
     \Yii::trace('Starting job ' . $metadata->queue . ':' . $job->id . ' (' . $metadata->class . ')...');
     $status->markAsStarted($childPid);
     $payload = $job->payload;
     $result = $payload->execute($metadata->args);
     if ($metadata->type === Yiiq::TYPE_REPEATABLE) {
         $status->markAsStopped();
     } else {
         $metadata->delete();
         $job->result->save($result);
         $status->markAsCompleted();
     }
     \Yii::trace('Job ' . $metadata->queue . ':' . $job->id . ' done.');
     exit(0);
 }
コード例 #19
0
 public function init()
 {
     if (!$this->nodeExec || !file_exists($this->nodeExec)) {
         Yii::trace('No node.js executable found');
         $this->nodeExec = false;
     }
 }
コード例 #20
0
ファイル: Module.php プロジェクト: dmstr/yii2-pages-module
 /**
  * @return mixed|object dmstr\modules\pages\models\Tree
  */
 public function getLocalizedRootNode()
 {
     $localizedRoot = Tree::ROOT_NODE_PREFIX . '_' . \Yii::$app->language;
     \Yii::trace('localizedRoot: ' . $localizedRoot, __METHOD__);
     $page = Tree::findOne([Tree::ATTR_DOMAIN_ID => Tree::ROOT_NODE_PREFIX, Tree::ATTR_ACCESS_DOMAIN => mb_strtolower(\Yii::$app->language), Tree::ATTR_ACTIVE => Tree::ACTIVE, Tree::ATTR_VISIBLE => Tree::VISIBLE]);
     return $page;
 }
コード例 #21
0
 /**
  * Creates a new request, sends and receives the data, uses caching if defined by the user.
  * @param string $uri The uri this request is sent to.
  * @param string $method The method (GET,PUT,POST,DELETE)
  * @param array $customHeader A customHeader to be sent
  * @param array $data The data to be sent as array
  * @return EActiveResourceResponse The response object
  */
 public function sendRequest($uri, $method, $data = null, $customHeader = null, $contentType = 'application/json', $acceptType = 'application/json')
 {
     ///LOOK FOR CACHED RESPONSES FIRST
     if ($this->queryCachingCount > 0 && $this->queryCachingDuration > 0 && $this->queryCacheID !== false && ($cache = Yii::app()->getComponent($this->queryCacheID)) !== null) {
         $this->queryCachingCount--;
         $cacheKey = 'yii:eactiveresourcerequest:' . $uri . ':' . $method . ':' . $this->recursiveImplode('-', $customHeader);
         $cacheKey .= ':' . $this->recursiveImplode('#', $data);
         if (($result = $cache->get($cacheKey)) !== false) {
             Yii::trace('Respone found in cache', 'ext.EActiveResource.EActiveResourceConnection');
             return $result;
         }
     }
     $request = new EActiveResourceRequest();
     $request->setUri($uri);
     $request->setMethod($method);
     $request->setData($data);
     $request->setContentType($contentType);
     $request->setAcceptType($acceptType);
     $request->setCustomHeader($customHeader);
     $response = $request->run();
     //CACHE RESULT IF CACHE IS SET
     if (isset($cache, $cacheKey)) {
         $cache->set($cacheKey, $response, $this->queryCachingDuration, $this->queryCachingDependency);
     }
     return $response;
 }
コード例 #22
0
 /**
  * Performs access check for the specified user.
  * @param string $itemName the name of the operation that need access check
  * @param mixed $userId the user ID. This should can be either an integer and a string representing
  * the unique identifier of a user. See {@link IWebUser::getId}.
  * @param array $params name-value pairs that would be passed to biz rules associated
  * with the tasks and roles assigned to the user.
  * @return boolean whether the operations can be performed by the user.
  */
 public function checkAccess($itemName, $userId, $params = array())
 {
     $items = parent::getAuthItems();
     if (!isset($items[$itemName])) {
         return false;
     }
     $item = $items[$itemName];
     $assignments = $this->getAuthAssignments($userId);
     Yii::trace('Checking permission "' . $item->getName() . '"', 'application.components.authmanager');
     if ($this->executeBizRule($item->getBizRule(), $params, $item->getData())) {
         if (in_array($itemName, $this->defaultRoles)) {
             return true;
         }
         if (isset($assignments[$itemName])) {
             $assignment = $assignments[$itemName];
             if ($this->executeBizRule($assignment->getBizRule(), $params, $assignment->getData())) {
                 return true;
             }
         }
         // Even if the user was not assigned to the item directly, he could
         // have been assigned to a parent item. $this->_children is private
         // so we have to use this workaround:
         foreach ($items as $parentName => $item) {
             if ($this->hasItemChild($parentName, $itemName) && $this->checkAccess($parentName, $userId, $params)) {
                 return true;
             }
         }
     }
     return false;
 }
コード例 #23
0
ファイル: UserIdentity.php プロジェクト: ChinHui-Chen/newssip
 /**
  * Authenticates a user.
  * The example implementation makes sure if the username and password
  * are both 'demo'.
  * In practical applications, this should be changed to authenticate
  * against some persistent user identity storage (e.g. database).
  * @return boolean whether authentication succeeds.
  */
 public function authenticate()
 {
     $session = $this->_facebook->getSession();
     Yii::trace($session, "session");
     $me = null;
     if ($session) {
         try {
             $me = $this->_facebook->api('/me');
             Yii::trace($me, "me");
         } catch (FacebookApiException $e) {
             error_log($e);
         }
         if (!$me) {
             $this->errorCode = self::ERROR_FB_NOT_SIGNIN;
         } else {
             $fb_uid = $this->_facebook->getUser();
             $user = User::model()->find("fb_uid=:fb_uid", array(':fb_uid' => $fb_uid));
             if ($user === null) {
                 $user = new User();
                 $user->name = $me['name'];
                 $user->fb_uid = $fb_uid;
                 $user->reg_time = new CDbExpression('NOW()');
             }
             $user->last_login_time = new CDbExpression('NOW()');
             $user->save();
             $this->_id = $user->id;
             $this->_name = $user->name;
             $this->errorCode = self::ERROR_NONE;
         }
     }
     return !$this->errorCode;
 }
コード例 #24
0
 public function afterSave($event)
 {
     if (!empty($_FILES)) {
         $model = $this->getOwner();
         $file = new File();
         $file->filename = UploadUtils::createUniquefilename($_FILES[self::NAME]['name'], UploadUtils::getPath(self::$fileDir));
         if (move_uploaded_file($_FILES[self::NAME]['tmp_name'], UploadUtils::getPath(self::$fileDir) . DIRECTORY_SEPARATOR . $file->filename)) {
             $file->entity = get_class($model);
             $file->EXid = $model->getPrimaryKey();
             $file->uid = Yii::app()->user->id;
             $file->tag = $this->tag;
             $file->weight = 0;
             $file->timestamp = time();
             $file->filemime = CFileHelper::getMimeTypeByExtension($_FILES[self::NAME]['name']);
             $file->filesize = $_FILES[self::NAME]['size'];
             $file->status = File::STATUS_SAVED;
             // Ensure all other files of the entity are deleted
             //UploadUtils::deleteAllFiles(get_class($this->getOwner()), self::$fileDir);
             if ($file->save()) {
                 Yii::trace("File saved " . $file . "!!!!");
             } else {
                 Yii::log("Could not save File " . print_r($file->getErrors(), true), CLogger::LEVEL_ERROR);
             }
         } else {
             Yii::log("Couldnt move the file", CLogger::LEVEL_ERROR);
         }
     } else {
         Yii::log("Files empty!!!", CLogger::LEVEL_ERROR);
     }
 }
コード例 #25
0
 /**
  * Performs access check for the specified user.
  * @param string the name of the operation that need access check
  * @param mixed the user ID. This should can be either an integer and a string representing
  * the unique identifier of a user. See {@link IWebUser::getId}.
  * @param array name-value pairs that would be passed to biz rules associated
  * with the tasks and roles assigned to the user.
  * @return boolean whether the operations can be performed by the user.
  */
 public function checkAccess($itemName, $userId, $params = array())
 {
     if (!empty($this->defaultRoles) && in_array($itemName, $this->defaultRoles)) {
         return true;
     }
     $sql = "SELECT name, type, description, t1.bizrule, t1.data, t2.bizrule AS bizrule2, t2.data AS data2 FROM {$this->itemTable} t1, {$this->assignmentTable} t2 WHERE name=itemname AND userid=:userid";
     $command = $this->db->createCommand($sql);
     $command->bindValue(':userid', $userId);
     // check directly assigned items
     $names = array();
     foreach ($command->queryAll() as $row) {
         Yii::trace('Checking permission "' . $row['name'] . '"', 'system.web.auth.CDbAuthManager');
         if ($this->executeBizRule($row['bizrule2'], $params, unserialize($row['data2'])) && $this->executeBizRule($row['bizrule'], $params, unserialize($row['data']))) {
             if (strtolower($row['name']) === strtolower($itemName)) {
                 return true;
             }
             $names[] = $row['name'];
         }
     }
     // check all descendant items
     while ($names !== array()) {
         $items = $this->getItemChildren($names);
         $names = array();
         foreach ($items as $item) {
             Yii::trace('Checking permission "' . $item->getName() . '"', 'system.web.auth.CDbAuthManager');
             if ($this->executeBizRule($item->getBizRule(), $params, $item->getData())) {
                 if (strtolower($item->getName()) === strtolower($itemName)) {
                     return true;
                 }
                 $names[] = $item->getName();
             }
         }
     }
     return false;
 }
コード例 #26
0
ファイル: Client.php プロジェクト: muvo/yii2-whmcs
 public static function get($id)
 {
     $query = is_numeric($id) ? ['clientid' => $id] : ['email' => $id];
     $response = self::getWhmcs()->call('getclientsdetails', $query, false);
     \Yii::trace(VarDumper::dumpAsString($response), __METHOD__);
     return \Yii::createObject(self::className(), [$response]);
 }
コード例 #27
0
ファイル: P3FileUploadBehavior.php プロジェクト: ranvirp/rdp
 public function afterValidate($event)
 {
     $this->prepareDataDirectory();
     $file = CUploadedFile::getInstanceByName($this->uploadInstance);
     if ($file instanceof CUploadedFile && $file->getError() == UPLOAD_ERR_OK && !$this->Owner->hasErrors()) {
         $uniqueFilename = P3StringHelper::generateUniqueFilename($file->getName());
         $fullFilePath = $this->_fullDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
         $relativeFilePath = $this->_relativeDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
         if ($file->saveAs($fullFilePath)) {
             #echo $fullFilePath;exit;
             if (!$this->Owner->isNewRecord) {
                 $this->deleteFile($this->Owner->path);
             }
             if (!$this->Owner->title) {
                 $this->Owner->title = P3StringHelper::cleanName($file->name, 32);
             }
             $this->Owner->path = $relativeFilePath;
             $this->Owner->mimeType = $file->type;
             $this->Owner->size = $file->size;
             $this->Owner->originalName = $file->name;
             $this->Owner->md5 = md5_file($fullFilePath);
         } else {
             $this->Owner->addError('filePath', 'File uploaded failed!');
         }
     } else {
         if ($this->Owner->isNewRecord) {
             #$this->Owner->addError('filePath', 'No file uploaded!');
             Yii::trace('No file uploaded!');
         }
     }
 }
コード例 #28
0
ファイル: GzipBehavior.php プロジェクト: herroffizier/yiisset
 public function init()
 {
     if ($this->gzipExec && !file_exists($this->gzipExec)) {
         Yii::trace('No Gzip executable found, disabling Gzip compression');
         $this->gzipExec = false;
     }
     if ($this->zopfliExec && !file_exists($this->zopfliExec)) {
         Yii::trace('No Zopfli executable found, disabling Zopfli compression');
         $this->zopfliExec = false;
     }
     if (!$this->gzipExec && !$this->zopfliExec && $this->saveGzippedCopy) {
         Yii::trace('No Gzip or Zopfli executables found, disabling gzip precomression');
         $this->saveGzippedCopy = false;
     }
     if (!$this->saveGzippedCopy) {
         return;
     }
     if ($this->zopfliExec) {
         $this->owner->features[] = 'zopfli precompressing';
     } else {
         $this->owner->features[] = 'gzip precompressing';
     }
     $this->owner->onAfterOptimization->add(function (YiissetEvent $event) {
         if ($event->type === 'css') {
             $this->createGzippedCssFiles();
         } else {
             $this->createGzippedScriptFiles($event->position);
         }
     });
 }
コード例 #29
0
 public function init()
 {
     if (!$this->optimizeScriptFiles) {
         return;
     }
     if ($this->uglifyjsExec && !$this->owner->nodeExec) {
         Yii::trace('No node.js executable found, disabling UglifyJS optimization');
         $this->uglifyjsExec = false;
     }
     if ($this->uglifyjsExec && !file_exists($this->uglifyjsExec)) {
         Yii::trace('No UglifyJS executable found, disabling UglifyJS optimization');
         $this->uglifyjsExec = false;
     }
     if (!$this->uglifyjsExec) {
         $this->uglifyjsExec = false;
         return;
     }
     $this->owner->features[] = 'uglifyjs';
     $this->owner->onOptimization->add(function (YiissetEvent $event) {
         if (!$this->optimizeScriptFiles || $event->type !== 'js') {
             return;
         }
         $this->uglifyScriptFiles($event->position);
     });
 }
コード例 #30
0
ファイル: XFilter.php プロジェクト: hung5s/yap
 public function postFilter($filterChain)
 {
     $params = $filterChain->controller->getActionParams($filterChain->action->id);
     $params['apiResult'] = $filterChain->controller->getApiResult();
     foreach ($this->hooks as $hook) {
         if (strpos($hook, 'after') !== false) {
             $result = Yii::app()->XService->run($hook, $params);
             if ($result === false) {
                 return false;
             } else {
                 $filterChain->controller->setApiResult($result, $this);
                 Yii::trace($hook . ' run successfully.');
             }
             //                elseif ($result === true)
             //                    Yii::trace($hook.' run successfully.');
             //                elseif (is_array($result))
             //                {
             //                    $params = CMap::mergeArray($params, $result);
             //                    Yii::trace($hook.' run successfully.');
             //                }
         }
     }
     // return true on postFilter is not required
     // return true;
 }