SettingsController.php 34 KB

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