Manager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. namespace AdminAddonUserManager\Users;
  3. use Grav\Common\Grav;
  4. use Grav\Plugin\AdminAddonUserManagerPlugin;
  5. use Grav\Common\Assets;
  6. use Grav\Common\Data\Blueprints;
  7. use RocketTheme\Toolbox\Event\Event;
  8. use AdminAddonUserManager\Manager as IManager;
  9. use AdminAddonUserManager\Pagination\ArrayPagination;
  10. use Grav\Common\Utils;
  11. use Grav\Common\User\User;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  14. use Symfony\Component\ExpressionLanguage\ExpressionFunction;
  15. use AdminAddonUserManager\Group;
  16. use AdminAddonUserManager\Dot;
  17. class Manager implements IManager, EventSubscriberInterface {
  18. private $grav;
  19. private $plugin;
  20. private $adminController;
  21. /**
  22. * In-memory caching for users
  23. *
  24. * @var Array<User>
  25. */
  26. private $usersCached = null;
  27. /**
  28. * In-memory cache of the account directory
  29. *
  30. * @var String
  31. */
  32. private $accountDirCached = null;
  33. public static $instance;
  34. public function __construct(Grav $grav, AdminAddonUserManagerPlugin $plugin) {
  35. $this->grav = $grav;
  36. $this->plugin = $plugin;
  37. self::$instance = $this;
  38. $this->grav['events']->addSubscriber($this);
  39. }
  40. public static function getSubscribedEvents() {
  41. return [
  42. 'onAdminControllerInit' => ['onAdminControllerInit', 0],
  43. 'onAdminData' => ['onAdminData', 0]
  44. ];
  45. }
  46. public function onAdminControllerInit($e) {
  47. $controller = $e['controller'];
  48. $this->adminController = $controller;
  49. }
  50. public function onAdminData($e) {
  51. $type = $e['type'];
  52. if (preg_match('|user-manager/|', $type)) {
  53. $post = $this->adminController->data;
  54. $obj = $this->grav['accounts']->load(preg_replace('|user-manager/|', '', $type));
  55. $obj->merge($post);
  56. $e['data_type'] = $obj;
  57. }
  58. }
  59. /**
  60. * Returns the required permission to access the manager
  61. *
  62. * @return string
  63. */
  64. public function getRequiredPermission() {
  65. return $this->plugin->name . '.users';
  66. }
  67. /**
  68. * Returns the location of the manager
  69. * It will be accessible at this path
  70. *
  71. * @return string
  72. */
  73. public function getLocation() {
  74. return 'user-manager';
  75. }
  76. /**
  77. * Returns the plugin hooked nav array
  78. *
  79. * @return array
  80. */
  81. public function getNav() {
  82. return [
  83. 'label' => 'PLUGIN_ADMIN_ADDON_USER_MANAGER.USER_MANAGER',
  84. 'location' => $this->getLocation(),
  85. 'icon' => 'fa-user',
  86. 'authorize' => $this->getRequiredPermission(),
  87. 'badge' => [
  88. 'count' => count($this->users())
  89. ]
  90. ];
  91. }
  92. /**
  93. * Initialiaze required assets
  94. *
  95. * @param \Grav\Common\Assets $assets
  96. * @return void
  97. */
  98. public function initializeAssets(Assets $assets) {
  99. $assets->addCss('plugin://' . $this->plugin->name . '/assets/users/style.css');
  100. }
  101. /**
  102. * Handle task requests
  103. *
  104. * @param \RocketTheme\Toolbox\Event\Event $event
  105. * @return boolean
  106. */
  107. public function handleTask(Event $event) {
  108. $method = $event['method'];
  109. if ($method === 'taskUserDelete') {
  110. $username = $this->grav['uri']->paths()[2];
  111. if ($this->removeUser($username)) {
  112. $this->adminController->setRedirect($this->getLocation());
  113. }
  114. } elseif ($method === 'taskUserLoginAs') {
  115. $username = $this->grav['uri']->paths()[2];
  116. $user = $this->grav['accounts']->load($username);
  117. $user->authenticated = true;
  118. $this->grav['session']->user = $user;
  119. unset($this->grav['user']);
  120. $this->grav['user'] = $user;
  121. if ($user->authorize('admin.login')) {
  122. $this->adminController->setRedirect('/');
  123. } else {
  124. $this->grav->redirect('/');
  125. }
  126. }
  127. return false;
  128. }
  129. /**
  130. * Logic of the manager goes here
  131. *
  132. * @return array The array to be merged to Twig vars
  133. */
  134. public function handleRequest() {
  135. $vars = [];
  136. $twig = $this->grav['twig'];
  137. $uri = $this->grav['uri'];
  138. $user = $this->grav['uri']->paths();
  139. if (count($user) == 3) {
  140. $user = $user[2];
  141. } else {
  142. $user = false;
  143. }
  144. if ($user) {
  145. if (isset($_POST['task']) && $_POST['task'] === 'admin-addon-user-manager-save') {
  146. $user = $this->grav['accounts']->load($user);
  147. $post = $_POST['data'];
  148. try {
  149. $user->merge($post);
  150. $method = new \ReflectionMethod('\Grav\Plugin\Admin\AdminController', 'storeFiles');
  151. $method->setAccessible(true);
  152. $user = $method->invoke($this->adminController, $user);
  153. $user->validate();
  154. $user->filter();
  155. $user->save();
  156. } catch (\Exception $e) {
  157. $this->grav['admin']->setMessage($e->getMessage(), 'error');
  158. }
  159. $this->grav->redirect($this->plugin->getPreviousUrl());
  160. } else {
  161. $blueprints = new Blueprints;
  162. $blueprint = $blueprints->get('user/aaum-account');
  163. $vars['blueprints'] = $blueprint;
  164. $vars['user'] = $user = $this->grav['accounts']->load($user);
  165. $vars['exists'] = $user->exists();
  166. }
  167. } else {
  168. // Bulk actions
  169. if (isset($_POST['selected'])) {
  170. $usernames = $_POST['selected'];
  171. if (isset($_POST['bulk_delete'])) {
  172. // Bulk delete
  173. foreach ($usernames as $username) {
  174. $this->removeUser($username);
  175. }
  176. $this->grav->redirect($this->plugin->getPreviousUrl());
  177. } else if (isset($_POST['bulk_add_to_group']) && isset($_POST['groups'])) {
  178. // Bulk add users to groups
  179. $groups = $_POST['groups'];
  180. foreach ($usernames as $username) {
  181. $user = $this->grav['accounts']->load($username);
  182. if ($user->file()->exists()) {
  183. if (!isset($user['groups']) || !is_array($user['groups'])) {
  184. $user['groups'] = [];
  185. }
  186. $user['groups'] = array_unique(array_merge($user['groups'], $groups));
  187. $user->save();
  188. }
  189. }
  190. $this->grav->redirect($this->plugin->getPreviousUrl());
  191. } else if (isset($_POST['bulk_remove_from_group']) && isset($_POST['groups'])) {
  192. // Bulk remove users from groups
  193. $groups = $_POST['groups'];
  194. foreach ($usernames as $username) {
  195. $user = $this->grav['accounts']->load($username);
  196. if ($user->file()->exists()) {
  197. if (!isset($user['groups']) || !is_array($user['groups'])) {
  198. $user['groups'] = [];
  199. }
  200. $user['groups'] = array_unique(array_diff($user['groups'], $groups));
  201. $user->save();
  202. }
  203. }
  204. $this->grav->redirect($this->plugin->getPreviousUrl());
  205. } else if (isset($_POST['bulk_add_acl']) && isset($_POST['permissions'])) {
  206. // Bulk add permissions to users
  207. $access = [];
  208. foreach ($_POST['permissions'] as $p) {
  209. Dot::set($access, $p, true);
  210. }
  211. foreach ($usernames as $username) {
  212. $user = $this->grav['accounts']->load($username);
  213. if ($user->file()->exists()) {
  214. if (!isset($user['access']) || !is_array($user['access'])) {
  215. $user['access'] = [];
  216. }
  217. $user['access'] = array_merge_recursive($user['access'], $access);
  218. $user->save();
  219. }
  220. }
  221. $this->grav->redirect($this->plugin->getPreviousUrl());
  222. } else if (isset($_POST['bulk_remove_acl']) && isset($_POST['permissions'])) {
  223. // Bulk remove permissions from users
  224. foreach ($usernames as $username) {
  225. $user = $this->grav['accounts']->load($username);
  226. if ($user->file()->exists()) {
  227. if (!isset($user['access']) || !is_array($user['access'])) {
  228. $user['access'] = [];
  229. }
  230. $access = $user['access'];
  231. foreach ($_POST['permissions'] as $p) {
  232. Dot::delete($access, $p);
  233. }
  234. $user['access'] = $access;
  235. $user->save();
  236. }
  237. }
  238. $this->grav->redirect($this->plugin->getPreviousUrl());
  239. }
  240. }
  241. $vars['fields'] = $this->plugin->getModalsConfiguration()['add_user']['fields'];
  242. $vars['bulkFields'] = $this->plugin->getModalsConfiguration()['bulk_user']['fields'];
  243. $vars['groupnames'] = Group::groupNames();
  244. $permissions = array_keys($this->grav['admin']->getPermissions());
  245. foreach ($permissions as $k=>&$v) $v = ['text' => $v, 'value' => $v];
  246. $vars['permissions'] = $permissions;
  247. // List style (grid or list)
  248. $listStyle = $uri->param('listStyle');
  249. if ($listStyle !== 'grid' && $listStyle !== 'list') {
  250. $listStyle = $this->plugin->getPluginConfigValue('default_list_style', 'grid');
  251. }
  252. $vars['listStyle'] = $listStyle;
  253. $users = $this->users();
  254. // Filtering
  255. $filterException = false;
  256. $filter = (empty($_GET['filter'])) ? '' : $_GET['filter'];
  257. $vars['filter'] = $filter;
  258. if ($filter) {
  259. try {
  260. $language = new ExpressionLanguage();
  261. $language->addFunction(ExpressionFunction::fromPhp('count'));
  262. foreach ($users as $k => $user) {
  263. if (!is_array($user->groups)) {
  264. $user->groups = [];
  265. }
  266. if (!$language->evaluate($_GET['filter'], ['user' => $user])) {
  267. unset($users[$k]);
  268. }
  269. }
  270. } catch (\Exception $exception) {
  271. $vars['filterException'] = $exception;
  272. $filterException = true;
  273. }
  274. }
  275. if ($filterException) {
  276. $users = [];
  277. }
  278. // Pagination
  279. $perPage = $this->plugin->getPluginConfigValue('pagination.per_page', 10);
  280. $pagination = new ArrayPagination($users, $perPage);
  281. $pagination->paginate($uri->param('page'));
  282. $vars['pagination'] = [
  283. 'current' => $pagination->getCurrentPage(),
  284. 'count' => $pagination->getPagesCount(),
  285. 'total' => $pagination->getRowsCount(),
  286. 'perPage' => $pagination->getRowsPerPage(),
  287. 'startOffset' => $pagination->getStartOffset(),
  288. 'endOffset' => $pagination->getEndOffset()
  289. ];
  290. $vars['users'] = $pagination->getPaginatedRows();
  291. $vars['user'] = false;
  292. }
  293. return $vars;
  294. }
  295. public function users() {
  296. if ($this->usersCached) {
  297. return $this->usersCached;
  298. }
  299. $users = [];
  300. $dir = $this->getAccountDir();
  301. // Try cache
  302. $cache = $this->grav['cache'];
  303. $cacheKey = $this->plugin->name . '.users';
  304. $modifyTime = filemtime($dir);
  305. $usersCache = $cache->fetch($cacheKey);
  306. if (!$usersCache || $modifyTime > $usersCache['modifyTime']) {
  307. // Find accounts
  308. $files = $dir ? array_diff(scandir($dir), ['.', '..']) : [];
  309. foreach ($files as $file) {
  310. if (Utils::endsWith($file, YAML_EXT)) {
  311. $user = $this->grav['accounts']->load(trim(pathinfo($file, PATHINFO_FILENAME)));
  312. $users[$user->username] = $user;
  313. }
  314. }
  315. // Populate and/or refresh cache
  316. $this->saveUsersToCache($users);
  317. } else {
  318. $users = $usersCache['users'];
  319. }
  320. $this->usersCached = $users;
  321. return $users;
  322. }
  323. private function saveUsersToCache($users) {
  324. $cache = $this->grav['cache'];
  325. $cacheKey = $this->plugin->name . '.users';
  326. $dir = $this->getAccountDir();
  327. $modifyTime = filemtime($dir);
  328. $usersCache = [
  329. 'modifyTime' => $modifyTime,
  330. 'users' => $users,
  331. ];
  332. $cache->save($cacheKey, $usersCache);
  333. }
  334. private function getAccountDir() {
  335. if ($this->accountDirCached) {
  336. return $this->grav['locator']->findResource('account://');
  337. }
  338. return $this->accountDirCached = $this->grav['locator']->findResource('account://');
  339. }
  340. public function removeUser($username) {
  341. $user = $this->grav['accounts']->load($username);
  342. if ($user->file()->exists()) {
  343. $users = $this->users();
  344. $user->file()->delete();
  345. // Prevent users cache refresh
  346. unset($users[$username]);
  347. $this->saveUsersToCache($users);
  348. return true;
  349. }
  350. return false;
  351. }
  352. public static function userNames() {
  353. $instance = self::$instance;
  354. $users = $instance->users();
  355. $userNames = [];
  356. foreach ($users as $u) {
  357. $userNames[$u['username']] = $u['username'];
  358. }
  359. return $userNames;
  360. }
  361. }