ContentApiController.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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
  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
  233. $url = $this->uri->getBaseUrl() . '/tm/content' . $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
  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. foreach($content as $key => $block)
  459. {
  460. /* parse markdown-file to content-array */
  461. $contentArray = $parsedown->text($block);
  462. /* parse markdown-content-array to content-string */
  463. $content[$key] = $parsedown->markup($contentArray, $relurl);
  464. }
  465. return $response->withJson(array('data' => $content, 'errors' => false));
  466. }
  467. public function addBlock(Request $request, Response $response, $args)
  468. {
  469. /* get params from call */
  470. $this->params = $request->getParams();
  471. $this->uri = $request->getUri();
  472. /* validate input */
  473. if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  474. # set structure
  475. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  476. /* set item */
  477. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  478. # set the status for published and drafted
  479. $this->setPublishStatus();
  480. # set path
  481. $this->setItemPath($this->item->fileType);
  482. # read content from file
  483. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  484. # make it more clear which content we have
  485. $pageMarkdown = $this->content;
  486. $blockMarkdown = $this->params['markdown'];
  487. # standardize line breaks
  488. $blockMarkdown = str_replace(array("\r\n", "\r"), "\n", $blockMarkdown);
  489. # remove surrounding line breaks
  490. $blockMarkdown = trim($blockMarkdown, "\n");
  491. if($pageMarkdown == '')
  492. {
  493. $pageMarkdown = [];
  494. }
  495. # initialize parsedown extension
  496. $parsedown = new ParsedownExtension();
  497. # if content is not an array, then transform it
  498. if(!is_array($pageMarkdown))
  499. {
  500. # turn markdown into an array of markdown-blocks
  501. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  502. }
  503. # if it is a new content-block
  504. if($this->params['block_id'] == 99999)
  505. {
  506. # set the id of the markdown-block (it will be one more than the actual array, so count is perfect)
  507. $id = count($pageMarkdown);
  508. # add the new markdown block to the page content
  509. $pageMarkdown[] = $blockMarkdown;
  510. }
  511. elseif(($this->params['block_id'] == 0) OR !isset($pageMarkdown[$this->params['block_id']]))
  512. {
  513. # if the block does not exists, return an error
  514. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  515. }
  516. else
  517. {
  518. # insert new markdown block
  519. array_splice( $pageMarkdown, $this->params['block_id'], 0, $blockMarkdown );
  520. $id = $this->params['block_id'];
  521. }
  522. # encode the content into json
  523. $pageJson = json_encode($pageMarkdown);
  524. # set path for the file (or folder)
  525. $this->setItemPath('txt');
  526. /* update the file */
  527. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  528. {
  529. # update the internal structure
  530. $this->setStructure($draft = true, $cache = false);
  531. }
  532. else
  533. {
  534. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  535. }
  536. /* set safe mode to escape javascript and html in markdown */
  537. $parsedown->setSafeMode(true);
  538. /* parse markdown-file to content-array */
  539. $blockArray = $parsedown->text($blockMarkdown);
  540. # needed for ToC links
  541. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  542. /* parse markdown-content-array to content-string */
  543. $blockHTML = $parsedown->markup($blockArray, $relurl);
  544. return $response->withJson(array('content' => $blockHTML, 'markdown' => $blockMarkdown, 'id' => $id, 'errors' => false));
  545. }
  546. public function updateBlock(Request $request, Response $response, $args)
  547. {
  548. /* get params from call */
  549. $this->params = $request->getParams();
  550. $this->uri = $request->getUri();
  551. /* validate input */
  552. if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  553. # set structure
  554. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  555. /* set item */
  556. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  557. # set the status for published and drafted
  558. $this->setPublishStatus();
  559. # set path
  560. $this->setItemPath($this->item->fileType);
  561. # read content from file
  562. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  563. # make it more clear which content we have
  564. $pageMarkdown = $this->content;
  565. $blockMarkdown = $this->params['markdown'];
  566. # standardize line breaks
  567. $blockMarkdown = str_replace(array("\r\n", "\r"), "\n", $blockMarkdown);
  568. # remove surrounding line breaks
  569. $blockMarkdown = trim($blockMarkdown, "\n");
  570. if($pageMarkdown == '')
  571. {
  572. $pageMarkdown = [];
  573. }
  574. # initialize parsedown extension
  575. $parsedown = new ParsedownExtension();
  576. # if content is not an array, then transform it
  577. if(!is_array($pageMarkdown))
  578. {
  579. # turn markdown into an array of markdown-blocks
  580. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  581. }
  582. if(!isset($pageMarkdown[$this->params['block_id']]))
  583. {
  584. # if the block does not exists, return an error
  585. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  586. }
  587. elseif($this->params['block_id'] == 0)
  588. {
  589. # if it is the title, then delete the "# " if it exists
  590. $blockMarkdown = trim($blockMarkdown, "# ");
  591. # store the markdown-headline in a separate variable
  592. $blockMarkdownTitle = '# ' . $blockMarkdown;
  593. # add the markdown-headline to the page-markdown
  594. $pageMarkdown[0] = $blockMarkdownTitle;
  595. $id = 0;
  596. }
  597. else
  598. {
  599. # update the markdown block in the page content
  600. $pageMarkdown[$this->params['block_id']] = $blockMarkdown;
  601. $id = $this->params['block_id'];
  602. }
  603. # encode the content into json
  604. $pageJson = json_encode($pageMarkdown);
  605. # set path for the file (or folder)
  606. $this->setItemPath('txt');
  607. /* update the file */
  608. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  609. {
  610. # update the internal structure
  611. $this->setStructure($draft = true, $cache = false);
  612. }
  613. else
  614. {
  615. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  616. }
  617. /* set safe mode to escape javascript and html in markdown */
  618. $parsedown->setSafeMode(true);
  619. /* parse markdown-file to content-array, if title parse title. */
  620. if($this->params['block_id'] == 0)
  621. {
  622. $blockArray = $parsedown->text($blockMarkdownTitle);
  623. }
  624. else
  625. {
  626. $blockArray = $parsedown->text($blockMarkdown);
  627. }
  628. # needed for ToC links
  629. $relurl = '/tm/content/' . $this->settings['editor'] . '/' . $this->item->urlRel;
  630. /* parse markdown-content-array to content-string */
  631. $blockHTML = $parsedown->markup($blockArray, $relurl);
  632. return $response->withJson(array('content' => $blockHTML, 'markdown' => $blockMarkdown, 'id' => $id, 'errors' => false));
  633. }
  634. public function moveBlock(Request $request, Response $response, $args)
  635. {
  636. # get params from call
  637. $this->params = $request->getParams();
  638. $this->uri = $request->getUri();
  639. # validate input
  640. # if(!$this->validateBlockInput()){ return $response->withJson($this->errors,422); }
  641. # set structure
  642. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  643. # set item
  644. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  645. # set the status for published and drafted
  646. $this->setPublishStatus();
  647. # set path
  648. $this->setItemPath($this->item->fileType);
  649. # read content from file
  650. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  651. # make it more clear which content we have
  652. $pageMarkdown = $this->content;
  653. if($pageMarkdown == '')
  654. {
  655. $pageMarkdown = [];
  656. }
  657. # initialize parsedown extension
  658. $parsedown = new ParsedownExtension();
  659. # if content is not an array, then transform it
  660. if(!is_array($pageMarkdown))
  661. {
  662. # turn markdown into an array of markdown-blocks
  663. $pageMarkdown = $parsedown->markdownToArrayBlocks($pageMarkdown);
  664. }
  665. $oldIndex = ($this->params['old_index'] + 1);
  666. $newIndex = ($this->params['new_index'] + 1);
  667. if(!isset($pageMarkdown[$oldIndex]))
  668. {
  669. # if the block does not exists, return an error
  670. return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404);
  671. }
  672. $extract = array_splice($pageMarkdown, $oldIndex, 1);
  673. array_splice($pageMarkdown, $newIndex, 0, $extract);
  674. # encode the content into json
  675. $pageJson = json_encode($pageMarkdown);
  676. # set path for the file (or folder)
  677. $this->setItemPath('txt');
  678. /* update the file */
  679. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  680. {
  681. # update the internal structure
  682. $this->setStructure($draft = true, $cache = false);
  683. }
  684. else
  685. {
  686. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  687. }
  688. # if it is the title, then delete the "# " if it exists
  689. $pageMarkdown[0] = trim($pageMarkdown[0], "# ");
  690. return $response->withJson(array('markdown' => $pageMarkdown, 'errors' => false));
  691. }
  692. public function deleteBlock(Request $request, Response $response, $args)
  693. {
  694. /* get params from call */
  695. $this->params = $request->getParams();
  696. $this->uri = $request->getUri();
  697. $errors = false;
  698. # set structure
  699. if(!$this->setStructure($draft = true)){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  700. # set item
  701. if(!$this->setItem()){ return $response->withJson($this->errors, 404); }
  702. # set the status for published and drafted
  703. $this->setPublishStatus();
  704. # set path
  705. $this->setItemPath($this->item->fileType);
  706. # read content from file
  707. if(!$this->setContent()){ return $response->withJson(array('data' => false, 'errors' => $this->errors), 404); }
  708. # get content
  709. $this->content;
  710. if($this->content == '')
  711. {
  712. $this->content = [];
  713. }
  714. # initialize parsedown extension
  715. $parsedown = new ParsedownExtension();
  716. # if content is not an array, then transform it
  717. if(!is_array($this->content))
  718. {
  719. # turn markdown into an array of markdown-blocks
  720. $this->content = $parsedown->markdownToArrayBlocks($this->content);
  721. }
  722. # check if id exists
  723. if(!isset($this->content[$this->params['block_id']])){ return $response->withJson(array('data' => false, 'errors' => 'The ID of the content-block is wrong.'), 404); }
  724. # check if block is image
  725. $contentBlock = $this->content[$this->params['block_id']];
  726. $contentBlockStart = substr($contentBlock, 0, 2);
  727. if($contentBlockStart == '[!' OR $contentBlockStart == '![')
  728. {
  729. # extract image path
  730. preg_match("/\((.*?)\)/",$contentBlock,$matches);
  731. if(isset($matches[1]))
  732. {
  733. $imageBaseName = explode('-', $matches[1]);
  734. $imageBaseName = str_replace('media/live/', '', $imageBaseName[0]);
  735. $processImage = new ProcessImage();
  736. if(!$processImage->deleteImage($imageBaseName))
  737. {
  738. $errors = 'Could not delete some of the images, please check manually';
  739. }
  740. }
  741. }
  742. # delete the block
  743. unset($this->content[$this->params['block_id']]);
  744. $this->content = array_values($this->content);
  745. $pageMarkdown = $this->content;
  746. # delete markdown from title
  747. if(isset($pageMarkdown[0]))
  748. {
  749. $pageMarkdown[0] = trim($pageMarkdown[0], "# ");
  750. }
  751. # encode the content into json
  752. $pageJson = json_encode($this->content);
  753. # set path for the file (or folder)
  754. $this->setItemPath('txt');
  755. /* update the file */
  756. if($this->write->writeFile($this->settings['contentFolder'], $this->path, $pageJson))
  757. {
  758. # update the internal structure
  759. $this->setStructure($draft = true, $cache = false);
  760. }
  761. else
  762. {
  763. return $response->withJson(['errors' => ['message' => 'Could not write to file. Please check if the file is writable']], 404);
  764. }
  765. return $response->withJson(array('markdown' => $pageMarkdown, 'errors' => $errors));
  766. }
  767. public function createImage(Request $request, Response $response, $args)
  768. {
  769. /* get params from call */
  770. $this->params = $request->getParams();
  771. $this->uri = $request->getUri();
  772. $imageProcessor = new ProcessImage();
  773. if($imageProcessor->createImage($this->params['image'], $this->settings['images']))
  774. {
  775. return $response->withJson(array('errors' => false));
  776. }
  777. return $response->withJson(array('errors' => 'could not store image to temporary folder'));
  778. }
  779. public function publishImage(Request $request, Response $response, $args)
  780. {
  781. $params = $request->getParsedBody();
  782. $imageProcessor = new ProcessImage();
  783. $imageUrl = $imageProcessor->publishImage($this->settings['images'], $name = false);
  784. if($imageUrl)
  785. {
  786. $params['markdown'] = str_replace('imgplchldr', $imageUrl, $params['markdown']);
  787. $request = $request->withParsedBody($params);
  788. return $this->addBlock($request, $response, $args);
  789. }
  790. return $response->withJson(array('errors' => 'could not store image to media folder'));
  791. }
  792. public function saveVideoImage(Request $request, Response $response, $args)
  793. {
  794. /* get params from call */
  795. $this->params = $request->getParams();
  796. $this->uri = $request->getUri();
  797. $class = false;
  798. $imageUrl = $this->params['markdown'];
  799. if(strpos($imageUrl, 'https://www.youtube.com/watch?v=') !== false)
  800. {
  801. $videoID = str_replace('https://www.youtube.com/watch?v=', '', $imageUrl);
  802. $videoID = strpos($videoID, '&') ? substr($videoID, 0, strpos($videoID, '&')) : $videoID;
  803. $class = 'youtube';
  804. }
  805. if(strpos($imageUrl, 'https://youtu.be/') !== false)
  806. {
  807. $videoID = str_replace('https://youtu.be/', '', $imageUrl);
  808. $videoID = strpos($videoID, '?') ? substr($videoID, 0, strpos($videoID, '?')) : $videoID;
  809. $class = 'youtube';
  810. }
  811. if($class == 'youtube')
  812. {
  813. $videoURLmaxres = 'https://i1.ytimg.com/vi/' . $videoID . '/maxresdefault.jpg';
  814. $videoURL0 = 'https://i1.ytimg.com/vi/' . $videoID . '/0.jpg';
  815. }
  816. $ctx = stream_context_create(array(
  817. 'https' => array(
  818. 'timeout' => 1
  819. )
  820. )
  821. );
  822. $imageData = @file_get_contents($videoURLmaxres, 0, $ctx);
  823. if($imageData === false)
  824. {
  825. $imageData = @file_get_contents($videoURL0, 0, $ctx);
  826. if($imageData === false)
  827. {
  828. return $response->withJson(array('errors' => 'could not get the video image'));
  829. }
  830. }
  831. $imageData64 = 'data:image/jpeg;base64,' . base64_encode($imageData);
  832. $desiredSizes = ['live' => ['width' => 560, 'height' => 315]];
  833. $imageProcessor = new ProcessImage();
  834. $tmpImage = $imageProcessor->createImage($imageData64, $desiredSizes);
  835. if(!$tmpImage)
  836. {
  837. return $response->withJson(array('errors' => 'could not create temporary image'));
  838. }
  839. $imageUrl = $imageProcessor->publishImage($desiredSizes, $videoID);
  840. if($imageUrl)
  841. {
  842. $this->params['markdown'] = '![' . $class . '-video](' . $imageUrl . ' "click to load video"){#' . $videoID. ' .' . $class . '}';
  843. $request = $request->withParsedBody($this->params);
  844. return $this->addBlock($request, $response, $args);
  845. }
  846. return $response->withJson(array('errors' => 'could not store the preview image'));
  847. }
  848. }