MetaApiController.php 14 KB

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