コード例 #1
0
ファイル: ItemController.php プロジェクト: AbuMuhammad/ap3
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUbah($id)
 {
     $model = $this->loadModel($id);
     $child = new AuthItemChild('search');
     $child->unsetAttributes();
     $child->setAttribute('parent', '=' . $id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['AuthItem'])) {
         $model->attributes = $_POST['AuthItem'];
         $model->save();
     }
     $this->render('ubah', array('model' => $model, 'child' => $child, 'authItem' => $this->_listAuthItem($id)));
 }
コード例 #2
0
ファイル: RbacTree.php プロジェクト: alextravin/yupe
 /**
  * Загрузка данных из бд и распределение их по спискам
  */
 private function getData()
 {
     $userAssign = CHtml::listData(AuthAssignment::model()->findAllByAttributes(['userid' => $this->user->id]), 'itemname', 'userid');
     $authItems = AuthItem::model()->findAll(['order' => 'type DESC, description ASC']);
     foreach ((array) $authItems as $item) {
         $this->itemsGroupedByTypes[$item->type][$item->name] = $item;
         $this->itemsList[$item->name] = $item;
         // если проверять каждый элемент, то генерируется огромное количество запросов, но получается правильное дерево с отмеченными дочерними элементами
         // созможно стоит при сохранении ролей что-то придумать
         $this->permissionList[$item->name] = isset($userAssign[$item->name]);
         //Yii::app()->authManager->checkAccess($item->name, $this->user->id);
     }
     $authItemsChild = AuthItemChild::model()->findAll();
     foreach ((array) $authItemsChild as $item) {
         $this->hierarchy[$item->parent][] = $item->child;
         $this->wereChildren[] = $item->child;
     }
 }
コード例 #3
0
 public function actionManage()
 {
     if (isset($_POST['AuthItem'])) {
         $items_names = array();
         foreach ($_POST['AuthItem'] as $task_name => $data) {
             p($_POST['AuthItem']);
             die;
             if (!isset($data['description'])) {
                 continue;
             }
             $items_names[] = $task_name;
             if (!isset($data['operations'])) {
                 continue;
             }
             foreach ($data['operations'] as $name => $description) {
                 $items_names[] = $name;
             }
         }
         $items_names = array_map(function ($v) {
             return "'{$v}'";
         }, $items_names);
         $items_names = implode(',', $items_names);
         AuthItem::model()->delete("name NOT IN ({$items_names})");
         foreach ($_POST['AuthItem'] as $task_name => $data) {
             if (!isset($data['description'])) {
                 continue;
             }
             $task = AuthItem::model()->findByPk($task_name);
             if (!$task) {
                 $task = new AuthItem();
                 $task->type = CAuthItem::TYPE_TASK;
                 $task->name = $task_name;
                 $task->description = $data['description'];
             }
             if ($task->save() && isset($data['operations'])) {
                 foreach ($data['operations'] as $name => $description) {
                     $operation = AuthItem::model()->findByPk($name);
                     if (!$operation) {
                         $operation = new AuthItem();
                         $operation->type = CAuthItem::TYPE_OPERATION;
                         $operation->name = $name;
                         $operation->description = $description;
                     }
                     if ($operation->save()) {
                         $auth_item_child = AuthItemChild::model()->findByAttributes(array('parent' => $task->name, 'child' => $operation->name));
                         if (!$auth_item_child) {
                             $auth_item_child = new AuthItemChild();
                             $auth_item_child->parent = $task->name;
                             $auth_item_child->child = $operation->name;
                             $auth_item_child->save();
                         }
                     }
                 }
             }
         }
     }
     $auth_items = array();
     $tasks = $this->getModulesTasks();
     foreach ($tasks as $task) {
         $auth_items[] = array('id' => $task['name'], 'name' => $task['name'], 'exists' => $task['exists'], 'description' => $task['description']);
         if (isset($task['operations'])) {
             foreach ($task['operations'] as $operation) {
                 $operation['parent'] = $task['name'];
                 $operation['id'] = $operation['name'];
                 $auth_items[] = $operation;
             }
         }
     }
     $data_provider = new CArrayDataProvider($auth_items, array('pagination' => false));
     $this->render('manage', array('data_provider' => $data_provider, 'tasks' => $this->getModulesTasks()));
 }
コード例 #4
0
 /**
  * Функция рекурсивно удаляет роль и ее детей.      * 
  * Если дети используются в других ролях, то они только открепляются от текущей роли.
  * Операции не удаляются
  * Задачи только открепляются
  */
 function RemoveAuthItemPortal($AuthItem = '', $authitemparent = '')
 {
     if ($AuthItem === '') {
         throw new CHttpException(500, 'RemoveAuthItemPortal($AuthItem): Отсутствует параметр $AuthItem');
     }
     $auth = Yii::app()->authManager;
     /* Если CAuthItem корневая роль или ее родитель является ролью */
     if ($authitemparent === '' || $auth->getAuthItem($authitemparent)->type === 2) {
         /* $parentsarray = Массив родителей $AuthItem */
         $parentsarray = AuthItemChild::GetItemParent($AuthItem);
         /* Открепляем текущую CAuthItem от родителя, если он есть */
         if ($authitemparent !== '' && count((array) $parentsarray) > 0) {
             $auth->removeItemChild($authitemparent, $AuthItem);
         }
         /* Если после открепления от своего родителя CAuthItem больше не имеет родителей */
         if (count((array) $parentsarray) === 0) {
             /* Создаем список с именами детей текущего CAuthItem */
             $childrenarray = array_keys($auth->getItemChildren($AuthItem));
             /* Идем по детям и применяем рекурсивно текущую функцию */
             foreach ($childrenarray as $childitem) {
                 $this->RemoveAuthItemPortal($childitem, $AuthItem);
             }
             /* Удаляем текущую роль, если она нигде больше не прикреплена */
             if ($auth->getAuthItem($AuthItem)->type === 2) {
                 $auth->removeAuthItem($AuthItem);
             }
         }
     }
 }
コード例 #5
0
ファイル: AuthItem.php プロジェクト: rainyjune/YSMusic
 protected function afterDelete()
 {
     parent::afterDelete();
     AuthAssignment::model()->deleteAll('itemname="' . $this->name . '"');
     AuthItemChild::model()->deleteAll('parent="' . $this->name . '" OR child="' . $this->name . '"');
 }
コード例 #6
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getAuthItemChildren0()
 {
     return $this->hasMany(AuthItemChild::className(), ['child' => 'name']);
 }
コード例 #7
0
ファイル: RbacController.php プロジェクト: ranvirp/rdp
 /**
  * 
  * @desc
  */
 public function actionMove()
 {
     $this->checkAccess('RbacViewer', true);
     if (!empty($_POST)) {
         $this->checkAccess('RbacEditor', true);
         $from = isset($_POST['moveFromItem']) ? $_POST['moveFromItem'] : null;
         $to = isset($_POST['moveToItem']) ? $_POST['moveToItem'] : null;
         // check only if parent is protected
         if (in_array($to, $this->protectedItems)) {
             if (in_array($from, $this->protectedItems)) {
                 $this->messageErrors[] = "Sorry, Item is protected by Controller";
                 $this->actionIndex();
             }
         }
         if (!$from || !$to || $from == $to) {
             $this->messageErrors[] = "Please select Parent- and Childitem and care that they are not same.";
             $this->actionIndex();
         }
         // default validate
         $model = new AuthItemChild();
         $model->attributes = array('child' => $from, 'parent' => $to);
         if (!$model->validate()) {
             $this->messageErrors[] = "Post validation Error. Please mail Siteadmin if this Error returns.";
             $this->actionIndex();
         }
         // check if branch already exists
         if ($model->findByAttributes(array('child' => $from, 'parent' => $to)) !== null) {
             $this->messageErrors[] = "Create Brunch Error: Brunch already exists.";
             $this->actionIndex();
         }
         // Items exist?
         $model = new AuthItem();
         if (!count($model->findByAttributes(array('name' => $from))) || !count($model->findByAttributes(array('name' => $to)))) {
             $this->messageErrors[] = "Check Items exists Error. Please mail Siteadmin if this Error returns.";
             $this->actionIndex();
         }
         // make recursioncheck and move Items
         $model = new RBACTree();
         $model->moveFrom = $from;
         $model->moveTo = $to;
         if ($model->checkRecursion()) {
             $model->moveItem();
             $this->messageSuccess[] = "Item {$from} successfull moved to {$to}.";
         } else {
             $this->messageErrors[] = "Can't move Selection cause that will produce a Recursion.\n\t\t\t\t<br>If you can't see producing a Recursion, it may help to eject Item before moving it.";
             $this->actionIndex();
         }
     }
     $this->actionIndex();
 }
コード例 #8
0
 /**
  * adding auth item child relationships
  */
 public function actionAddItemChild()
 {
     // Check Access
     checkAccessThrowException('op_permission_add_item_child');
     $model = new AuthItemChild();
     $roles = AuthItem::model()->findAll(array('order' => 'type DESC, name ASC'));
     $_roles = array();
     if (count($roles)) {
         foreach ($roles as $role) {
             $_roles[AuthItem::model()->types[$role->type]][$role->name] = $role->description . ' (' . $role->name . ')';
         }
     }
     // Did we choose a parent already?
     if (isset($_GET['parent']) && $_GET['parent'] != '') {
         $model->parent = $_GET['parent'];
     }
     if (isset($_POST['AuthItemChild'])) {
         if (isset($_POST['AuthItemChild']['child']) && count($_POST['AuthItemChild']['child'])) {
             // We need to delete all child items selected up until now
             $existsalready = AuthItemChild::model()->findAll('parent=:parent', array(':parent' => $model->parent));
             if (count($existsalready)) {
                 foreach ($existsalready as $existitem) {
                     Yii::app()->authManager->removeItemChild($existitem->parent, $existitem->child);
                 }
             }
             $added = 0;
             foreach ($_POST['AuthItemChild']['child'] as $childItem) {
                 $model->child = $childItem;
                 if ($model->validate()) {
                     $added++;
                 }
             }
             // Get model parent
             $authItem = AuthItem::model()->find('name=:name', array(':name' => $model->parent));
             fok(at('{number} Child item(s) Added.', array('{number}' => $added)));
             // Log Message
             alog(at("Added {number} child items for {name}", array('{number}' => $added, '{name}' => $model->parent)));
             if ($authItem) {
                 $this->redirect(array('view', 'id' => $authItem->id, '#' => 'tabs-2'));
             } else {
                 $this->redirect(array('index'));
             }
         }
     }
     // Selected values
     $selected = AuthItemChild::model()->findAll('parent=:parent', array(':parent' => $model->parent));
     $_selected = array();
     if (count($selected)) {
         foreach ($selected as $select) {
             $_selected[] = $select->child;
         }
     }
     $model->child = $_selected;
     // Add Breadcrumb
     $this->addBreadCrumb(at('Adding Child Permissions'));
     $this->title[] = at('Adding Child Permissions');
     $this->render('child_form', array('model' => $model, 'roles' => $_roles));
 }
コード例 #9
0
 /**
  * View auth item action
  */
 public function actionviewauthitem()
 {
     // Perms
     if (!Yii::app()->user->checkAccess('op_roles_add_auth')) {
         throw new CHttpException(403, Yii::t('error', 'Sorry, You don\'t have the required permissions to enter this section'));
     }
     $parent = isset($_GET['parent']) && $_GET['parent'] != '' ? $_GET['parent'] : null;
     if (!$parent) {
         Yii::app()->user->setFlash('error', Yii::t('adminroles', 'Could not find that item.'));
         $this->redirect(array('roles/index'));
     }
     // Load members and display
     $criteria = new CDbCriteria();
     $criteria->condition = "parent='{$parent}'";
     $count = AuthItemChild::model()->count("parent='{$parent}'");
     $pages = new CPagination($count);
     $pages->pageSize = self::PAGE_SIZE;
     $pages->applyLimit($criteria);
     $sort = new CSort('AuthItemChild');
     $sort->defaultOrder = 'parent ASC';
     $sort->applyOrder($criteria);
     $sort->attributes = array('parent' => 'parent', 'child' => 'child');
     $roles = AuthItemChild::model()->findAll($criteria);
     $this->breadcrumbs[Yii::t('adminroles', 'Viewing Child Items')] = '';
     $this->pageTitle[] = Yii::t('adminroles', 'Viewing Child Items');
     $this->render('item_childs', array('rows' => $roles, 'pages' => $pages, 'sort' => $sort, 'count' => $count));
 }
コード例 #10
0
ファイル: extention.php プロジェクト: AxelPanda/ibos
<?php

Nav::model()->deleteAllByAttributes(array("module" => "workflow"));
Notify::model()->deleteAllByAttributes(array("module" => "workflow"));
NotifyMessage::model()->deleteAllByAttributes(array("module" => "workflow"));
CacheUtil::set("notifyNode", null);
Node::model()->deleteAllByAttributes(array("module" => "workflow"));
NodeRelated::model()->deleteAllByAttributes(array("module" => "workflow"));
AuthItem::model()->deleteAll("name LIKE 'workflow%'");
AuthItemChild::model()->deleteAll("child LIKE 'workflow%'");
MenuCommon::model()->deleteAllByAttributes(array("module" => "workflow"));
$settingFields = "wfremindbefore,wfremindafter,sealfrom";
Setting::model()->deleteAll("FIND_IN_SET(skey,'{$settingFields}')");
Menu::model()->deleteAllByAttributes(array("m" => "workflow"));
Nav::model()->deleteAllByAttributes(array("module" => "workflow"));
Node::model()->deleteAllByAttributes(array("module" => "workflow"));
NodeRelated::model()->deleteAllByAttributes(array("module" => "workflow"));
AuthItem::model()->deleteAll("name LIKE 'workflow%'");
AuthItemChild::model()->deleteAll("child LIKE 'workflow%'");
$db = Ibos::app()->db->createCommand();
$prefix = $db->getConnection()->tablePrefix;
$tables = $db->setText("SHOW TABLES LIKE '" . str_replace("_", "\\_", $prefix . "flow_data_%") . "'")->queryAll(false);
foreach ($tables as $table) {
    $tableName = $table[0];
    !empty($tableName) && $db->dropTable($tableName);
}
コード例 #11
0
 public function actionImport()
 {
     $modulesList = [];
     $modules = [];
     foreach (Yii::app()->getModules() as $key => $value) {
         $key = strtolower($key);
         $module = Yii::app()->getModule($key);
         if ($module instanceof \yupe\components\WebModule) {
             $modulesList[$key] = $module->getName();
             $modules[$key] = $module;
         }
     }
     if (Yii::app()->getRequest()->isPostRequest) {
         $importModules = array_intersect(Yii::app()->getRequest()->getPost('modules', []), array_keys($modules));
         foreach ($importModules as $moduleName) {
             /* @var $module \yupe\components\WebModule */
             $module = $modules[$moduleName];
             $rules = $module->getAuthItems();
             // 1 - получить все элементы из дерева
             $items = $this->getRulesList($rules);
             $parentsChildren = $this->getRulesParentsAndChildren($items);
             // обновляем
             foreach ($items as $item) {
                 $model = AuthItem::model()->findByPk($item['name']);
                 if (!$model) {
                     $model = new AuthItem();
                 }
                 $model->attributes = $item;
                 $model->save();
             }
             // удаляем удаленные из модуля
             // оставшиеся
             $availableItems = array_map(function ($x) {
                 return $x['name'];
             }, $items);
             /* удаляем правила */
             $criteria = new CDbCriteria();
             $criteria->addCondition('name like :rule');
             $criteria->params = [':rule' => ucfirst($moduleName) . '.%'];
             $criteria->addNotInCondition('name', $availableItems);
             AuthItem::model()->deleteAll($criteria);
             /* создаем связи */
             foreach ($parentsChildren as $pair) {
                 $model = AuthItemChild::model()->findByPk(['parent' => $pair['parent'], 'child' => $pair['child']]);
                 if (!$model) {
                     $model = new AuthItemChild();
                     $model->attributes = $pair;
                     $model->save();
                 }
             }
         }
         Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('RbacModule.rbac', 'Items successfully imported!'));
         $this->redirect(['import']);
     }
     $this->render('import', ['modules' => $modulesList]);
 }
コード例 #12
0
ファイル: PositionController.php プロジェクト: AxelPanda/ibos
 private function updateAuthItem($positionId, $authItem = array(), $dataVal = array())
 {
     if (!empty($authItem)) {
         $nodes = Node::model()->fetchAllSortByPk("id");
         NodeRelated::model()->deleteAllByPositionId($positionId);
         $auth = Ibos::app()->authManager;
         $role = $auth->getAuthItem($positionId);
         if ($role === null) {
             $role = $auth->createRole($positionId, "", "", "");
         }
         AuthItemChild::model()->deleteByParent($positionId);
         foreach ($authItem as $key => $nodeId) {
             $node = $nodes[$key];
             if (strcasecmp($key, $nodeId) !== 0 && $nodeId === "data") {
                 $vals = $dataVal[$key];
                 if (is_array($vals)) {
                     NodeRelated::model()->addRelated("", $positionId, $node);
                     foreach ($vals as $id => $val) {
                         $childNode = Node::model()->fetchByPk($id);
                         NodeRelated::model()->addRelated($val, $positionId, $childNode, $id);
                         AuthUtil::addRoleChildItem($role, $childNode, explode(",", $childNode["routes"]));
                     }
                 }
             } else {
                 NodeRelated::model()->addRelated("", $positionId, $node);
                 $routes = explode(",", $node["routes"]);
                 AuthUtil::addRoleChildItem($role, $node, $routes);
             }
         }
     }
 }
コード例 #13
0
ファイル: extention.php プロジェクト: AxelPanda/ibos
<?php

$settingFields = "emailexternalmail,emailrecall,emailsystemremind,emailroleallocation,emaildefsize";
Setting::model()->deleteAll("FIND_IN_SET(skey,'{$settingFields}')");
Setting::model()->updateSettingValueByKey("emailtableids", "a:2:{i:0;i:0;i:1;i:1;}");
Setting::model()->updateSettingValueByKey("emailtable_info", "a:2:{i:0;a:1:{s:4:\"memo\";s:0:\"\";}i:1;a:2:{s:4:\"memo\";s:0:\"\";s:11:\"displayname\";s:12:\"默认归档\";}}");
Nav::model()->deleteAllByAttributes(array("module" => "email"));
Menu::model()->deleteAllByAttributes(array("m" => "email"));
MenuCommon::model()->deleteAllByAttributes(array("module" => "email"));
Notify::model()->deleteAllByAttributes(array("node" => "email_message"));
NotifyMessage::model()->deleteAllByAttributes(array("module" => "email"));
CacheUtil::set("notifyNode", null);
Node::model()->deleteAllByAttributes(array("module" => "email"));
NodeRelated::model()->deleteAllByAttributes(array("module" => "email"));
AuthItem::model()->deleteAll("name LIKE 'email%'");
AuthItemChild::model()->deleteAll("child LIKE 'email%'");
$db = Ibos::app()->db->createCommand();
$prefix = $db->getConnection()->tablePrefix;
$tables = $db->setText("SHOW TABLES LIKE '" . str_replace("_", "\\_", $prefix . "email_%") . "'")->queryAll(false);
foreach ($tables as $table) {
    $tableName = $table[0];
    !empty($tableName) && $db->dropTable($tableName);
}
コード例 #14
0
 /**
  * Assigning Operations/Tasks to the User Roles/Groups of the Sysytem
  */
 public function actionAssignItems($name)
 {
     if (isset($_POST['submit'])) {
         $clear = AuthItemChild::clearAll($name);
         $auth = Yii::app()->authManager;
         //Initialing The Authentication Manager
         $role = $auth->getAuthItem($name);
         if (isset($_POST['name'])) {
             foreach ($_POST['name'] as $var) {
                 if ($var != 1) {
                     $role->addChild($var);
                     //Elements Checked
                     $this->logAudit("Action " . $var . " was assigned to role " . $name);
                 }
             }
         }
         $success = "<div class='success'><p class='success'>Actions were added successfully...</p></div>";
         Yii::app()->user->setFlash('success', $success);
     } else {
         $success = "<div class='failure'><p class='failure'>Please,select atleast one action for the Group...</p></div>";
         Yii::app()->user->setFlash('success', $success);
     }
     $dataProvider = AuthItem::getItems();
     $this->render('batch', array('dataProvider' => $dataProvider, 'name' => $name));
 }
コード例 #15
0
ファイル: AuthItem.php プロジェクト: YiiCoded/yii-ecommerce
 public function getChildsCount()
 {
     return AuthItemChild::model()->count('parent=:name', array(':name' => $this->name));
 }
コード例 #16
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = AuthItem::model()->with('parents.parentItem')->findByPk($id);
     $operationsList = $tasksList = $listModels = array();
     if ($model->type == AuthItem::TYPE_TASK) {
         $operations = AuthItem::model()->findAll('type = :type', array(':type' => AuthItem::TYPE_OPERATION));
         foreach ($operations as $op) {
             $listModels[$op->name] = $op->description . "({$op->name})";
         }
     } elseif ($model->type == AuthItem::TYPE_ROLE) {
         $tasks = AuthItem::model()->findAll('type = :type', array(':type' => AuthItem::TYPE_TASK));
         foreach ($tasks as $task) {
             $listModels[$task->name] = $task->description . "({$task->name})";
         }
     }
     foreach ($model->parents as $item) {
         if ($item->childItem->type == AuthItem::TYPE_OPERATION) {
             $operationsList[$item->childItem->name] = $item->childItem->description . " ({$item->childItem->name})";
         } elseif ($item->childItem->type == AuthItem::TYPE_TASK) {
             $tasksList[$item->childItem->name] = $item->childItem->description . " ({$item->childItem->name})";
         }
     }
     if (Yii::app()->request->isPostRequest && isset($_POST['AuthItem'])) {
         $transaction = Yii::app()->db->beginTransaction();
         try {
             $model->attributes = $_POST['AuthItem'];
             if ($model->save()) {
                 $items = array();
                 if ($model->type == AuthItem::TYPE_TASK) {
                     $items = Yii::app()->request->getPost('operations', array());
                 } elseif ($model->type == AuthItem::TYPE_ROLE) {
                     $items = Yii::app()->request->getPost('tasks', array());
                 }
                 // удалим и создадим чайлдов заново
                 AuthItemChild::model()->deleteAll('parent = :parent', array(':parent' => $model->name));
                 if (count($items)) {
                     foreach ($items as $name) {
                         $child = new AuthItemChild();
                         $child->setAttributes(array('parent' => $model->name, 'child' => $name));
                         if (!$child->save()) {
                             throw new CException('Ошибка при сохранении связанных объектов!');
                         }
                     }
                 }
                 $transaction->commit();
                 Yii::app()->user->setFlash('success', 'Действие изменено!');
                 $this->redirect(array('update', 'id' => $model->name));
             }
         } catch (Exception $e) {
             Yii::app()->user->setFlash('error', $e->getMessage());
             $transaction->rollback();
         }
     }
     $this->render('update', array('model' => $model, 'operations' => $operationsList, 'tasks' => $tasksList, 'listModels' => $listModels));
 }
コード例 #17
0
 protected function getChildsFlat($name, &$result = array())
 {
     $childs = new CDbCriteria();
     $childs->condition = 'parent=:parent';
     $childs->params = array(':parent' => $name);
     $childs->order = 'child ASC';
     $childs = AuthItemChild::model()->findAll($childs);
     if (count($childs) > 0) {
         foreach ($childs as $i => $child) {
             $result[count($result)] = $child->child;
             $this->getChildsFlat($child->child, $result);
         }
     } else {
         return array();
     }
     $result = array_unique($result);
     return $result;
 }
コード例 #18
0
ファイル: RBACTree.php プロジェクト: ranvirp/rdp
 /**
  * 
  * @desc recursive method 
  * @uses AuthItem::findUnboundItems()
  * @param array $tree Part of or empty array as main RBAC Tree container
  * @param integer $depth the Tree depth, which is not realy needed and nowhere used yet
  * @return array with AuthItem ['this', 'childs' => ['this', 'childs[...]]]
  * 
  */
 private function _buildItemTree($tree, $depth)
 {
     if (count($tree) < 1) {
         /*
          * find the Top Level Items with its childs
          * 
          * SELECT 
          * 		`t`.`parent` AS `t0_c0`, 
          * 		`t`.`parent` AS `t0_c0`, 
          * 		`t`.`child` AS `t0_c1`, 
          * 		`parents`.`parent` AS `t1_c0`, 
          * 		`parents`.`child` AS `t1_c1`, 
          * 		`items`.`name` AS `t2_c0`, 
          * 		`items`.`type` AS `t2_c1`, 
          * 		`items`.`description` AS `t2_c2`, 
          * 		`items`.`bizrule` AS `t2_c3`, 
          * 		`items`.`data` AS `t2_c4` 
          * FROM `AuthItemChild` `t`  
          * LEFT OUTER JOIN `AuthItemChild` `parents` 
          * 		ON (`parents`.`child`=`t`.`parent`)  
          * LEFT OUTER JOIN `AuthItem` `items` 
          * 		ON (`t`.`child`=`items`.`name`)  
          * WHERE (parents.parent IS NULL) 
          * ORDER BY t.parent
          */
         $result = $this->findAll(array('with' => array('parents', 'childs'), 'condition' => 'parents.parent IS NULL', 'order' => 'parents.parent DESC'));
         $depth++;
         $tree['depth'] = 0;
         $tree['parent-name'] = null;
         $tree['this-name'] = null;
         $tree['this'] = null;
         $tree['childs'] = array();
         $modelAuthItem = new AuthItem();
         //if(!count($result)) return $tree;
         foreach ($result as $row) {
             $cnt = count($tree['childs']) - 1;
             if (isset($tree['childs'][0]) && $tree['childs'][$cnt]['this-name'] == $row->parent) {
                 // build second depth in existing first depth
                 $tree['childs'][$cnt]['childs'][] = $this->_buildItemTree(array('depth' => $depth + 1, 'parent-name' => $row->parent, 'this-name' => $row->childs->name, 'this' => $row->childs, 'childs' => array()), $depth + 1);
             } else {
                 // build new first depth and included second depth
                 $tree['childs'][] = array('depth' => $depth, 'parent-name' => null, 'this-name' => $row->parent, 'this' => $modelAuthItem->findByAttributes(array('name' => $row->parent)), 'childs' => array($this->_buildItemTree(array('depth' => $depth + 1, 'parent-name' => $row->parent, 'this-name' => $row->childs->name, 'this' => $row->childs, 'childs' => array()), $depth + 1)));
             }
         }
         // add unbound items
         $model = new AuthItem();
         $unboundItems = $model->findUnboundItems();
         foreach ($unboundItems as $item) {
             $child = array('depth' => 1, 'parent-name' => null, 'this-name' => $item->name, 'this' => $item, 'childs' => array());
             array_unshift($tree['childs'], $child);
         }
         return $tree;
     } else {
         /*
          * SELECT 
          * 		`t`.`parent` AS `t0_c0`, 
          * 		`t`.`child` AS `t0_c1`, 
          * 		`childs`.`name` AS `t1_c0`, 
          * 		`childs`.`type` AS `t1_c1`, 
          * 		`childs`.`description` AS `t1_c2`, 
          * 		`childs`.`bizrule` AS `t1_c3`, 
          * 		`childs`.`data` AS `t1_c4` 
          * FROM `AuthItemChild` `t`  
          * LEFT OUTER JOIN `AuthItem` `childs` 
          * 		ON (`t`.`child`=`childs`.`name`)  
          * WHERE (`t`.`parent`=:yp0) 
          * ORDER BY childs.name
          */
         $ct = new CDbCriteria(array('order' => 'childs.name'));
         $ct->addColumnCondition(array('t.parent' => $tree['this']->name));
         $result = AuthItemChild::model()->with('childs')->findAll($ct);
         /*
         $result = $this->findAllByAttributes(
         	array('parent'=>$tree['this']->name),
         	array(
         		'with' => 'childs',
         		//'condition' => array('t.parent'=>$tree['this']->name),
         		'order' => 'childs.name',
         		)
         );
         */
         $depth++;
         if (count($result) > 0) {
             foreach ($result as $row) {
                 $tree['childs'][] = $this->_buildItemTree(array('depth' => $depth, 'parent-name' => $row->parent, 'this-name' => $row->childs->name, 'this' => $row->childs, 'childs' => array()), $depth);
             }
         }
         return $tree;
     }
 }
コード例 #19
0
 public function actionAddSubItem($id)
 {
     $auth = Yii::app()->authManager;
     $children = $auth->getItemChildren($id);
     $allOperations = $auth->getOperations();
     $availOperations = array();
     foreach ($allOperations as $k => $v) {
         if (!isset($children[$k])) {
             $availOperations[$k] = empty($v->description) ? $k : $v->description;
         }
     }
     $model = new AuthItemChild();
     if (isset($_POST['AuthItemChild'])) {
         $model->attributes = $_POST['AuthItemChild'];
         if ($model->validate()) {
             $model->parent = $id;
             $auth->addItemChild($id, $model->child);
             // form inputs are valid, do something here
             $this->redirect(array('permission/viewTasks', 'id' => $id));
         }
     }
     $this->render('addSubItem', array('operations' => $availOperations, 'model' => $model));
 }