AuthitemController.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. <?php
  2. /**
  3. * AuthitemController class file.
  4. *
  5. * @author Spyros Soldatos <spyros@valor.gr>
  6. * @link http://code.google.com/p/srbac/
  7. */
  8. /**
  9. * AuthitemController is the main controller for all of the srbac actions
  10. *
  11. * @author Spyros Soldatos <spyros@valor.gr>
  12. * @package srbac.controllers
  13. * @since 1.0.0
  14. */
  15. class AuthitemController extends SBaseController {
  16. /**
  17. * @var string specifies the default action to be 'list'.
  18. */
  19. public $defaultAction = 'frontpage';
  20. /**
  21. * @var $breadcrumbs
  22. */
  23. public $breadcrumbs;
  24. /**
  25. * @var CActiveRecord the currently loaded data model instance.
  26. */
  27. private $_model;
  28. public function init() {
  29. parent::init();
  30. }
  31. /**
  32. * Checks if the user has the authority role
  33. * @param String $action The current action
  34. * @return Boolean true if user has the authority role
  35. */
  36. protected function beforeAction($action) {
  37. if (!$this->module->isInstalled() && $action->id != "install") {
  38. $this->redirect(array("install"));
  39. return false;
  40. }
  41. if ($this->module->debug) {
  42. return true;
  43. }
  44. if (Yii::app()->user->checkAccess(Helper::findModule('srbac')->superUser) ||
  45. !Helper::isAuthorizer()) {
  46. return true;
  47. } else {
  48. parent::beforeAction($action);
  49. }
  50. }
  51. /**
  52. * Assigns roles to a user
  53. *
  54. * @param int $userid The user's id
  55. * @param String $roles The roles to assign
  56. * @param String $bizRules Not used yet
  57. * @param String $data Not used yet
  58. */
  59. private function _assignUser($userid, $roles, $bizRules, $data) {
  60. if ($userid) {
  61. $auth = Yii::app()->authManager;
  62. /* @var $auth CDbAuthManager */
  63. foreach ($roles as $role) {
  64. $auth->assign($role, $userid, $bizRules, $data);
  65. }
  66. }
  67. }
  68. /**
  69. * Revokes roles from a user
  70. * @param int $userid The user's id
  71. * @param String $roles The roles to revoke
  72. */
  73. private function _revokeUser($userid, $roles) {
  74. if ($userid) {
  75. $auth = Yii::app()->authManager;
  76. /* @var $auth CDbAuthManager */
  77. foreach ($roles as $role) {
  78. if ($role == $this->module->superUser) {
  79. $count = Assignments::model()->count("itemname='" . $role . "'");
  80. if ($count == 1) {
  81. return false;
  82. }
  83. }
  84. $auth->revoke($role, $userid);
  85. return true;
  86. }
  87. }
  88. }
  89. /**
  90. * Assigns child items to a parent item
  91. * @param String $parent The parent item
  92. * @param String $children The child items
  93. */
  94. private function _assignChild($parent, $children) {
  95. if ($parent) {
  96. $auth = Yii::app()->authManager;
  97. /* @var $auth CDbAuthManager */
  98. foreach ($children as $child) {
  99. $auth->addItemChild($parent, $child);
  100. }
  101. }
  102. }
  103. /**
  104. * Revokes child items from a parent item
  105. * @param String $parent The parent item
  106. * @param String $children The child items
  107. */
  108. private function _revokeChild($parent, $children) {
  109. if ($parent) {
  110. $auth = Yii::app()->authManager;
  111. /* @var $auth CDbAuthManager */
  112. foreach ($children as $child) {
  113. $auth->removeItemChild($parent, $child);
  114. }
  115. }
  116. }
  117. /**
  118. * The assignment action
  119. * First checks if the user is authorized to perform this action
  120. * Then initializes the needed variables for the assign view.
  121. * If there's a post back it performs the assign action
  122. */
  123. public function actionAssign() {
  124. //CVarDumper::dump($_POST, 5, true);
  125. $userid = isset($_POST[Helper::findModule('srbac')->userclass][$this->module->userid]) ?
  126. $_POST[Helper::findModule('srbac')->userclass][$this->module->userid] :
  127. "";
  128. //Init values
  129. $model = AuthItem::model();
  130. $data['userAssignedRoles'] = array();
  131. $data['userNotAssignedRoles'] = array();
  132. $data['roleAssignedTasks'] = array();
  133. $data['roleNotAssignedTasks'] = array();
  134. $data['taskAssignedOpers'] = array();
  135. $data['taskNotAssignedOpers'] = array();
  136. $data["assign"] = array("disabled" => true);
  137. $data["revoke"] = array("disabled" => true);
  138. $this->_setMessage("");
  139. $auth = Yii::app()->authManager;
  140. /* @var $auth CDbAuthManager */
  141. $authItemAssignName = isset($_POST['AuthItem']['name']['assign']) ?
  142. $_POST['AuthItem']['name']['assign'] : "";
  143. $assBizRule = isset($_POST['Assignments']['bizrule']) ?
  144. $_POST['Assignments']['bizrule'] : "";
  145. $assData = isset($_POST['Assignments']['data']) ?
  146. $_POST['Assignments']['data'] : "";
  147. $authItemRevokeName = isset($_POST['AuthItem']['name']['revoke']) ?
  148. $_POST['AuthItem']['name']['revoke'] : "";
  149. if (isset($_POST['AuthItem']['name'])) {
  150. if (isset($_POST['AuthItem']['name'][0])) {
  151. $authItemName = $_POST['AuthItem']['name'][0];
  152. } else {
  153. $authItemName = $_POST['AuthItem']['name'];
  154. }
  155. }
  156. $assItemName = isset($_POST['Assignments']['itemname']) ? $_POST['Assignments']['itemname'] : "";
  157. $assignRoles = Yii::app()->request->getParam('assignRoles', 0);
  158. $revokeRoles = Yii::app()->request->getParam('revokeRoles', 0);
  159. $assignTasks = isset($_GET['assignTasks']) ? $_GET['assignTasks'] : 0;
  160. $revokeTasks = isset($_GET['revokeTasks']) ? $_GET['revokeTasks'] : 0;
  161. $assignOpers = isset($_GET['assignOpers']) ? $_GET['assignOpers'] : 0;
  162. $revokeOpers = isset($_GET['revokeOpers']) ? $_GET['revokeOpers'] : 0;
  163. if ($assignRoles && is_array($authItemAssignName)) {
  164. $this->_assignUser($userid, $authItemAssignName, $assBizRule, $assData);
  165. $this->_setMessage(Helper::translate('srbac', 'Role(s) Assigned'));
  166. } else if ($revokeRoles && is_array($authItemRevokeName)) {
  167. $revoke = $this->_revokeUser($userid, $authItemRevokeName);
  168. if ($revoke) {
  169. $this->_setMessage(Helper::translate('srbac', 'Role(s) Revoked'));
  170. } else {
  171. $this->_setMessage(Helper::translate('srbac', 'Can\'t revoke this role'));
  172. }
  173. } else if ($assignTasks && is_array($authItemAssignName)) {
  174. $this->_assignChild($authItemName, $authItemAssignName);
  175. $this->_setMessage(Helper::translate('srbac', 'Task(s) Assigned'));
  176. } else if ($revokeTasks && is_array($authItemRevokeName)) {
  177. $this->_revokeChild($authItemName, $authItemRevokeName);
  178. $this->_setMessage(Helper::translate('srbac', 'Task(s) Revoked'));
  179. } else if ($assignOpers && is_array($authItemAssignName)) {
  180. $this->_assignChild($assItemName, $authItemAssignName);
  181. $this->_setMessage(Helper::translate('srbac', 'Operation(s) Assigned'));
  182. } else if ($revokeOpers && is_array($authItemRevokeName)) {
  183. $this->_revokeChild($assItemName, $authItemRevokeName);
  184. $this->_setMessage(Helper::translate('srbac', 'Operation(s) Revoked'));
  185. }
  186. //If not ajax show the assign page
  187. if (!Yii::app()->request->isAjaxRequest) {
  188. $this->render('assign', array(
  189. 'model' => $model,
  190. 'message' => $this->_getMessage(),
  191. 'userid' => $userid,
  192. 'data' => $data
  193. ));
  194. } else {
  195. // assign to user show the user tab
  196. if ($userid != "") {
  197. $this->_getTheRoles();
  198. } else if ($assignTasks != 0 || $revokeTasks != 0) {
  199. $this->_getTheTasks();
  200. } else if ($assignOpers != 0 || $revokeOpers != 0) {
  201. $this->_getTheOpers();
  202. }
  203. }
  204. }
  205. /**
  206. * Used by Ajax to get the roles of a user when he is selected in the Assign
  207. * roles to user tab
  208. */
  209. public function actionGetRoles() {
  210. $this->_setMessage("");
  211. $this->_getTheRoles();
  212. }
  213. /**
  214. * Gets the assigned and not assigned roles of the selected user
  215. */
  216. private function _getTheRoles() {
  217. $model = new AuthItem();
  218. $userid = $_POST[Helper::findModule('srbac')->userclass][$this->module->userid];
  219. $data['userAssignedRoles'] = Helper::getUserAssignedRoles($userid);
  220. $data['userNotAssignedRoles'] = Helper::getUserNotAssignedRoles($userid);
  221. if ($data['userAssignedRoles'] == array()) {
  222. $data['revoke'] = array("name" => "revokeUser", "disabled" => true);
  223. } else {
  224. $data['revoke'] = array("name" => "revokeUser");
  225. }
  226. if ($data['userNotAssignedRoles'] == array()) {
  227. $data['assign'] = array("name" => "assignUser", "disabled" => true);
  228. } else {
  229. $data['assign'] = array("name" => "assignUser");
  230. }
  231. $this->renderPartial('tabViews/userAjax',
  232. array('model' => $model, 'userid' => $userid, 'data' => $data, 'message' => $this->_getMessage()),
  233. false, true);
  234. }
  235. /**
  236. * Used by Ajax to get the tasks of a role when it is selected in the Assign
  237. * tasks to roles tab
  238. */
  239. public function actionGetTasks() {
  240. $this->_setMessage("");
  241. $this->_getTheTasks();
  242. }
  243. /**
  244. * Gets the assigned and not assigned tasks of the selected user
  245. */
  246. private function _getTheTasks() {
  247. $model = new AuthItem();
  248. $name = isset($_POST["AuthItem"]["name"][0]) ? $_POST["AuthItem"]["name"][0] : "";
  249. $data['roleAssignedTasks'] = Helper::getRoleAssignedTasks($name);
  250. $data['roleNotAssignedTasks'] = Helper::getRoleNotAssignedTasks($name);
  251. if ($data['roleAssignedTasks'] == array()) {
  252. $data['revoke'] = array("name" => "revokeTask", "disabled" => true);
  253. } else {
  254. $data['revoke'] = array("name" => "revokeTask");
  255. }
  256. if ($data['roleNotAssignedTasks'] == array()) {
  257. $data['assign'] = array("name" => "assignTasks", "disabled" => true);
  258. } else {
  259. $data['assign'] = array("name" => "assignTasks");
  260. }
  261. $this->renderPartial('tabViews/roleAjax',
  262. array('model' => $model, 'name' => $name, 'data' => $data, 'message' => $this->_getMessage()), false, true);
  263. }
  264. /**
  265. * Used by Ajax to get the operations of a task when he is selected in the Assign
  266. * operations to tasks tab
  267. */
  268. public function actionGetOpers() {
  269. $this->_setMessage("");
  270. $this->_getTheOpers();
  271. }
  272. /**
  273. * Gets the assigned and not assigned operations of the selected user
  274. */
  275. private function _getTheOpers() {
  276. $model = new AuthItem();
  277. $data['taskAssignedOpers'] = array();
  278. $data['taskNotAssignedOpers'] = array();
  279. $name = isset($_POST["Assignments"]["itemname"]) ?
  280. $_POST["Assignments"]["itemname"] :
  281. Yii::app()->getGlobalState("cleverName");
  282. if (Yii::app()->getGlobalState("cleverAssigning") && $name) {
  283. $data['taskAssignedOpers'] = Helper::getTaskAssignedOpers($name, true);
  284. $data['taskNotAssignedOpers'] = Helper::getTaskNotAssignedOpers($name, true);
  285. } else if ($name) {
  286. $data['taskAssignedOpers'] = Helper::getTaskAssignedOpers($name, false);
  287. $data['taskNotAssignedOpers'] = Helper::getTaskNotAssignedOpers($name, false);
  288. }
  289. if ($data['taskAssignedOpers'] == array()) {
  290. $data['revoke'] = array("name" => "revokeOpers", "disabled" => true);
  291. } else {
  292. $data['revoke'] = array("name" => "revokeOpers");
  293. }
  294. if ($data['taskNotAssignedOpers'] == array()) {
  295. $data['assign'] = array("name" => "assignOpers", "disabled" => true);
  296. } else {
  297. $data['assign'] = array("name" => "assignOpers");
  298. }
  299. $this->renderPartial('tabViews/taskAjax',
  300. array('model' => $model, 'name' => $name, 'data' => $data, 'message' => $this->_getMessage()), false, true);
  301. }
  302. /**
  303. * Shows a particular model.
  304. */
  305. public function actionShow() {
  306. $deleted = Yii::app()->request->getParam('deleted', false);
  307. $delete = Yii::app()->request->getParam('delete', false);
  308. $model = $this->loadAuthItem();
  309. $this->renderPartial('manage/show', array('model' => $model,
  310. 'deleted' => $deleted,
  311. 'updateList' => false,
  312. 'delete' => $delete));
  313. }
  314. /**
  315. * Creates a new model.
  316. * If creation is successful, the browser will be redirected to the 'show' page.
  317. */
  318. public function actionCreate() {
  319. $model = new AuthItem;
  320. if (isset($_POST['AuthItem'])) {
  321. $model->attributes = $_POST['AuthItem'];
  322. try {
  323. if ($model->save()) {
  324. Yii::app()->user->setFlash('updateSuccess',
  325. "'" . $model->name . "' " .
  326. Helper::translate('srbac', 'created successfully'));
  327. $model->data = unserialize($model->data);
  328. $this->renderPartial('manage/update', array('model' => $model));
  329. } else {
  330. $this->renderPartial('manage/create', array('model' => $model));
  331. }
  332. } catch (CDbException $exc) {
  333. Yii::app()->user->setFlash('updateError',
  334. Helper::translate('srbac', 'Error while creating')
  335. . ' ' . $model->name . "<br />" .
  336. Helper::translate('srbac', 'Possible there\'s already an item with the same name'));
  337. $this->renderPartial('manage/create', array('model' => $model));
  338. }
  339. } else {
  340. $this->renderPartial('manage/create', array('model' => $model));
  341. }
  342. }
  343. /**
  344. * Updates a particular model.
  345. * If update is successful, the browser will be redirected to the 'show' page.
  346. */
  347. public function actionUpdate() {
  348. $model = $this->loadAuthItem();
  349. $message = "";
  350. if (isset($_POST['AuthItem'])) {
  351. $model->oldName = isset($_POST["oldName"]) ? $_POST["oldName"] : $_POST["name"];
  352. $model->attributes = $_POST['AuthItem'];
  353. if ($model->save()) {
  354. Yii::app()->user->setFlash('updateSuccess',
  355. "'" . $model->name . "' " .
  356. Helper::translate('srbac', 'updated successfully'));
  357. } else {
  358. }
  359. }
  360. $this->renderPartial('manage/update', array('model' => $model));
  361. }
  362. /**
  363. * Deletes a particular model.
  364. * If deletion is successful, the browser will be redirected to the 'list' page.
  365. */
  366. public function actionDelete() {
  367. if (Yii::app()->request->isAjaxRequest) {
  368. $this->loadAuthItem()->delete();
  369. //$this->processAdminCommand();
  370. //$criteria = new CDbCriteria;
  371. //$pages = new CPagination(AuthItem::model()->count($criteria));
  372. //$pages->pageSize = $this->module->pageSize;
  373. //$pages->applyLimit($criteria);
  374. //$sort = new CSort('AuthItem');
  375. //$sort->applyOrder($criteria);
  376. //$models = AuthItem::model()->findAll($criteria);
  377. Yii::app()->user->setFlash('updateName',
  378. Helper::translate('srbac', 'Updating list'));
  379. $this->renderPartial('manage/show', array(
  380. //'models' => $models,
  381. //'pages' => $pages,
  382. //'sort' => $sort,
  383. 'updateList' => true,
  384. ), false, false);
  385. } else {
  386. throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
  387. }
  388. }
  389. /**
  390. * Show the confirmation view for deleting auth items
  391. */
  392. public function actionConfirm() {
  393. $this->renderPartial('manage/show',
  394. array('model' => $this->loadAuthItem(), 'updateList' => false, 'delete' => true),
  395. false, true);
  396. }
  397. /**
  398. * Lists all models.
  399. */
  400. public function actionList() {
  401. // Get selected type
  402. $selectedType =
  403. Yii::app()->request->getParam('selectedType',
  404. Yii::app()->user->getState("selectedType"));
  405. Yii::app()->user->setState("selectedType", $selectedType);
  406. //Get selected name
  407. $selectedName =
  408. Yii::app()->request->getParam('name',
  409. Yii::app()->user->getState("selectedName"));
  410. Yii::app()->user->setState("selectedName", $selectedName);
  411. if (!Yii::app()->request->isAjaxRequest) {
  412. Yii::app()->user->setState("currentPage", Yii::app()->request->getParam('page', 0) - 1);
  413. }
  414. $criteria = new CDbCriteria;
  415. $criteria->condition = "1=1";
  416. if ($selectedName != "") {
  417. $criteria->condition .= " AND name LIKE '%" . $selectedName . "%'";
  418. }
  419. if ($selectedType != "") {
  420. $criteria->condition .= " AND type = " . $selectedType;
  421. }
  422. $pages = new CPagination(AuthItem::model()->count($criteria));
  423. $pages->pageSize = $this->module->pageSize;
  424. $pages->applyLimit($criteria);
  425. $pages->route = "manage";
  426. $pages->setCurrentPage(Yii::app()->user->getState("currentPage"));
  427. $models = AuthItem::model()->findAll($criteria);
  428. $this->renderPartial('manage/list', array(
  429. 'models' => $models,
  430. 'pages' => $pages,
  431. ), false, true);
  432. }
  433. /**
  434. * Installs srbac (only in debug mode)
  435. */
  436. public function actionInstall() {
  437. if ($this->module->debug) {
  438. $action = Yii::app()->getRequest()->getParam("action", "");
  439. $demo = Yii::app()->getRequest()->getParam("demo", 0);
  440. if ($action) {
  441. $error = Helper::install($action, $demo);
  442. if ($error == 1) {
  443. $this->render('install/overwrite', array("demo" => $demo));
  444. } else if ($error == 0) {
  445. $this->render('install/success', array("demo" => $demo));
  446. } else if ($error == 2) {
  447. $error = Helper::translate("srbac", "Error while installing srbac.<br />Please check your database and try again");
  448. $this->render('install/error', array("demo" => $demo, "error" => $error));
  449. }
  450. } else {
  451. $this->render('install/install');
  452. }
  453. } else {
  454. $error = Helper::translate("srbac", "srbac must be in debug mode");
  455. $this->render("install/error", array("error" => $error));
  456. }
  457. }
  458. /**
  459. * Displayes the authitem manage page
  460. */
  461. public function actionManage() {
  462. $this->processAdminCommand();
  463. $page = Yii::app()->getRequest()->getParam("page", "");
  464. if (Yii::app()->request->isAjaxRequest || $page != "") {
  465. $selectedType = Yii::app()->request->getParam('selectedType', Yii::app()->user->getState("selectedType"));
  466. } else {
  467. $selectedType = "";
  468. }
  469. Yii::app()->user->setState("selectedType", $selectedType);
  470. $criteria = new CDbCriteria;
  471. if ($selectedType != "") {
  472. $criteria->condition = "type = " . $selectedType;
  473. }
  474. if (!Yii::app()->request->isAjaxRequest) {
  475. Yii::app()->user->setState("currentPage", Yii::app()->request->getParam('page', 0) - 1);
  476. }
  477. $pages = new CPagination(AuthItem::model()->count($criteria));
  478. $pages->route = "manage";
  479. $pages->pageSize = $this->module->pageSize;
  480. $pages->applyLimit($criteria);
  481. $pages->setCurrentPage(Yii::app()->user->getState('currentPage'));
  482. $sort = new CSort('AuthItem');
  483. $sort->applyOrder($criteria);
  484. $models = AuthItem::model()->findAll($criteria);
  485. $full = Yii::app()->request->getParam("full");
  486. if (Yii::app()->request->isAjaxRequest && !$full) {
  487. $this->renderPartial('manage/list', array(
  488. 'models' => $models,
  489. 'pages' => $pages,
  490. 'sort' => $sort,
  491. 'full' => $full,
  492. ), false, true);
  493. } else if (Yii::app()->request->isAjaxRequest && $full) {
  494. $this->renderPartial('manage/manage', array(
  495. 'models' => $models,
  496. 'pages' => $pages,
  497. 'sort' => $sort,
  498. 'full' => $full
  499. ), false, true);
  500. } else {
  501. $this->render('manage/manage', array(
  502. 'models' => $models,
  503. 'pages' => $pages,
  504. 'sort' => $sort,
  505. 'full' => $full,
  506. ));
  507. }
  508. }
  509. /**
  510. * Gets the authitems for the CAutocomplete textbox
  511. */
  512. public function actionAutocomplete() {
  513. $criteria = new CDbCriteria();
  514. $criteria->condition = "name LIKE :name";
  515. $criteria->params = array(":name" => "%" . Yii::app()->request->getParam('q') . "%");
  516. $items = AuthItem::model()->findAll($criteria);
  517. foreach ($items as $item) {
  518. $valuesArray[] = $item->name;
  519. }
  520. echo join("\n", $valuesArray);
  521. }
  522. /**
  523. * Returns the data model based on the primary key given in the GET variable.
  524. * If the data model is not found, an HTTP exception will be raised.
  525. * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
  526. */
  527. public function loadAuthItem($id=null) {
  528. if ($this->_model === null) {
  529. $r_id = urldecode(Yii::app()->getRequest()->getParam("id", ""));
  530. if ($id !== null || $r_id != "")
  531. $this->_model = AuthItem::model()->findbyPk($id !== null ? $id : $r_id);
  532. if ($this->_model === null)
  533. throw new CHttpException(404, 'The requested page does not exist.');
  534. }
  535. return $this->_model;
  536. }
  537. /**
  538. * Executes any command triggered on the admin page.
  539. */
  540. protected function processAdminCommand() {
  541. if (isset($_POST['command'], $_POST['id']) && $_POST['command'] === 'delete') {
  542. // $this->loadAuthItem($_POST['id'])->delete();
  543. // reload the current page to avoid duplicated delete actions
  544. //$this->refresh();
  545. }
  546. }
  547. //TODO These messages should be replaced by flash messages
  548. /**
  549. * Sets the message that is displayed to the user
  550. * @param String $mess The message to show
  551. */
  552. private function _setMessage($mess) {
  553. Yii::app()->user->setState("message", $mess);
  554. }
  555. /**
  556. *
  557. * @return String Gets the message that will be displayed to the user
  558. */
  559. private function _getMessage() {
  560. return Yii::app()->user->getState("message");
  561. }
  562. /**
  563. * Displayes the assignments page with no user selected
  564. */
  565. public function actionAssignments() {
  566. $this->render('assignments', array("id" => 0));
  567. }
  568. /**
  569. * Show a user's assignments.The user is passed by $_GET
  570. */
  571. public function actionShowAssignments() {
  572. $userid = isset($_GET["id"]) ? $_GET["id"] :
  573. $_POST[Helper::findModule('srbac')->userclass][$this->module->userid];
  574. $user = $this->module->getUserModel()->findByPk($userid);
  575. $username = $user->{$this->module->username};
  576. $r = array(0 => array(0 => array()));
  577. if ($userid > 0) {
  578. $auth = Yii::app()->authManager;
  579. /* @var $auth CDbAuthManager */
  580. $ass = $auth->getAuthItems(2, $userid);
  581. $r = array();
  582. foreach ($ass as $i => $role) {
  583. $curRole = $role->name;
  584. $r[$i] = $curRole;
  585. $children = $auth->getItemChildren($curRole);
  586. $r[$i] = array();
  587. foreach ($children as $j => $task) {
  588. $curTask = $task->name;
  589. $r[$i][$j] = $curTask;
  590. $grandchildren = $auth->getItemChildren($curTask);
  591. $r[$i][$j] = array();
  592. foreach ($grandchildren as $k => $oper) {
  593. $curOper = $oper->name;
  594. $r[$i][$j][$k] = $curOper;
  595. }
  596. }
  597. }
  598. // Add always allowed opers
  599. $r["AlwaysAllowed"][""] = $this->module->getAlwaysAllowed();
  600. $this->renderPartial('userAssignments', array('data' => $r, 'username' => $username));
  601. }
  602. }
  603. /**
  604. * Scans applications controllers and find the actions for autocreating of
  605. * authItems
  606. */
  607. public function actionScan() {
  608. if (Yii::app()->request->getParam('module') != '') {
  609. $controller = Yii::app()->request->getParam('module') .
  610. Helper::findModule('srbac')->delimeter
  611. . Yii::app()->request->getParam('controller');
  612. } else {
  613. $controller = Yii::app()->request->getParam('controller');
  614. }
  615. $controllerInfo = $this->_getControllerInfo($controller);
  616. $this->renderPartial("manage/createItems",
  617. array("actions" => $controllerInfo[0],
  618. "controller" => $controller,
  619. "delete" => $controllerInfo[2],
  620. "task" => $controllerInfo[3],
  621. "taskViewingExists" => $controllerInfo[4],
  622. "taskAdministratingExists" => $controllerInfo[5],
  623. "allowed" => $controllerInfo[1]),
  624. false, true);
  625. }
  626. /**
  627. * Getting a controllers actions and also th actions that are always allowed
  628. * return array
  629. * */
  630. private function _getControllerInfo($controller, $getAll = false) {
  631. $del = Helper::findModule('srbac')->delimeter;
  632. $actions = array();
  633. $allowed = array();
  634. $auth = Yii::app()->authManager;
  635. //Check if it's a module controller
  636. if (substr_count($controller,$del )) {
  637. $c = explode($del, $controller);
  638. $controller = $c[1];
  639. $module = $c[0] .$del;
  640. $contPath = Yii::app()->getModule($c[0])->getControllerPath();
  641. $control = $contPath . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $controller) . ".php";
  642. } else {
  643. $module = "";
  644. $contPath = Yii::app()->getControllerPath();
  645. $control = $contPath . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $controller) . ".php";
  646. }
  647. $task = $module . str_replace("Controller", "", $controller);
  648. $taskViewingExists = $auth->getAuthItem($task . "Viewing") !== null ? true : false;
  649. $taskAdministratingExists = $auth->getAuthItem($task . "Administrating") !== null ? true : false;
  650. $delete = Yii::app()->request->getParam('delete');
  651. $h = file($control);
  652. for ($i = 0; $i < count($h); $i++) {
  653. $line = trim($h[$i]);
  654. if (preg_match("/^(.+)function( +)action*/", $line)) {
  655. $posAct = strpos(trim($line), "action");
  656. $posPar = strpos(trim($line), "(");
  657. $action = trim(substr(trim($line),$posAct, $posPar-$posAct));
  658. $patterns[0] = '/\s*/m';
  659. $patterns[1] = '#\((.*)\)#';
  660. $patterns[2] = '/\{/m';
  661. $replacements[2] = '';
  662. $replacements[1] = '';
  663. $replacements[0] = '';
  664. $action = preg_replace($patterns, $replacements, trim($action));
  665. $itemId = $module . str_replace("Controller", "", $controller) .
  666. preg_replace("/action/", "", $action,1);
  667. if ($action != "actions") {
  668. if ($getAll) {
  669. $actions[$module . $action] = $itemId;
  670. if (in_array($itemId, $this->allowedAccess())) {
  671. $allowed[] = $itemId;
  672. }
  673. } else {
  674. if (in_array($itemId, $this->allowedAccess())) {
  675. $allowed[] = $itemId;
  676. } else {
  677. if ($auth->getAuthItem($itemId) === null && !$delete) {
  678. if (!in_array($itemId, $this->allowedAccess())) {
  679. $actions[$module . $action] = $itemId;
  680. }
  681. } else if ($auth->getAuthItem($itemId) !== null && $delete) {
  682. if (!in_array($itemId, $this->allowedAccess())) {
  683. $actions[$module . $action] = $itemId;
  684. }
  685. }
  686. }
  687. }
  688. } else {
  689. //load controller
  690. if (!class_exists($controller, false)) {
  691. require($control);
  692. }
  693. $tmp = array();
  694. $controller_obj = new $controller($controller, $module);
  695. //Get actions
  696. $controller_actions = $controller_obj->actions();
  697. foreach ($controller_actions as $cAction => $value) {
  698. $itemId = $module . str_replace("Controller", "", $controller) . ucfirst($cAction);
  699. if ($getAll) {
  700. $actions[$cAction] = $itemId;
  701. if (in_array($itemId, $this->allowedAccess())) {
  702. $allowed[] = $itemId;
  703. }
  704. } else {
  705. if (in_array($itemId, $this->allowedAccess())) {
  706. $allowed[] = $itemId;
  707. } else {
  708. if ($auth->getAuthItem($itemId) === null && !$delete) {
  709. if (!in_array($itemId, $this->allowedAccess())) {
  710. $actions[$cAction] = $itemId;
  711. }
  712. } else if ($auth->getAuthItem($itemId) !== null && $delete) {
  713. if (!in_array($itemId, $this->allowedAccess())) {
  714. $actions[$cAction] = $itemId;
  715. }
  716. }
  717. }
  718. }
  719. }
  720. }
  721. }
  722. }
  723. return array($actions, $allowed, $delete, $task, $taskViewingExists, $taskAdministratingExists);
  724. }
  725. /**
  726. * Deletes autocreated authItems
  727. */
  728. public function actionAutoDeleteItems() {
  729. $del = Helper::findModule('srbac')->delimeter;
  730. $cont = str_replace("Controller", "", $_POST["controller"]);
  731. //Check for module controller
  732. $controllerArr = explode($del, $cont);
  733. $controller = $controllerArr[sizeof($controllerArr) - 1];
  734. $actions = isset($_POST["actions"]) ? $_POST["actions"] : array();
  735. $deleteTasks = isset($_POST["createTasks"]) ? $_POST["createTasks"] : 0;
  736. $tasks = isset($_POST["tasks"]) ? $_POST["tasks"] : array();
  737. $message = "<div style='font-weight:bold'>" . Helper::translate('srbac', 'Delete operations') . "</div>";
  738. foreach ($actions as $key => $action) {
  739. if (substr_count($action, "action") > 0) {
  740. //controller action
  741. $action = trim(preg_replace("/action/", $controller, $action,1));
  742. } else {
  743. // actions actionstr_replace
  744. $action = $controller . ucfirst($action);
  745. }
  746. $auth = AuthItem::model()->findByPk($action);
  747. if ($auth !== null) {
  748. $auth->delete();
  749. $message .= "<div>" . $action . " " . Helper::translate('srbac', 'deleted') . "</div>";
  750. } else {
  751. $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac',
  752. 'Error while deleting')
  753. . ' ' . $action . "</div>";
  754. }
  755. }
  756. if ($deleteTasks) {
  757. $message .= "<div style='font-weight:bold'>" . Helper::translate('srbac', 'Delete tasks') . "</div>";
  758. foreach ($tasks as $key => $taskname) {
  759. $auth = AuthItem::model()->findByPk($taskname);
  760. if ($auth !== null) {
  761. $auth->delete();
  762. $message .= "<div>" . $taskname . " " . Helper::translate('srbac', 'deleted') . "</div>";
  763. } else {
  764. $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac',
  765. 'Error while deleting')
  766. . ' ' . $taskname . "</div>";
  767. }
  768. }
  769. }
  770. echo $message;
  771. }
  772. /**
  773. * Autocreating of authItems
  774. */
  775. public function actionAutoCreateItems() {
  776. $controller = str_replace("Controller", "", $_POST["controller"]);
  777. $actions = isset($_POST["actions"]) ? $_POST["actions"] : array();
  778. $message = "";
  779. $createTasks = isset($_POST["createTasks"]) ? $_POST["createTasks"] : 0;
  780. $tasks = isset($_POST["tasks"]) ? $_POST["tasks"] : array("");
  781. if ($createTasks == "1") {
  782. $message = "<div style='font-weight:bold'>" . Helper::translate('srbac', 'Creating tasks') . "</div>";
  783. foreach ($tasks as $key => $taskname) {
  784. $auth = new AuthItem();
  785. $auth->name = $taskname;
  786. $auth->type = 1;
  787. try {
  788. if ($auth->save()) {
  789. $message .= "'" . $auth->name . "' " .
  790. Helper::translate('srbac', 'created successfully') . "<br />";
  791. } else {
  792. $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac',
  793. 'Error while creating')
  794. . ' ' . $auth->name . '<br />' .
  795. Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />";
  796. }
  797. } catch (Exception $e) {
  798. $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac',
  799. 'Error while creating')
  800. . ' ' . $auth->name . '<br />' .
  801. Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />";
  802. }
  803. }
  804. }
  805. $message .= "<div style='font-weight:bold'>" . Helper::translate('srbac', 'Creating operations') . "</div>";
  806. foreach ($actions as $action) {
  807. $act = explode("action", $action,2);
  808. $a = trim($controller . (count($act) > 1 ? $act[1] : ucfirst($act[0])));
  809. $auth = new AuthItem();
  810. $auth->name = $a;
  811. $auth->type = 0;
  812. try {
  813. if ($auth->save()) {
  814. $message .= "'" . $auth->name . "' " .
  815. Helper::translate('srbac', 'created successfully') . "<br />";
  816. if ($createTasks == "1") {
  817. if ($this->_isUserOperation($auth->name)) {
  818. $this->_assignChild($tasks["user"], array($auth->name));
  819. }
  820. $this->_assignChild($tasks["admin"], array($auth->name));
  821. }
  822. } else {
  823. $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac',
  824. 'Error while creating')
  825. . ' ' . $auth->name . '<br />' .
  826. Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />";
  827. }
  828. } catch (Exception $e) {
  829. $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac',
  830. 'Error while creating')
  831. . ' ' . $auth->name . '<br />' .
  832. Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />";
  833. }
  834. }
  835. echo $message;
  836. }
  837. /**
  838. * Gets the controllers and the modules' controllers for the autocreating of
  839. * authItems
  840. */
  841. public function actionAuto() {
  842. $controllers = $this->_getControllers();
  843. $this->renderPartial("manage/wizard", array(
  844. 'controllers' => $controllers), false, true);
  845. }
  846. /**
  847. * Geting all the application's and modules controllers
  848. * @return array The application's and modules controllers
  849. */
  850. private function _getControllers() {
  851. $contPath = Yii::app()->getControllerPath();
  852. $controllers = $this->_scanDir($contPath);
  853. //Scan modules
  854. $modules = Yii::app()->getModules();
  855. $modControllers = array();
  856. foreach ($modules as $mod_id => $mod) {
  857. $moduleControllersPath = Yii::app()->getModule($mod_id)->controllerPath;
  858. $modControllers = $this->_scanDir($moduleControllersPath, $mod_id, "", $modControllers);
  859. }
  860. return array_merge($controllers, $modControllers);
  861. }
  862. private function _scanDir($contPath, $module="", $subdir="", $controllers = array()) {
  863. $handle = opendir($contPath);
  864. $del = Helper::findModule('srbac')->delimeter;
  865. while (($file = readdir($handle)) !== false) {
  866. $filePath = $contPath . DIRECTORY_SEPARATOR . $file;
  867. if (is_file($filePath)) {
  868. if (preg_match("/^(.+)Controller.php$/", basename($file))) {
  869. if ($this->_extendsSBaseController($filePath)) {
  870. $controllers[] = (($module) ? $module . $del : "") .
  871. (($subdir) ? $subdir . "." : "") .
  872. str_replace(".php", "", $file);
  873. }
  874. }
  875. } else if (is_dir($filePath) && $file != "." && $file != "..") {
  876. $controllers = $this->_scanDir($filePath, $module, $file, $controllers);
  877. }
  878. }
  879. return $controllers;
  880. }
  881. private function _extendsSBaseController($controller) {
  882. $c = basename(str_replace(".php", "", $controller));
  883. if (!class_exists($c, false)) {
  884. include_once $controller;
  885. } else {
  886. }
  887. $cont = new $c($c);
  888. if ($cont instanceof SBaseController) {
  889. return true;
  890. }
  891. return false;
  892. }
  893. public function actionGetCleverOpers() {
  894. $cleverAssigning = Yii::app()->getRequest()->getParam("checked") == "true" ? 1 : 0;
  895. $cleverName = Yii::app()->getRequest()->getParam("name");
  896. Yii::app()->setGlobalState("cleverAssigning", $cleverAssigning);
  897. Yii::app()->setGlobalState("cleverName", $cleverName);
  898. $this->_getTheOpers();
  899. }
  900. /**
  901. *
  902. * @param <type> $operation
  903. * @return <type> Checks if an operations should be assigned to using task or not
  904. */
  905. function _isUserOperation($operation) {
  906. foreach ($this->module->userActions as $oper) {
  907. if (strpos(strtolower($operation), strtolower($oper)) > -1) {
  908. return true;
  909. }
  910. }
  911. return false;
  912. }
  913. /**
  914. * Displays srbac frontpage
  915. */
  916. public function actionFrontPage() {
  917. $this->render('frontpage', array());
  918. }
  919. /**
  920. * Displays the editor for the alwaysAllowed items
  921. */
  922. public function actionEditAllowed() {
  923. if (!Helper::isAlwaysAllowedFileWritable()) {
  924. echo Helper::translate("srbac", "The always allowed file is not writeable by the server") . "<br />";
  925. echo "File : " . $this->module->getAlwaysAllowedFile();
  926. return;
  927. }
  928. $controllers = $this->_getControllers();
  929. foreach ($controllers as $n => $controller) {
  930. $info = $this->_getControllerInfo($controller, true);
  931. $c[$n]["title"] = $controller;
  932. $c[$n]["actions"] = $info[0];
  933. $c[$n]["allowed"] = $info[1];
  934. }
  935. $this->renderPartial('allowed', array('controllers' => $c), false, true);
  936. }
  937. public function actionSaveAllowed() {
  938. if (!Helper::isAlwaysAllowedFileWritable()) {
  939. echo Helper::translate("srbac", "The always allowed file is not writable by the server") . "<br />";
  940. echo "File : " . $this->module->getAlwaysAllowedFile();
  941. return;
  942. }
  943. $allowed = array();
  944. foreach ($_POST as $controller) {
  945. foreach ($controller as $action) {
  946. //Delete items
  947. $auth = AuthItem::model()->findByPk($action);
  948. if ($auth !== null) {
  949. $auth->delete();
  950. }
  951. $allowed[] = $action;
  952. }
  953. }
  954. $handle = fopen($this->module->getAlwaysAllowedFile(), "wb");
  955. fwrite($handle, "<?php \n return array(\n\t'" . implode("',\n\t'", $allowed) . "'\n);\n?>");
  956. fclose($handle);
  957. $this->renderPartial("saveAllowed", array("allowed" => $allowed));
  958. }
  959. public function actionClearObsolete() {
  960. $obsolete = array();
  961. $controllers = $this->_getControllers();
  962. $controllers = array_map(array($this, "replace"), $controllers);
  963. /* @var $auth CDbAuthManager */
  964. $auth = Yii::app()->authManager;
  965. $items = array_merge($auth->tasks, $auth->operations);
  966. foreach ($controllers as $contId => $cont) {
  967. foreach ($items as $item => $val) {
  968. $length = strlen($cont);
  969. $contItem = substr($item, 0, $length);
  970. if ($cont == $contItem) {
  971. unset($items[$item]);
  972. }
  973. }
  974. }
  975. foreach ($items as $key => $value) {
  976. $obsolete[$key] = $key;
  977. }
  978. $this->renderPartial("manage/clearObsolete", array("items" => $obsolete), false, true);
  979. }
  980. private function replace($value) {
  981. return str_replace("Controller", "", $value);
  982. }
  983. public function actionDeleteObsolete() {
  984. $removed = array();
  985. $notRemoved = array();
  986. if (isset($_POST["items"])) {
  987. $auth = Yii::app()->authManager;
  988. foreach ($_POST["items"] as $item) {
  989. if ($auth->removeAuthItem($item)) {
  990. $removed[] = $item;
  991. } else {
  992. $notRemoved[] = $item;
  993. }
  994. }
  995. }
  996. $this->renderPartial("manage/obsoleteRemoved", array("removed" => $removed, "notRemoved" => $notRemoved));
  997. }
  998. }