ContentApiController.php 41 KB

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