MetaApiController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. namespace Typemill\Controllers;
  3. use Slim\Http\Request;
  4. use Slim\Http\Response;
  5. use Typemill\Models\WriteYaml;
  6. use Typemill\Models\WriteMeta;
  7. use Typemill\Models\Folder;
  8. use Typemill\Events\OnMetaDefinitionsLoaded;
  9. class MetaApiController extends ContentController
  10. {
  11. # get the standard meta-definitions and the meta-definitions from plugins (same for all sites)
  12. public function getMetaDefinitions(Request $request, Response $response, $args)
  13. {
  14. $metatabs = $this->aggregateMetaDefinitions();
  15. return $response->withJson(array('definitions' => $metatabs, 'errors' => false));
  16. }
  17. # get the standard meta-definitions and the meta-definitions from plugins (same for all sites)
  18. public function aggregateMetaDefinitions($folder = null)
  19. {
  20. $writeYaml = new writeYaml();
  21. $metatabs = $writeYaml->getYaml('system' . DIRECTORY_SEPARATOR . 'author', 'metatabs.yaml');
  22. # add radio buttons to choose posts or pages for folder.
  23. if($folder)
  24. {
  25. $metatabs['meta']['fields']['contains'] = [
  26. 'type' => 'radio',
  27. 'label' => 'This folder contains:',
  28. 'options' => ['pages' => 'PAGES (sort in navigation with drag & drop)', 'posts' => 'POSTS (sorted by publish date, for news or blogs)'],
  29. 'class' => 'medium'
  30. ];
  31. }
  32. # loop through all plugins
  33. if(!empty($this->settings['plugins']))
  34. {
  35. foreach($this->settings['plugins'] as $name => $plugin)
  36. {
  37. if($plugin['active'])
  38. {
  39. $pluginSettings = \Typemill\Settings::getObjectSettings('plugins', $name);
  40. if($pluginSettings && isset($pluginSettings['metatabs']))
  41. {
  42. $metatabs = array_merge_recursive($metatabs, $pluginSettings['metatabs']);
  43. }
  44. }
  45. }
  46. }
  47. # add the meta from theme settings here
  48. $themeSettings = \Typemill\Settings::getObjectSettings('themes', $this->settings['theme']);
  49. if($themeSettings && isset($themeSettings['metatabs']))
  50. {
  51. $metatabs = array_merge_recursive($metatabs, $themeSettings['metatabs']);
  52. }
  53. # dispatch meta
  54. $metatabs = $this->c->dispatcher->dispatch('onMetaDefinitionsLoaded', new OnMetaDefinitionsLoaded($metatabs))->getData();
  55. return $metatabs;
  56. }
  57. public function getArticleMetaObject(Request $request, Response $response, $args)
  58. {
  59. /* get params from call */
  60. $this->params = $request->getParams();
  61. $this->uri = $request->getUri()->withUserInfo('');
  62. # set structure
  63. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  64. # set information for homepage
  65. $this->setHomepage($args = false);
  66. # set item
  67. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  68. $writeMeta = new writeMeta();
  69. $pagemeta = $writeMeta->getPageMeta($this->settings, $this->item);
  70. if(!$pagemeta)
  71. {
  72. # set the status for published and drafted
  73. $this->setPublishStatus();
  74. # set path
  75. $this->setItemPath($this->item->fileType);
  76. # read content from file
  77. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  78. $pagemeta = $writeMeta->getPageMetaBlank($this->content, $this->settings, $this->item);
  79. }
  80. # if item is a folder
  81. if($this->item->elementType == "folder" && isset($this->item->contains))
  82. {
  83. $pagemeta['meta']['contains'] = isset($pagemeta['meta']['contains']) ? $pagemeta['meta']['contains'] : $this->item->contains;
  84. # get global metadefinitions
  85. $metadefinitions = $this->aggregateMetaDefinitions($folder = true);
  86. }
  87. else
  88. {
  89. # get global metadefinitions
  90. $metadefinitions = $this->aggregateMetaDefinitions();
  91. }
  92. $metadata = [];
  93. $metascheme = [];
  94. foreach($metadefinitions as $tabname => $tab )
  95. {
  96. $metadata[$tabname] = [];
  97. foreach($tab['fields'] as $fieldname => $fielddefinitions)
  98. {
  99. $metascheme[$tabname][$fieldname] = true;
  100. $metadata[$tabname][$fieldname] = isset($pagemeta[$tabname][$fieldname]) ? $pagemeta[$tabname][$fieldname] : null;
  101. # special treatment for customfields
  102. if(isset($fielddefinitions['type']) && ($fielddefinitions['type'] == 'customfields' ) && $metadata[$tabname][$fieldname] )
  103. {
  104. $metadata[$tabname][$fieldname] = $this->customfieldsPrepareForEdit($metadata[$tabname][$fieldname]);
  105. }
  106. }
  107. }
  108. # store the metascheme in cache for frontend
  109. $writeMeta->updateYaml('cache', 'metatabs.yaml', $metascheme);
  110. return $response->withJson(array('metadata' => $metadata, 'metadefinitions' => $metadefinitions, 'item' => $this->item, 'errors' => false));
  111. }
  112. public function updateArticleMeta(Request $request, Response $response, $args)
  113. {
  114. # get params from call
  115. $this->params = $request->getParams();
  116. $this->uri = $request->getUri()->withUserInfo('');
  117. # minimum permission is that user is allowed to update his own content
  118. if(!$this->c->acl->isAllowed($_SESSION['role'], 'mycontent', 'update'))
  119. {
  120. return $response->withJson(array('data' => false, 'errors' => ['message' => 'You are not allowed to update content.']), 403);
  121. }
  122. $tab = isset($this->params['tab']) ? $this->params['tab'] : false;
  123. $metaInput = isset($this->params['data']) ? $this->params['data'] : false ;
  124. $objectName = 'meta';
  125. $errors = false;
  126. if(!$tab or !$metaInput)
  127. {
  128. return $response->withJson($this->errors, 404);
  129. }
  130. # set structure
  131. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  132. # set information for homepage
  133. $this->setHomepage($args = false);
  134. # set item
  135. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  136. # if user has no right to delete content from others (eg admin or editor)
  137. if(!$this->c->acl->isAllowed($_SESSION['role'], 'content', 'update'))
  138. {
  139. # check ownership. This code should nearly never run, because there is no button/interface to trigger it.
  140. if(!$this->checkContentOwnership())
  141. {
  142. return $response->withJson(array('data' => false, 'errors' => ['message' => 'You are not allowed to edit content.']), 403);
  143. }
  144. }
  145. # if item is a folder
  146. if($this->item->elementType == "folder")
  147. {
  148. $pagemeta['meta']['contains'] = isset($pagemeta['meta']['contains']) ? $pagemeta['meta']['contains'] : $this->item->contains;
  149. # get global metadefinitions
  150. $metaDefinitions = $this->aggregateMetaDefinitions($folder = true);
  151. }
  152. else
  153. {
  154. # get global metadefinitions
  155. $metaDefinitions = $this->aggregateMetaDefinitions();
  156. }
  157. # create validation object
  158. $validate = $this->getValidator();
  159. # take the user input data and iterate over all fields and values
  160. foreach($metaInput as $fieldName => $fieldValue)
  161. {
  162. # get the corresponding field definition from original plugin settings */
  163. $fieldDefinition = isset($metaDefinitions[$tab]['fields'][$fieldName]) ? $metaDefinitions[$tab]['fields'][$fieldName] : false;
  164. if(!$fieldDefinition)
  165. {
  166. $errors[$tab][$fieldName] = 'This field is not defined';
  167. }
  168. else
  169. {
  170. # validate user input for this field
  171. $result = $validate->objectField($fieldName, $fieldValue, $objectName, $fieldDefinition);
  172. if($result !== true)
  173. {
  174. $errors[$tab][$fieldName] = $result[$fieldName][0];
  175. }
  176. # special treatment for customfields
  177. if($fieldDefinition && isset($fieldDefinition['type']) && ($fieldDefinition['type'] == 'customfields' ) )
  178. {
  179. $arrayFeatureOn = false;
  180. if(isset($fieldDefinition['data']) && ($fieldDefinition['data'] == 'array'))
  181. {
  182. $arrayFeatureOn = true;
  183. }
  184. $metaInput[$fieldName] = $this->customfieldsPrepareForSave($metaInput[$fieldName], $arrayFeatureOn);
  185. }
  186. }
  187. }
  188. # return validation errors
  189. if($errors){ return $response->withJson(array('errors' => $errors),422); }
  190. $writeMeta = new writeMeta();
  191. # get existing metadata for page
  192. $metaPage = $writeMeta->getYaml($this->settings['contentFolder'], $this->item->pathWithoutType . '.yaml');
  193. # get extended structure
  194. $extended = $writeMeta->getYaml('cache', 'structure-extended.yaml');
  195. # flag for changed structure
  196. $structure = false;
  197. if($tab == 'meta')
  198. {
  199. # if manual date has been modified
  200. if( $this->hasChanged($metaInput, $metaPage['meta'], 'manualdate'))
  201. {
  202. # update the time
  203. $metaInput['time'] = date('H-i-s', time());
  204. # if it is a post, then rename the post
  205. if($this->item->elementType == "file" && strlen($this->item->order) == 12)
  206. {
  207. # create file-prefix with date
  208. $datetime = $metaInput['manualdate'] . '-' . $metaInput['time'];
  209. $datetime = implode(explode('-', $datetime));
  210. $datetime = substr($datetime,0,12);
  211. # create the new filename
  212. $pathWithoutFile = str_replace($this->item->originalName, "", $this->item->path);
  213. $newPathWithoutType = $pathWithoutFile . $datetime . '-' . $this->item->slug;
  214. $writeMeta->renamePost($this->item->pathWithoutType, $newPathWithoutType);
  215. # recreate the draft structure
  216. $this->setStructure($draft = true, $cache = false);
  217. # update item
  218. $this->setItem();
  219. }
  220. }
  221. # if folder has changed and contains pages instead of posts or posts instead of pages
  222. if($this->item->elementType == "folder" && isset($metaInput['contains']) && $this->hasChanged($metaInput, $metaPage['meta'], 'contains'))
  223. {
  224. $structure = true;
  225. if($metaInput['contains'] == "posts")
  226. {
  227. $writeMeta->transformPagesToPosts($this->item);
  228. }
  229. if($metaInput['contains'] == "pages")
  230. {
  231. $writeMeta->transformPostsToPages($this->item);
  232. }
  233. }
  234. # normalize the meta-input
  235. $metaInput['navtitle'] = (isset($metaInput['navtitle']) && $metaInput['navtitle'] !== null )? $metaInput['navtitle'] : '';
  236. $metaInput['hide'] = (isset($metaInput['hide']) && $metaInput['hide'] !== null) ? $metaInput['hide'] : false;
  237. # input values are empty but entry in structure exists
  238. if(!$metaInput['hide'] && $metaInput['navtitle'] == "" && isset($extended[$this->item->urlRelWoF]))
  239. {
  240. # delete the entry in the structure
  241. unset($extended[$this->item->urlRelWoF]);
  242. $structure = true;
  243. }
  244. elseif(
  245. # check if navtitle or hide-value has been changed
  246. ($this->hasChanged($metaInput, $metaPage['meta'], 'navtitle'))
  247. OR
  248. ($this->hasChanged($metaInput, $metaPage['meta'], 'hide'))
  249. )
  250. {
  251. # add new file data. Also makes sure that the value is set.
  252. $extended[$this->item->urlRelWoF] = ['hide' => $metaInput['hide'], 'navtitle' => $metaInput['navtitle']];
  253. $structure = true;
  254. }
  255. }
  256. # add the new/edited metadata
  257. $metaPage[$tab] = $metaInput;
  258. # store the metadata
  259. $writeMeta->updateYaml($this->settings['contentFolder'], $this->item->pathWithoutType . '.yaml', $metaPage);
  260. if($structure)
  261. {
  262. # store the extended file
  263. $writeMeta->updateYaml('cache', 'structure-extended.yaml', $extended);
  264. # recreate the draft structure
  265. $this->setStructure($draft = true, $cache = false);
  266. # update item
  267. $this->setItem();
  268. # set item in navigation active again
  269. $activeItem = Folder::getItemForUrl($this->structure, $this->item->urlRel, $this->uri->getBaseUrl());
  270. # send new structure to frontend
  271. $structure = $this->structure;
  272. }
  273. # return with the new metadata
  274. return $response->withJson(array('metadata' => $metaInput, 'structure' => $structure, 'item' => $this->item, 'errors' => false));
  275. }
  276. private function customfieldsPrepareForEdit($customfields)
  277. {
  278. # to edit fields in vue we have to transform the arrays in yaml into an array of objects like [{key: abc, value: xyz}{...}]
  279. $customfieldsForEdit = [];
  280. foreach($customfields as $key => $value)
  281. {
  282. $valuestring = $value;
  283. # and make sure that arrays are transformed back into strings
  284. if(isset($value) && is_array($value))
  285. {
  286. $valuestring = '- ' . implode(PHP_EOL . '- ', $value);
  287. }
  288. $customfieldsForEdit[] = ['key' => $key, 'value' => $valuestring];
  289. }
  290. return $customfieldsForEdit;
  291. }
  292. private function customfieldsPrepareForSave($customfields, $arrayFeatureOn)
  293. {
  294. # we have to convert the incoming array of objects from vue [{key: abc, value: xyz}{...}] into key-value arrays for yaml.
  295. $customfieldsForSave = [];
  296. foreach($customfields as $valuePair)
  297. {
  298. # doupbe check, not really needed because it is validated already
  299. if(!isset($valuePair['key']) OR ($valuePair['key'] == ''))
  300. {
  301. # do not use data without valid keys
  302. continue;
  303. }
  304. $key = $valuePair['key'];
  305. $value = '';
  306. if(isset($valuePair['value']))
  307. {
  308. $value = $valuePair['value'];
  309. # check if value is formatted as a list, then transform it into an array
  310. if($arrayFeatureOn)
  311. {
  312. # normalize line breaks, php-eol does not work here
  313. $cleanvalue = str_replace(array("\r\n", "\r"), "\n", $valuePair['value']);
  314. $cleanvalue = trim($cleanvalue, "\n");
  315. $arrayValues = explode("\n- ",$cleanvalue);
  316. if(count($arrayValues) > 1)
  317. {
  318. $value = array_map(function($item) { return trim($item, '- '); }, $arrayValues);
  319. }
  320. }
  321. }
  322. $customfieldsForSave[$key] = $value;
  323. }
  324. return $customfieldsForSave;
  325. }
  326. protected function hasChanged($input, $page, $field)
  327. {
  328. if(isset($input[$field]) && isset($page[$field]) && $input[$field] == $page[$field])
  329. {
  330. return false;
  331. }
  332. if(!isset($input[$field]) && !isset($input[$field]))
  333. {
  334. return false;
  335. }
  336. return true;
  337. }
  338. }