MetaApiController.php 13 KB

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