MetaApiController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. /*
  102. # special treatment for customfields
  103. if(isset($fielddefinitions['type']) && ($fielddefinitions['type'] == 'customfields' ) && $metadata[$tabname][$fieldname] )
  104. {
  105. $metadata[$tabname][$fieldname] = $this->customfieldsPrepareForEdit($metadata[$tabname][$fieldname]);
  106. }
  107. */
  108. }
  109. }
  110. # store the metascheme in cache for frontend
  111. $writeMeta->updateYaml('cache', 'metatabs.yaml', $metascheme);
  112. return $response->withJson(array('metadata' => $metadata, 'metadefinitions' => $metadefinitions, 'item' => $this->item, 'errors' => false));
  113. }
  114. public function updateArticleMeta(Request $request, Response $response, $args)
  115. {
  116. # get params from call
  117. $this->params = $request->getParams();
  118. $this->uri = $request->getUri()->withUserInfo('');
  119. # minimum permission is that user is allowed to update his own content
  120. if(!$this->c->acl->isAllowed($_SESSION['role'], 'mycontent', 'update'))
  121. {
  122. return $response->withJson(array('data' => false, 'errors' => ['message' => 'You are not allowed to update content.']), 403);
  123. }
  124. $tab = isset($this->params['tab']) ? $this->params['tab'] : false;
  125. $metaInput = isset($this->params['data']) ? $this->params['data'] : false ;
  126. $objectName = 'meta';
  127. $errors = false;
  128. if(!$tab or !$metaInput)
  129. {
  130. return $response->withJson($this->errors, 404);
  131. }
  132. # set structure
  133. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  134. # set information for homepage
  135. $this->setHomepage($args = false);
  136. # set item
  137. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  138. # if user has no right to delete content from others (eg admin or editor)
  139. if(!$this->c->acl->isAllowed($_SESSION['role'], 'content', 'update'))
  140. {
  141. # check ownership. This code should nearly never run, because there is no button/interface to trigger it.
  142. if(!$this->checkContentOwnership())
  143. {
  144. return $response->withJson(array('data' => false, 'errors' => ['message' => 'You are not allowed to edit content.']), 403);
  145. }
  146. }
  147. # if item is a folder
  148. if($this->item->elementType == "folder")
  149. {
  150. $pagemeta['meta']['contains'] = isset($pagemeta['meta']['contains']) ? $pagemeta['meta']['contains'] : $this->item->contains;
  151. # get global metadefinitions
  152. $metaDefinitions = $this->aggregateMetaDefinitions($folder = true);
  153. }
  154. else
  155. {
  156. # get global metadefinitions
  157. $metaDefinitions = $this->aggregateMetaDefinitions();
  158. }
  159. # create validation object
  160. $validate = $this->getValidator();
  161. # take the user input data and iterate over all fields and values
  162. foreach($metaInput as $fieldName => $fieldValue)
  163. {
  164. # get the corresponding field definition from original plugin settings */
  165. $fieldDefinition = isset($metaDefinitions[$tab]['fields'][$fieldName]) ? $metaDefinitions[$tab]['fields'][$fieldName] : false;
  166. if(!$fieldDefinition)
  167. {
  168. $errors[$tab][$fieldName] = 'This field is not defined';
  169. }
  170. else
  171. {
  172. # validate user input for this field
  173. $result = $validate->objectField($fieldName, $fieldValue, $objectName, $fieldDefinition);
  174. if($result !== true)
  175. {
  176. $errors[$tab][$fieldName] = $result[$fieldName][0];
  177. }
  178. /*
  179. # special treatment for customfields
  180. if($fieldDefinition && isset($fieldDefinition['type']) && ($fieldDefinition['type'] == 'customfields' ) )
  181. {
  182. $arrayFeatureOn = false;
  183. if(isset($fieldDefinition['data']) && ($fieldDefinition['data'] == 'array'))
  184. {
  185. $arrayFeatureOn = true;
  186. }
  187. $metaInput[$fieldName] = $this->customfieldsPrepareForSave($metaInput[$fieldName], $arrayFeatureOn);
  188. }
  189. */
  190. }
  191. }
  192. # return validation errors
  193. if($errors){ return $response->withJson(array('errors' => $errors),422); }
  194. $writeMeta = new writeMeta();
  195. # get existing metadata for page
  196. $metaPage = $writeMeta->getYaml($this->settings['contentFolder'], $this->item->pathWithoutType . '.yaml');
  197. # get extended structure
  198. $extended = $writeMeta->getYaml('cache', 'structure-extended.yaml');
  199. # flag for changed structure
  200. $structure = false;
  201. if($tab == 'meta')
  202. {
  203. # if manual date has been modified
  204. if( $this->hasChanged($metaInput, $metaPage['meta'], 'manualdate'))
  205. {
  206. # update the time
  207. $metaInput['time'] = date('H-i-s', time());
  208. # if it is a post, then rename the post
  209. if($this->item->elementType == "file" && strlen($this->item->order) == 12)
  210. {
  211. # create file-prefix with date
  212. $datetime = $metaInput['manualdate'] . '-' . $metaInput['time'];
  213. $datetime = implode(explode('-', $datetime));
  214. $datetime = substr($datetime,0,12);
  215. # create the new filename
  216. $pathWithoutFile = str_replace($this->item->originalName, "", $this->item->path);
  217. $newPathWithoutType = $pathWithoutFile . $datetime . '-' . $this->item->slug;
  218. $writeMeta->renamePost($this->item->pathWithoutType, $newPathWithoutType);
  219. # recreate the draft structure
  220. $this->setStructure($draft = true, $cache = false);
  221. # update item
  222. $this->setItem();
  223. }
  224. }
  225. # if folder has changed and contains pages instead of posts or posts instead of pages
  226. if($this->item->elementType == "folder" && isset($metaInput['contains']) && $this->hasChanged($metaInput, $metaPage['meta'], 'contains'))
  227. {
  228. $structure = true;
  229. if($metaInput['contains'] == "posts")
  230. {
  231. $writeMeta->transformPagesToPosts($this->item);
  232. }
  233. if($metaInput['contains'] == "pages")
  234. {
  235. $writeMeta->transformPostsToPages($this->item);
  236. }
  237. }
  238. # normalize the meta-input
  239. $metaInput['navtitle'] = (isset($metaInput['navtitle']) && $metaInput['navtitle'] !== null )? $metaInput['navtitle'] : '';
  240. $metaInput['hide'] = (isset($metaInput['hide']) && $metaInput['hide'] !== null) ? $metaInput['hide'] : false;
  241. # input values are empty but entry in structure exists
  242. if(!$metaInput['hide'] && $metaInput['navtitle'] == "" && isset($extended[$this->item->urlRelWoF]))
  243. {
  244. # delete the entry in the structure
  245. unset($extended[$this->item->urlRelWoF]);
  246. $structure = true;
  247. }
  248. elseif(
  249. # check if navtitle or hide-value has been changed
  250. ($this->hasChanged($metaInput, $metaPage['meta'], 'navtitle'))
  251. OR
  252. ($this->hasChanged($metaInput, $metaPage['meta'], 'hide'))
  253. )
  254. {
  255. # add new file data. Also makes sure that the value is set.
  256. $extended[$this->item->urlRelWoF] = ['hide' => $metaInput['hide'], 'navtitle' => $metaInput['navtitle']];
  257. $structure = true;
  258. }
  259. }
  260. # add the new/edited metadata
  261. $metaPage[$tab] = $metaInput;
  262. # store the metadata
  263. $writeMeta->updateYaml($this->settings['contentFolder'], $this->item->pathWithoutType . '.yaml', $metaPage);
  264. if($structure)
  265. {
  266. # store the extended file
  267. $writeMeta->updateYaml('cache', 'structure-extended.yaml', $extended);
  268. # recreate the draft structure
  269. $this->setStructure($draft = true, $cache = false);
  270. # update item
  271. $this->setItem();
  272. # set item in navigation active again
  273. $activeItem = Folder::getItemForUrl($this->structure, $this->item->urlRel, $this->uri->getBaseUrl());
  274. # send new structure to frontend
  275. $structure = $this->structure;
  276. }
  277. # return with the new metadata
  278. return $response->withJson(array('metadata' => $metaInput, 'structure' => $structure, 'item' => $this->item, 'errors' => false));
  279. }
  280. private function customfieldsPrepareForEdit($customfields)
  281. {
  282. # to edit fields in vue we have to transform the arrays in yaml into an array of objects like [{key: abc, value: xyz}{...}]
  283. $customfieldsForEdit = [];
  284. foreach($customfields as $key => $value)
  285. {
  286. $valuestring = $value;
  287. # and make sure that arrays are transformed back into strings
  288. if(isset($value) && is_array($value))
  289. {
  290. $valuestring = '- ' . implode(PHP_EOL . '- ', $value);
  291. }
  292. $customfieldsForEdit[] = ['key' => $key, 'value' => $valuestring];
  293. }
  294. return $customfieldsForEdit;
  295. }
  296. private function customfieldsPrepareForSave($customfields, $arrayFeatureOn)
  297. {
  298. # we have to convert the incoming array of objects from vue [{key: abc, value: xyz}{...}] into key-value arrays for yaml.
  299. $customfieldsForSave = [];
  300. foreach($customfields as $valuePair)
  301. {
  302. # doupbe check, not really needed because it is validated already
  303. if(!isset($valuePair['key']) OR ($valuePair['key'] == ''))
  304. {
  305. # do not use data without valid keys
  306. continue;
  307. }
  308. $key = $valuePair['key'];
  309. $value = '';
  310. if(isset($valuePair['value']))
  311. {
  312. $value = $valuePair['value'];
  313. # check if value is formatted as a list, then transform it into an array
  314. if($arrayFeatureOn)
  315. {
  316. # normalize line breaks, php-eol does not work here
  317. $cleanvalue = str_replace(array("\r\n", "\r"), "\n", $valuePair['value']);
  318. $cleanvalue = trim($cleanvalue, "\n");
  319. $arrayValues = explode("\n- ",$cleanvalue);
  320. if(count($arrayValues) > 1)
  321. {
  322. $value = array_map(function($item) { return trim($item, '- '); }, $arrayValues);
  323. }
  324. }
  325. }
  326. $customfieldsForSave[$key] = $value;
  327. }
  328. return $customfieldsForSave;
  329. }
  330. protected function hasChanged($input, $page, $field)
  331. {
  332. if(isset($input[$field]) && isset($page[$field]) && $input[$field] == $page[$field])
  333. {
  334. return false;
  335. }
  336. if(!isset($input[$field]) && !isset($input[$field]))
  337. {
  338. return false;
  339. }
  340. return true;
  341. }
  342. }