SettingsController.php 37 KB

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