ContentApiController.php 38 KB

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