ContentApiController.php 40 KB

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