SettingsController.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. <?php
  2. namespace Typemill\Controllers;
  3. use \Symfony\Component\Yaml\Yaml;
  4. use Typemill\Models\Write;
  5. use Typemill\Models\Fields;
  6. use Typemill\Models\Validation;
  7. use Typemill\Models\User;
  8. use Typemill\Models\ProcessFile;
  9. use Typemill\Models\ProcessImage;
  10. use Typemill\Events\OnUserfieldsLoaded;
  11. use Typemill\Events\OnSystemnaviLoaded;
  12. class SettingsController extends Controller
  13. {
  14. public function showBlank($request, $response, $args)
  15. {
  16. $user = new User();
  17. $settings = $this->c->get('settings');
  18. # $users = $user->getUsers();
  19. $route = $request->getAttribute('route');
  20. $navigation = $this->getNavigation();
  21. $content = '<h1>Hello</h1>';
  22. return $this->render($response, 'settings/blank.twig', array(
  23. 'settings' => $settings,
  24. 'acl' => $this->c->acl,
  25. 'navigation' => $navigation,
  26. 'content' => $content,
  27. # 'users' => $users,
  28. 'route' => $route->getName()
  29. ));
  30. }
  31. /*********************
  32. ** BASIC SETTINGS **
  33. *********************/
  34. public function showSettings($request, $response, $args)
  35. {
  36. $user = new User();
  37. $settings = $this->c->get('settings');
  38. $defaultSettings = \Typemill\Settings::getDefaultSettings();
  39. $copyright = $this->getCopyright();
  40. $languages = $this->getLanguages();
  41. $locale = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2) : 'en';
  42. $route = $request->getAttribute('route');
  43. $navigation = $this->getNavigation();
  44. # set navigation active
  45. $navigation['System']['active'] = true;
  46. # set option for registered website
  47. $options = ['' => 'all', 'registered' => 'registered users only'];
  48. return $this->render($response, 'settings/system.twig', array(
  49. 'settings' => $settings,
  50. 'acl' => $this->c->acl,
  51. 'navigation' => $navigation,
  52. 'copyright' => $copyright,
  53. 'languages' => $languages,
  54. 'locale' => $locale,
  55. 'formats' => $defaultSettings['formats'],
  56. 'access' => $options,
  57. 'route' => $route->getName()
  58. ));
  59. }
  60. public function saveSettings($request, $response, $args)
  61. {
  62. if($request->isPost())
  63. {
  64. $settings = \Typemill\Settings::getUserSettings();
  65. $defaultSettings = \Typemill\Settings::getDefaultSettings();
  66. $params = $request->getParams();
  67. $files = $request->getUploadedFiles();
  68. $newSettings = isset($params['settings']) ? $params['settings'] : false;
  69. $validate = new Validation();
  70. $processFiles = new ProcessFile();
  71. if($newSettings)
  72. {
  73. /* make sure only allowed fields are stored */
  74. $newSettings = array(
  75. 'title' => $newSettings['title'],
  76. 'author' => $newSettings['author'],
  77. 'copyright' => $newSettings['copyright'],
  78. 'year' => $newSettings['year'],
  79. 'language' => $newSettings['language'],
  80. 'langattr' => $newSettings['langattr'],
  81. 'editor' => $newSettings['editor'],
  82. 'access' => $newSettings['access'],
  83. 'formats' => $newSettings['formats'],
  84. 'headlineanchors' => isset($newSettings['headlineanchors']) ? $newSettings['headlineanchors'] : null,
  85. );
  86. # https://www.slimframework.com/docs/v3/cookbook/uploading-files.html;
  87. $copyright = $this->getCopyright();
  88. $validate->settings($newSettings, $copyright, $defaultSettings['formats'], 'settings');
  89. }
  90. else
  91. {
  92. $this->c->flash->addMessage('error', 'Wrong Input');
  93. return $response->withRedirect($this->c->router->pathFor('settings.show'));
  94. }
  95. if(isset($_SESSION['errors']))
  96. {
  97. $this->c->flash->addMessage('error', 'Please correct the errors');
  98. return $response->withRedirect($this->c->router->pathFor('settings.show'));
  99. }
  100. if(!$processFiles->checkFolders())
  101. {
  102. $this->c->flash->addMessage('error', 'Please make sure that your media folder exists and is writable.');
  103. return $response->withRedirect($this->c->router->pathFor('settings.show'));
  104. }
  105. # handle single input with single file upload
  106. $logo = $files['settings']['logo'];
  107. if($logo->getError() === UPLOAD_ERR_OK)
  108. {
  109. $allowed = ['jpg', 'jpeg', 'png', 'svg'];
  110. $extension = pathinfo($logo->getClientFilename(), PATHINFO_EXTENSION);
  111. if(!in_array(strtolower($extension), $allowed))
  112. {
  113. $_SESSION['errors']['settings']['logo'] = array('Only jpg, jpeg, png and svg allowed');
  114. $this->c->flash->addMessage('error', 'Please correct the errors');
  115. return $response->withRedirect($this->c->router->pathFor('settings.show'));
  116. }
  117. $processFiles->deleteFileWithName('logo');
  118. $newSettings['logo'] = $processFiles->moveUploadedFile($logo, $overwrite = true, $name = 'logo');
  119. }
  120. elseif(isset($params['settings']['deletelogo']) && $params['settings']['deletelogo'] == 'delete')
  121. {
  122. $processFiles->deleteFileWithName('logo');
  123. $newSettings['logo'] = '';
  124. }
  125. else
  126. {
  127. $newSettings['logo'] = isset($settings['logo']) ? $settings['logo'] : '';
  128. }
  129. # handle single input with single file upload
  130. $favicon = $files['settings']['favicon'];
  131. if ($favicon->getError() === UPLOAD_ERR_OK)
  132. {
  133. $extension = pathinfo($favicon->getClientFilename(), PATHINFO_EXTENSION);
  134. if(strtolower($extension) != 'png')
  135. {
  136. $_SESSION['errors']['settings']['favicon'] = array('Only .png-files allowed');
  137. $this->c->flash->addMessage('error', 'Please correct the errors');
  138. return $response->withRedirect($this->c->router->pathFor('settings.show'));
  139. }
  140. $processImage = new ProcessImage([
  141. '16' => ['width' => 16, 'height' => 16],
  142. '32' => ['width' => 32, 'height' => 32],
  143. '72' => ['width' => 72, 'height' => 72],
  144. '114' => ['width' => 114, 'height' => 114],
  145. '144' => ['width' => 144, 'height' => 144],
  146. '180' => ['width' => 180, 'height' => 180],
  147. ]);
  148. $favicons = $processImage->generateSizesFromImageFile('favicon.png', $favicon->file);
  149. foreach($favicons as $key => $favicon)
  150. {
  151. imagepng( $favicon, $processFiles->fileFolder . 'favicon-' . $key . '.png' );
  152. # $processFiles->moveUploadedFile($favicon, $overwrite = true, $name = 'favicon-' . $key);
  153. }
  154. $newSettings['favicon'] = 'favicon';
  155. }
  156. elseif(isset($params['settings']['deletefav']) && $params['settings']['deletefav'] == 'delete')
  157. {
  158. $processFiles->deleteFileWithName('favicon');
  159. $newSettings['favicon'] = '';
  160. }
  161. else
  162. {
  163. $newSettings['favicon'] = isset($settings['favicon']) ? $settings['favicon'] : '';
  164. }
  165. # store updated settings
  166. \Typemill\Settings::updateSettings(array_merge($settings, $newSettings));
  167. $this->c->flash->addMessage('info', 'Settings are stored');
  168. return $response->withRedirect($this->c->router->pathFor('settings.show'));
  169. }
  170. }
  171. /*********************
  172. ** THEME SETTINGS **
  173. *********************/
  174. public function showThemes($request, $response, $args)
  175. {
  176. $userSettings = $this->c->get('settings');
  177. $themes = $this->getThemes();
  178. $themedata = array();
  179. $fieldsModel = new Fields();
  180. foreach($themes as $themeName)
  181. {
  182. /* if theme is active, list it first */
  183. if($userSettings['theme'] == $themeName)
  184. {
  185. $themedata = array_merge(array($themeName => null), $themedata);
  186. }
  187. else
  188. {
  189. $themedata[$themeName] = null;
  190. }
  191. $themeSettings = \Typemill\Settings::getObjectSettings('themes', $themeName);
  192. # add standard-textarea for custom css
  193. $themeSettings['forms']['fields']['customcss'] = ['type' => 'textarea', 'label' => 'Custom CSS', 'rows' => 10, 'class' => 'codearea', 'description' => 'You can overwrite the theme-css with your own css here.'];
  194. # load custom css-file
  195. $write = new write();
  196. $customcss = $write->getFile('cache', $themeName . '-custom.css');
  197. $themeSettings['settings']['customcss'] = $customcss;
  198. if($themeSettings)
  199. {
  200. /* store them as default theme data with author, year, default settings and field-definitions */
  201. $themedata[$themeName] = $themeSettings;
  202. }
  203. if(isset($themeSettings['forms']['fields']))
  204. {
  205. $fields = $fieldsModel->getFields($userSettings, 'themes', $themeName, $themeSettings);
  206. /* overwrite original theme form definitions with enhanced form objects */
  207. $themedata[$themeName]['forms']['fields'] = $fields;
  208. }
  209. /* add the preview image */
  210. $img = getcwd() . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $themeName . DIRECTORY_SEPARATOR . $themeName;
  211. $image = false;
  212. if(file_exists($img . '.jpg'))
  213. {
  214. $image = $themeName . '.jpg';
  215. }
  216. if(file_exists($img . '.png'))
  217. {
  218. $image = $themeName . '.png';
  219. }
  220. $themedata[$themeName]['img'] = $image;
  221. }
  222. /* add the users for navigation */
  223. $route = $request->getAttribute('route');
  224. $navigation = $this->getNavigation();
  225. # set navigation active
  226. $navigation['Themes']['active'] = true;
  227. return $this->render($response, 'settings/themes.twig', array(
  228. 'settings' => $userSettings,
  229. 'acl' => $this->c->acl,
  230. 'navigation' => $navigation,
  231. 'themes' => $themedata,
  232. 'route' => $route->getName()
  233. ));
  234. }
  235. public function showPlugins($request, $response, $args)
  236. {
  237. $userSettings = $this->c->get('settings');
  238. $plugins = array();
  239. $fieldsModel = new Fields();
  240. $fields = array();
  241. /* iterate through the plugins in the stored user settings */
  242. foreach($userSettings['plugins'] as $pluginName => $pluginUserSettings)
  243. {
  244. /* add plugin to plugin Data, if active, set it first */
  245. /* if plugin is active, list it first */
  246. if($userSettings['plugins'][$pluginName]['active'] == true)
  247. {
  248. $plugins = array_merge(array($pluginName => null), $plugins);
  249. }
  250. else
  251. {
  252. $plugins[$pluginName] = Null;
  253. }
  254. /* Check if the user has deleted a plugin. Then delete it in the settings and store the updated settings. */
  255. if(!is_dir($userSettings['rootPath'] . 'plugins' . DIRECTORY_SEPARATOR . $pluginName))
  256. {
  257. /* remove the plugin settings and store updated settings */
  258. \Typemill\Settings::removePluginSettings($pluginName);
  259. continue;
  260. }
  261. /* load the original plugin definitions from the plugin folder (author, version and stuff) */
  262. $pluginOriginalSettings = \Typemill\Settings::getObjectSettings('plugins', $pluginName);
  263. if($pluginOriginalSettings)
  264. {
  265. /* store them as default plugin data with plugin author, plugin year, default settings and field-definitions */
  266. $plugins[$pluginName] = $pluginOriginalSettings;
  267. }
  268. /* check, if the plugin has been disabled in the form-session-data */
  269. if(isset($_SESSION['old']) && !isset($_SESSION['old'][$pluginName]['active']))
  270. {
  271. $plugins[$pluginName]['settings']['active'] = false;
  272. }
  273. /* if the plugin defines forms and fields, so that the user can edit the plugin settings in the frontend */
  274. if(isset($pluginOriginalSettings['forms']['fields']))
  275. {
  276. # if the plugin defines frontend fields
  277. if(isset($pluginOriginalSettings['public']))
  278. {
  279. $pluginOriginalSettings['forms']['fields']['recaptcha'] = ['type' => 'checkbox', 'label' => 'Google Recaptcha', 'checkboxlabel' => 'Activate Recaptcha' ];
  280. $pluginOriginalSettings['forms']['fields']['recaptcha_webkey'] = ['type' => 'text', 'label' => 'Recaptcha Website Key', 'help' => 'Add the recaptcha website key here. You can get the key from the recaptcha website.', 'description' => 'The website key is mandatory if you activate the recaptcha field'];
  281. $pluginOriginalSettings['forms']['fields']['recaptcha_secretkey'] = ['type' => 'text', 'label' => 'Recaptcha Secret Key', 'help' => 'Add the recaptcha secret key here. You can get the key from the recaptcha website.', 'description' => 'The secret key is mandatory if you activate the recaptcha field'];
  282. }
  283. /* get all the fields and prefill them with the dafault-data, the user-data or old input data */
  284. $fields = $fieldsModel->getFields($userSettings, 'plugins', $pluginName, $pluginOriginalSettings);
  285. /* overwrite original plugin form definitions with enhanced form objects */
  286. $plugins[$pluginName]['forms']['fields'] = $fields;
  287. }
  288. }
  289. $route = $request->getAttribute('route');
  290. $navigation = $this->getNavigation();
  291. # set navigation active
  292. $navigation['Plugins']['active'] = true;
  293. return $this->render($response, 'settings/plugins.twig', array(
  294. 'settings' => $userSettings,
  295. 'acl' => $this->c->acl,
  296. 'navigation' => $navigation,
  297. 'plugins' => $plugins,
  298. 'route' => $route->getName()
  299. ));
  300. }
  301. /*************************************
  302. ** SAVE THEME- AND PLUGIN-SETTINGS **
  303. *************************************/
  304. public function saveThemes($request, $response, $args)
  305. {
  306. if($request->isPost())
  307. {
  308. $userSettings = \Typemill\Settings::getUserSettings();
  309. $params = $request->getParams();
  310. $themeName = isset($params['theme']) ? $params['theme'] : false;
  311. $userInput = isset($params[$themeName]) ? $params[$themeName] : false;
  312. $validate = new Validation();
  313. $themeSettings = \Typemill\Settings::getObjectSettings('themes', $themeName);
  314. if(isset($themeSettings['settings']['images']))
  315. {
  316. # get the default settings
  317. $defaultSettings = \Typemill\Settings::getDefaultSettings();
  318. # merge the default image settings with the theme image settings, delete all others (image settings from old theme)
  319. $userSettings['images'] = array_merge($defaultSettings['images'], $themeSettings['settings']['images']);
  320. }
  321. /* set theme name and delete theme settings from user settings for the case, that the new theme has no settings */
  322. $userSettings['theme'] = $themeName;
  323. # extract the custom css from user input
  324. $customcss = isset($userInput['customcss']) ? $userInput['customcss'] : false;
  325. # delete custom css from userinput
  326. unset($userInput['customcss']);
  327. $write = new write();
  328. # make sure no file is set if there is no custom css
  329. if(!$customcss OR $customcss == '')
  330. {
  331. # delete the css file if exists
  332. $write->deleteFileWithPath('cache' . DIRECTORY_SEPARATOR . $themeName . '-custom.css');
  333. }
  334. else
  335. {
  336. if ( $customcss != strip_tags($customcss) )
  337. {
  338. $_SESSION['errors'][$themeName]['customcss'][] = 'custom css contains html';
  339. }
  340. else
  341. {
  342. # store css
  343. $write = new write();
  344. $write->writeFile('cache', $themeName . '-custom.css', $customcss);
  345. }
  346. }
  347. if($userInput)
  348. {
  349. # validate the user-input and return image-fields if they are defined
  350. $imageFields = $this->validateInput('themes', $themeName, $userInput, $validate);
  351. /* set user input as theme settings */
  352. $userSettings['themes'][$themeName] = $userInput;
  353. }
  354. # handle images
  355. $images = $request->getUploadedFiles();
  356. if(!isset($_SESSION['errors']) && isset($images[$themeName]))
  357. {
  358. $userInput = $this->saveImages($imageFields, $userInput, $userSettings, $images[$themeName]);
  359. # set user input as theme settings
  360. $userSettings['themes'][$themeName] = $userInput;
  361. }
  362. /* check for errors and redirect to path, if errors found */
  363. if(isset($_SESSION['errors']))
  364. {
  365. $this->c->flash->addMessage('error', 'Please correct the errors');
  366. return $response->withRedirect($this->c->router->pathFor('themes.show'));
  367. }
  368. /* store updated settings */
  369. \Typemill\Settings::updateSettings($userSettings);
  370. $this->c->flash->addMessage('info', 'Settings are stored');
  371. return $response->withRedirect($this->c->router->pathFor('themes.show'));
  372. }
  373. }
  374. public function savePlugins($request, $response, $args)
  375. {
  376. if($request->isPost())
  377. {
  378. $userSettings = \Typemill\Settings::getUserSettings();
  379. $pluginSettings = array();
  380. $userInput = $request->getParams();
  381. $validate = new Validation();
  382. /* use the stored user settings and iterate over all original plugin settings, so we do not forget any... */
  383. foreach($userSettings['plugins'] as $pluginName => $pluginUserSettings)
  384. {
  385. /* if there are no input-data for this plugin, then use the stored plugin settings */
  386. if(!isset($userInput[$pluginName]))
  387. {
  388. $pluginSettings[$pluginName] = $pluginUserSettings;
  389. }
  390. else
  391. {
  392. /* validate the user-input */
  393. $imageFields = $this->validateInput('plugins', $pluginName, $userInput[$pluginName], $validate);
  394. /* use the input data */
  395. $pluginSettings[$pluginName] = $userInput[$pluginName];
  396. }
  397. # handle images
  398. $images = $request->getUploadedFiles();
  399. if(!isset($_SESSION['errors']) && isset($images[$pluginName]))
  400. {
  401. $userInput[$pluginName] = $this->saveImages($imageFields, $userInput[$pluginName], $userSettings, $images[$pluginName]);
  402. # set user input as theme settings
  403. $pluginSettings[$pluginName] = $userInput[$pluginName];
  404. }
  405. /* deactivate the plugin, if there is no active flag */
  406. if(!isset($userInput[$pluginName]['active']))
  407. {
  408. $pluginSettings[$pluginName]['active'] = false;
  409. }
  410. }
  411. if(isset($_SESSION['errors']))
  412. {
  413. $this->c->flash->addMessage('error', 'Please correct the errors below');
  414. }
  415. else
  416. {
  417. /* if everything is valid, add plugin settings to base settings again */
  418. $userSettings['plugins'] = $pluginSettings;
  419. /* store updated settings */
  420. \Typemill\Settings::updateSettings($userSettings);
  421. $this->c->flash->addMessage('info', 'Settings are stored');
  422. }
  423. return $response->withRedirect($this->c->router->pathFor('plugins.show'));
  424. }
  425. }
  426. /***********************
  427. ** USER MANAGEMENT **
  428. ***********************/
  429. public function showAccount($request, $response, $args)
  430. {
  431. $username = $_SESSION['user'];
  432. $validate = new Validation();
  433. if($validate->username($username))
  434. {
  435. # get settings
  436. $settings = $this->c->get('settings');
  437. # get user with userdata
  438. $user = new User();
  439. $userdata = $user->getSecureUser($username);
  440. # instantiate field-builder
  441. $fieldsModel = new Fields();
  442. # get the field-definitions
  443. $fieldDefinitions = $this->getUserFields($userdata['userrole']);
  444. # prepare userdata for field-builder
  445. $userSettings['users']['user'] = $userdata;
  446. # generate the input form
  447. $userform = $fieldsModel->getFields($userSettings, 'users', 'user', $fieldDefinitions);
  448. $route = $request->getAttribute('route');
  449. $navigation = $this->getNavigation();
  450. # set navigation active
  451. $navigation['Account']['active'] = true;
  452. return $this->render($response, 'settings/user.twig', array(
  453. 'settings' => $settings,
  454. 'acl' => $this->c->acl,
  455. 'navigation' => $navigation,
  456. 'usersettings' => $userSettings, // needed for image url in form, will overwrite settings for field-template
  457. 'userform' => $userform, // field model, needed to generate frontend-field
  458. 'userdata' => $userdata, // needed to fill form with data
  459. # 'userrole' => false, // not needed ?
  460. # 'username' => $args['username'], // not needed ?
  461. 'route' => $route->getName() // needed to set link active
  462. ));
  463. }
  464. $this->c->flash->addMessage('error', 'User does not exists');
  465. return $response->withRedirect($this->c->router->pathFor('home'));
  466. }
  467. public function showUser($request, $response, $args)
  468. {
  469. # if user has no rights to watch userlist, then redirect to
  470. if(!$this->c->acl->isAllowed($_SESSION['role'], 'userlist', 'view') && $_SESSION['user'] !== $args['username'] )
  471. {
  472. return $response->withRedirect($this->c->router->pathFor('user.show', ['username' => $_SESSION['user']] ));
  473. }
  474. $validate = new Validation();
  475. if($validate->username($args['username']))
  476. {
  477. # get settings
  478. $settings = $this->c->get('settings');
  479. # get user with userdata
  480. $user = new User();
  481. $userdata = $user->getSecureUser($args['username']);
  482. $username = $userdata['username'];
  483. # instantiate field-builder
  484. $fieldsModel = new Fields();
  485. # get the field-definitions
  486. $fieldDefinitions = $this->getUserFields($userdata['userrole']);
  487. # prepare userdata for field-builder
  488. $userSettings['users']['user'] = $userdata;
  489. # generate the input form
  490. $userform = $fieldsModel->getFields($userSettings, 'users', 'user', $fieldDefinitions);
  491. $route = $request->getAttribute('route');
  492. $navigation = $this->getNavigation();
  493. # set navigation active
  494. $navigation['Users']['active'] = true;
  495. return $this->render($response, 'settings/user.twig', array(
  496. 'settings' => $settings,
  497. 'acl' => $this->c->acl,
  498. 'navigation' => $navigation,
  499. 'usersettings' => $userSettings, // needed for image url in form, will overwrite settings for field-template
  500. 'userform' => $userform, // field model, needed to generate frontend-field
  501. 'userdata' => $userdata, // needed to fill form with data
  502. # 'userrole' => false, // not needed ?
  503. # 'username' => $args['username'], // not needed ?
  504. 'route' => $route->getName() // needed to set link active
  505. ));
  506. }
  507. $this->c->flash->addMessage('error', 'User does not exists');
  508. return $response->withRedirect($this->c->router->pathFor('user.account'));
  509. }
  510. public function listUser($request, $response)
  511. {
  512. $user = new User();
  513. $users = $user->getUsers();
  514. $userdata = array();
  515. $route = $request->getAttribute('route');
  516. $settings = $this->c->get('settings');
  517. $navigation = $this->getNavigation();
  518. # set navigation active
  519. $navigation['Users']['active'] = true;
  520. foreach($users as $username)
  521. {
  522. $userdata[] = $user->getUser($username);
  523. }
  524. return $this->render($response, 'settings/userlist.twig', array(
  525. 'settings' => $settings,
  526. 'acl' => $this->c->acl,
  527. 'navigation' => $navigation,
  528. 'users' => $users,
  529. 'userdata' => $userdata,
  530. 'route' => $route->getName()
  531. ));
  532. }
  533. public function newUser($request, $response, $args)
  534. {
  535. $user = new User();
  536. $users = $user->getUsers();
  537. $userroles = $this->c->acl->getRoles();
  538. $route = $request->getAttribute('route');
  539. $settings = $this->c->get('settings');
  540. $navigation = $this->getNavigation();
  541. # set navigation active
  542. $navigation['Users']['active'] = true;
  543. return $this->render($response, 'settings/usernew.twig', array(
  544. 'settings' => $settings,
  545. 'acl' => $this->c->acl,
  546. 'navigation' => $navigation,
  547. 'users' => $users,
  548. 'userrole' => $userroles,
  549. 'route' => $route->getName()
  550. ));
  551. }
  552. public function createUser($request, $response, $args)
  553. {
  554. if($request->isPost())
  555. {
  556. $params = $request->getParams();
  557. $user = new User();
  558. $validate = new Validation();
  559. $userroles = $this->c->acl->getRoles();
  560. if($validate->newUser($params, $userroles))
  561. {
  562. $userdata = array(
  563. 'username' => $params['username'],
  564. 'email' => $params['email'],
  565. 'userrole' => $params['userrole'],
  566. 'password' => $params['password']);
  567. $user->createUser($userdata);
  568. $this->c->flash->addMessage('info', 'Welcome, there is a new user!');
  569. return $response->withRedirect($this->c->router->pathFor('user.list'));
  570. }
  571. $this->c->flash->addMessage('error', 'Please correct your input');
  572. return $response->withRedirect($this->c->router->pathFor('user.new'));
  573. }
  574. }
  575. public function updateUser($request, $response, $args)
  576. {
  577. if($request->isPost())
  578. {
  579. $params = $request->getParams();
  580. $userdata = $params['user'];
  581. $user = new User();
  582. $validate = new Validation();
  583. $userroles = $this->c->acl->getRoles();
  584. $redirectRoute = ($userdata['username'] == $_SESSION['user']) ? $this->c->router->pathFor('user.account') : $this->c->router->pathFor('user.show', ['username' => $userdata['username']]);
  585. # check if user is allowed to view (edit) userlist and other users
  586. if(!$this->c->acl->isAllowed($_SESSION['role'], 'userlist', 'write'))
  587. {
  588. # if an editor tries to update other userdata than its own */
  589. if($_SESSION['user'] !== $userdata['username'])
  590. {
  591. return $response->withRedirect($this->c->router->pathFor('user.account'));
  592. }
  593. # non admins cannot change their userrole, so set it to session-value
  594. $userdata['userrole'] = $_SESSION['role'];
  595. }
  596. # validate standard fields for users
  597. if($validate->existingUser($userdata, $userroles))
  598. {
  599. # validate custom input fields and return images
  600. $userfields = $this->getUserFields($userdata['userrole']);
  601. $imageFields = $this->validateInput('users', 'user', $userdata, $validate, $userfields);
  602. if(!empty($imageFields))
  603. {
  604. $images = $request->getUploadedFiles();
  605. if(isset($images['user']))
  606. {
  607. # set image size
  608. $settings = $this->c->get('settings');
  609. $settings->replace(['images' => ['live' => ['width' => 500, 'height' => 500]]]);
  610. $imageresult = $this->saveImages($imageFields, $userdata, $settings, $images['user']);
  611. if(isset($_SESSION['slimFlash']['error']))
  612. {
  613. return $response->withRedirect($redirectRoute);
  614. }
  615. elseif(isset($imageresult['username']))
  616. {
  617. $userdata = $imageresult;
  618. }
  619. }
  620. }
  621. # check for errors and redirect to path, if errors found */
  622. if(isset($_SESSION['errors']))
  623. {
  624. $this->c->flash->addMessage('error', 'Please correct the errors');
  625. return $response->withRedirect($redirectRoute);
  626. }
  627. if(empty($userdata['password']) AND empty($userdata['newpassword']))
  628. {
  629. # make sure no invalid passwords go into model
  630. unset($userdata['password']);
  631. unset($userdata['newpassword']);
  632. $user->updateUser($userdata);
  633. $this->c->flash->addMessage('info', 'Saved all changes');
  634. return $response->withRedirect($redirectRoute);
  635. }
  636. elseif($validate->newPassword($userdata))
  637. {
  638. $userdata['password'] = $userdata['newpassword'];
  639. unset($userdata['newpassword']);
  640. $user->updateUser($userdata);
  641. $this->c->flash->addMessage('info', 'Saved all changes');
  642. return $response->withRedirect($redirectRoute);
  643. }
  644. }
  645. $this->c->flash->addMessage('error', 'Please correct your input');
  646. return $response->withRedirect($redirectRoute);
  647. }
  648. }
  649. public function deleteUser($request, $response, $args)
  650. {
  651. if($request->isPost())
  652. {
  653. $params = $request->getParams();
  654. $validate = new Validation();
  655. $user = new User();
  656. # check if user is allowed to view (edit) userlist and other users
  657. if(!$this->c->acl->isAllowed($_SESSION['role'], 'userlist', 'write'))
  658. {
  659. # if an editor tries to delete other user than its own
  660. if($_SESSION['user'] !== $params['username'])
  661. {
  662. return $response->withRedirect($this->c->router->pathFor('user.account'));
  663. }
  664. }
  665. if($validate->username($params['username']))
  666. {
  667. $user->deleteUser($params['username']);
  668. # if user deleted his own account
  669. if($_SESSION['user'] == $params['username'])
  670. {
  671. session_destroy();
  672. return $response->withRedirect($this->c->router->pathFor('auth.show'));
  673. }
  674. $this->c->flash->addMessage('info', 'Say goodbye, the user is gone!');
  675. return $response->withRedirect($this->c->router->pathFor('user.list'));
  676. }
  677. $this->c->flash->addMessage('error', 'Ups, we did not find that user');
  678. return $response->withRedirect($this->c->router->pathFor('user.show', ['username' => $params['username']]));
  679. }
  680. }
  681. private function getUserFields($role)
  682. {
  683. $fields = [];
  684. $fields['username'] = ['label' => 'Username (read only)', 'type' => 'text', 'readonly' => true];
  685. $fields['firstname'] = ['label' => 'First Name', 'type' => 'text'];
  686. $fields['lastname'] = ['label' => 'Last Name', 'type' => 'text'];
  687. $fields['email'] = ['label' => 'E-Mail', 'type' => 'text', 'required' => true];
  688. $fields['userrole'] = ['label' => 'Role', 'type' => 'text', 'readonly' => true];
  689. $fields['password'] = ['label' => 'Actual Password', 'type' => 'password'];
  690. $fields['newpassword'] = ['label' => 'New Password', 'type' => 'password'];
  691. # dispatch fields;
  692. $fields = $this->c->dispatcher->dispatch('onUserfieldsLoaded', new OnUserfieldsLoaded($fields))->getData();
  693. # only roles who can edit content need profile image and description
  694. if($this->c->acl->isAllowed($role, 'mycontent', 'create'))
  695. {
  696. $newfield['image'] = ['label' => 'Profile-Image', 'type' => 'image'];
  697. $newfield['description'] = ['label' => 'Author-Description (Markdown)', 'type' => 'textarea'];
  698. $fields = array_slice($fields, 0, 1, true) + $newfield + array_slice($fields, 1, NULL, true);
  699. # array_splice($fields,1,0,$newfield);
  700. }
  701. # Only admin can change userroles
  702. if($this->c->acl->isAllowed($_SESSION['role'], 'userlist', 'write'))
  703. {
  704. $userroles = $this->c->acl->getRoles();
  705. $options = [];
  706. # we need associative array to make select-field with key/value work
  707. foreach($userroles as $userrole)
  708. {
  709. $options[$userrole] = $userrole;
  710. }
  711. $fields['userrole'] = ['label' => 'Role', 'type' => 'select', 'options' => $options];
  712. }
  713. $userform = [];
  714. $userform['forms']['fields'] = $fields;
  715. return $userform;
  716. }
  717. private function getThemes()
  718. {
  719. $themeFolder = $this->c->get('settings')['rootPath'] . $this->c->get('settings')['themeFolder'];
  720. $themeFolderC = scandir($themeFolder);
  721. $themes = array();
  722. foreach ($themeFolderC as $key => $theme)
  723. {
  724. if (!in_array($theme, array(".","..")))
  725. {
  726. if (is_dir($themeFolder . DIRECTORY_SEPARATOR . $theme))
  727. {
  728. $themes[] = $theme;
  729. }
  730. }
  731. }
  732. return $themes;
  733. }
  734. private function getCopyright()
  735. {
  736. return array(
  737. "©",
  738. "CC-BY",
  739. "CC-BY-NC",
  740. "CC-BY-NC-ND",
  741. "CC-BY-NC-SA",
  742. "CC-BY-ND",
  743. "CC-BY-SA",
  744. "None"
  745. );
  746. }
  747. private function getLanguages()
  748. {
  749. return array(
  750. 'en' => 'English',
  751. 'ru' => 'Russian',
  752. 'nl' => 'Dutch, Flemish',
  753. 'de' => 'German',
  754. 'it' => 'Italian',
  755. 'fr' => 'French',
  756. );
  757. }
  758. private function getNavigation()
  759. {
  760. $navigation = [
  761. 'System' => ['routename' => 'settings.show', 'icon' => 'icon-wrench', 'aclresource' => 'system', 'aclprivilege' => 'view'],
  762. 'Themes' => ['routename' => 'themes.show', 'icon' => 'icon-paint-brush', 'aclresource' => 'system', 'aclprivilege' => 'view'],
  763. 'Plugins' => ['routename' => 'plugins.show', 'icon' => 'icon-plug', 'aclresource' => 'system', 'aclprivilege' => 'view'],
  764. 'Account' => ['routename' => 'user.account', 'icon' => 'icon-user', 'aclresource' => 'user', 'aclprivilege' => 'view'],
  765. 'Users' => ['routename' => 'user.list', 'icon' => 'icon-group', 'aclresource' => 'userlist', 'aclprivilege' => 'view']
  766. ];
  767. # dispatch fields;
  768. $navigation = $this->c->dispatcher->dispatch('onSystemnaviLoaded', new OnSystemnaviLoaded($navigation))->getData();
  769. return $navigation;
  770. }
  771. private function validateInput($objectType, $objectName, $userInput, $validate, $originalSettings = NULL)
  772. {
  773. if(!$originalSettings)
  774. {
  775. # fetch the original settings from the folder (plugin or theme) to get the field definitions
  776. $originalSettings = \Typemill\Settings::getObjectSettings($objectType, $objectName);
  777. }
  778. # images get special treatment
  779. $imageFieldDefinitions = array();
  780. if(isset($originalSettings['forms']['fields']))
  781. {
  782. /* flaten the multi-dimensional array with fieldsets to a one-dimensional array */
  783. $originalFields = array();
  784. foreach($originalSettings['forms']['fields'] as $fieldName => $fieldValue)
  785. {
  786. if(isset($fieldValue['fields']))
  787. {
  788. foreach($fieldValue['fields'] as $subFieldName => $subFieldValue)
  789. {
  790. $originalFields[$subFieldName] = $subFieldValue;
  791. }
  792. }
  793. else
  794. {
  795. $originalFields[$fieldName] = $fieldValue;
  796. }
  797. }
  798. # if the plugin defines frontend fields
  799. if(isset($originalSettings['public']))
  800. {
  801. $originalFields['recaptcha'] = ['type' => 'checkbox', 'label' => 'Google Recaptcha', 'checkboxlabel' => 'Activate Recaptcha' ];
  802. $originalFields['recaptcha_webkey'] = ['type' => 'text', 'label' => 'Recaptcha Website Key', 'help' => 'Add the recaptcha website key here. You can get the key from the recaptcha website.', 'description' => 'The website key is mandatory if you activate the recaptcha field'];
  803. $originalFields['recaptcha_secretkey'] = ['type' => 'text', 'label' => 'Recaptcha Secret Key', 'help' => 'Add the recaptcha secret key here. You can get the key from the recaptcha website.', 'description' => 'The secret key is mandatory if you activate the recaptcha field'];
  804. }
  805. # if plugin is not active, then skip required
  806. $skiprequired = false;
  807. if($objectType == 'plugins' && !isset($userInput['active']))
  808. {
  809. $skiprequired = true;
  810. }
  811. /* take the user input data and iterate over all fields and values */
  812. foreach($userInput as $fieldName => $fieldValue)
  813. {
  814. /* get the corresponding field definition from original plugin settings */
  815. $fieldDefinition = isset($originalFields[$fieldName]) ? $originalFields[$fieldName] : false;
  816. if($fieldDefinition)
  817. {
  818. /* validate user input for this field */
  819. $validate->objectField($fieldName, $fieldValue, $objectName, $fieldDefinition, $skiprequired);
  820. if($fieldDefinition['type'] == 'image')
  821. {
  822. # we want to return all images-fields for further processing
  823. $imageFieldDefinitions[$fieldName] = $fieldDefinition;
  824. }
  825. }
  826. if(!$fieldDefinition && $objectType != 'users' && $fieldName != 'active')
  827. {
  828. $_SESSION['errors'][$objectName][$fieldName] = array('This field is not defined!');
  829. }
  830. }
  831. }
  832. return $imageFieldDefinitions;
  833. }
  834. protected function saveImages($imageFields, $userInput, $userSettings, $files)
  835. {
  836. # initiate image processor with standard image sizes
  837. $processImages = new ProcessImage($userSettings['images']);
  838. if(!$processImages->checkFolders('images'))
  839. {
  840. $this->c->flash->addMessage('error', 'Please make sure that your media folder exists and is writable.');
  841. return false;
  842. }
  843. foreach($imageFields as $fieldName => $imageField)
  844. {
  845. if(isset($userInput[$fieldName]))
  846. {
  847. # handle single input with single file upload
  848. $image = $files[$fieldName];
  849. if($image->getError() === UPLOAD_ERR_OK)
  850. {
  851. # not the most elegant, but createImage expects a base64-encoded string.
  852. $imageContent = $image->getStream()->getContents();
  853. $imageData = base64_encode($imageContent);
  854. $imageSrc = 'data: ' . $image->getClientMediaType() . ';base64,' . $imageData;
  855. if($processImages->createImage($imageSrc, $image->getClientFilename(), $userSettings['images'], $overwrite = NULL))
  856. {
  857. # returns image path to media library
  858. $userInput[$fieldName] = $processImages->publishImage();
  859. }
  860. }
  861. }
  862. }
  863. return $userInput;
  864. }
  865. }