create_document.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * This file allows creating new html documents with an online WYSIWYG html editor.
  6. *
  7. * @package chamilo.document
  8. */
  9. require_once __DIR__.'/../inc/global.inc.php';
  10. api_protect_course_script();
  11. api_protect_course_group(GroupManager::GROUP_TOOL_DOCUMENTS);
  12. $this_section = SECTION_COURSES;
  13. $groupRights = Session::read('group_member_with_upload_rights');
  14. $htmlHeadXtra[] = '
  15. <script>
  16. $(function() {
  17. $(".scrollbar-light").scrollbar();
  18. expandColumnToogle("#hide_bar_template", {
  19. selector: "#template_col",
  20. width: 3
  21. }, {
  22. selector: "#doc_form",
  23. width: 9
  24. });
  25. CKEDITOR.on("instanceReady", function (e) {
  26. showTemplates();
  27. });
  28. });
  29. $(document).on("change", ".selectpicker", function () {
  30. var dirValue = $(this).val();
  31. $.ajax({
  32. contentType: "application/x-www-form-urlencoded",
  33. data: "dirValue="+dirValue,
  34. url: "'.api_get_path(WEB_AJAX_PATH).'document.ajax.php?a=document_destination",
  35. type: "POST",
  36. success: function(response) {
  37. $("[name=\'dirValue\']").val(response)
  38. }
  39. });
  40. });
  41. function setFocus() {
  42. $("#document_title").focus();
  43. }
  44. $(window).on("load", function () {
  45. setFocus();
  46. });
  47. </script>';
  48. //I'm in the certification module?
  49. $is_certificate_mode = false;
  50. if (isset($_REQUEST['certificate']) && $_REQUEST['certificate'] == 'true') {
  51. $is_certificate_mode = true;
  52. }
  53. $nameTools = get_lang('Create a rich media page / activity');
  54. if ($is_certificate_mode) {
  55. $nameTools = get_lang('Create certificate');
  56. }
  57. /* Constants and variables */
  58. $doc_table = Database::get_course_table(TABLE_DOCUMENT);
  59. $course_id = api_get_course_int_id();
  60. $courseCode = api_get_course_id();
  61. $sessionId = api_get_session_id();
  62. $userId = api_get_user_id();
  63. $_course = api_get_course_info();
  64. $groupId = api_get_group_id();
  65. $document_data = [];
  66. if (isset($_REQUEST['id'])) {
  67. $documentData = DocumentManager::get_document_data_by_id(
  68. $_REQUEST['id'],
  69. $courseCode,
  70. true,
  71. 0
  72. );
  73. }
  74. if (!empty($sessionId) && empty($documentData)) {
  75. $documentData = DocumentManager::get_document_data_by_id(
  76. $_REQUEST['id'],
  77. $courseCode,
  78. true,
  79. $sessionId
  80. );
  81. }
  82. $groupIid = 0;
  83. $group_properties = [];
  84. if (!empty($groupId)) {
  85. $group_properties = GroupManager::get_group_properties($groupId);
  86. $groupIid = $group_properties['iid'];
  87. }
  88. if (empty($documentData)) {
  89. if (api_is_in_group()) {
  90. $document_id = DocumentManager::get_document_id($_course, $group_properties['directory']);
  91. $documentData = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
  92. $dir = $documentData['path'];
  93. $folder_id = $documentData['id'];
  94. } else {
  95. $dir = '/';
  96. $folder_id = 0;
  97. }
  98. } else {
  99. $folder_id = $documentData['id'];
  100. $dir = $documentData['path'];
  101. }
  102. // Please, do not modify this dirname formatting
  103. if (strstr($dir, '..')) {
  104. $dir = '/';
  105. }
  106. if ($dir[0] == '.') {
  107. $dir = substr($dir, 1);
  108. }
  109. if ($dir[0] != '/') {
  110. $dir = '/'.$dir;
  111. }
  112. if ($dir[strlen($dir) - 1] != '/') {
  113. $dir .= '/';
  114. }
  115. if ($is_certificate_mode) {
  116. $document_id = DocumentManager::get_document_id(
  117. api_get_course_info(),
  118. '/certificates'
  119. );
  120. $documentData = DocumentManager::get_document_data_by_id(
  121. $document_id,
  122. api_get_course_id(),
  123. true
  124. );
  125. $folder_id = $documentData['id'];
  126. $dir = '/certificates/';
  127. }
  128. $doc_tree = explode('/', $dir);
  129. $count_dir = count($doc_tree) - 2; // "2" because at the begin and end there are 2 "/"
  130. if (api_is_in_group()) {
  131. $group_properties = GroupManager::get_group_properties(api_get_group_id());
  132. // Level correction for group documents.
  133. if (!empty($group_properties['directory'])) {
  134. $count_dir = $count_dir > 0 ? $count_dir - 1 : 0;
  135. }
  136. }
  137. $relative_url = '';
  138. for ($i = 0; $i < ($count_dir); $i++) {
  139. $relative_url .= '../';
  140. }
  141. if ($relative_url == '') {
  142. $relative_url = '/';
  143. }
  144. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  145. $editorConfig = [
  146. 'ToolbarSet' => ($is_allowed_to_edit ? 'Documents' : 'DocumentsStudent'),
  147. 'Width' => '100%',
  148. 'Height' => '400',
  149. 'cols-size' => [2, 10, 0],
  150. 'FullPage' => true,
  151. 'InDocument' => true,
  152. 'CreateDocumentDir' => $relative_url,
  153. 'CreateDocumentWebDir' => (empty($group_properties['directory']))
  154. ? api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/'
  155. : api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document'.$group_properties['directory'].'/',
  156. 'BaseHref' => api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir,
  157. ];
  158. if ($is_certificate_mode) {
  159. $editorConfig['CreateDocumentDir'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
  160. $editorConfig['CreateDocumentWebDir'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document/';
  161. $editorConfig['BaseHref'] = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir;
  162. }
  163. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
  164. if (!is_dir($filepath)) {
  165. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  166. $dir = '/';
  167. }
  168. if (!$is_certificate_mode) {
  169. if (api_is_in_group()) {
  170. $interbreadcrumb[] = [
  171. "url" => "../group/group_space.php?".api_get_cidreq(),
  172. "name" => get_lang('Group area'),
  173. ];
  174. $path = explode('/', $dir);
  175. if ('/'.$path[1] != $group_properties['directory']) {
  176. api_not_allowed(true);
  177. }
  178. }
  179. $interbreadcrumb[] = [
  180. "url" => "./document.php?curdirpath=".urlencode($dir)."&".api_get_cidreq(),
  181. "name" => get_lang('Documents'),
  182. ];
  183. } else {
  184. $interbreadcrumb[] = [
  185. 'url' => Category::getUrl(),
  186. 'name' => get_lang('Assessments'),
  187. ];
  188. }
  189. if (!api_is_allowed_in_course()) {
  190. api_not_allowed(true);
  191. }
  192. if (!($is_allowed_to_edit ||
  193. $groupRights ||
  194. DocumentManager::is_my_shared_folder($userId, $dir, api_get_session_id()))
  195. ) {
  196. api_not_allowed(true);
  197. }
  198. /* Header */
  199. Event::event_access_tool(TOOL_DOCUMENT);
  200. $display_dir = $dir;
  201. if (isset($group_properties)) {
  202. $display_dir = explode('/', $dir);
  203. unset($display_dir[0]);
  204. unset($display_dir[1]);
  205. $display_dir = implode('/', $display_dir);
  206. }
  207. $select_cat = isset($_GET['selectcat']) ? intval($_GET['selectcat']) : null;
  208. $curDirPath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : null;
  209. // Create a new form
  210. $form = new FormValidator(
  211. 'create_document',
  212. 'post',
  213. api_get_self().'?'.api_get_cidreq().'&dir='.Security::remove_XSS(urlencode($dir)).'&selectcat='.$select_cat,
  214. null
  215. );
  216. // form title
  217. $form->addElement('header', $nameTools);
  218. if ($is_certificate_mode) {//added condition for certicate in gradebook
  219. $form->addElement(
  220. 'hidden',
  221. 'certificate',
  222. 'true',
  223. ['id' => 'certificate']
  224. );
  225. if (isset($_GET['selectcat'])) {
  226. $form->addElement('hidden', 'selectcat', $select_cat);
  227. }
  228. }
  229. // Hidden element with current directory
  230. $form->addElement('hidden', 'id');
  231. $defaults = [];
  232. $defaults['id'] = $folder_id;
  233. // Filename
  234. $form->addElement('hidden', 'title_edited', 'false', 'id="title_edited"');
  235. /**
  236. * Check if a document width the chosen filename already exists.
  237. */
  238. function document_exists($filename)
  239. {
  240. global $dir;
  241. $cleanName = api_replace_dangerous_char($filename);
  242. // No "dangerous" files
  243. $cleanName = disable_dangerous_file($cleanName);
  244. return !DocumentManager::documentExists(
  245. $dir.$cleanName.'.html',
  246. api_get_course_info(),
  247. api_get_session_id(),
  248. api_get_group_id()
  249. );
  250. }
  251. // Add group to the form
  252. if ($is_certificate_mode) {
  253. $form->addText(
  254. 'title',
  255. get_lang('Certificate name'),
  256. true,
  257. ['cols-size' => [2, 10, 0], 'autofocus']
  258. );
  259. } else {
  260. $form->addText(
  261. 'title',
  262. get_lang('Title'),
  263. true,
  264. ['cols-size' => [2, 10, 0], 'autofocus']
  265. );
  266. }
  267. // Show read-only box only in groups
  268. if (!empty($groupId)) {
  269. $group[] = $form->createElement(
  270. 'checkbox',
  271. 'readonly',
  272. '',
  273. get_lang('Read only')
  274. );
  275. }
  276. $form->addRule('title', get_lang('Required field'), 'required');
  277. $form->addRule('title', get_lang('The operation is impossible, a file with this name already exists.'), 'callback', 'document_exists');
  278. $current_session_id = api_get_session_id();
  279. $form->addHtmlEditor(
  280. 'content',
  281. get_lang('Content'),
  282. true,
  283. true,
  284. $editorConfig
  285. );
  286. // Comment-field
  287. $folders = DocumentManager::get_all_document_folders(
  288. $_course,
  289. $groupIid,
  290. $is_allowed_to_edit
  291. );
  292. // If we are not in the certificates creation, display a folder chooser for the
  293. // new document created
  294. if (!$is_certificate_mode &&
  295. !DocumentManager::is_my_shared_folder($userId, $dir, $current_session_id)
  296. ) {
  297. $folders = DocumentManager::get_all_document_folders(
  298. $_course,
  299. $groupIid,
  300. $is_allowed_to_edit
  301. );
  302. $parent_select = $form->addSelect(
  303. 'curdirpath',
  304. get_lang('Destination folder'),
  305. null,
  306. ['cols-size' => [2, 10, 0]]
  307. );
  308. $folder_titles = [];
  309. if (is_array($folders)) {
  310. $escaped_folders = [];
  311. foreach ($folders as $key => &$val) {
  312. // Hide some folders
  313. if ($val == '/HotPotatoes_files' || $val == '/certificates' || basename($val) == 'css') {
  314. continue;
  315. }
  316. // Admin setting for Hide/Show the folders of all users
  317. if (api_get_setting('show_users_folders') == 'false' &&
  318. (strstr($val, '/shared_folder') || strstr($val, 'shared_folder_session_'))
  319. ) {
  320. continue;
  321. }
  322. // Admin setting for Hide/Show Default folders to all users
  323. if (api_get_setting('show_default_folders') == 'false' && ($val == '/images' || $val == '/flash' || $val == '/audio' || $val == '/video' || strstr($val, '/images/gallery') || $val == '/video/flv')) {
  324. continue;
  325. }
  326. // Admin setting for Hide/Show chat history folder
  327. if (api_get_setting('show_chat_folder') == 'false' && $val == '/chat_files') {
  328. continue;
  329. }
  330. $escaped_folders[$key] = Database::escape_string($val);
  331. }
  332. $folder_sql = implode("','", $escaped_folders);
  333. $sql = "SELECT * FROM $doc_table
  334. WHERE
  335. c_id = $course_id AND
  336. filetype = 'folder' AND
  337. path IN ('".$folder_sql."')";
  338. $res = Database::query($sql);
  339. $folder_titles = [];
  340. while ($obj = Database::fetch_object($res)) {
  341. $folder_titles[$obj->path] = $obj->title;
  342. }
  343. }
  344. if (empty($group_dir)) {
  345. $parent_select->addOption(get_lang('Home'), '/');
  346. if (is_array($folders)) {
  347. foreach ($folders as &$folder) {
  348. //Hide some folders
  349. if ($folder == '/HotPotatoes_files' || $folder == '/certificates' || basename($folder) == 'css') {
  350. continue;
  351. }
  352. //Admin setting for Hide/Show the folders of all users
  353. if (api_get_setting('show_users_folders') == 'false' &&
  354. (strstr($folder, '/shared_folder') || strstr($folder, 'shared_folder_session_'))
  355. ) {
  356. continue;
  357. }
  358. //Admin setting for Hide/Show Default folders to all users
  359. if (api_get_setting('show_default_folders') == 'false' &&
  360. (
  361. $folder == '/images' ||
  362. $folder == '/flash' ||
  363. $folder == '/audio' ||
  364. $folder == '/video' ||
  365. strstr($folder, '/images/gallery') ||
  366. $folder == '/video/flv'
  367. )
  368. ) {
  369. continue;
  370. }
  371. //Admin setting for Hide/Show chat history folder
  372. if (api_get_setting('show_chat_folder') == 'false' &&
  373. $folder == '/chat_files'
  374. ) {
  375. continue;
  376. }
  377. $selected = (substr($dir, 0, -1) == $folder) ? ' selected="selected"' : '';
  378. $path_parts = explode('/', $folder);
  379. $folder_titles[$folder] = cut($folder_titles[$folder], 80);
  380. $space_counter = count($path_parts) - 2;
  381. if ($space_counter > 0) {
  382. $label = str_repeat('&nbsp;&nbsp;&nbsp;', $space_counter).' &mdash; '.$folder_titles[$folder];
  383. } else {
  384. $label = ' &mdash; '.$folder_titles[$folder];
  385. }
  386. $parent_select->addOption($label, $folder);
  387. if ($selected != '') {
  388. $parent_select->setSelected($folder);
  389. }
  390. }
  391. }
  392. } else {
  393. if (is_array($folders) && !empty($folders)) {
  394. foreach ($folders as &$folder) {
  395. $selected = (substr($dir, 0, -1) == $folder) ? ' selected="selected"' : '';
  396. $label = $folder_titles[$folder];
  397. if ($folder == $group_dir) {
  398. $label = '/ ('.get_lang('Home').')';
  399. } else {
  400. $path_parts = explode('/', str_replace($group_dir, '', $folder));
  401. $label = cut($label, 80);
  402. $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
  403. }
  404. $parent_select->addOption($label, $folder);
  405. if ($selected != '') {
  406. $parent_select->setSelected($folder);
  407. }
  408. }
  409. }
  410. }
  411. }
  412. $form->addHidden('dirValue', '');
  413. if ($is_certificate_mode) {
  414. $form->addButtonCreate(get_lang('Create certificate'));
  415. } else {
  416. $form->addButtonCreate(get_lang('Create a rich media page / activity'));
  417. }
  418. $form->setDefaults($defaults);
  419. // If form validates -> save the new document
  420. if ($form->validate()) {
  421. $values = $form->exportValues();
  422. $readonly = isset($values['readonly']) ? 1 : 0;
  423. $values['title'] = trim($values['title']);
  424. if (!empty($values['dirValue'])) {
  425. $dir = $values['dirValue'];
  426. }
  427. if ($dir[strlen($dir) - 1] != '/') {
  428. $dir .= '/';
  429. }
  430. $filepath = $filepath.$dir;
  431. // Setting the filename
  432. $filename = $values['title'];
  433. $filename = addslashes(trim($filename));
  434. $filename = Security::remove_XSS($filename);
  435. $filename = api_replace_dangerous_char($filename);
  436. $filename = disable_dangerous_file($filename);
  437. $filename .= DocumentManager::getDocumentSuffix(
  438. $_course,
  439. api_get_session_id(),
  440. api_get_group_id()
  441. );
  442. // Setting the title
  443. $title = $values['title'];
  444. // Setting the extension
  445. $extension = 'html';
  446. $content = Security::remove_XSS($values['content'], COURSEMANAGERLOWSECURITY);
  447. $content = str_replace(
  448. api_get_path(WEB_COURSE_PATH),
  449. api_get_configuration_value('url_append').api_get_path(REL_COURSE_PATH),
  450. $content
  451. );
  452. $save_file_path = $dir.$filename.'.'.$extension;
  453. $document = DocumentManager::addDocument(
  454. $_course,
  455. $save_file_path,
  456. 'file',
  457. '',
  458. $title,
  459. $_POST['comment'] ?? '',
  460. $readonly,
  461. null,
  462. 0,
  463. 0,
  464. 0,
  465. true,
  466. $content
  467. );
  468. if ($document) {
  469. $certificate_condition = '';
  470. if ($is_certificate_mode) {
  471. $df = DocumentManager::get_default_certificate_id($_course['real_id']);
  472. if (!isset($df)) {
  473. DocumentManager::attach_gradebook_certificate($_course['real_id'], $document_id);
  474. }
  475. $certificate_condition = '&certificate=true&curdirpath=/certificates';
  476. }
  477. Display::addFlash(Display::return_message(get_lang('Item added')));
  478. header('Location: document.php?'.api_get_cidreq().'&id='.$folder_id.$certificate_condition);
  479. exit();
  480. } else {
  481. Display::addFlash(Display::return_message(get_lang('Operation impossible'), 'error'));
  482. header('Location: document.php?'.api_get_cidreq().'&id='.$folder_id);
  483. exit();
  484. }
  485. } else {
  486. // Copied from document.php
  487. $dir_array = explode('/', $dir);
  488. $array_len = count($dir_array);
  489. // Breadcrumb for the current directory root path
  490. if (!empty($documentData)) {
  491. if (empty($documentData['parents'])) {
  492. $interbreadcrumb[] = [
  493. 'url' => '#',
  494. 'name' => $documentData['title'],
  495. ];
  496. } else {
  497. foreach ($documentData['parents'] as $document_sub_data) {
  498. $interbreadcrumb[] = [
  499. 'url' => $document_sub_data['document_url'],
  500. 'name' => $document_sub_data['title'],
  501. ];
  502. }
  503. }
  504. }
  505. Display::display_header($nameTools, "Doc");
  506. // actions
  507. // link back to the documents overview
  508. if ($is_certificate_mode) {
  509. $actionsLeft = '<a href="document.php?certificate=true&id='.$folder_id.'&selectcat='.Security::remove_XSS($_GET['selectcat']).'">'.
  510. Display::return_icon('back.png', get_lang('Back').' '.get_lang('To').' '.get_lang('Certificate overview'), '', ICON_SIZE_MEDIUM).'</a>';
  511. $actionsLeft .= '<a id="hide_bar_template" href="#" role="button">'.
  512. Display::return_icon('expand.png', get_lang('Back'), ['id' => 'expand'], ICON_SIZE_MEDIUM).Display::return_icon('contract.png', get_lang('Back'), ['id' => 'contract', 'class' => 'hide'], ICON_SIZE_MEDIUM).'</a>';
  513. } else {
  514. $actionsLeft = '<a href="document.php?curdirpath='.Security::remove_XSS($dir).'">'.
  515. Display::return_icon('back.png', get_lang('Back').' '.get_lang('To').' '.get_lang('Documents overview'), '', ICON_SIZE_MEDIUM).'</a>';
  516. $actionsLeft .= '<a id="hide_bar_template" href="#" role="button">'.
  517. Display::return_icon('expand.png', get_lang('Expand'), ['id' => 'expand'], ICON_SIZE_MEDIUM).
  518. Display::return_icon('contract.png', get_lang('Collapse'), ['id' => 'contract', 'class' => 'hide'], ICON_SIZE_MEDIUM).'</a>';
  519. }
  520. echo $toolbar = Display::toolbarAction('actions-documents', [$actionsLeft]);
  521. if ($is_certificate_mode) {
  522. $all_information_by_create_certificate = DocumentManager::get_all_info_to_certificate(
  523. api_get_user_id(),
  524. api_get_course_id()
  525. );
  526. $str_info = '';
  527. foreach ($all_information_by_create_certificate[0] as $info_value) {
  528. $str_info .= $info_value.'<br/>';
  529. }
  530. $create_certificate = get_lang('Create certificateWithTags');
  531. echo Display::return_message($create_certificate.': <br /><br/>'.$str_info, 'normal', false);
  532. }
  533. // HTML-editor
  534. echo '<div class="page-create row">
  535. <div id="doc_form" class="col-md-9">
  536. '.$form->returnForm().'
  537. </div>
  538. <div id="template_col" class="col-md-3">
  539. <div id="frmModel" class="items-templates scrollbar-light"></div>
  540. </div></div>';
  541. Display::display_footer();
  542. }