create_document.php 20 KB

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