ContentApiController.php 41 KB

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