MetaApiController.php 13 KB

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