ContentApiController.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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 getArticleMarkdown(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)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  400. /* set item */
  401. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  402. # set the status for published and drafted
  403. $this->setPublishStatus();
  404. # set path
  405. $this->setItemPath($this->item->fileType);
  406. # read content from file
  407. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  408. $content = $this->content;
  409. if($content == '')
  410. {
  411. $content = [];
  412. }
  413. # if content is not an array, then transform it
  414. if(!is_array($content))
  415. {
  416. # initialize parsedown extension
  417. $parsedown = new ParsedownExtension();
  418. # turn markdown into an array of markdown-blocks
  419. $content = $parsedown->markdownToArrayBlocks($content);
  420. }
  421. # delete markdown from title
  422. if(isset($content[0]))
  423. {
  424. $content[0] = trim($content[0], "# ");
  425. }
  426. return $response->withJson(array('data' => $content, 'errors' => false));
  427. }
  428. public function getArticleHtml(Request $request, Response $response, $args)
  429. {
  430. /* get params from call */
  431. $this->params = $request->getParams();
  432. $this->uri = $request->getUri();
  433. # set structure
  434. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  435. /* set item */
  436. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  437. # set the status for published and drafted
  438. $this->setPublishStatus();
  439. # set path
  440. $this->setItemPath($this->item->fileType);
  441. # read content from file
  442. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  443. $content = $this->content;
  444. if($content == '')
  445. {
  446. $content = [];
  447. }
  448. # initialize parsedown extension
  449. $parsedown = new ParsedownExtension();
  450. # if content is not an array, then transform it
  451. if(!is_array($content))
  452. {
  453. # turn markdown into an array of markdown-blocks
  454. $content = $parsedown->markdownToArrayBlocks($content);
  455. }
  456. # needed for ToC links
  457. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  458. # flag for TOC
  459. $toc = false;
  460. # loop through mardkown-array and create html-blocks
  461. foreach($content as $key => $block)
  462. {
  463. # parse markdown-file to content-array
  464. $contentArray = $parsedown->text($block);
  465. if($block == '[TOC]')
  466. {
  467. $toc = $key;
  468. }
  469. # parse markdown-content-array to content-string
  470. $content[$key] = ['id' => $key, 'html' => $parsedown->markup($contentArray, $relurl)];
  471. }
  472. if($toc)
  473. {
  474. $tocMarkup = $parsedown->buildTOC($parsedown->headlines);
  475. $content[$toc] = ['id' => $toc, 'html' => $tocMarkup];
  476. }
  477. /*
  478. $footnotes = $parsedown->getFootnotes();
  479. print_r($footnotes);
  480. die();
  481. */
  482. return $response->withJson(array('data' => $content, 'errors' => false));
  483. }
  484. public function addBlock(Request $request, Response $response, $args)
  485. {
  486. /* get params from call */
  487. $this->params = $request->getParams();
  488. $this->uri = $request->getUri();
  489. /* validate input */
  490. if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  491. # set structure
  492. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  493. /* set item */
  494. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  495. # set the status for published and drafted
  496. $this->setPublishStatus();
  497. # set path
  498. $this->setItemPath($this->item->fileType);
  499. # read content from file
  500. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  501. # make it more clear which content we have
  502. $pageMarkdown = $this->content;
  503. $blockMarkdown = $this->params['markdown'];
  504. # standardize line breaks
  505. $blockMarkdown = str_replace(array("\r\n", "\r"), "\n", $blockMarkdown);
  506. # remove surrounding line breaks
  507. $blockMarkdown = trim($blockMarkdown, "\n");
  508. if($pageMarkdown == '')
  509. {
  510. $pageMarkdown = [];
  511. }
  512. # initialize parsedown extension
  513. $parsedown = new ParsedownExtension();
  514. # if content is not an array, then transform it
  515. if(!is_array($pageMarkdown))
  516. {
  517. # turn markdown into an array of markdown-blocks
  518. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  519. }
  520. # if it is a new content-block
  521. if($this->params['block_id'] == 99999)
  522. {
  523. # set the id of the markdown-block (it will be one more than the actual array, so count is perfect)
  524. $id = count($pageMarkdown);
  525. # add the new markdown block to the page content
  526. $pageMarkdown[] = $blockMarkdown;
  527. }
  528. elseif(($this->params['block_id'] == 0) OR !isset($pageMarkdown[$this->params['block_id']]))
  529. {
  530. # if the block does not exists, return an error
  531. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  532. }
  533. else
  534. {
  535. # insert new markdown block
  536. array_splice( $pageMarkdown, $this->params['block_id'], 0, $blockMarkdown );
  537. $id = $this->params['block_id'];
  538. }
  539. # encode the content into json
  540. $pageJson = json_encode($pageMarkdown);
  541. # set path for the file (or folder)
  542. $this->setItemPath('txt');
  543. /* update the file */
  544. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  545. {
  546. # update the internal structure
  547. $this->setStructure($draft = true, $cache = false);
  548. $this->content = $pageMarkdown;
  549. }
  550. else
  551. {
  552. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  553. }
  554. /* set safe mode to escape javascript and html in markdown */
  555. $parsedown->setSafeMode(true);
  556. /* parse markdown-file to content-array */
  557. $blockArray = $parsedown->text($blockMarkdown);
  558. # we assume that toc is not relevant
  559. $toc = false;
  560. # needed for ToC links
  561. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  562. if($blockMarkdown == '[TOC]')
  563. {
  564. # if block is table of content itself, then generate the table of content
  565. $tableofcontent = $this->generateToc();
  566. # and only use the html-markup
  567. $blockHTML = $tableofcontent['html'];
  568. }
  569. else
  570. {
  571. # parse markdown-content-array to content-string
  572. $blockHTML = $parsedown->markup($blockArray, $relurl);
  573. # if it is a headline
  574. if($blockMarkdown[0] == '#')
  575. {
  576. # then the TOC holds either false (if no toc used in the page) or it holds an object with the id and toc-markup
  577. $toc = $this->generateToc();
  578. }
  579. }
  580. return $response->withJson(array('content' => [ 'id' => $id, 'html' => $blockHTML ] , 'markdown' => $blockMarkdown, 'id' => $id, 'toc' => $toc, 'errors' => false));
  581. }
  582. protected function generateToc()
  583. {
  584. # we assume that page has no table of content
  585. $toc = false;
  586. # make sure $this->content is updated
  587. $content = $this->content;
  588. if($content == '')
  589. {
  590. $content = [];
  591. }
  592. # initialize parsedown extension
  593. $parsedown = new ParsedownExtension();
  594. # if content is not an array, then transform it
  595. if(!is_array($content))
  596. {
  597. # turn markdown into an array of markdown-blocks
  598. $content = $parsedown->markdownToArrayBlocks($content);
  599. }
  600. # needed for ToC links
  601. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  602. # loop through mardkown-array and create html-blocks
  603. foreach($content as $key => $block)
  604. {
  605. # parse markdown-file to content-array
  606. $contentArray = $parsedown->text($block);
  607. if($block == '[TOC]')
  608. {
  609. # toc is true and holds the key of the table of content now
  610. $toc = $key;
  611. }
  612. # parse markdown-content-array to content-string
  613. $content[$key] = ['id' => $key, 'html' => $parsedown->markup($contentArray, $relurl)];
  614. }
  615. # if page has a table of content
  616. if($toc)
  617. {
  618. # generate the toc markup
  619. $tocMarkup = $parsedown->buildTOC($parsedown->headlines);
  620. # toc holds the id of the table of content and the html-markup now
  621. $toc = ['id' => $toc, 'html' => $tocMarkup];
  622. }
  623. return $toc;
  624. }
  625. public function updateBlock(Request $request, Response $response, $args)
  626. {
  627. /* get params from call */
  628. $this->params = $request->getParams();
  629. $this->uri = $request->getUri();
  630. /* validate input */
  631. if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  632. # set structure
  633. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  634. /* set item */
  635. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  636. # set the status for published and drafted
  637. $this->setPublishStatus();
  638. # set path
  639. $this->setItemPath($this->item->fileType);
  640. # read content from file
  641. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  642. # make it more clear which content we have
  643. $pageMarkdown = $this->content;
  644. $blockMarkdown = $this->params['markdown'];
  645. # standardize line breaks
  646. $blockMarkdown = str_replace(array("\r\n", "\r"), "\n", $blockMarkdown);
  647. # remove surrounding line breaks
  648. $blockMarkdown = trim($blockMarkdown, "\n");
  649. if($pageMarkdown == '')
  650. {
  651. $pageMarkdown = [];
  652. }
  653. # initialize parsedown extension
  654. $parsedown = new ParsedownExtension();
  655. # if content is not an array, then transform it
  656. if(!is_array($pageMarkdown))
  657. {
  658. # turn markdown into an array of markdown-blocks
  659. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  660. }
  661. if(!isset($pageMarkdown[$this->params['block_id']]))
  662. {
  663. # if the block does not exists, return an error
  664. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  665. }
  666. elseif($this->params['block_id'] == 0)
  667. {
  668. # if it is the title, then delete the "# " if it exists
  669. $blockMarkdown = trim($blockMarkdown, "# ");
  670. # store the markdown-headline in a separate variable
  671. $blockMarkdownTitle = '# ' . $blockMarkdown;
  672. # add the markdown-headline to the page-markdown
  673. $pageMarkdown[0] = $blockMarkdownTitle;
  674. $id = 0;
  675. }
  676. else
  677. {
  678. # update the markdown block in the page content
  679. $pageMarkdown[$this->params['block_id']] = $blockMarkdown;
  680. $id = $this->params['block_id'];
  681. }
  682. # encode the content into json
  683. $pageJson = json_encode($pageMarkdown);
  684. # set path for the file (or folder)
  685. $this->setItemPath('txt');
  686. /* update the file */
  687. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  688. {
  689. # update the internal structure
  690. $this->setStructure($draft = true, $cache = false);
  691. # updated the content variable
  692. $this->content = $pageMarkdown;
  693. }
  694. else
  695. {
  696. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  697. }
  698. /* set safe mode to escape javascript and html in markdown */
  699. $parsedown->setSafeMode(true);
  700. /* parse markdown-file to content-array, if title parse title. */
  701. if($this->params['block_id'] == 0)
  702. {
  703. $blockArray = $parsedown->text($blockMarkdownTitle);
  704. }
  705. else
  706. {
  707. $blockArray = $parsedown->text($blockMarkdown);
  708. }
  709. # we assume that toc is not relevant
  710. $toc = false;
  711. # needed for ToC links
  712. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  713. if($blockMarkdown == '[TOC]')
  714. {
  715. # if block is table of content itself, then generate the table of content
  716. $tableofcontent = $this->generateToc();
  717. # and only use the html-markup
  718. $blockHTML = $tableofcontent['html'];
  719. }
  720. else
  721. {
  722. # parse markdown-content-array to content-string
  723. $blockHTML = $parsedown->markup($blockArray, $relurl);
  724. # if it is a headline
  725. if($blockMarkdown[0] == '#')
  726. {
  727. # then the TOC holds either false (if no toc used in the page) or it holds an object with the id and toc-markup
  728. $toc = $this->generateToc();
  729. }
  730. }
  731. return $response->withJson(array('content' => [ 'id' => $id, 'html' => $blockHTML ] , 'markdown' => $blockMarkdown, 'id' => $id, 'toc' => $toc, 'errors' => false));
  732. }
  733. public function moveBlock(Request $request, Response $response, $args)
  734. {
  735. # get params from call
  736. $this->params = $request->getParams();
  737. $this->uri = $request->getUri();
  738. # validate input
  739. # if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  740. # set structure
  741. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  742. # set item
  743. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  744. # set the status for published and drafted
  745. $this->setPublishStatus();
  746. # set path
  747. $this->setItemPath($this->item->fileType);
  748. # read content from file
  749. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  750. # make it more clear which content we have
  751. $pageMarkdown = $this->content;
  752. if($pageMarkdown == '')
  753. {
  754. $pageMarkdown = [];
  755. }
  756. # initialize parsedown extension
  757. $parsedown = new ParsedownExtension();
  758. # if content is not an array, then transform it
  759. if(!is_array($pageMarkdown))
  760. {
  761. # turn markdown into an array of markdown-blocks
  762. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  763. }
  764. $oldIndex = ($this->params['old_index'] + 1);
  765. $newIndex = ($this->params['new_index'] + 1);
  766. if(!isset($pageMarkdown[$oldIndex]))
  767. {
  768. # if the block does not exists, return an error
  769. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  770. }
  771. $extract = array_splice($pageMarkdown, $oldIndex, 1);
  772. array_splice($pageMarkdown, $newIndex, 0, $extract);
  773. # encode the content into json
  774. $pageJson = json_encode($pageMarkdown);
  775. # set path for the file (or folder)
  776. $this->setItemPath('txt');
  777. /* update the file */
  778. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  779. {
  780. # update the internal structure
  781. $this->setStructure($draft = true, $cache = false);
  782. # update this content
  783. $this->content = $pageMarkdown;
  784. }
  785. else
  786. {
  787. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  788. }
  789. # we assume that toc is not relevant
  790. $toc = false;
  791. # needed for ToC links
  792. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  793. # if the moved item is a headline
  794. if($extract[0][0] == '#')
  795. {
  796. $toc = $this->generateToc();
  797. }
  798. # if it is the title, then delete the "# " if it exists
  799. $pageMarkdown[0] = trim($pageMarkdown[0], "# ");
  800. return $response->withJson(array('markdown' => $pageMarkdown, 'toc' => $toc, 'errors' => false));
  801. }
  802. public function deleteBlock(Request $request, Response $response, $args)
  803. {
  804. /* get params from call */
  805. $this->params = $request->getParams();
  806. $this->uri = $request->getUri();
  807. $errors = false;
  808. # set structure
  809. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  810. # set item
  811. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  812. # set the status for published and drafted
  813. $this->setPublishStatus();
  814. # set path
  815. $this->setItemPath($this->item->fileType);
  816. # read content from file
  817. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  818. # get content
  819. $this->content;
  820. if($this->content == '')
  821. {
  822. $this->content = [];
  823. }
  824. # initialize parsedown extension
  825. $parsedown = new ParsedownExtension();
  826. # if content is not an array, then transform it
  827. if(!is_array($this->content))
  828. {
  829. # turn markdown into an array of markdown-blocks
  830. $this->content = $parsedown->markdownToArrayBlocks($this->content);
  831. }
  832. # check if id exists
  833. if(!isset($this->content[$this->params['block_id']])){ return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404); }
  834. # check if block is image
  835. $contentBlock = $this->content[$this->params['block_id']];
  836. $contentBlockStart = substr($contentBlock, 0, 2);
  837. if($contentBlockStart == '[!' OR $contentBlockStart == '![')
  838. {
  839. # extract image path
  840. preg_match("/\((.*?)\)/",$contentBlock,$matches);
  841. if(isset($matches[1]))
  842. {
  843. $imageBaseName = explode('-', $matches[1]);
  844. $imageBaseName = str_replace('media/live/', '', $imageBaseName[0]);
  845. $processImage = new ProcessImage();
  846. if(!$processImage->deleteImage($imageBaseName))
  847. {
  848. $errors = 'Could not delete some of the images, please check manually';
  849. }
  850. }
  851. }
  852. # delete the block
  853. unset($this->content[$this->params['block_id']]);
  854. $this->content = array_values($this->content);
  855. $pageMarkdown = $this->content;
  856. # delete markdown from title
  857. if(isset($pageMarkdown[0]))
  858. {
  859. $pageMarkdown[0] = trim($pageMarkdown[0], "# ");
  860. }
  861. # encode the content into json
  862. $pageJson = json_encode($this->content);
  863. # set path for the file (or folder)
  864. $this->setItemPath('txt');
  865. /* update the file */
  866. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  867. {
  868. # update the internal structure
  869. $this->setStructure($draft = true, $cache = false);
  870. }
  871. else
  872. {
  873. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  874. }
  875. $toc = false;
  876. if($contentBlock[0] == '#')
  877. {
  878. $toc = $this->generateToc();
  879. }
  880. return $response->withJson(array('markdown' => $pageMarkdown, 'toc' => $toc, 'errors' => $errors));
  881. }
  882. public function createImage(Request $request, Response $response, $args)
  883. {
  884. /* get params from call */
  885. $this->params = $request->getParams();
  886. $this->uri = $request->getUri();
  887. $imageProcessor = new ProcessImage();
  888. if($imageProcessor->createImage($this->params['image'], $this->settings['images']))
  889. {
  890. return $response->withJson(array('errors' => false));
  891. }
  892. return $response->withJson(array('errors' => 'could not store image to temporary folder'));
  893. }
  894. public function publishImage(Request $request, Response $response, $args)
  895. {
  896. $params = $request->getParsedBody();
  897. $imageProcessor = new ProcessImage();
  898. $imageUrl = $imageProcessor->publishImage($this->settings['images'], $name = false);
  899. if($imageUrl)
  900. {
  901. $params['markdown'] = str_replace('imgplchldr', $imageUrl, $params['markdown']);
  902. $request = $request->withParsedBody($params);
  903. return $this->addBlock($request, $response, $args);
  904. }
  905. return $response->withJson(array('errors' => 'could not store image to media folder'));
  906. }
  907. public function saveVideoImage(Request $request, Response $response, $args)
  908. {
  909. /* get params from call */
  910. $this->params = $request->getParams();
  911. $this->uri = $request->getUri();
  912. $class = false;
  913. $imageUrl = $this->params['markdown'];
  914. if(strpos($imageUrl, 'https://www.youtube.com/watch?v=') !== false)
  915. {
  916. $videoID = str_replace('https://www.youtube.com/watch?v=', '', $imageUrl);
  917. $videoID = strpos($videoID, '&') ? substr($videoID, 0, strpos($videoID, '&')) : $videoID;
  918. $class = 'youtube';
  919. }
  920. if(strpos($imageUrl, 'https://youtu.be/') !== false)
  921. {
  922. $videoID = str_replace('https://youtu.be/', '', $imageUrl);
  923. $videoID = strpos($videoID, '?') ? substr($videoID, 0, strpos($videoID, '?')) : $videoID;
  924. $class = 'youtube';
  925. }
  926. if($class == 'youtube')
  927. {
  928. $videoURLmaxres = 'https://i1.ytimg.com/vi/' . $videoID . '/maxresdefault.jpg';
  929. $videoURL0 = 'https://i1.ytimg.com/vi/' . $videoID . '/0.jpg';
  930. }
  931. $ctx = stream_context_create(array(
  932. 'https' => array(
  933. 'timeout' => 1
  934. )
  935. )
  936. );
  937. $imageData = @file_get_contents($videoURLmaxres, 0, $ctx);
  938. if($imageData === false)
  939. {
  940. $imageData = @file_get_contents($videoURL0, 0, $ctx);
  941. if($imageData === false)
  942. {
  943. return $response->withJson(array('errors' => 'could not get the video image'));
  944. }
  945. }
  946. $imageData64 = 'data:image/jpeg;base64,' . base64_encode($imageData);
  947. $desiredSizes = ['live' => ['width' => 560, 'height' => 315]];
  948. $imageProcessor = new ProcessImage();
  949. $tmpImage = $imageProcessor->createImage($imageData64, $desiredSizes);
  950. if(!$tmpImage)
  951. {
  952. return $response->withJson(array('errors' => 'could not create temporary image'));
  953. }
  954. $imageUrl = $imageProcessor->publishImage($desiredSizes, $videoID);
  955. if($imageUrl)
  956. {
  957. $this->params['markdown'] = '![' . $class . '-video](' . $imageUrl . ' "click to load video"){#' . $videoID. ' .' . $class . '}';
  958. $request = $request->withParsedBody($this->params);
  959. return $this->addBlock($request, $response, $args);
  960. }
  961. return $response->withJson(array('errors' => 'could not store the preview image'));
  962. }
  963. }