ContentApiController.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. <?php
  2. namespace Typemill\Controllers;
  3. use Slim\Http\Request;
  4. use Slim\Http\Response;
  5. use Typemill\Models\Folder;
  6. use Typemill\Models\Write;
  7. use Typemill\Models\WriteYaml;
  8. use Typemill\Models\ProcessImage;
  9. use Typemill\Extensions\ParsedownExtension;
  10. use Typemill\Events\OnPagePublished;
  11. use Typemill\Events\OnPageUnpublished;
  12. use Typemill\Events\OnPageDeleted;
  13. use Typemill\Events\OnPageSorted;
  14. class ContentApiController extends ContentController
  15. {
  16. public function publishArticle(Request $request, Response $response, $args)
  17. {
  18. # get params from call
  19. $this->params = $request->getParams();
  20. $this->uri = $request->getUri();
  21. # validate input only if raw mode
  22. if($this->params['raw'])
  23. {
  24. if(!$this->validateEditorInput()){ return $response->withJson($this->errors,422); }
  25. }
  26. # set structure
  27. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  28. # set item
  29. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  30. # set the status for published and drafted
  31. $this->setPublishStatus();
  32. # set path
  33. $this->setItemPath($this->item->fileType);
  34. # if raw mode, use the content from request
  35. if($this->params['raw'])
  36. {
  37. $this->content = '# ' . $this->params['title'] . "\r\n\r\n" . $this->params['content'];
  38. }
  39. else
  40. {
  41. # read content from file
  42. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  43. # If it is a draft, then create clean markdown content
  44. if(is_array($this->content))
  45. {
  46. # initialize parsedown extension
  47. $parsedown = new ParsedownExtension();
  48. # turn markdown into an array of markdown-blocks
  49. $this->content = $parsedown->arrayBlocksToMarkdown($this->content);
  50. }
  51. }
  52. # set path for the file (or folder)
  53. $this->setItemPath('md');
  54. # update the file
  55. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $this->content))
  56. {
  57. # update the file
  58. $delete = $this->deleteContentFiles(['txt']);
  59. # update the internal structure
  60. $this->setStructure($draft = true, $cache = false);
  61. # update the public structure
  62. $this->setStructure($draft = false, $cache = false);
  63. # dispatch event
  64. $this->c->dispatcher->dispatch('onPagePublished', new OnPagePublished($this->item));
  65. return $response->withJson(['success'], 200);
  66. }
  67. else
  68. {
  69. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  70. }
  71. }
  72. public function unpublishArticle(Request $request, Response $response, $args)
  73. {
  74. # get params from call
  75. $this->params = $request->getParams();
  76. $this->uri = $request->getUri();
  77. # set structure
  78. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  79. # set item
  80. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  81. # set the status for published and drafted
  82. $this->setPublishStatus();
  83. # check if draft exists, if not, create one.
  84. if(!$this->item->drafted)
  85. {
  86. # set path for the file (or folder)
  87. $this->setItemPath('md');
  88. # set content of markdown-file
  89. if(!$this->setContent()){ return $response->withJson($this->errors, 404); }
  90. # initialize parsedown extension
  91. $parsedown = new ParsedownExtension();
  92. # turn markdown into an array of markdown-blocks
  93. $contentArray = $parsedown->markdownToArrayBlocks($this->content);
  94. # encode the content into json
  95. $contentJson = json_encode($contentArray);
  96. # set path for the file (or folder)
  97. $this->setItemPath('txt');
  98. /* update the file */
  99. if(!$this->write->writeFile($this->settings['contentFolder'], $this->path, $contentJson))
  100. {
  101. return $response->withJson(['errors' => ['message' => 'Could not create a draft of the page. Please check if the folder is writable']], 404);
  102. }
  103. }
  104. # check if it is a folder and if the folder has published pages.
  105. $message = false;
  106. if($this->item->elementType == 'folder')
  107. {
  108. foreach($this->item->folderContent as $folderContent)
  109. {
  110. if($folderContent->status == 'published')
  111. {
  112. $message = 'There are published pages within this folder. The pages are not visible on your website anymore.';
  113. }
  114. }
  115. }
  116. # update the file
  117. $delete = $this->deleteContentFiles(['md']);
  118. if($delete)
  119. {
  120. # update the internal structure
  121. $this->setStructure($draft = true, $cache = false);
  122. # update the live structure
  123. $this->setStructure($draft = false, $cache = false);
  124. # dispatch event
  125. $this->c->dispatcher->dispatch('onPageUnpublished', new OnPageUnpublished($this->item));
  126. return $response->withJson(['success' => ['message' => $message]], 200);
  127. }
  128. else
  129. {
  130. return $response->withJson(['errors' => ['message' => "Could not delete some files. Please check if the files exists and are writable"]], 404);
  131. }
  132. }
  133. public function discardArticleChanges(Request $request, Response $response, $args)
  134. {
  135. # get params from call
  136. $this->params = $request->getParams();
  137. $this->uri = $request->getUri();
  138. # set structure
  139. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  140. # set item
  141. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  142. # remove the unpublished changes
  143. $delete = $this->deleteContentFiles(['txt']);
  144. # set redirect url to edit page
  145. $url = $this->uri->getBaseUrl() . '/tm/content/' . $this->settings['editor'];
  146. if(isset($this->item->urlRelWoF))
  147. {
  148. $url = $url . $this->item->urlRelWoF;
  149. }
  150. # remove the unpublished changes
  151. $delete = $this->deleteContentFiles(['txt']);
  152. if($delete)
  153. {
  154. # update the backend structure
  155. $this->setStructure($draft = true, $cache = false);
  156. return $response->withJson(['data' => $this->structure, 'errors' => false, 'url' => $url], 200);
  157. }
  158. else
  159. {
  160. return $response->withJson(['data' => $this->structure, 'errors' => $this->errors], 404);
  161. }
  162. }
  163. public function deleteArticle(Request $request, Response $response, $args)
  164. {
  165. # get params from call
  166. $this->params = $request->getParams();
  167. $this->uri = $request->getUri();
  168. # set url to base path initially
  169. $url = $this->uri->getBaseUrl() . '/tm/content/' . $this->settings['editor'];
  170. # set structure
  171. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  172. # set item
  173. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  174. if($this->item->elementType == 'file')
  175. {
  176. $delete = $this->deleteContentFiles(['md','txt', 'yaml']);
  177. }
  178. elseif($this->item->elementType == 'folder')
  179. {
  180. $delete = $this->deleteContentFolder();
  181. }
  182. if($delete)
  183. {
  184. # check if it is a subfile or subfolder and set the redirect-url to the parent item
  185. if(count($this->item->keyPathArray) > 1)
  186. {
  187. # get the parent item
  188. $parentItem = Folder::getParentItem($this->structure, $this->item->keyPathArray);
  189. if($parentItem)
  190. {
  191. # an active file has been moved to another folder
  192. $url .= $parentItem->urlRelWoF;
  193. }
  194. }
  195. # update the live structure
  196. $this->setStructure($draft = false, $cache = false);
  197. # update the backend structure
  198. $this->setStructure($draft = true, $cache = false);
  199. # check if page is in extended structure and delete it
  200. $this->deleteFromExtended();
  201. # dispatch event
  202. $this->c->dispatcher->dispatch('onPageDeleted', new OnPageDeleted($this->item));
  203. return $response->withJson(array('data' => $this->structure, 'errors' => false, 'url' => $url), 200);
  204. }
  205. else
  206. {
  207. return $response->withJson(array('data' => $this->structure, 'errors' => $this->errors), 404);
  208. }
  209. }
  210. public function updateArticle(Request $request, Response $response, $args)
  211. {
  212. # get params from call
  213. $this->params = $request->getParams();
  214. $this->uri = $request->getUri();
  215. # validate input
  216. if(!$this->validateEditorInput()){ return $response->withJson($this->errors,422); }
  217. # set structure
  218. if(!$this->setStructure($draft = true)){ return $response->withJson($this->errors, 404); }
  219. # set item
  220. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  221. # set path for the file (or folder)
  222. $this->setItemPath('txt');
  223. # merge title with content for complete markdown document
  224. $updatedContent = '# ' . $this->params['title'] . "\r\n\r\n" . $this->params['content'];
  225. # initialize parsedown extension
  226. $parsedown = new ParsedownExtension();
  227. # turn markdown into an array of markdown-blocks
  228. $contentArray = $parsedown->markdownToArrayBlocks($updatedContent);
  229. # encode the content into json
  230. $contentJson = json_encode($contentArray);
  231. /* update the file */
  232. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $contentJson))
  233. {
  234. # update the internal structure
  235. $this->setStructure($draft = true, $cache = false);
  236. return $response->withJson(['success'], 200);
  237. }
  238. else
  239. {
  240. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  241. }
  242. }
  243. public function sortArticle(Request $request, Response $response, $args)
  244. {
  245. # get params from call
  246. $this->params = $request->getParams();
  247. $this->uri = $request->getUri();
  248. # url is only needed, if an active page is moved to another folder, so user has to be redirected to the new url
  249. $url = false;
  250. # set structure
  251. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors, 'url' => $url), 404); }
  252. # validate input
  253. if(!$this->validateNavigationSort()){ return $response->withJson(array('data' => $this->structure, 'errors' => 'Data not valid. Please refresh the page and try again.', 'url' => $url), 422); }
  254. # get the ids (key path) for item, old folder and new folder
  255. $itemKeyPath = explode('.', $this->params['item_id']);
  256. $parentKeyFrom = explode('.', $this->params['parent_id_from']);
  257. $parentKeyTo = explode('.', $this->params['parent_id_to']);
  258. # get the item from structure
  259. $item = Folder::getItemWithKeyPath($this->structure, $itemKeyPath);
  260. if(!$item){ return $response->withJson(array('data' => $this->structure, 'errors' => 'We could not find this page. Please refresh and try again.', 'url' => $url), 404); }
  261. # if an item is moved to the first level
  262. if($this->params['parent_id_to'] == 'navi')
  263. {
  264. # create empty and default values so that the logic below still works
  265. $newFolder = new \stdClass();
  266. $newFolder->path = '';
  267. $folderContent = $this->structure;
  268. }
  269. else
  270. {
  271. # get the target folder from structure
  272. $newFolder = Folder::getItemWithKeyPath($this->structure, $parentKeyTo);
  273. # get the content of the target folder
  274. $folderContent = $newFolder->folderContent;
  275. }
  276. # if the item has been moved within the same folder
  277. if($this->params['parent_id_from'] == $this->params['parent_id_to'])
  278. {
  279. # get key of item
  280. $itemKey = end($itemKeyPath);
  281. reset($itemKeyPath);
  282. # delete item from folderContent
  283. unset($folderContent[$itemKey]);
  284. }
  285. else
  286. {
  287. # rename links in extended file
  288. $this->renameExtended($item, $newFolder);
  289. # an active file has been moved to another folder, so send new url with response
  290. if($this->params['active'] == 'active')
  291. {
  292. $url = $this->uri->getBaseUrl() . '/tm/content/' . $this->settings['editor'] . $newFolder->urlRelWoF . '/' . $item->slug;
  293. }
  294. }
  295. # add item to newFolder
  296. array_splice($folderContent, $this->params['index_new'], 0, array($item));
  297. # initialize index
  298. $index = 0;
  299. # initialise write object
  300. $write = new Write();
  301. # iterate through the whole content of the new folder to rename the files
  302. $writeError = false;
  303. foreach($folderContent as $folderItem)
  304. {
  305. if(!$write->moveElement($folderItem, $newFolder->path, $index))
  306. {
  307. $writeError = true;
  308. }
  309. $index++;
  310. }
  311. if($writeError){ return $response->withJson(array('data' => $this->structure, 'errors' => 'Something went wrong. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404); }
  312. # update the structure for editor
  313. $this->setStructure($draft = true, $cache = false);
  314. # get item for url and set it active again
  315. if(isset($this->params['url']))
  316. {
  317. $activeItem = Folder::getItemForUrl($this->structure, $this->params['url'], $this->uri->getBaseUrl());
  318. }
  319. # keep the internal structure for response
  320. $internalStructure = $this->structure;
  321. # update the structure for website
  322. $this->setStructure($draft = false, $cache = false);
  323. # dispatch event
  324. $this->c->dispatcher->dispatch('onPageSorted', new OnPageSorted($this->params));
  325. return $response->withJson(array('data' => $internalStructure, 'errors' => false, 'url' => $url));
  326. }
  327. public function createArticle(Request $request, Response $response, $args)
  328. {
  329. # get params from call
  330. $this->params = $request->getParams();
  331. $this->uri = $request->getUri();
  332. # url is only needed, if an active page is moved
  333. $url = false;
  334. # set structure
  335. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors, 'url' => $url), 404); }
  336. # validate input
  337. if(!$this->validateNaviItem()){ return $response->withJson(array('data' => $this->structure, 'errors' => 'Special Characters not allowed. Length between 1 and 20 chars.', 'url' => $url), 422); }
  338. # get the ids (key path) for item, old folder and new folder
  339. $folderKeyPath = explode('.', $this->params['folder_id']);
  340. # get the item from structure
  341. $folder = Folder::getItemWithKeyPath($this->structure, $folderKeyPath);
  342. if(!$folder){ return $response->withJson(array('data' => $this->structure, 'errors' => 'We could not find this page. Please refresh and try again.', 'url' => $url), 404); }
  343. # Rename all files within the folder to make sure, that namings and orders are correct
  344. # get the content of the target folder
  345. $folderContent = $folder->folderContent;
  346. # create the name for the new item
  347. $nameParts = Folder::getStringParts($this->params['item_name']);
  348. $name = implode("-", $nameParts);
  349. $slug = $name;
  350. # initialize index
  351. $index = 0;
  352. # initialise write object
  353. $write = new Write();
  354. # iterate through the whole content of the new folder
  355. $writeError = false;
  356. foreach($folderContent as $folderItem)
  357. {
  358. # check, if the same name as new item, then return an error
  359. if($folderItem->slug == $slug)
  360. {
  361. return $response->withJson(array('data' => $this->structure, 'errors' => 'There is already a page with this name. Please choose another name.', 'url' => $url), 404);
  362. }
  363. if(!$write->moveElement($folderItem, $folder->path, $index))
  364. {
  365. $writeError = true;
  366. }
  367. $index++;
  368. }
  369. if($writeError){ return $response->withJson(array('data' => $this->structure, 'errors' => 'Something went wrong. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404); }
  370. # add prefix number to the name
  371. $namePath = $index > 9 ? $index . '-' . $name : '0' . $index . '-' . $name;
  372. $folderPath = 'content' . $folder->path;
  373. $title = implode(" ", $nameParts);
  374. # create default content
  375. $content = json_encode(['# ' . $title, 'Content']);
  376. if($this->params['type'] == 'file')
  377. {
  378. if(!$write->writeFile($folderPath, $namePath . '.txt', $content))
  379. {
  380. return $response->withJson(array('data' => $this->structure, 'errors' => 'We could not create the file. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404);
  381. }
  382. }
  383. elseif($this->params['type'] == 'folder')
  384. {
  385. if(!$write->checkPath($folderPath . DIRECTORY_SEPARATOR . $namePath))
  386. {
  387. return $response->withJson(array('data' => $this->structure, 'errors' => 'We could not create the folder. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404);
  388. }
  389. $write->writeFile($folderPath . DIRECTORY_SEPARATOR . $namePath, 'index.txt', $content);
  390. }
  391. # update the structure for editor
  392. $this->setStructure($draft = true, $cache = false);
  393. # get item for url and set it active again
  394. if(isset($this->params['url']))
  395. {
  396. $activeItem = Folder::getItemForUrl($this->structure, $this->params['url'], $this->uri->getBaseUrl());
  397. }
  398. # activate this if you want to redirect after creating the page...
  399. # $url = $this->uri->getBaseUrl() . '/tm/content' . $folder->urlRelWoF . '/' . $name;
  400. return $response->withJson(array('data' => $this->structure, 'errors' => false, 'url' => $url));
  401. }
  402. public function createBaseItem(Request $request, Response $response, $args)
  403. {
  404. # get params from call
  405. $this->params = $request->getParams();
  406. $this->uri = $request->getUri();
  407. # url is only needed, if an active page is moved
  408. $url = false;
  409. # set structure
  410. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors, 'url' => $url), 404); }
  411. # validate input
  412. if(!$this->validateBaseNaviItem()){ return $response->withJson(array('data' => $this->structure, 'errors' => 'Special Characters not allowed. Length between 1 and 20 chars.', 'url' => $url), 422); }
  413. # create the name for the new item
  414. $nameParts = Folder::getStringParts($this->params['item_name']);
  415. $name = implode("-", $nameParts);
  416. $slug = $name;
  417. # initialize index
  418. $index = 0;
  419. # initialise write object
  420. $write = new Write();
  421. # iterate through the whole content of the new folder
  422. $writeError = false;
  423. foreach($this->structure as $item)
  424. {
  425. # check, if the same name as new item, then return an error
  426. if($item->slug == $slug)
  427. {
  428. return $response->withJson(array('data' => $this->structure, 'errors' => 'There is already a page with this name. Please choose another name.', 'url' => $url), 404);
  429. }
  430. if(!$write->moveElement($item, '', $index))
  431. {
  432. $writeError = true;
  433. }
  434. $index++;
  435. }
  436. if($writeError){ return $response->withJson(array('data' => $this->structure, 'errors' => 'Something went wrong. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404); }
  437. # add prefix number to the name
  438. $namePath = $index > 9 ? $index . '-' . $name : '0' . $index . '-' . $name;
  439. $folderPath = 'content';
  440. # create default content
  441. $content = json_encode(['# Add Title', 'Add Content']);
  442. if($this->params['type'] == 'file')
  443. {
  444. if(!$write->writeFile($folderPath, $namePath . '.txt', $content))
  445. {
  446. return $response->withJson(array('data' => $this->structure, 'errors' => 'We could not create the file. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404);
  447. }
  448. }
  449. elseif($this->params['type'] == 'folder')
  450. {
  451. if(!$write->checkPath($folderPath . DIRECTORY_SEPARATOR . $namePath))
  452. {
  453. return $response->withJson(array('data' => $this->structure, 'errors' => 'We could not create the folder. Please refresh the page and check, if all folders and files are writable.', 'url' => $url), 404);
  454. }
  455. $write->writeFile($folderPath . DIRECTORY_SEPARATOR . $namePath, 'index.txt', $content);
  456. }
  457. # update the structure for editor
  458. $this->setStructure($draft = true, $cache = false);
  459. # get item for url and set it active again
  460. if(isset($this->params['url']))
  461. {
  462. $activeItem = Folder::getItemForUrl($this->structure, $this->params['url'], $this->uri->getBaseUrl());
  463. }
  464. return $response->withJson(array('data' => $this->structure, 'errors' => false, 'url' => $url));
  465. }
  466. public function getNavigation(Request $request, Response $response, $args)
  467. {
  468. # get params from call
  469. $this->params = $request->getParams();
  470. $this->uri = $request->getUri();
  471. # set structure
  472. if(!$this->setStructure($draft = true, $cache = false)){ return $response->withJson(array('data' => false, 'errors' => $this->errors, 'url' => $url), 404); }
  473. # set information for homepage
  474. $this->setHomepage();
  475. # get item for url and set it active again
  476. if(isset($this->params['url']))
  477. {
  478. $activeItem = Folder::getItemForUrl($this->structure, $this->params['url'], $this->uri->getBaseUrl());
  479. }
  480. return $response->withJson(array('data' => $this->structure, 'homepage' => $this->homepage, 'errors' => false));
  481. }
  482. public function getArticleMarkdown(Request $request, Response $response, $args)
  483. {
  484. /* get params from call */
  485. $this->params = $request->getParams();
  486. $this->uri = $request->getUri();
  487. # set structure
  488. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  489. /* set item */
  490. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  491. # set the status for published and drafted
  492. $this->setPublishStatus();
  493. # set path
  494. $this->setItemPath($this->item->fileType);
  495. # read content from file
  496. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  497. $content = $this->content;
  498. if($content == '')
  499. {
  500. $content = [];
  501. }
  502. # if content is not an array, then transform it
  503. if(!is_array($content))
  504. {
  505. # initialize parsedown extension
  506. $parsedown = new ParsedownExtension();
  507. # turn markdown into an array of markdown-blocks
  508. $content = $parsedown->markdownToArrayBlocks($content);
  509. }
  510. # delete markdown from title
  511. if(isset($content[0]))
  512. {
  513. $content[0] = trim($content[0], "# ");
  514. }
  515. return $response->withJson(array('data' => $content, 'errors' => false));
  516. }
  517. public function getArticleHtml(Request $request, Response $response, $args)
  518. {
  519. /* get params from call */
  520. $this->params = $request->getParams();
  521. $this->uri = $request->getUri();
  522. # set structure
  523. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  524. /* set item */
  525. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  526. # set the status for published and drafted
  527. $this->setPublishStatus();
  528. # set path
  529. $this->setItemPath($this->item->fileType);
  530. # read content from file
  531. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  532. $content = $this->content;
  533. if($content == '')
  534. {
  535. $content = [];
  536. }
  537. # initialize parsedown extension
  538. $parsedown = new ParsedownExtension();
  539. # fix footnotes in parsedown, might break with complicated footnotes
  540. $parsedown->setVisualMode();
  541. # if content is not an array, then transform it
  542. if(!is_array($content))
  543. {
  544. # turn markdown into an array of markdown-blocks
  545. $content = $parsedown->markdownToArrayBlocks($content);
  546. }
  547. # needed for ToC links
  548. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  549. # flag for TOC
  550. $toc = false;
  551. # loop through mardkown-array and create html-blocks
  552. foreach($content as $key => $block)
  553. {
  554. # parse markdown-file to content-array
  555. $contentArray = $parsedown->text($block);
  556. if($block == '[TOC]')
  557. {
  558. $toc = $key;
  559. }
  560. # parse markdown-content-array to content-string
  561. $content[$key] = ['id' => $key, 'html' => $parsedown->markup($contentArray, $relurl)];
  562. }
  563. if($toc)
  564. {
  565. $tocMarkup = $parsedown->buildTOC($parsedown->headlines);
  566. $content[$toc] = ['id' => $toc, 'html' => $tocMarkup];
  567. }
  568. return $response->withJson(array('data' => $content, 'errors' => false));
  569. }
  570. public function addBlock(Request $request, Response $response, $args)
  571. {
  572. /* get params from call */
  573. $this->params = $request->getParams();
  574. $this->uri = $request->getUri();
  575. /* validate input */
  576. if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  577. # set structure
  578. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  579. /* set item */
  580. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  581. # set the status for published and drafted
  582. $this->setPublishStatus();
  583. # set path
  584. $this->setItemPath($this->item->fileType);
  585. # read content from file
  586. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  587. # make it more clear which content we have
  588. $pageMarkdown = $this->content;
  589. $blockMarkdown = $this->params['markdown'];
  590. # standardize line breaks
  591. $blockMarkdown = str_replace(array("\r\n", "\r"), "\n", $blockMarkdown);
  592. # remove surrounding line breaks
  593. $blockMarkdown = trim($blockMarkdown, "\n");
  594. if($pageMarkdown == '')
  595. {
  596. $pageMarkdown = [];
  597. }
  598. # initialize parsedown extension
  599. $parsedown = new ParsedownExtension();
  600. # if content is not an array, then transform it
  601. if(!is_array($pageMarkdown))
  602. {
  603. # turn markdown into an array of markdown-blocks
  604. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  605. }
  606. # if it is a new content-block
  607. if($this->params['block_id'] == 99999)
  608. {
  609. # set the id of the markdown-block (it will be one more than the actual array, so count is perfect)
  610. $id = count($pageMarkdown);
  611. # add the new markdown block to the page content
  612. $pageMarkdown[] = $blockMarkdown;
  613. }
  614. elseif(($this->params['block_id'] == 0) OR !isset($pageMarkdown[$this->params['block_id']]))
  615. {
  616. # if the block does not exists, return an error
  617. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  618. }
  619. else
  620. {
  621. # insert new markdown block
  622. array_splice( $pageMarkdown, $this->params['block_id'], 0, $blockMarkdown );
  623. $id = $this->params['block_id'];
  624. }
  625. # encode the content into json
  626. $pageJson = json_encode($pageMarkdown);
  627. # set path for the file (or folder)
  628. $this->setItemPath('txt');
  629. /* update the file */
  630. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  631. {
  632. # update the internal structure
  633. $this->setStructure($draft = true, $cache = false);
  634. $this->content = $pageMarkdown;
  635. }
  636. else
  637. {
  638. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  639. }
  640. /* set safe mode to escape javascript and html in markdown */
  641. $parsedown->setSafeMode(true);
  642. /* parse markdown-file to content-array */
  643. $blockArray = $parsedown->text($blockMarkdown);
  644. # we assume that toc is not relevant
  645. $toc = false;
  646. # needed for ToC links
  647. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  648. if($blockMarkdown == '[TOC]')
  649. {
  650. # if block is table of content itself, then generate the table of content
  651. $tableofcontent = $this->generateToc();
  652. # and only use the html-markup
  653. $blockHTML = $tableofcontent['html'];
  654. }
  655. else
  656. {
  657. # parse markdown-content-array to content-string
  658. $blockHTML = $parsedown->markup($blockArray, $relurl);
  659. # if it is a headline
  660. if($blockMarkdown[0] == '#')
  661. {
  662. # then the TOC holds either false (if no toc used in the page) or it holds an object with the id and toc-markup
  663. $toc = $this->generateToc();
  664. }
  665. }
  666. return $response->withJson(array('content' => [ 'id' => $id, 'html' => $blockHTML ] , 'markdown' => $blockMarkdown, 'id' => $id, 'toc' => $toc, 'errors' => false));
  667. }
  668. protected function generateToc()
  669. {
  670. # we assume that page has no table of content
  671. $toc = false;
  672. # make sure $this->content is updated
  673. $content = $this->content;
  674. if($content == '')
  675. {
  676. $content = [];
  677. }
  678. # initialize parsedown extension
  679. $parsedown = new ParsedownExtension();
  680. # if content is not an array, then transform it
  681. if(!is_array($content))
  682. {
  683. # turn markdown into an array of markdown-blocks
  684. $content = $parsedown->markdownToArrayBlocks($content);
  685. }
  686. # needed for ToC links
  687. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  688. # loop through mardkown-array and create html-blocks
  689. foreach($content as $key => $block)
  690. {
  691. # parse markdown-file to content-array
  692. $contentArray = $parsedown->text($block);
  693. if($block == '[TOC]')
  694. {
  695. # toc is true and holds the key of the table of content now
  696. $toc = $key;
  697. }
  698. # parse markdown-content-array to content-string
  699. $content[$key] = ['id' => $key, 'html' => $parsedown->markup($contentArray, $relurl)];
  700. }
  701. # if page has a table of content
  702. if($toc)
  703. {
  704. # generate the toc markup
  705. $tocMarkup = $parsedown->buildTOC($parsedown->headlines);
  706. # toc holds the id of the table of content and the html-markup now
  707. $toc = ['id' => $toc, 'html' => $tocMarkup];
  708. }
  709. return $toc;
  710. }
  711. public function updateBlock(Request $request, Response $response, $args)
  712. {
  713. /* get params from call */
  714. $this->params = $request->getParams();
  715. $this->uri = $request->getUri();
  716. /* validate input */
  717. if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  718. # set structure
  719. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  720. /* set item */
  721. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  722. # set the status for published and drafted
  723. $this->setPublishStatus();
  724. # set path
  725. $this->setItemPath($this->item->fileType);
  726. # read content from file
  727. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  728. # make it more clear which content we have
  729. $pageMarkdown = $this->content;
  730. $blockMarkdown = $this->params['markdown'];
  731. # standardize line breaks
  732. $blockMarkdown = str_replace(array("\r\n", "\r"), "\n", $blockMarkdown);
  733. # remove surrounding line breaks
  734. $blockMarkdown = trim($blockMarkdown, "\n");
  735. if($pageMarkdown == '')
  736. {
  737. $pageMarkdown = [];
  738. }
  739. # initialize parsedown extension
  740. $parsedown = new ParsedownExtension();
  741. $parsedown->setVisualMode();
  742. # if content is not an array, then transform it
  743. if(!is_array($pageMarkdown))
  744. {
  745. # turn markdown into an array of markdown-blocks
  746. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  747. }
  748. if(!isset($pageMarkdown[$this->params['block_id']]))
  749. {
  750. # if the block does not exists, return an error
  751. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  752. }
  753. elseif($this->params['block_id'] == 0)
  754. {
  755. # if it is the title, then delete the "# " if it exists
  756. $blockMarkdown = trim($blockMarkdown, "# ");
  757. # store the markdown-headline in a separate variable
  758. $blockMarkdownTitle = '# ' . $blockMarkdown;
  759. # add the markdown-headline to the page-markdown
  760. $pageMarkdown[0] = $blockMarkdownTitle;
  761. $id = 0;
  762. }
  763. else
  764. {
  765. # update the markdown block in the page content
  766. $pageMarkdown[$this->params['block_id']] = $blockMarkdown;
  767. $id = $this->params['block_id'];
  768. }
  769. # encode the content into json
  770. $pageJson = json_encode($pageMarkdown);
  771. # set path for the file (or folder)
  772. $this->setItemPath('txt');
  773. /* update the file */
  774. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  775. {
  776. # update the internal structure
  777. $this->setStructure($draft = true, $cache = false);
  778. # updated the content variable
  779. $this->content = $pageMarkdown;
  780. }
  781. else
  782. {
  783. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  784. }
  785. /* set safe mode to escape javascript and html in markdown */
  786. $parsedown->setSafeMode(true);
  787. /* parse markdown-file to content-array, if title parse title. */
  788. if($this->params['block_id'] == 0)
  789. {
  790. $blockArray = $parsedown->text($blockMarkdownTitle);
  791. }
  792. else
  793. {
  794. $blockArray = $parsedown->text($blockMarkdown);
  795. }
  796. # we assume that toc is not relevant
  797. $toc = false;
  798. # needed for ToC links
  799. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  800. if($blockMarkdown == '[TOC]')
  801. {
  802. # if block is table of content itself, then generate the table of content
  803. $tableofcontent = $this->generateToc();
  804. # and only use the html-markup
  805. $blockHTML = $tableofcontent['html'];
  806. }
  807. else
  808. {
  809. # parse markdown-content-array to content-string
  810. $blockHTML = $parsedown->markup($blockArray, $relurl);
  811. # if it is a headline
  812. if($blockMarkdown[0] == '#')
  813. {
  814. # then the TOC holds either false (if no toc used in the page) or it holds an object with the id and toc-markup
  815. $toc = $this->generateToc();
  816. }
  817. }
  818. return $response->withJson(array('content' => [ 'id' => $id, 'html' => $blockHTML ] , 'markdown' => $blockMarkdown, 'id' => $id, 'toc' => $toc, 'errors' => false));
  819. }
  820. public function moveBlock(Request $request, Response $response, $args)
  821. {
  822. # get params from call
  823. $this->params = $request->getParams();
  824. $this->uri = $request->getUri();
  825. # validate input
  826. # if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  827. # set structure
  828. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  829. # set item
  830. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  831. # set the status for published and drafted
  832. $this->setPublishStatus();
  833. # set path
  834. $this->setItemPath($this->item->fileType);
  835. # read content from file
  836. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  837. # make it more clear which content we have
  838. $pageMarkdown = $this->content;
  839. if($pageMarkdown == '')
  840. {
  841. $pageMarkdown = [];
  842. }
  843. # initialize parsedown extension
  844. $parsedown = new ParsedownExtension();
  845. # if content is not an array, then transform it
  846. if(!is_array($pageMarkdown))
  847. {
  848. # turn markdown into an array of markdown-blocks
  849. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  850. }
  851. $oldIndex = ($this->params['old_index'] + 1);
  852. $newIndex = ($this->params['new_index'] + 1);
  853. if(!isset($pageMarkdown[$oldIndex]))
  854. {
  855. # if the block does not exists, return an error
  856. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  857. }
  858. $extract = array_splice($pageMarkdown, $oldIndex, 1);
  859. array_splice($pageMarkdown, $newIndex, 0, $extract);
  860. # encode the content into json
  861. $pageJson = json_encode($pageMarkdown);
  862. # set path for the file (or folder)
  863. $this->setItemPath('txt');
  864. /* update the file */
  865. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  866. {
  867. # update the internal structure
  868. $this->setStructure($draft = true, $cache = false);
  869. # update this content
  870. $this->content = $pageMarkdown;
  871. }
  872. else
  873. {
  874. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  875. }
  876. # we assume that toc is not relevant
  877. $toc = false;
  878. # needed for ToC links
  879. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  880. # if the moved item is a headline
  881. if($extract[0][0] == '#')
  882. {
  883. $toc = $this->generateToc();
  884. }
  885. # if it is the title, then delete the "# " if it exists
  886. $pageMarkdown[0] = trim($pageMarkdown[0], "# ");
  887. return $response->withJson(array('markdown' => $pageMarkdown, 'toc' => $toc, 'errors' => false));
  888. }
  889. public function deleteBlock(Request $request, Response $response, $args)
  890. {
  891. /* get params from call */
  892. $this->params = $request->getParams();
  893. $this->uri = $request->getUri();
  894. $errors = false;
  895. # set structure
  896. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  897. # set item
  898. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  899. # set the status for published and drafted
  900. $this->setPublishStatus();
  901. # set path
  902. $this->setItemPath($this->item->fileType);
  903. # read content from file
  904. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  905. # get content
  906. $this->content;
  907. if($this->content == '')
  908. {
  909. $this->content = [];
  910. }
  911. # initialize parsedown extension
  912. $parsedown = new ParsedownExtension();
  913. # if content is not an array, then transform it
  914. if(!is_array($this->content))
  915. {
  916. # turn markdown into an array of markdown-blocks
  917. $this->content = $parsedown->markdownToArrayBlocks($this->content);
  918. }
  919. # check if id exists
  920. if(!isset($this->content[$this->params['block_id']])){ return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404); }
  921. # check if block is image
  922. $contentBlock = $this->content[$this->params['block_id']];
  923. $contentBlockStart = substr($contentBlock, 0, 2);
  924. if($contentBlockStart == '[!' OR $contentBlockStart == '![')
  925. {
  926. # extract image path
  927. preg_match("/\((.*?)\)/",$contentBlock,$matches);
  928. if(isset($matches[1]))
  929. {
  930. $imageBaseName = explode('-', $matches[1]);
  931. $imageBaseName = str_replace('media/live/', '', $imageBaseName[0]);
  932. $processImage = new ProcessImage();
  933. if(!$processImage->deleteImage($imageBaseName))
  934. {
  935. $errors = 'Could not delete some of the images, please check manually';
  936. }
  937. }
  938. }
  939. # delete the block
  940. unset($this->content[$this->params['block_id']]);
  941. $this->content = array_values($this->content);
  942. $pageMarkdown = $this->content;
  943. # delete markdown from title
  944. if(isset($pageMarkdown[0]))
  945. {
  946. $pageMarkdown[0] = trim($pageMarkdown[0], "# ");
  947. }
  948. # encode the content into json
  949. $pageJson = json_encode($this->content);
  950. # set path for the file (or folder)
  951. $this->setItemPath('txt');
  952. /* update the file */
  953. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  954. {
  955. # update the internal structure
  956. $this->setStructure($draft = true, $cache = false);
  957. }
  958. else
  959. {
  960. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  961. }
  962. $toc = false;
  963. if($contentBlock[0] == '#')
  964. {
  965. $toc = $this->generateToc();
  966. }
  967. return $response->withJson(array('markdown' => $pageMarkdown, 'toc' => $toc, 'errors' => $errors));
  968. }
  969. public function createImage(Request $request, Response $response, $args)
  970. {
  971. /* get params from call */
  972. $this->params = $request->getParams();
  973. $this->uri = $request->getUri();
  974. $imageProcessor = new ProcessImage();
  975. if($imageProcessor->createImage($this->params['image'], $this->settings['images']))
  976. {
  977. return $response->withJson(array('errors' => false));
  978. }
  979. return $response->withJson(array('errors' => 'could not store image to temporary folder'));
  980. }
  981. public function publishImage(Request $request, Response $response, $args)
  982. {
  983. $params = $request->getParsedBody();
  984. $imageProcessor = new ProcessImage();
  985. $imageUrl = $imageProcessor->publishImage($this->settings['images'], $name = false);
  986. if($imageUrl)
  987. {
  988. $params['markdown'] = str_replace('imgplchldr', $imageUrl, $params['markdown']);
  989. $request = $request->withParsedBody($params);
  990. return $this->addBlock($request, $response, $args);
  991. }
  992. return $response->withJson(array('errors' => 'could not store image to media folder'));
  993. }
  994. public function saveVideoImage(Request $request, Response $response, $args)
  995. {
  996. /* get params from call */
  997. $this->params = $request->getParams();
  998. $this->uri = $request->getUri();
  999. $class = false;
  1000. $imageUrl = $this->params['markdown'];
  1001. if(strpos($imageUrl, 'https://www.youtube.com/watch?v=') !== false)
  1002. {
  1003. $videoID = str_replace('https://www.youtube.com/watch?v=', '', $imageUrl);
  1004. $videoID = strpos($videoID, '&') ? substr($videoID, 0, strpos($videoID, '&')) : $videoID;
  1005. $class = 'youtube';
  1006. }
  1007. if(strpos($imageUrl, 'https://youtu.be/') !== false)
  1008. {
  1009. $videoID = str_replace('https://youtu.be/', '', $imageUrl);
  1010. $videoID = strpos($videoID, '?') ? substr($videoID, 0, strpos($videoID, '?')) : $videoID;
  1011. $class = 'youtube';
  1012. }
  1013. if($class == 'youtube')
  1014. {
  1015. $videoURLmaxres = 'https://i1.ytimg.com/vi/' . $videoID . '/maxresdefault.jpg';
  1016. $videoURL0 = 'https://i1.ytimg.com/vi/' . $videoID . '/0.jpg';
  1017. }
  1018. $ctx = stream_context_create(array(
  1019. 'https' => array(
  1020. 'timeout' => 1
  1021. )
  1022. )
  1023. );
  1024. $imageData = @file_get_contents($videoURLmaxres, 0, $ctx);
  1025. if($imageData === false)
  1026. {
  1027. $imageData = @file_get_contents($videoURL0, 0, $ctx);
  1028. if($imageData === false)
  1029. {
  1030. return $response->withJson(array('errors' => 'could not get the video image'));
  1031. }
  1032. }
  1033. $imageData64 = 'data:image/jpeg;base64,' . base64_encode($imageData);
  1034. $desiredSizes = ['live' => ['width' => 560, 'height' => 315]];
  1035. $imageProcessor = new ProcessImage();
  1036. $tmpImage = $imageProcessor->createImage($imageData64, $desiredSizes);
  1037. if(!$tmpImage)
  1038. {
  1039. return $response->withJson(array('errors' => 'could not create temporary image'));
  1040. }
  1041. $imageUrl = $imageProcessor->publishImage($desiredSizes, $videoID);
  1042. if($imageUrl)
  1043. {
  1044. $this->params['markdown'] = '![' . $class . '-video](' . $imageUrl . ' "click to load video"){#' . $videoID. ' .' . $class . '}';
  1045. $request = $request->withParsedBody($this->params);
  1046. return $this->addBlock($request, $response, $args);
  1047. }
  1048. return $response->withJson(array('errors' => 'could not store the preview image'));
  1049. }
  1050. }