ContentApiController.php 40 KB

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