function check_and_create_resource_directory($repository_path, $resource_directory, $resource_directory_name) { global $permissions_for_new_directories; $resource_directory_full_path = substr($repository_path, 0, strlen($repository_path) - 1) . $resource_directory . '/'; if (!is_dir($resource_directory_full_path)) { if (@mkdir($resource_directory_full_path, $permissions_for_new_directories)) { // While we are in a course: Registering the newly created folder in the course's database. if (api_is_in_course()) { global $_course, $_user; global $group_properties, $to_group_id; $group_directory = !empty($group_properties['directory']) ? $group_properties['directory'] : ''; $doc_id = add_document($_course, $group_directory . $resource_directory, 'folder', 0, $resource_directory_name); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], $to_group_id); } return true; } return false; } return true; }
$dirBaseDocuments = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document'; $saveDir = $dirBaseDocuments . $webcamdir; $current_session_id = api_get_session_id(); $groupId = api_get_group_id(); //Avoid duplicates $webcamname_to_save = $webcamname; $title_to_save = str_replace('_', ' ', $webcamname); $webcamname_noex = basename($webcamname, ".jpg"); if (file_exists($saveDir . '/' . $webcamname_noex . '.' . $ext)) { $i = 1; while (file_exists($saveDir . '/' . $webcamname_noex . '_' . $i . '.' . $ext)) { $i++; } $webcamname_to_save = $webcamname_noex . '_' . $i . '.' . $ext; $title_to_save = $webcamname_noex . '_' . $i . '.' . $ext; $title_to_save = str_replace('_', ' ', $title_to_save); } $documentPath = $saveDir . '/' . $webcamname_to_save; //read content //Change to move_uploaded_file() function instead file_get_contents() to adapt the new lib $content = move_uploaded_file($_FILES['webcam']['tmp_name'], $documentPath); if (!$content) { print "PHP ERROR: Failed to read data\n"; exit; } //add document to database $doc_id = add_document($_course, $webcamdir . '/' . $webcamname_to_save, 'file', filesize($documentPath), $title_to_save); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id); /// $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $documentPath; print get_lang('ClipSent');
/** * Returns the form to update or create a document * * @param string Action (add/edit) * @param integer ID of the lp_item (if already exists) * @param mixed Integer if document ID, string if info ('new') * @return string HTML form */ function display_document_form($action = 'add', $id = 0, $extra_info = 'new') { global $charset, $_course; require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'; require_once api_get_path(LIBRARY_PATH) . 'document.lib.php'; $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM); $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $path_parts = pathinfo($extra_info['dir']); $no_display_edit_textarea = false; //If action==edit document //We don't display the document form if it's not an editable document (html or txt file) if ($action == "edit") { if (is_array($extra_info)) { if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") { $no_display_edit_textarea = true; } } } $no_display_add = false; //If action==add an existing document //We don't display the document form if it's not an editable document (html or txt file) if ($action == "add") { if (is_numeric($extra_info)) { $sql_doc = "SELECT path FROM " . $tbl_doc . "WHERE id = " . Database::escape_string($extra_info); $result = Database::query($sql_doc, __FILE__, __LINE__); $path_file = Database::result($result, 0, 0); $path_parts = pathinfo($path_file); if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") { $no_display_add = true; } } } // create css folder $css_name = api_get_setting('stylesheets'); $perm = api_get_setting('permissions_for_new_directories'); $perm = octdec(!empty($perm) ? $perm : '0770'); $css_folder = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/css'; if (!is_dir($css_folder)) { mkdir($css_folder); chmod($css_folder, $perm); $doc_id = add_document($_course, '/css', 'folder', 0, 'css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id']); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id']); } if (!file_exists($css_folder . '/templates.css')) { if (file_exists(api_get_path(SYS_PATH) . 'main/css/' . $css_name . '/templates.css')) { $template_content = str_replace('../../img/', api_get_path(REL_CODE_PATH) . 'img/', file_get_contents(api_get_path(SYS_PATH) . 'main/css/' . $css_name . '/templates.css')); $template_content = str_replace('images/', api_get_path(REL_CODE_PATH) . 'css/' . $css_name . '/images/', $template_content); file_put_contents($css_folder . '/templates.css', $template_content); } } if ($action == 'add' && (isset($_GET['tplid']) && $_GET['tplid'] >= 0)) { $table_sys_template = Database::get_main_table(TABLE_MAIN_SYSTEM_TEMPLATE); $user_id = api_get_user_id(); // Session used by the ajax request when we are using php 5.3 $_SESSION['dbName'] = $_course['dbName']; // setting some paths $img_dir = api_get_path(REL_CODE_PATH) . 'img/'; $default_course_dir = api_get_path(REL_CODE_PATH) . 'default_course_document/'; if (!isset($_GET['resource'])) { // Load a template into a document $query = 'SELECT content, title FROM ' . $table_sys_template . ' WHERE id=' . Database::escape_string(Security::remove_XSS($_GET['tplid'])); $result = Database::query($query, __FILE__, __LINE__); $obj = Database::fetch_object($result); $valcontent = $obj->content; $valtitle = $obj->title != '' ? get_lang($obj->title) : get_lang('Empty'); if (isset($_GET['tplid']) && $_GET['tplid'] == 0) { $valcontent = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body></body>'; } $template_css = ''; if (strpos($valcontent, '/css/templates.css') === false) { $template_css = '<link rel="stylesheet" href="' . api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/document/css/templates.css" type="text/css" />'; } $js = ''; if (strpos($valcontent, 'javascript/jquery.highlight.js') === false) { $js .= '<script type="text/javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/jquery-1.4.2.min.js" language="javascript"></script>'; $js .= '<script type="text/javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'jwplayer/jwplayer.js" language="javascript"></script>' . PHP_EOL; if (api_get_setting('show_glossary_in_documents') != 'none') { $js .= '<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/jquery.highlight.js"></script>'; if (api_get_setting('show_glossary_in_documents') == 'ismanual') { $js .= '<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'fckeditor/editor/plugins/glossary/fck_glossary_manual.js"></script>'; } else { $js .= '<script language="javascript" src="' . api_get_path(WEB_LIBRARY_PATH) . 'fckeditor/editor/plugins/glossary/fck_glossary_automatic.js"></script>'; } } } $valcontent = str_replace('{CSS}', $template_css . $js, $valcontent); if (strpos($valcontent, '/css/templates.css') === false) { $valcontent = str_replace('</head>', $template_css . '</head>', $valcontent); } if (strpos($valcontent, 'javascript/jquery.highlight.js') === false) { $valcontent = str_replace('</head>', $js . '</head>', $valcontent); } $valcontent = str_replace('{IMG_DIR}', $img_dir, $valcontent); $valcontent = str_replace('{REL_PATH}', api_get_path(REL_PATH), $valcontent); $valcontent = str_replace('{COURSE_DIR}', $default_course_dir, $valcontent); } elseif (isset($_GET['resource']) && $_GET['resource'] == 'mindmap' || $_GET['resource'] == 'video') { // Load a mindmap or video into a document $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY); $curdirpath = '/mindmaps/'; if ($_GET['resource'] == 'video') { $curdirpath = '/video/'; $curdirpath_flv = '/video/flv/'; } $my_course = api_get_course_id(); $src_path = api_get_path(WEB_COURSE_PATH) . $my_course . '/document'; $sql = "SELECT path,title FROM {$tbl_doc} doc,{$propTable} prop WHERE doc.id = prop.ref AND prop.tool = '" . TOOL_DOCUMENT . "'\n AND doc.filetype = 'file' AND (doc.path LIKE '" . $curdirpath . "%' OR doc.path LIKE '" . $curdirpath_flv . "%') AND (doc.path NOT LIKE '" . $curdirpath . "%/%' OR doc.path NOT LIKE '" . $curdirpath_flv . "%/%')\n AND prop.visibility = 1 AND doc.id = '" . Database::escape_string(Security::remove_XSS($_GET['tplid'])) . "'"; $rs = Database::query($sql); $row = Database::fetch_array($rs); $resource = $src_path . $row['path']; $valtitle = $row['title']; if ($valtitle != '') { $search = array('.png', '.gif', '.jpg', '.mpg', '.flv', '.swf'); // Add other extensions $replace = array('', '', '', '', '', ''); $valtitle = str_replace($search, $replace, $valtitle); } if ($_GET['resource'] == 'mindmap') { $valcontent = '<table cellspacing="2" cellpadding="10" border="0" style="width: 95%; height: 500px;"> <tbody> <tr> <td valign="top"><img border="0" vspace="0" hspace="0" src="' . $resource . '" alt="' . $title . '" title="' . $title . '"/></td> </tr> </tbody> </table>'; } elseif ($_GET['resource'] == 'video') { $sys_resource = api_get_path(SYS_COURSE_PATH) . $my_course . '/document' . $row['path']; $resource_info = pathinfo($sys_resource); //$video_web_path = api_get_path(WEB_LIBRARY_PATH) . 'fckeditor/editor/plugins/flvPlayer/'; $valcontent = '<table cellspacing="2" cellpadding="10" border="0" style="width: 95%; height: 500px;"> <tbody> <tr> <td valign="top"> <!-- Video player plugin --> <div id="player986311-parent" align="left"> <div style="border-style: none; height: 240px; width: 375px; overflow: hidden; background-color: rgb(220, 220, 220);" id="test"> <div style="display: none; visibility: hidden; width: 0px; height: 0px; overflow: hidden;" id="player986311-config">url=' . $resource . ' width=375 height=240 loop=1 play=true downloadable=false fullscreen=true</div> <div class="thePlayer" id="player986311">'; if (in_array($resource_info['extension'], array('flv', 'mp4', 'mov'))) { /*if (!api_is_windows_os()) { $valcontent .= ' <script src="'.api_get_path(WEB_CODE_PATH).'inc/lib/fckeditor/editor/plugins/videoPlayer/jwplayer.min.js" type="text/javascript"></script> <object id="player986311-parent2" name="player986311-parent2" width="375" height="240" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> <param name="movie" value="'.api_get_path(WEB_CODE_PATH).'inc/lib/fckeditor/editor/plugins/videoPlayer/player.swf" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <param name="seamlesstabbing" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="id=player986311-parent2&autostart=true&repeat=false&file='.$resource.'&skin='.api_get_path(WEB_CODE_PATH).'inc/lib/fckeditor/editor/plugins/videoPlayer/skins/facebook.zip&controlbar.position=over" /> </object> '; } else {*/ $valcontent .= ' <script src="' . api_get_path(WEB_CODE_PATH) . 'inc/lib/fckeditor/editor/plugins/videoPlayer/jwplayer.min.js" type="text/javascript"></script> <div id="player986311-parent2">Loading the player ...</div> <script type="text/javascript">jwplayer("player986311-parent2").setup({flashplayer: "' . api_get_path(WEB_CODE_PATH) . 'inc/lib/fckeditor/editor/plugins/videoPlayer/player.swf",autostart: "true",repeat: "always",file: "' . $resource . '",height: 240,width: 375,skin: "' . api_get_path(WEB_CODE_PATH) . 'inc/lib/fckeditor/editor/plugins/videoPlayer/skins/facebook.zip"});</script>'; //} } else { $sType = ''; if ($resource_info['extension'] == 'mpg' || $resource_info['extension'] == 'mpeg') { $sType = 'video/mpeg'; } else { if ($resource_info['extension'] == 'avi' || $resource_info['extension'] == 'wmv' || $resource_info['extension'] == 'asf') { $sType = 'video/x-msvideo'; } } $valcontent .= '<embed type="' . $sType . '" src="' . $resource . '" autosize = "false" autostart = "true" loop = "false" fullscreen = "true" showcontrols = "true" showpositioncontrols = "false" showtracker = "true" showaudiocontrols = "true" showgotobar = "true" showstatusbar = "true" pluginspace = "http://www.microsoft.com/Windows/MediaPlayer/" codebase = "http://www.microsoft.com/Windows/MediaPlayer/"'; $valcontent .= 'width="375px" height="240px"'; $valcontent .= '></embed>'; } $valcontent .= ' </div> </div> </div> </td> </tr> </tbody> </table>'; } } } if ($id != 0 && is_array($extra_info)) { $item_title = stripslashes($extra_info['title']); $item_description = stripslashes($extra_info['description']); $item_terms = stripslashes($extra_info['terms']); if (empty($item_title)) { $path_parts = pathinfo($extra_info['path']); $item_title = stripslashes($path_parts['filename']); } } elseif (is_numeric($extra_info)) { $sql_doc = "SELECT path, title\n\t\t\t\t\t\t\t\t\tFROM " . $tbl_doc . "\n\t\t\t\t\t\t\t\t\tWHERE id = " . Database::escape_string($extra_info); $result = Database::query($sql_doc, __FILE__, __LINE__); $row = Database::fetch_array($result); $explode = explode('.', $row['title']); if (count($explode) > 1) { for ($i = 0; $i < count($explode) - 1; $i++) { $item_title .= $explode[$i]; } } else { $item_title = $row['title']; } $item_title = str_replace('_', ' ', $item_title); if (empty($item_title)) { $path_parts = pathinfo($row['path']); $item_title = stripslashes($path_parts['filename']); } } else { $item_title = ''; $item_description = ''; } /* $return = ' <div class="row"> <div class="form_header">'; */ if ($id != 0 && is_array($extra_info)) { $parent = $extra_info['parent_item_id']; } else { $parent = 0; } $sql = "\n\t\t\t\t\t\tSELECT *\n\t\t\t\t\t\tFROM " . $tbl_lp_item . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tlp_id = " . $this->lp_id; $result = Database::query($sql, __FILE__, __LINE__); $arrLP = array(); while ($row = Database::fetch_array($result)) { $arrLP[] = array('id' => $row['id'], 'item_type' => $row['item_type'], 'title' => $row['title'], 'path' => $row['path'], 'description' => $row['description'], 'parent_item_id' => $row['parent_item_id'], 'previous_item_id' => $row['previous_item_id'], 'next_item_id' => $row['next_item_id'], 'display_order' => $row['display_order'], 'max_score' => $row['max_score'], 'min_score' => $row['min_score'], 'mastery_score' => $row['mastery_score'], 'prerequisite' => $row['prerequisite']); } $this->tree_array($arrLP); $arrLP = $this->arrMenu; unset($this->arrMenu); if (isset($_GET['edit']) && $_GET['edit'] == 'true') { $return .= Display::return_warning_message('<strong>' . get_lang("Warning") . ' !</strong><br />' . get_lang("WarningEditingDocument"), false); } require_once api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php'; $form = new FormValidator('form', 'POST', api_get_self() . "?" . $_SERVER["QUERY_STRING"], '', 'enctype="multipart/form-data"'); $defaults["title"] = Security::remove_XSS(api_convert_encoding($item_title, api_get_system_encoding(), $this->encoding)); if (empty($item_title)) { $defaults["title"] = Security::remove_XSS($item_title); } $defaults["description"] = api_convert_encoding($item_description, $charset, $this->encoding); $form->addElement('html', $return); if ($action != 'move') { $form->addElement('html', '<div style="float:left;padding-right:135px;">'); $form->addElement('text', 'title', get_lang('Title'), 'id="idTitle" class="learnpath_item_form" size=44%'); $form->applyFilter('title', 'html_filter'); $form->addElement('html', '</div>'); } //$arrHide = array($id); $arrHide[0]['value'] = $this->name; $arrHide[0]['padding'] = 3; for ($i = 0; $i < count($arrLP); $i++) { if ($action != 'add') { if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) { $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title']; $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10; if ($parent == $arrLP[$i]['id']) { $s_selected_parent = $arrHide[$arrLP[$i]['id']]; } } } else { if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') { $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title']; $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10; if ($parent == $arrLP[$i]['id']) { $s_selected_parent = $arrHide[$arrLP[$i]['id']]; } } } } //$parent_select = & $form->addElement('select', 'parent', get_lang('Parent'), '', 'class="learnpath_item_form" style="width:40%;" onchange="load_cbo(this.value);"'); $parent_select =& $form->addElement('select', 'parent', '', '', 'class="learnpath_item_form" style="width:40%;display:none;float:left" onchange="load_cbo(this.value);"'); $my_count = 0; foreach ($arrHide as $key => $value) { if ($my_count != 0) { // the LP name is also the first section and is not in the same charset like the other sections $value['value'] = Security::remove_XSS(api_convert_encoding($value['value'], api_get_system_encoding(), $this->encoding)); $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"'); } else { $value['value'] = Security::remove_XSS($value['value']); $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"'); } $my_count++; } if (!empty($id)) { $parent_select->setSelected($parent); } else { $parent_item_id = $_SESSION['parent_item_id']; $parent_select->setSelected($parent_item_id); } if (is_array($arrLP)) { reset($arrLP); } $arrHide = array(); //POSITION for ($i = 0; $i < count($arrLP); $i++) { if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) { if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) { $s_selected_position = $arrLP[$i]['id']; } elseif ($action == 'add') { $s_selected_position = $arrLP[$i]['id']; } $arrHide[$arrLP[$i]['id']]['value'] = get_lang("After") . ' "' . api_convert_encoding($arrLP[$i]['title'], $charset, $this->encoding) . '"'; } } //$position = & $form->addElement('select', 'previous', get_lang('Position'), '', 'id="idPosition" class="learnpath_item_form" style="width:40%;"'); $position =& $form->addElement('select', 'previous', '', '', 'id="idPosition" class="learnpath_item_form" style="width:40%;float:left;display:none;"'); $position->addOption(get_lang("FirstPosition"), 0); foreach ($arrHide as $key => $value) { $position->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"'); } $position->setSelected($s_selected_position); if (is_array($arrLP)) { reset($arrLP); } if ($action != 'move') { $id_prerequisite = 0; if (is_array($arrLP)) { foreach ($arrLP as $key => $value) { if ($value['id'] == $id) { $id_prerequisite = $value['prerequisite']; break; } } } //comented the prerequisites, only visible in edit (new document) //$select_prerequisites=$form->addElement('select', 'prerequisites', get_lang('Prerequisites'),null,'id="prerequisites" class="learnpath_item_form" style="width:263px;"'); //$select_prerequisites->addOption(get_lang("NoPrerequisites"),0); // form element for uploading an mp3 file //$form->addElement('file','mp3',get_lang('UploadMp3audio'),'id="mp3" size="33"'); //$form->addRule('file', 'The extension of the Song file should be *.mp3', 'filename', '/^.*\.mp3$/'); /* Code deprecated - moved to lp level (not lp-item) if ( api_get_setting('search_enabled') === 'true' ) { //add terms field $terms = $form->addElement('text','terms', get_lang('SearchFeatureTerms').' :','id="idTerms" class="learnpath_item_form"'); $terms->setValue($item_terms); } */ $arrHide = array(); for ($i = 0; $i < count($arrLP); $i++) { if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') { if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) { $s_selected_position = $arrLP[$i]['id']; } elseif ($action == 'add') { $s_selected_position = $arrLP[$i]['id']; } $arrHide[$arrLP[$i]['id']]['value'] = api_convert_encoding($arrLP[$i]['title'], $charset, $this->encoding); } } /* foreach($arrHide as $key => $value){ $select_prerequisites->addOption($value['value'],$key,'style="padding-left:'.$value['padding'].'px;"'); if($key==$s_selected_position && $action == 'add'){ $select_prerequisites -> setSelected(0); } elseif($key==$id_prerequisite && $action == 'edit'){ $select_prerequisites -> setSelected($id_prerequisite); } } */ if (!$no_display_add) { if ($extra_info == 'new' || $extra_info['item_type'] == TOOL_DOCUMENT || $_GET['edit'] == 'true') { if (isset($_POST['content'])) { $content = stripslashes($_POST['content']); } elseif (is_array($extra_info)) { //If it's an html document or a text file if (!$no_display_edit_textarea) { $content = $this->display_document($extra_info['path'], false, false); } } elseif (is_numeric($extra_info)) { $content = $this->display_document($extra_info, false, false); } else { $content = ''; } if (!$no_display_edit_textarea) { // We need to claculate here some specific settings for the online editor. // The calculated settings work for documents in the Documents tool // (on the root or in subfolders). // For documents in native scorm packages it is unclear whether the // online editor should be activated or not. $relative_path = $extra_info['dir']; if ($relative_path == 'n/') { // A new document, it is in the root of the repository. $relative_path = ''; $relative_prefix = ''; } else { // The document already exists. Whe have to determine its relative path towards the repository root. $relative_path = explode('/', $relative_path); $cnt = count($relative_path) - 2; if ($cnt < 0) { $cnt = 0; } $relative_prefix = str_repeat('../', $cnt); $relative_path = array_slice($relative_path, 1, $cnt); $relative_path = implode('/', $relative_path); if (strlen($relative_path) > 0) { $relative_path = $relative_path . '/'; } } $editor_config = array('ToolbarSet' => api_is_allowed_to_edit() ? 'Documents' : 'DocumentsStudent', 'Width' => '100%', 'Height' => '700', 'FullPage' => true, 'CreateDocumentDir' => $relative_prefix, 'CreateDocumentWebDir' => api_get_path('WEB_COURSE_PATH') . api_get_course_path() . '/document/', 'BaseHref' => api_get_path('WEB_COURSE_PATH') . api_get_course_path() . '/document/' . $relative_path); if ($_GET['action'] == 'add_item') { $class = 'save'; $text = get_lang('Validate'); } else { if ($_GET['action'] == 'edit_item') { $class = 'save'; $text = get_lang('SaveDocument'); } } $form->addElement('html', '<div style="float:right;margin-top:-55px">'); $form->addElement('style_submit_button', 'submit_button', $text, 'class="' . $class . '"'); $form->addElement('html', '</div>'); $renderer = $form->defaultRenderer(); $renderer->setElementTemplate('{label}{element}', 'content_lp'); //$form->addElement('html', '<div'); $form->addElement('html_editor', 'content_lp', '', null, $editor_config); //$form->addElement('html', '</div>'); $defaults["content_lp"] = $content; } } elseif (is_numeric($extra_info)) { $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'class="save"'); $return = $this->display_document($extra_info, true, true, true); $form->addElement('html', $return); } } } // Add template to content if ($action == 'add' && (isset($_GET['tplid']) && $_GET['tplid'] >= 0)) { $defaults["content_lp"] = $valcontent; $defaults["title"] = $valtitle; } if ($action == 'move') { $form->addElement('hidden', 'title', $item_title); $form->addElement('hidden', 'description', $item_description); } if (is_numeric($extra_info)) { $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'value="submit_button", class="save" style="float:right"'); $form->addElement('hidden', 'path', $extra_info); } elseif (is_array($extra_info)) { $form->addElement('html', '<div style="float:right;margin-top:-55px">'); $form->addElement('style_submit_button', 'submit_button', get_lang('SaveDocument'), 'class="save"'); $form->addElement('hidden', 'path', $extra_info['path']); $form->addElement('html', '</div>'); } $form->addElement('hidden', 'type', TOOL_DOCUMENT); $form->addElement('hidden', 'post_time', time()); $form->setDefaults($defaults); return $form->return_form(); }
/** * Manages page splitting * @param string Page header * @param string Page body * @return void */ function dealPerPage($header, $body) { $_course = api_get_course_info(); // Split document to pages. $pages = explode('||page_break||', $body); $first_item = 0; foreach ($pages as $key => $page_content) { // For every pages, we create a new file. $key += 1; $page_content = $this->format_page_content($header, $page_content, $this->base_work_dir . $this->created_dir); $html_file = $this->created_dir . '-' . $key . '.html'; $handle = fopen($this->base_work_dir . $this->created_dir . '/' . $html_file, 'w+'); fwrite($handle, $page_content); fclose($handle); $document_id = add_document($_course, $this->created_dir . $html_file, 'file', filesize($this->base_work_dir . $this->created_dir . $html_file), $html_file); $slide_name = ''; if ($document_id) { // Put the document in item_property update. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_SESSION['_uid'], 0, 0, null, null, api_get_session_id()); $infos = pathinfo($this->filepath); $slide_name = 'Page ' . str_repeat('0', 2 - strlen($key)) . $key; $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, ''); if ($this->first_item == 0) { $this->first_item = $previous; } // Code for text indexing. if (isset($_POST['index_document']) && $_POST['index_document']) { //Display::display_normal_message(print_r($_POST)); $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(NULL, NULL, $lang); $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $slide_name); $specific_fields = get_specific_field_list(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); $all_specific_terms .= ' ' . $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); } } } } $page_content = $all_specific_terms . ' ' . $page_content; $ic_slide->addValue('content', $page_content); // Add a comment to say terms separated by commas. $courseid = api_get_course_id(); $ic_slide->addCourseId($courseid); $ic_slide->addToolId(TOOL_LEARNPATH); $lp_id = $this->lp_id; $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { // Save it to db. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF); $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did) VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)'; $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did); Database::query($sql); } } } } }
/** * Import PDFs * @param string Filename * @param string The subdirectory in which to put the files in each course */ function import_pdfs($file, $subDir = '/') { $baseDir = api_get_path(SYS_ARCHIVE_PATH); $uploadPath = 'pdfimport/'; $errors = array(); if (!is_dir($baseDir . $uploadPath)) { @mkdir($baseDir . $uploadPath); } if (!unzip_uploaded_file($_FILES['import_file'], $uploadPath, $baseDir, 1024 * 1024 * 1024)) { error_log('Could not unzip uploaded file in ' . __FILE__ . ', line ' . __LINE__); return $errors; } $list = scandir($baseDir . $uploadPath); $i = 0; foreach ($list as $file) { if (substr($file, 0, 1) == '.' or !is_file($baseDir . $uploadPath . $file)) { continue; } $parts = preg_split('/_/', $file); $course = api_get_course_info($parts[0]); if (count($course) > 0) { // Build file info because handle_uploaded_document() needs it (name, type, size, tmp_name) $fileSize = filesize($baseDir . $uploadPath . $file); $docId = add_document($course, $subDir . '/' . $file, 'file', $fileSize, $parts[1] . ' ' . substr($parts[2], 0, -4)); if ($docId > 0) { if (!is_file($baseDir . $uploadPath . $file)) { error_log($baseDir . $uploadPath . $file . ' does not exists in ' . __FILE__); } if (is_file(api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . '/' . $file)) { error_log(api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . '/' . $file . ' exists at destination in ' . __FILE__); } if (!is_writeable(api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir)) { error_log('Destination ' . api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . ' is NOT writeable in ' . __FILE__); } // Place each file in its folder in each course $move = rename($baseDir . $uploadPath . $file, api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document' . $subDir . '/' . $file); api_item_property_update($course, TOOL_DOCUMENT, $docId, 'DocumentAdded', api_get_user_id()); // Redo visibility api_set_default_visibility($docId, TOOL_DOCUMENT); $errors[] = array('Line' => 0, 'Code' => $course['code'], 'Title' => $course['title']); // Now add a link to the file from the Course description tool $link = '<p>Sílabo de la asignatura <a href="' . api_get_path(WEB_CODE_PATH) . 'document/document.php?cidReq=' . $course['code'] . '&id_session=0&gidReq=0&action=download&id=' . $docId . '" target="_blank"><img src="' . api_get_path(WEB_IMG_PATH) . 'icons/32/pdf.png"></a></p>'; $course_description = new CourseDescription(); $session_id = api_get_session_id(); $course_description->set_course_id($course['real_id']); $course_description->set_session_id($session_id); $course_description->set_title('Presentación de la asignatura'); $course_description->set_content($link); $course_description->set_description_type(1); $course_description->insert(); } } else { error_log($parts[0] . ' is not a course, apparently'); $errors[] = array('Line' => 0, 'Code' => $parts[0], 'Title' => $parts[0] . ' - ' . get_lang('CodeDoesNotExists')); } $i++; //found at least one entry that is not a dir or a . } if ($i == 0) { $errors[] = array('Line' => 0, 'Code' => '.', 'Title' => get_lang('NoPDFFoundAtRoot')); } return $errors; }
/** * changes the exercise sound file * * @author Olivier Brouckaert * @param string $sound - exercise sound file * @param string $delete - ask to delete the file */ public function updateSound($sound, $delete) { global $audioPath, $documentPath; $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT); if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) { $this->sound = $sound['name']; if (@move_uploaded_file($sound['tmp_name'], $audioPath . '/' . $this->sound)) { $query = "SELECT 1 FROM {$TBL_DOCUMENT}\n WHERE c_id = " . $this->course_id . " AND path='" . str_replace($documentPath, '', $audioPath) . '/' . $this->sound . "'"; $result = Database::query($query); if (!Database::num_rows($result)) { $id = add_document($this->course, str_replace($documentPath, '', $audioPath) . '/' . $this->sound, 'file', $sound['size'], $sound['name']); api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded', api_get_user_id()); item_property_update_on_folder($this->course, str_replace($documentPath, '', $audioPath), api_get_user_id()); } } } elseif ($delete && is_file($audioPath . '/' . $this->sound)) { $this->sound = ''; } }
$filepath = Security::remove_XSS(urldecode($_GET['filepath'])); $dir = Security::remove_XSS(urldecode($_GET['dir'])); $course_code = Security::remove_XSS(urldecode($_GET['course_code'])); $_course = api_get_course_info($course_code); $filename = trim($_GET['filename']); $filename = Security::remove_XSS($filename); $filename = Database::escape_string($filename); $filename = api_replace_dangerous_char($filename); $filename = disable_dangerous_file($filename); $title = trim(str_replace('_chnano_.', '.', $filename)); //hide nanogong wav tag at title $title = str_replace('_', ' ', $title); $documentPath = $filepath . $filename; if ($nano_user_id != api_get_user_id() || api_get_user_id() == 0 || $nano_user_id == 0) { echo 'Not allowed'; exit; } // Do not use here check Fileinfo method because return: text/plain if (!file_exists($documentPath)) { //add document to disk move_uploaded_file($_FILES['voicefile']['tmp_name'], $documentPath); //add document to database $current_session_id = $nano_session_id; $groupId = $nano_group_id; $file_size = filesize($documentPath); $relativeUrlPath = $dir; $doc_id = add_document($_course, $relativeUrlPath . $filename, 'file', filesize($documentPath), $title); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $nano_user_id, $groupId, null, null, null, $current_session_id); } else { return get_lang('FileExistRename'); }
function CreateServerFolder($folderPath, $lastFolder = null) { global $Config; $sParent = GetParentFolder($folderPath); // Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms while (strpos($folderPath, '//') !== false) { $folderPath = str_replace('//', '/', $folderPath); } // Check if the parent exists, or create it. if (!empty($sParent) && !file_exists($sParent)) { //prevents agains infinite loop when we can't create root folder if (!is_null($lastFolder) && $lastFolder === $sParent) { return "Can't create {$folderPath} directory"; } $sErrorMsg = CreateServerFolder($sParent, $folderPath); if ($sErrorMsg != '') { return $sErrorMsg; } } if (!file_exists($folderPath)) { // Turn off all error reporting. error_reporting(0); $php_errormsg = ''; // Enable error tracking to catch the error. ini_set('track_errors', '1'); if (isset($Config['ChmodOnFolderCreate']) && !$Config['ChmodOnFolderCreate']) { mkdir($folderPath); } else { $permissions = 0777; // $permissions = 0770 ; if (isset($Config['ChmodOnFolderCreate'])) { $permissions = $Config['ChmodOnFolderCreate']; } // To create the folder with 0777 permissions, we need to set umask to zero. //$oldumask = umask(0) ; mkdir($folderPath, $permissions); //umask( $oldumask ) ; } // While we are in a course: Registering the newly created folder in the course's database. if (api_is_in_course()) { global $_course, $_user; $repository_path = api_get_path(REL_COURSE_PATH) . api_get_course_path() . '/document/'; $to_group_id = 0; if (api_is_in_group()) { global $group_properties; $to_group_id = $group_properties['id']; } $folder_path = preg_replace("/^.*" . TOOL_DOCUMENT . "/", "", $folderPath); // $folder_path = preg_replace("/\\/\$/", "", $folder_path); // should be done in 1 regexp I guess ... // $folder_path = substr($folderPath, strpos($folderPath, $repository_path) + strlen($repository_path) - 1); $folder_name = explode('/', $folder_path); $folder_name = $folder_name[count($folder_name) - 1]; $doc_id = add_document($_course, $folder_path, 'folder', 0, $folder_name); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], $to_group_id); } $sErrorMsg = $php_errormsg; // Restore the configurations. ini_restore('track_errors'); ini_restore('error_reporting'); return $sErrorMsg; } else { return ''; } }
/** * Manages page splitting * @param string Page header * @param string Page body * @return void */ function dealPerPage($header, $body) { $em = Database::getManager(); $_course = api_get_course_info(); // Split document to pages. $pages = explode('||page_break||', $body); $first_item = 0; foreach ($pages as $key => $page_content) { // For every pages, we create a new file. $key += 1; $page_content = $this->format_page_content($header, $page_content, $this->base_work_dir . $this->created_dir); $html_file = $this->created_dir . '-' . $key . '.html'; $handle = fopen($this->base_work_dir . $this->created_dir . '/' . $html_file, 'w+'); fwrite($handle, $page_content); fclose($handle); $document_id = add_document($_course, $this->created_dir . $html_file, 'file', filesize($this->base_work_dir . $this->created_dir . $html_file), $html_file); $slide_name = ''; if ($document_id) { // Put the document in item_property update. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id()); $infos = pathinfo($this->filepath); $slide_name = 'Page ' . str_repeat('0', 2 - strlen($key)) . $key; $previous = learnpath::add_item(0, $previous, 'document', $document_id, $slide_name, ''); if ($this->first_item == 0) { $this->first_item = $previous; } // Code for text indexing. if (api_get_setting('search.search_enabled') == 'true') { if (isset($_POST['index_document']) && $_POST['index_document']) { //Display::display_normal_message(print_r($_POST)); $di = new ChamiloIndexer(); isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english'); $di->connectDb(NULL, NULL, $lang); $ic_slide = new IndexableChunk(); $ic_slide->addValue('title', $slide_name); $specific_fields = get_specific_field_list(); $all_specific_terms = ''; foreach ($specific_fields as $specific_field) { if (isset($_REQUEST[$specific_field['code']])) { $sterms = trim($_REQUEST[$specific_field['code']]); $all_specific_terms .= ' ' . $sterms; if (!empty($sterms)) { $sterms = explode(',', $sterms); foreach ($sterms as $sterm) { $ic_slide->addTerm(trim($sterm), $specific_field['code']); } } } } $page_content = $all_specific_terms . ' ' . $page_content; $ic_slide->addValue('content', $page_content); // Add a comment to say terms separated by commas. $courseid = api_get_course_id(); $ic_slide->addCourseId($courseid); $ic_slide->addToolId(TOOL_LEARNPATH); $lp_id = $this->lp_id; $xapian_data = array(SE_COURSE_ID => $courseid, SE_TOOL_ID => TOOL_LEARNPATH, SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id), SE_USER => (int) api_get_user_id()); $ic_slide->xapian_data = serialize($xapian_data); $di->addChunk($ic_slide); // Index and return search engine document id. $did = $di->index(); if ($did) { $course = $em->find('ChamiloCoreBundle:Course', api_get_course_int_id()); // Save it to db. $searchEngineRef = new \Chamilo\CoreBundle\Entity\SearchEngineRef(); $searchEngineRef->setCourse($course)->setToolId(TOOL_LEARNPATH)->setRefIdHighLevel($lp_id)->setRefIdSecondLevel($previous)->setSearchDid($did); $em->persist($searchEngineRef); $em->flush(); } } } } } }
/** * {@inheritdoc} */ public function upload($fp, $dst, $name, $tmpname) { $this->setConnectorFromPlugin(); $sessionId = api_get_session_id(); if ($this->allow()) { // upload file by elfinder. $result = parent::upload($fp, $dst, $name, $tmpname); $name = $result['name']; $filtered = \URLify::filter($result['name'], 80, '', true); if (strcmp($name, $filtered) != 0) { $result = $this->customRename($result['hash'], $filtered); } $realPath = $this->realpath($result['hash']); if (!empty($realPath)) { // Getting file info //$info = $elFinder->exec('file', array('target' => $file['hash'])); /** @var elFinderVolumeLocalFileSystem $volume */ //$volume = $info['volume']; //$root = $volume->root(); //var/www/chamilogits/data/courses/NEWONE/document $realPathRoot = $this->getCourseDocumentSysPath(); // Removing course path $realPath = str_replace($realPathRoot, '/', $realPath); $documentId = add_document($this->connector->course, $realPath, 'file', intval($result['size']), $result['name']); api_item_property_update($this->connector->course, TOOL_DOCUMENT, $documentId, 'DocumentAdded', api_get_user_id(), null, null, null, null, $sessionId); } //error_log(print_r($this->error(),1)); return $result; } return false; }
function FileUpload($resourceType, $currentFolder, $sCommand) { if (!isset($_FILES)) { global $_FILES; } $sErrorNumber = '0'; $sFileName = ''; if (isset($_FILES['NewFile']) && !is_null($_FILES['NewFile']['tmp_name'])) { global $Config; $oFile = $_FILES['NewFile']; // Map the virtual path to the local server path. $sServerDir = ServerMapFolder($resourceType, $currentFolder, $sCommand); // Get the uploaded file name. $sFileName = $oFile['name']; $sFileName = SanitizeFileName($sFileName, $oFile['type']); $sOriginalFileName = $sFileName; // Get the extension. $sExtension = substr($sFileName, strrpos($sFileName, '.') + 1); $sExtension = strtolower($sExtension); if (isset($Config['SecureImageUploads'])) { if (($isImageValid = IsImageValid($oFile['tmp_name'], $sExtension)) === false) { $sErrorNumber = '202'; } } if (isset($Config['HtmlExtensions'])) { if (!IsHtmlExtension($sExtension, $Config['HtmlExtensions']) && ($detectHtml = DetectHtml($oFile['tmp_name'])) === true) { $sErrorNumber = '202'; } } // Check if it is an allowed extension. if (!$sErrorNumber && IsAllowedExt($sExtension, $resourceType)) { $iCounter = 0; while (true) { $sFilePath = $sServerDir . $sFileName; if (is_file($sFilePath)) { $iCounter++; $sFileName = RemoveExtension($sOriginalFileName) . '(' . $iCounter . ').' . $sExtension; $sErrorNumber = '0'; // Change $sErrorNumber '201' to '0' to allow create record files renamed } else { move_uploaded_file($oFile['tmp_name'], $sFilePath); if (is_file($sFilePath)) { if (isset($Config['ChmodOnUpload']) && !$Config['ChmodOnUpload']) { break; } $permissions = 0777; if (isset($Config['ChmodOnUpload']) && $Config['ChmodOnUpload']) { $permissions = $Config['ChmodOnUpload']; } //$oldumask = umask(0) ; chmod($sFilePath, $permissions); //umask( $oldumask ) ; } break; } } if (file_exists($sFilePath)) { //previous checks failed, try once again if (isset($isImageValid) && $isImageValid === -1 && IsImageValid($sFilePath, $sExtension) === false) { @unlink($sFilePath); $sErrorNumber = '202'; } else { if (isset($detectHtml) && $detectHtml === -1 && DetectHtml($sFilePath) === true) { @unlink($sFilePath); $sErrorNumber = '202'; } } } } else { $sErrorNumber = '202'; } } else { $sErrorNumber = '202'; } if ($sErrorNumber == '0') { // While we are in a course: Registering the newly uploaded file in the course's database. if (api_is_in_course()) { global $_course, $_user; $repository_path = api_get_path(REL_COURSE_PATH) . api_get_course_path() . '/document/'; $to_group_id = 0; if (api_is_in_group()) { global $group_properties; $to_group_id = $group_properties['id']; } if (file_exists($sFilePath)) { $file_path = substr($sFilePath, strpos($sFilePath, $repository_path) + strlen($repository_path) - 1); $path = explode('/', $file_path); $file_name = $path[count($path) - 1]; $path[count($path) - 1] = ''; $folder_path = '/' + implode('/', $path); $file_size = @filesize($sFilePath); $doc_id = add_document($_course, $file_path, 'file', $file_size, $file_name); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $to_group_id); item_property_update_on_folder($_course, $folder_path, $_user['user_id']); } } } $sFileUrl = CombinePaths(GetResourceTypePath($resourceType, $sCommand), $currentFolder); $sFileUrl = CombinePaths($sFileUrl, $sFileName); SendUploadResults($sErrorNumber, $sFileUrl, $sFileName); exit; }
/** * Create a new document //still needs some finetuning * @param array $_course * @return string */ public function create_document($_course) { $course_id = api_get_course_int_id(); global $charset; $dir = isset($_GET['dir']) ? $_GET['dir'] : $_POST['dir']; // Please, do not modify this dirname formatting. if (strstr($dir, '..')) { $dir = '/'; } if ($dir[0] == '.') { $dir = substr($dir, 1); } if ($dir[0] != '/') { $dir = '/' . $dir; } if ($dir[strlen($dir) - 1] != '/') { $dir .= '/'; } $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $dir; if (empty($_POST['dir']) && empty($_GET['dir'])) { //Generates folder $result = $this->generate_lp_folder($_course); $dir = $result['dir']; $filepath = $result['filepath']; } if (!is_dir($filepath)) { $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/'; $dir = '/'; } // stripslashes() before calling api_replace_dangerous_char() because $_POST['title'] // is already escaped twice when it gets here. $title = api_replace_dangerous_char(stripslashes($_POST['title'])); $title = disable_dangerous_file($title); $filename = $title; $content = $_POST['content_lp']; $tmp_filename = $filename; $i = 0; while (file_exists($filepath . $tmp_filename . '.html')) { $tmp_filename = $filename . '_' . ++$i; } $filename = $tmp_filename . '.html'; $content = stripslashes($content); $content = str_replace(api_get_path(WEB_COURSE_PATH), api_get_path(REL_PATH) . 'courses/', $content); // Change the path of mp3 to absolute. // The first regexp deals with :// urls. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "\$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/', $content); // The second regexp deals with audio/ urls. $content = preg_replace("|(flashvars=\"file=)([^/]+)/|", "\$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/$2/', $content); // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please). $content = str_replace('</body>', '<style type="text/css">body{}</style></body>', $content); if (!file_exists($filepath . $filename)) { if ($fp = @fopen($filepath . $filename, 'w')) { fputs($fp, $content); fclose($fp); $file_size = filesize($filepath . $filename); $save_file_path = $dir . $filename; $document_id = add_document($_course, $save_file_path, 'file', $file_size, $tmp_filename); if ($document_id) { api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), null, null, null, null, api_get_session_id()); $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : ''; $new_title = isset($_POST['title']) ? trim($_POST['title']) : ''; if ($new_comment || $new_title) { $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $ct = ''; if ($new_comment) { $ct .= ", comment='" . Database::escape_string($new_comment) . "'"; } if ($new_title) { $ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset)) . "' "; } $sql_update = "UPDATE " . $tbl_doc . " SET " . substr($ct, 1) . " WHERE c_id = " . $course_id . " AND id = " . $document_id; Database::query($sql_update); } } return $document_id; } } }
} //if the size is not defined, it's probably because there has been an error or no file was submitted if (!$_FILES['userFile']['size']) { $dialogBox .= get_lang('SendFileError') . '<br />' . get_lang('Notice') . ' : ' . get_lang('MaxFileSize') . ' ' . ini_get('upload_max_filesize'); } else { $unzip = 0; if (preg_match('/\\.zip$/i', $_FILES['userFile']['name'])) { //if it's a zip, allow zip upload $unzip = 1; } if ($finish == 0) { // Generate new test folder if on first step of file upload. $filename = api_replace_dangerous_char(trim($_FILES['userFile']['name'])); $fld = GenerateHpFolder($document_sys_path . $uploadPath . '/'); @mkdir($document_sys_path . $uploadPath . '/' . $fld, api_get_permissions_for_new_directories()); $doc_id = add_document($_course, '/HotPotatoes_files/' . $fld, 'folder', 0, $fld); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id()); } else { // It is not the first step... get the filename directly from the system params. $filename = $_FILES['userFile']['name']; } $allow_output_on_success = false; if (handle_uploaded_document($_course, $_FILES['userFile'], $document_sys_path, $uploadPath . '/' . $fld, api_get_user_id(), null, null, $unzip, '', $allow_output_on_success)) { if ($finish == 2) { $imgparams = $_POST['imgparams']; $checked = CheckImageName($imgparams, $filename); if ($checked) { $imgcount = $imgcount - 1; } else { $dialogBox .= $filename . ' ' . get_lang('NameNotEqual'); my_delete($document_sys_path . $uploadPath . '/' . $fld . '/' . $filename);
/** * Process upload files. The file must be an * uploaded file. If 'validate_images' is set to * true, only images will be processed. Any duplicate * file will be renamed. See Files::copyFile for details * on renaming. * @param string $relative the relative path where the file * should be copied to. * @param array $file the uploaded file from $_FILES * @return boolean true if the file was processed successfully, * false otherwise */ function _processFiles($relative, $file) { global $_course; if ($file['error'] != 0) { return false; } if (!is_file($file['tmp_name'])) { return false; } if (!is_uploaded_file($file['tmp_name'])) { Files::delFile($file['tmp_name']); return false; } $file['name'] = replace_dangerous_char($file['name'], 'strict'); $file_name = $file['name']; $extension = explode('.', $file_name); $count = count($extension); if ($count == 1) { $extension = ''; } else { $extension = strtolower($extension[$count - 1]); } // Checking for image by file extension first, using the configuration file. if (!in_array($extension, $this->config['accepted_extensions'])) { Files::delFile($file['tmp_name']); return false; } // Second, filtering using a special function of the system. $result = filter_extension($file_name); if ($result == 0 || $file_name != $file['name']) { Files::delFile($file['tmp_name']); return false; } // Checking for a valid image by reading binary file (partially in most cases). if ($this->config['validate_images']) { $imgInfo = @getImageSize($file['tmp_name']); if (!is_array($imgInfo)) { Files::delFile($file['tmp_name']); return false; } } //now copy the file $path = Files::makePath($this->getBaseDir(), $relative); $result = Files::copyFile($file['tmp_name'], $path, $file['name']); //no copy error if (!is_int($result)) { if (isset($_course) && !empty($_course) && isset($_course['code'])) { //adding the document to the DB global $to_group_id; // looking for the /document/ folder $document_path = substr($path, strpos($path, '/document/') + 9, strlen($path)); // /shared_folder/4/name $document_path .= $result; $chamiloFile = $file['name']; $chamiloFileSize = $file['size']; if (!empty($group_properties['directory'])) { $chamiloFolder = $group_properties['directory'] . $chamiloFolder; } $doc_id = add_document($_course, $document_path, 'file', $chamiloFileSize, $chamiloFile); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, api_get_session_id()); } $dimensionsIndex = isset($_REQUEST['uploadSize']) ? $_REQUEST['uploadSize'] : 0; // If maximum size is specified, constrain image to it. if ($this->config['maxWidth'][$dimensionsIndex] > 0 && $this->config['maxHeight'][$dimensionsIndex] > 0) { $img = Image_Transform::factory(IMAGE_CLASS); $img->load($path . $result); // image larger than max dimensions? if ($img->img_x > $this->config['maxWidth'][$dimensionsIndex] || $img->img_y > $this->config['maxHeight'][$dimensionsIndex]) { $percentage = min($this->config['maxWidth'][$dimensionsIndex] / $img->img_x, $this->config['maxHeight'][$dimensionsIndex] / $img->img_y); $img->scale($percentage); } $img->save($path . $result); $img->free(); } } // Delete tmp files. Files::delFile($file['tmp_name']); return false; }
$rows = str_replace(")(", "),(", $rows); //pone comas en cada fila $new_field_name = $column_new['meta_data_new_table']['field_name']; $new_table_name = $column_new['meta_data_new_table']['table_name']; $result = $link->query("INSERT INTO {$name_db_new}.{$new_table_name} ( {$new_field_name} ) VALUES {$rows}"); if ($result) { echo "<br>Exito {$new_table_name}"; } else { echo "<br>Error {$new_table_name}" . mysqli_error($link); } $offset = $offset + $cantidad_new_table; //paginador de registros } } else { if ($new_table['is_document'] == 'true' and $new_table['new_table'] == false) { add_document($table_name, $link, $name_db_new, $name_db_old, $db_old[$name_db_old][$table_name], $new_table['num_consultas']); exit; } else { if (isset($column_new['relations']) and $new_table['new_table'] != false) { $columns_old .= $column_old . ","; $columns_new .= $columns[$column_old]['relations']['fk_name'] . ","; } else { $columns_old .= $column_old . ","; $columns_new .= $column_new . ","; } } } } $columns_old = rtrim($columns_old, ','); //quita última coma (,) $columns_new = rtrim($columns_new, ',');
/** * Adds an audio file attached to the current item (store on disk and in db) * @return bool|null|string */ public function add_audio() { $course_info = api_get_course_info(); $filepath = api_get_path(SYS_COURSE_PATH) . $course_info['path'] . '/document/'; if (!is_dir($filepath . 'audio')) { mkdir($filepath . 'audio', api_get_permissions_for_new_directories()); $audio_id = add_document($course_info, '/audio', 'folder', 0, 'audio'); api_item_property_update($course_info, TOOL_DOCUMENT, $audio_id, 'FolderCreated', api_get_user_id(), null, null, null, null, api_get_session_id()); api_item_property_update($course_info, TOOL_DOCUMENT, $audio_id, 'invisible', api_get_user_id(), null, null, null, null, api_get_session_id()); } $key = 'file'; if (!isset($_FILES[$key]['name']) || !isset($_FILES[$key]['tmp_name'])) { return false; } $result = DocumentManager::upload_document($_FILES, '/audio', null, null, 0, 'rename', false, false); $file_path = null; if ($result) { $file_path = basename($result['path']); // Store the mp3 file in the lp_item table. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM); $sql = "UPDATE {$tbl_lp_item} SET\n audio = '" . Database::escape_string($file_path) . "'\n WHERE\n c_id = {$course_info['real_id']} AND\n id = '" . intval($this->db_id) . "'"; Database::query($sql); } return $file_path; }
/** * Generate a default certificate for a courses * * @global string $css CSS directory * @global string $img_dir image directory * @global string $default_course_dir Course directory * @global string $js JS directory * @param array $courseData The course info */ public static function generateDefaultCertificate($courseData) { global $css, $img_dir, $default_course_dir, $js; $codePath = api_get_path(REL_CODE_PATH); $dir = '/certificates'; $title = get_lang('DefaultCertificate'); $comment = null; $fileName = replace_dangerous_char($title); $filePath = api_get_path(SYS_COURSE_PATH) . "{$courseData['path']}/document{$dir}"; $fileFullPath = "{$filePath}/{$fileName}.html"; $fileSize = 0; $fileType = 'file'; $templateContent = file_get_contents(api_get_path(SYS_CODE_PATH) . 'gradebook/certificate_template/template.html'); $search = array('{CSS}', '{IMG_DIR}', '{REL_CODE_PATH}', '{COURSE_DIR}'); $replace = array($css . $js, $img_dir, $codePath, $default_course_dir); $fileContent = str_replace($search, $replace, $templateContent); $saveFilePath = "{$dir}/{$fileName}.html"; if (!is_dir($filePath)) { mkdir($filePath, api_get_permissions_for_new_directories()); } $defaultCertificateFile = $fp = @fopen($fileFullPath, 'w'); if ($defaultCertificateFile != false) { @fputs($defaultCertificateFile, $fileContent); fclose($defaultCertificateFile); chmod($fileFullPath, api_get_permissions_for_new_files()); $fileSize = filesize($fileFullPath); } $documentId = add_document($courseData, $saveFilePath, $fileType, $fileSize, $title, $comment); $defaultCertificateId = self::get_default_certificate_id($courseData['code']); if (!isset($defaultCertificateId)) { self::attach_gradebook_certificate($courseData['code'], $documentId); } }
/** * Restore documents * * @param int $session_id * @param bool $respect_base_content * @param string $destination_course_code */ public function restore_documents($session_id = 0, $respect_base_content = false, $destination_course_code = '') { $course_info = api_get_course_info($destination_course_code); if ($this->course->has_resources(RESOURCE_DOCUMENT)) { $table = Database::get_course_table(TABLE_DOCUMENT); $resources = $this->course->resources; $path = api_get_path(SYS_COURSE_PATH) . $this->course->destination_path . '/'; foreach ($resources[RESOURCE_DOCUMENT] as $id => $document) { if (empty($document->item_properties[0]['id_session'])) { $my_session_id = 0; } else { $my_session_id = $session_id; } if ($document->file_type == FOLDER) { $visibility = $document->item_properties[0]['visibility']; $new = substr($document->path, 8); $folderList = explode('/', $new); $tempFolder = ''; // Check if the parent path exists. foreach ($folderList as $folder) { $folderToCreate = $tempFolder . $folder; $sysFolderPath = $path . 'document' . $folderToCreate; $tempFolder .= $folder . '/'; if (empty($folderToCreate)) { continue; } $title = basename($sysFolderPath); // File doesn't exist in file system. if (!is_dir($sysFolderPath)) { // Creating directory create_unexisting_directory($course_info, api_get_user_id(), $my_session_id, 0, 0, $path . 'document', $folderToCreate, $title, $visibility); } else { // File exist in file system. $documentData = DocumentManager::get_document_id($course_info, $folderToCreate, $my_session_id); if (empty($documentData)) { /* This means the folder exists in the filesystem but not in the DB, trying to fix it */ add_document($course_info, $folderToCreate, 'folder', 0, $title, null, null, false, null, $my_session_id); } } } } elseif ($document->file_type == DOCUMENT) { //Checking if folder exists in the database otherwise we created it $dir_to_create = dirname($document->path); if (!empty($dir_to_create) && $dir_to_create != 'document' && $dir_to_create != '/') { if (is_dir($path . dirname($document->path))) { $sql = "SELECT id FROM {$table}\n WHERE\n c_id = " . $this->destination_course_id . " AND\n path = '/" . self::DBUTF8escapestring(substr(dirname($document->path), 9)) . "'"; $res = Database::query($sql); if (Database::num_rows($res) == 0) { //continue; $visibility = $document->item_properties[0]['visibility']; $new = '/' . substr(dirname($document->path), 9); $title = str_replace('/', '', $new); // This code fixes the possibility for a file without a directory entry to be $document_id = add_document($course_info, $new, 'folder', 0, $title, null, null, false); api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'FolderCreated', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } } } if (file_exists($path . $document->path)) { switch ($this->file_option) { case FILE_OVERWRITE: $origin_path = $this->course->backup_path . '/' . $document->path; if (file_exists($origin_path)) { copy($origin_path, $path . $document->path); $sql = "SELECT id FROM {$table}\n WHERE\n c_id = " . $this->destination_course_id . " AND\n path = '/" . self::DBUTF8escapestring(substr($document->path, 9)) . "'"; $res = Database::query($sql); $count = Database::num_rows($res); if ($count == 0) { $params = ['path' => "/" . self::DBUTF8(substr($document->path, 9)), 'c_id' => $this->destination_course_id, 'comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8($document->title), 'filetype' => self::DBUTF8($document->file_type), 'size' => self::DBUTF8($document->size), 'session_id' => $my_session_id]; $document_id = Database::insert($table, $params); if ($document_id) { $sql = "UPDATE {$table} SET id = iid WHERE iid = {$document_id}"; Database::query($sql); } $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id; api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } else { $obj = Database::fetch_object($res); $document_id = $obj->id; $params = ['path' => "/" . self::DBUTF8(substr($document->path, 9)), 'c_id' => $this->destination_course_id, 'comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8($document->title), 'filetype' => self::DBUTF8($document->file_type), 'size' => self::DBUTF8($document->size), 'session_id' => $my_session_id]; Database::update($table, $params, ['c_id = ? AND path = ?' => [$this->destination_course_id, "/" . self::DBUTF8escapestring(substr($document->path, 9))]]); $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id; api_item_property_update($course_info, TOOL_DOCUMENT, $obj->id, 'default', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } // Replace old course code with the new destination code $file_info = pathinfo($path . $document->path); if (in_array($file_info['extension'], array('html', 'htm'))) { $content = file_get_contents($path . $document->path); if (UTF8_CONVERT) { $content = utf8_encode($content); } $content = DocumentManager::replace_urls_inside_content_html_from_copy_course($content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); file_put_contents($path . $document->path, $content); } $params = ['comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8($document->title), 'size' => self::DBUTF8($document->size)]; Database::update($table, $params, ['c_id = ? AND id = ?' => [$this->destination_course_id, $document_id]]); } break; case FILE_SKIP: $sql = "SELECT id FROM {$table}\n\t\t\t\t\t\t\t\t WHERE\n\t\t\t\t\t\t\t\t c_id = " . $this->destination_course_id . " AND\n\t\t\t\t\t\t\t\t path='/" . self::DBUTF8escapestring(substr($document->path, 9)) . "'"; $res = Database::query($sql); $obj = Database::fetch_object($res); $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $obj->id; break; case FILE_RENAME: $i = 1; $ext = explode('.', basename($document->path)); if (count($ext) > 1) { $ext = array_pop($ext); $file_name_no_ext = substr($document->path, 0, -(strlen($ext) + 1)); $ext = '.' . $ext; } else { $ext = ''; $file_name_no_ext = $document->path; } $new_file_name = $file_name_no_ext . '_' . $i . $ext; $file_exists = file_exists($path . $new_file_name); while ($file_exists) { $i++; $new_file_name = $file_name_no_ext . '_' . $i . $ext; $file_exists = file_exists($path . $new_file_name); } if (!empty($session_id)) { $document_path = explode('/', $document->path, 3); $course_path = $path; $orig_base_folder = $document_path[1]; $orig_base_path = $course_path . $document_path[0] . '/' . $document_path[1]; if (is_dir($orig_base_path)) { $new_base_foldername = $orig_base_folder; $new_base_path = $orig_base_path; $originalFolderName = Session::read('orig_base_foldername'); if ($originalFolderName != $new_base_foldername) { Session::erase('new_base_foldername'); Session::erase('orig_base_foldername'); Session::erase('new_base_path'); } $folder_exists = file_exists($new_base_path); if ($folder_exists) { Session::write('orig_base_foldername', $new_base_foldername); $x = ''; while ($folder_exists) { $x = $x + 1; $new_base_foldername = $document_path[1] . '_' . $x; $new_base_path = $orig_base_path . '_' . $x; $baseFolder = Session::read('new_base_foldername'); if ($baseFolder == $new_base_foldername) { break; } $folder_exists = file_exists($new_base_path); } Session::write('new_base_foldername', $new_base_foldername); Session::write('new_base_path', $new_base_path); } $sessionVar1 = Session::read('new_base_foldername'); $sessionVar2 = Session::read('new_base_path'); if (isset($sessionVar) && isset($sessionVar2)) { $new_base_foldername = Session::read('new_base_foldername'); $new_base_path = Session::read('new_base_path'); } $dest_document_path = $new_base_path . '/' . $document_path[2]; // e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1_1/subcarpeta1/collaborative.png" $basedir_dest_path = dirname($dest_document_path); // e.g: "/var/www/wiener/courses/CURSO4/document/carpeta1_1/subcarpeta1" $base_path_document = $course_path . $document_path[0]; // e.g: "/var/www/wiener/courses/CURSO4/document" $path_title = '/' . $new_base_foldername . '/' . $document_path[2]; copy_folder_course_session($basedir_dest_path, $base_path_document, $session_id, $course_info, $document, $this->course_origin_id); if (file_exists($course_path . $document->path)) { copy($course_path . $document->path, $dest_document_path); } //Replace old course code with the new destination code see BT#1985 if (file_exists($dest_document_path)) { $file_info = pathinfo($dest_document_path); if (in_array($file_info['extension'], array('html', 'htm'))) { $content = file_get_contents($dest_document_path); if (UTF8_CONVERT) { $content = utf8_encode($content); } $content = DocumentManager::replace_urls_inside_content_html_from_copy_course($content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); file_put_contents($dest_document_path, $content); } } $params = ['path' => self::DBUTF8($path_title), 'c_id' => $this->destination_course_id, 'comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8(basename($path_title)), 'filetype' => self::DBUTF8($document->file_type), 'size' => self::DBUTF8($document->size), 'session_id' => $my_session_id]; $document_id = Database::insert($table, $params); if ($document_id) { $sql = "UPDATE {$table} SET id = iid WHERE iid = {$document_id}"; Database::query($sql); } $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id; api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } else { if (file_exists($path . $document->path)) { copy($path . $document->path, $path . $new_file_name); } //Replace old course code with the new destination code see BT#1985 if (file_exists($path . $new_file_name)) { $file_info = pathinfo($path . $new_file_name); if (in_array($file_info['extension'], array('html', 'htm'))) { $content = file_get_contents($path . $new_file_name); if (UTF8_CONVERT) { $content = utf8_encode($content); } $content = DocumentManager::replace_urls_inside_content_html_from_copy_course($content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); file_put_contents($path . $new_file_name, $content); } } $params = ['path' => "/" . self::DBUTF8escapestring(substr($new_file_name, 9)), 'c_id' => $this->destination_course_id, 'comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8($document->title), 'filetype' => self::DBUTF8($document->file_type), 'size' => self::DBUTF8($document->size), 'session_id' => $my_session_id]; $document_id = Database::insert($table, $params); if ($document_id) { $sql = "UPDATE {$table} SET id = iid WHERE iid = {$document_id}"; Database::query($sql); $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id; api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } } } else { copy($this->course->backup_path . '/' . $document->path, $path . $new_file_name); //Replace old course code with the new destination code see BT#1985 if (file_exists($path . $new_file_name)) { $file_info = pathinfo($path . $new_file_name); if (in_array($file_info['extension'], array('html', 'htm'))) { $content = file_get_contents($path . $new_file_name); if (UTF8_CONVERT) { $content = utf8_encode($content); } $content = DocumentManager::replace_urls_inside_content_html_from_copy_course($content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); file_put_contents($path . $new_file_name, $content); } } $params = ['c_id' => $this->destination_course_id, 'path' => "/" . self::DBUTF8escapestring(substr($new_file_name, 9)), 'comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8($document->title), 'filetype' => self::DBUTF8($document->file_type), 'size' => self::DBUTF8($document->size), 'session_id' => $my_session_id]; $document_id = Database::insert($table, $params); if ($document_id) { $sql = "UPDATE {$table} SET id = iid WHERE iid = {$document_id}"; Database::query($sql); } $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id; api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } break; } // end switch } else { // end if file exists //make sure the source file actually exists if (is_file($this->course->backup_path . '/' . $document->path) && is_readable($this->course->backup_path . '/' . $document->path) && is_dir(dirname($path . $document->path)) && is_writeable(dirname($path . $document->path))) { //echo 'Copying'; copy($this->course->backup_path . '/' . $document->path, $path . $document->path); //Replace old course code with the new destination code see BT#1985 if (file_exists($path . $document->path)) { $file_info = pathinfo($path . $document->path); if (in_array($file_info['extension'], array('html', 'htm'))) { $content = file_get_contents($path . $document->path); if (UTF8_CONVERT) { $content = utf8_encode($content); } $content = DocumentManager::replace_urls_inside_content_html_from_copy_course($content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); file_put_contents($path . $document->path, $content); } } $params = ['c_id' => $this->destination_course_id, 'path' => "/" . self::DBUTF8(substr($document->path, 9)), 'comment' => self::DBUTF8($document->comment), 'title' => self::DBUTF8($document->title), 'filetype' => self::DBUTF8($document->file_type), 'size' => self::DBUTF8($document->size), 'session_id' => $my_session_id]; $document_id = Database::insert($table, $params); if ($document_id) { $sql = "UPDATE {$table} SET id = iid WHERE iid = {$document_id}"; Database::query($sql); } $this->course->resources[RESOURCE_DOCUMENT][$id]->destination_id = $document_id; api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $document->item_properties[0]['insert_user_id'], $document->item_properties[0]['to_group_id'], $document->item_properties[0]['to_user_id'], null, null, $my_session_id); } else { //echo 'not Copying'; if (is_file($this->course->backup_path . '/' . $document->path) && is_readable($this->course->backup_path . '/' . $document->path)) { error_log('Course copy generated an ignoreable error while trying to copy ' . $this->course->backup_path . '/' . $document->path . ': file not found'); } if (!is_dir(dirname($path . $document->path))) { error_log('Course copy generated an ignoreable error while trying to copy to ' . dirname($path . $document->path) . ': directory not found'); } if (!is_writeable(dirname($path . $document->path))) { error_log('Course copy generated an ignoreable error while trying to copy to ' . dirname($path . $document->path) . ': directory not writeable'); } } } // end file doesn't exist } } // end for each // Delete sessions for the copy the new folder in session Session::erase('new_base_foldername'); Session::erase('orig_base_foldername'); Session::erase('new_base_path'); } }
/** * @param string $message * @param array $_course * @param int $group_id * @param int $session_id * @param bool $preview */ function saveMessage($message, $userId, $_course, $session_id, $group_id, $preview = true) { $userInfo = api_get_user_info($userId); $fullName = $userInfo['complete_name']; $isMaster = (bool) api_is_course_admin(); $document_path = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document'; if (!empty($group_id)) { $group_info = GroupManager::get_group_properties($group_id); $basepath_chat = $group_info['directory'] . '/chat_files'; } else { $basepath_chat = '/chat_files'; } $chat_path = $document_path . $basepath_chat . '/'; if (!is_dir($chat_path)) { if (is_file($chat_path)) { @unlink($chat_path); } } $date_now = date('Y-m-d'); $message = trim($message); $timeNow = date('d/m/y H:i:s'); if (!empty($group_id)) { $basename_chat = 'messages-' . $date_now . '_gid-' . $group_id; } elseif (!empty($session_id)) { $basename_chat = 'messages-' . $date_now . '_sid-' . $session_id; } else { $basename_chat = 'messages-' . $date_now; } if (!api_is_anonymous()) { if (!empty($message)) { Emojione\Emojione::$imagePathPNG = api_get_path(WEB_LIBRARY_PATH) . 'javascript/emojione/png/'; Emojione\Emojione::$ascii = true; // Parsing emojis $message = Emojione\Emojione::toImage($message); // Parsing text to understand markdown (code highlight) $message = MarkdownExtra::defaultTransform($message); // Security XSS $message = Security::remove_XSS($message); if ($preview == true) { return $message; } if (!file_exists($chat_path . $basename_chat . '.log.html')) { $doc_id = add_document($_course, $basepath_chat . '/' . $basename_chat . '.log.html', 'file', 0, $basename_chat . '.log.html'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $userId, $group_id, null, null, null, $session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, $group_id, null, null, null, $session_id); item_property_update_on_folder($_course, $basepath_chat, $userId); } else { $doc_id = DocumentManager::get_document_id($_course, $basepath_chat . '/' . $basename_chat . '.log.html'); } $fp = fopen($chat_path . $basename_chat . '.log.html', 'a'); $userPhoto = Usermanager::getUserPicture($userId, USER_IMAGE_SIZE_MEDIUM); $filePhoto = '<img class="chat-image" src="' . $userPhoto . '"/>'; if ($isMaster) { fputs($fp, '<div class="message-teacher"><div class="content-message"><div class="chat-message-block-name">' . $fullName . '</div><div class="chat-message-block-content">' . $message . '</div><div class="message-date">' . $timeNow . '</div></div><div class="icon-message"></div>' . $filePhoto . '</div>' . "\n"); } else { fputs($fp, '<div class="message-student">' . $filePhoto . '<div class="icon-message"></div><div class="content-message"><div class="chat-message-block-name">' . $fullName . '</div><div class="chat-message-block-content">' . $message . '</div><div class="message-date">' . $timeNow . '</div></div></div>' . "\n"); } fclose($fp); $chat_size = filesize($chat_path . $basename_chat . '.log.html'); update_existing_document($_course, $doc_id, $chat_size); item_property_update_on_folder($_course, $basepath_chat, $userId); } } }
$doc_id = add_document($_course, $relativeUrlPath . '/' . $drawFileName, 'file', filesize($documentPath), $title); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id); } elseif ($currentTool == 'document/editdraw') { //check path if (!isset($_SESSION['draw_file'])) { api_not_allowed(); //from Chamilo die; } if ($_SESSION['draw_file'] == $drawFileName) { $document_id = DocumentManager::get_document_id($_course, $relativeUrlPath . '/' . $drawFileName); update_existing_document($_course, $document_id, filesize($documentPath), null); api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $_user['user_id'], $groupId, null, null, null, $current_session_id); } else { //add a new document $doc_id = add_document($_course, $relativeUrlPath . '/' . $drawFileName, 'file', filesize($documentPath), $title); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id); } } //clean sessions and add messages and return to current document list unset($_SESSION['draw_dir']); unset($_SESSION['draw_file']); unset($_SESSION['whereami']); if ($suffix != 'png') { if ($relativeUrlPath == '') { $relativeUrlPath = '/'; } $url = api_get_path(WEB_CODE_PATH) . 'document/document.php?' . api_get_cidreq() . '&curdirpath=' . urlencode($relativeUrlPath); $message = get_lang('FileSavedAs') . ': ' . $title; //echo 'alert("'.get_lang('FileSavedAs').': '.$title.'");'; //echo 'window.top.location.href="'.$interbreadcrumb.'";';//return to current document list
/** * Exports a picture to another question * * @author Olivier Brouckaert * @param integer $questionId - ID of the target question * @return boolean - true if copied, otherwise false */ public function exportPicture($questionId, $course_info) { $course_id = $course_info['real_id']; $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION); $destination_path = api_get_path(SYS_COURSE_PATH) . $course_info['path'] . '/document/images'; $source_path = api_get_path(SYS_COURSE_PATH) . $this->course['path'] . '/document/images'; // if the question has got an ID and if the picture exists if ($this->id && !empty($this->picture)) { $picture = explode('.', $this->picture); $extension = $picture[sizeof($picture) - 1]; $picture = 'quiz-' . $questionId . '.' . $extension; $result = @copy($source_path . '/' . $this->picture, $destination_path . '/' . $picture) ? true : false; // If copy was correct then add to the database if ($result) { $sql = "UPDATE {$TBL_QUESTIONS} SET\n picture = '" . Database::escape_string($picture) . "'\n WHERE c_id = {$course_id} AND id='" . intval($questionId) . "'"; Database::query($sql); $document_id = add_document($course_info, '/images/' . $picture, 'file', filesize($destination_path . '/' . $picture), $picture); if ($document_id) { return api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id()); } } return $result; } return false; }
/** * Function export last wiki page version to document area * @param int $doc_id wiki page id * * @author Juan Carlos Raña <*****@*****.**> */ public function export2doc($doc_id) { $_course = $this->courseInfo; $groupId = api_get_group_id(); $data = self::get_wiki_data($doc_id); if (empty($data)) { return false; } $wikiTitle = $data['title']; $wikiContents = $data['content']; $template = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{LANGUAGE}" lang="{LANGUAGE}"> <head> <title>{TITLE}</title> <meta http-equiv="Content-Type" content="text/html; charset={ENCODING}" /> <style type="text/css" media="screen, projection"> /*<![CDATA[*/ {CSS} /*]]>*/ </style> {ASCIIMATHML_SCRIPT}</head> <body dir="{TEXT_DIRECTION}"> {CONTENT} </body> </html>'; $css_file = api_get_path(TO_SYS, WEB_CSS_PATH) . api_get_setting('stylesheets') . '/default.css'; if (file_exists($css_file)) { $css = @file_get_contents($css_file); } else { $css = ''; } // Fixing some bugs in css files. $root_rel = api_get_path(REL_PATH); $css_path = 'main/css/'; $theme = api_get_setting('stylesheets') . '/'; $css = str_replace('behavior:url("/main/css/csshover3.htc");', '', $css); $css = str_replace('main/', $root_rel . 'main/', $css); $css = str_replace('images/', $root_rel . $css_path . $theme . 'images/', $css); $css = str_replace('../../img/', $root_rel . 'main/img/', $css); $asciimathmal_script = api_contains_asciimathml($wikiContents) || api_contains_asciisvg($wikiContents) ? '<script src="' . api_get_path(TO_REL, SCRIPT_ASCIIMATHML) . '" type="text/javascript"></script>' . "\n" : ''; $template = str_replace(array('{LANGUAGE}', '{ENCODING}', '{TEXT_DIRECTION}', '{TITLE}', '{CSS}', '{ASCIIMATHML_SCRIPT}'), array(api_get_language_isocode(), api_get_system_encoding(), api_get_text_direction(), $wikiTitle, $css, $asciimathmal_script), $template); if (0 != $groupId) { $groupPart = '_group' . $groupId; // and add groupId to put the same document title in different groups $group_properties = GroupManager::get_group_properties($groupId); $groupPath = $group_properties['directory']; } else { $groupPart = ''; $groupPath = ''; } $exportDir = api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/document' . $groupPath; $exportFile = api_replace_dangerous_char($wikiTitle) . $groupPart; $wikiContents = trim(preg_replace("/\\[[\\[]?([^\\]|]*)[|]?([^|\\]]*)\\][\\]]?/", "\$1", $wikiContents)); //TODO: put link instead of title $wikiContents = str_replace('{CONTENT}', $wikiContents, $template); // replace relative path by absolute path for courses, so you can see items into this page wiki (images, mp3, etc..) exported in documents if (api_strpos($wikiContents, '../../courses/') !== false) { $web_course_path = api_get_path(WEB_COURSE_PATH); $wikiContents = str_replace('../../courses/', $web_course_path, $wikiContents); } $i = 1; //only export last version, but in new export new version in document area while (file_exists($exportDir . '/' . $exportFile . '_' . $i . '.html')) { $i++; } $wikiFileName = $exportFile . '_' . $i . '.html'; $exportPath = $exportDir . '/' . $wikiFileName; file_put_contents($exportPath, $wikiContents); $doc_id = add_document($_course, $groupPath . '/' . $wikiFileName, 'file', filesize($exportPath), $wikiTitle); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $groupId); return $doc_id; }
/** * Generate a default certificate for a courses * * @global string $css CSS directory * @global string $img_dir image directory * @global string $default_course_dir Course directory * @global string $js JS directory * @param array $courseData The course info * @param bool $fromBaseCourse * @param int $sessionId */ public static function generateDefaultCertificate($courseData, $fromBaseCourse = false, $sessionId = 0) { global $css, $img_dir, $default_course_dir, $js; $codePath = api_get_path(REL_CODE_PATH); $dir = '/certificates'; $title = get_lang('DefaultCertificate'); $comment = null; $fileName = api_replace_dangerous_char($title); $filePath = api_get_path(SYS_COURSE_PATH) . "{$courseData['path']}/document{$dir}"; $fileFullPath = "{$filePath}/{$fileName}.html"; $fileSize = 0; $fileType = 'file'; $templateContent = file_get_contents(api_get_path(SYS_CODE_PATH) . 'gradebook/certificate_template/template.html'); $search = array('{CSS}', '{IMG_DIR}', '{REL_CODE_PATH}', '{COURSE_DIR}'); $replace = array($css . $js, $img_dir, $codePath, $default_course_dir); $fileContent = str_replace($search, $replace, $templateContent); $saveFilePath = "{$dir}/{$fileName}.html"; if (!is_dir($filePath)) { mkdir($filePath, api_get_permissions_for_new_directories()); } if ($fromBaseCourse) { $defaultCertificateId = self::get_default_certificate_id($courseData['code'], 0); if (!empty($defaultCertificateId)) { // We have a certificate from the course base $documentData = DocumentManager::get_document_data_by_id($defaultCertificateId, $courseData['code'], false, 0); if ($documentData) { $fileContent = file_get_contents($documentData['absolute_path']); } } } $defaultCertificateFile = $fp = @fopen($fileFullPath, 'w'); if ($defaultCertificateFile != false) { @fputs($defaultCertificateFile, $fileContent); fclose($defaultCertificateFile); chmod($fileFullPath, api_get_permissions_for_new_files()); $fileSize = filesize($fileFullPath); } $documentId = add_document($courseData, $saveFilePath, $fileType, $fileSize, $title, $comment, 0, true, null, $sessionId); api_item_property_update($courseData, TOOL_DOCUMENT, $documentId, 'DocumentAdded', api_get_user_id(), null, null, null, null, $sessionId); $defaultCertificateId = self::get_default_certificate_id($courseData['code'], $sessionId); if (!isset($defaultCertificateId)) { self::attach_gradebook_certificate($courseData['code'], $documentId, $sessionId); } }
/** * This function save a post into a file mp3 from pediaphon services * * @param $filepath * @param $dir * @author Juan Carlos Raña Trabado <*****@*****.**> * @version january 2011, chamilo 1.8.8 */ function downloadMP3_pediaphon($filepath, $dir) { $location = 'create_audio.php?' . api_get_cidreq() . '&id=' . intval($_POST['id']) . '&dt2a=pediaphon'; //security if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) { echo '<script>window.location.href="' . $location . '"</script>'; return; } $_course = api_get_course_info(); $_user = api_get_user_info(); $clean_title = trim($_POST['title']); $clean_title = Database::escape_string($clean_title); $clean_text = trim($_POST['text']); $clean_voices = Security::remove_XSS($_POST['voices']); if (empty($clean_title) || empty($clean_text) || empty($clean_voices)) { echo '<script>window.location.href="' . $location . '"</script>'; return; } $clean_title = Security::remove_XSS($clean_title); $clean_title = Database::escape_string($clean_title); $clean_title = str_replace(' ', '_', $clean_title); //compound file names $clean_text = Security::remove_XSS($clean_text); $clean_lang = Security::remove_XSS($_POST['lang']); $clean_speed = Security::remove_XSS($_POST['speed']); $extension = 'mp3'; $audio_filename = $clean_title . '.' . $extension; $audio_title = str_replace('_', ' ', $clean_title); //prevent duplicates if (file_exists($filepath . '/' . $clean_title . '.' . $extension)) { $i = 1; while (file_exists($filepath . '/' . $clean_title . '_' . $i . '.' . $extension)) { $i++; } $audio_filename = $clean_title . '_' . $i . '.' . $extension; $audio_title = $clean_title . '_' . $i . '.' . $extension; $audio_title = str_replace('_', ' ', $audio_title); } $documentPath = $filepath . '/' . $audio_filename; /*//prev for a fine unicode, borrowed from main api TODO:clean // Safe replacements for some non-letter characters (whitout blank spaces) $search = array("\0", "\t", "\n", "\r", "\x0B", '/', "\\", '"', "'", '?', '*', '>', '<', '|', ':', '$', '(', ')', '^', '[', ']', '#', '+', '&', '%'); $replace = array('', '_', '_', '_', '_', '-', '-', '-', '_', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'); $filename=$clean_text; // Encoding detection. $encoding = api_detect_encoding($filename); // Converting html-entities into encoded characters. $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding); // Transliteration to ASCII letters, they are not dangerous for filesystems. $filename = api_transliterate($filename, 'x', $encoding); // Replacing remaining dangerous non-letter characters. $clean_text = str_replace($search, $replace, $filename);*/ $clean_text = api_replace_dangerous_char($clean_text); //adding the file if ($clean_lang == 'de') { $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi'; $find_t2v = '/http\\:\\/\\/www\\.pediaphon\\.org\\/\\~bischoff\\/radiopedia\\/mp3\\/(.*)\\.mp3\\"/'; } else { $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_' . $clean_lang . '.cgi'; //en, es, fr $find_t2v = '/http\\:\\/\\/www\\.pediaphon\\.org\\/\\~bischoff\\/radiopedia\\/mp3\\/' . $clean_lang . '\\/(.*)\\.mp3\\"/'; } $data = "stimme=" . $clean_voices . "&inputtext=" . $clean_text . "&speed=" . $clean_speed . "&go=speak"; $opts = array('http' => array('method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n", "Content-Length: " . strlen($data) . "\r\n", 'content' => $data)); $context = stream_context_create($opts); // Download the whole HTML page $previous_returntext2voice = file_get_contents($url_pediaphon, false, $context); //extract the audio file path $search_source = preg_match($find_t2v, $previous_returntext2voice, $hits); $souce_end = substr($hits[0], 0, -1); //download file $returntext2voice = file_get_contents($souce_end); //save file $f = @file_put_contents($documentPath, $returntext2voice); if ($f === false && !empty($php_errormsg)) { error_log($php_errormsg); } //add document to database $current_session_id = api_get_session_id(); $groupId = api_get_group_id(); $relativeUrlPath = $dir; $doc_id = add_document($_course, $relativeUrlPath . $audio_filename, 'file', filesize($documentPath), $audio_title); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id); Display::display_confirmation_message(get_lang('DocumentCreated')); //return to location echo '<script>window.location.href="' . $location . '"</script>'; }
/** * Used to convert copied from document * @param string $originalPath * @param string $convertedPath * @param string $convertedTitle * @return bool */ function convertCopyDocument($originalPath, $convertedPath, $convertedTitle) { $_course = api_get_course_info(); $ids = array(); $originalPathInfo = pathinfo($originalPath); $convertedPathInfo = pathinfo($convertedPath); $this->base_work_dir = $originalPathInfo['dirname']; $this->file_path = $originalPathInfo['basename']; $this->created_dir = $convertedPathInfo['basename']; $ppt2lpHost = api_get_setting('ppt_to_lp.host'); $permissionFile = api_get_permissions_for_new_files(); $permissionFolder = api_get_permissions_for_new_directories(); if (file_exists($this->base_work_dir . '/' . $this->created_dir)) { return $ids; } if ($ppt2lpHost == 'localhost') { if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php $converterPath = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png'); $classPath = $converterPath . ';' . $converterPath . '/jodconverter-2.2.2.jar;' . $converterPath . '/jodconverter-cli-2.2.2.jar'; $cmd = 'java -Dfile.encoding=UTF-8 -jar "' . $classPath . '/jodconverter-2.2.2.jar"'; } else { $converterPath = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png'; $classPath = ' -Dfile.encoding=UTF-8 -jar jodconverter-cli-2.2.2.jar'; $cmd = 'cd ' . $converterPath . ' && java ' . $classPath . ' '; } $cmd .= ' -p ' . api_get_setting('ppt_to_lp.port'); // Call to the function implemented by child. $cmd .= ' "' . $this->base_work_dir . '/' . $this->file_path . '" "' . $this->base_work_dir . '/' . $this->created_dir . '"'; // To allow openoffice to manipulate docs. @chmod($this->base_work_dir, $permissionFolder); @chmod($this->base_work_dir . '/' . $this->file_path, $permissionFile); $locale = $this->original_locale; // TODO: Improve it because we're not sure this locale is present everywhere. putenv('LC_ALL=' . $locale); $files = array(); $return = 0; $shell = exec($cmd, $files, $return); // TODO: Chown is not working, root keep user privileges, should be www-data @chown($this->base_work_dir . '/' . $this->created_dir, 'www-data'); @chmod($this->base_work_dir . '/' . $this->created_dir, $permissionFile); if ($return != 0) { // If the java application returns an error code. switch ($return) { // Can't connect to openoffice. case 1: $this->error = get_lang('CannotConnectToOpenOffice'); break; // Conversion failed in openoffice. // Conversion failed in openoffice. case 2: $this->error = get_lang('OogieConversionFailed'); break; // Conversion can't be launch because command failed. // Conversion can't be launch because command failed. case 255: $this->error = get_lang('OogieUnknownError'); break; } DocumentManager::delete_document($_course, $this->created_dir, $this->base_work_dir); return false; } } else { /* * @TODO Create method to use webservice // get result from webservices $result = $this->_get_remote_ppt2lp_files($file); $result = unserialize(base64_decode($result)); // Save remote images to server chmod($this->base_work_dir.$this->created_dir, api_get_permissions_for_new_directories()); if (!empty($result['images'])) { foreach ($result['images'] as $image => $img_data) { $image_path = $this->base_work_dir.$this->created_dir; @file_put_contents($image_path . '/' . $image, base64_decode($img_data)); @chmod($image_path . '/' . $image, 0777); } } // files info $files = $result['files']; */ } if (file_exists($this->base_work_dir . '/' . $this->created_dir)) { // Register Files to Document tool $ids[] = add_document($_course, '/' . $this->created_dir, 'file', filesize($this->base_work_dir . '/' . $this->created_dir), $convertedTitle, sprintf(get_lang('FileConvertedFromXToY'), strtoupper($originalPathInfo['extension']), strtoupper($convertedPathInfo['extension'])), 0, true, null, api_get_session_id()); chmod($this->base_work_dir, $permissionFolder); } return $ids; }
$basename_chat = 'messages-' . $date_now . '_gid-' . $group_id; } else { if (!empty($session_id)) { $basename_chat = 'messages-' . $date_now . '_sid-' . $session_id; } else { $basename_chat = 'messages-' . $date_now; } } if ($reset && $isMaster) { $i = 1; while (file_exists($chat_path . $basename_chat . '-' . $i . '.log.html')) { $i++; } @rename($chat_path . $basename_chat . '.log.html', $chat_path . $basename_chat . '-' . $i . '.log.html'); @fclose(fopen($chat_path . $basename_chat . '.log.html', 'w')); $doc_id = add_document($_course, $basepath_chat . '/' . $basename_chat . '-' . $i . '.log.html', 'file', filesize($chat_path . $basename_chat . '-' . $i . '.log.html'), $basename_chat . '-' . $i . '.log.html'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $userId, $group_id, null, null, null, $session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, $group_id, null, null, null, $session_id); item_property_update_on_folder($_course, $basepath_chat, $userId); $doc_id = DocumentManager::get_document_id($_course, $basepath_chat . '/' . $basename_chat . '.log.html'); update_existing_document($_course, $doc_id, 0); } $remove = 0; $content = array(); if (file_exists($chat_path . $basename_chat . '.log.html')) { $content = file($chat_path . $basename_chat . '.log.html'); $nbr_lines = sizeof($content); $remove = $nbr_lines - 100; } if ($remove < 0) { $remove = 0;
if (!is_dir($filepath . 'css')) { mkdir($filepath . 'css', api_get_permissions_for_new_directories()); $doc_id = add_document($_course, $dir . 'css', 'folder', 0, 'css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $userId, null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, null, null, null, null, $current_session_id); } if (!is_file($filepath . 'css/frames.css')) { // Make a copy of the current css for the new document copy(api_get_path(SYS_CODE_PATH) . 'css/' . api_get_setting('stylesheets') . '/frames.css', $filepath . 'css/frames.css'); $doc_id = add_document($_course, $dir . 'css/frames.css', 'file', filesize($filepath . 'css/frames.css'), 'frames.css'); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $userId, null, null, null, null, $current_session_id); api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $userId, null, null, null, null, $current_session_id); } $file_size = filesize($filepath . $filename . '.' . $extension); $save_file_path = $dir . $filename . '.' . $extension; $document_id = add_document($_course, $save_file_path, 'file', $file_size, $title, null, $readonly); if ($document_id) { api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $userId, $to_group_id, null, null, null, $current_session_id); // Update parent folders item_property_update_on_folder($_course, $dir, $userId); $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : ''; $new_comment = Database::escape_string($new_comment); $new_title = isset($_POST['title']) ? trim($_POST['title']) : ''; $new_title = htmlspecialchars($new_title); $new_title = Database::escape_string($new_title); if ($new_comment || $new_title) { $ct = ''; if ($new_comment) { $ct .= ", comment='{$new_comment}'"; } if ($new_title) {
/** * Creates a new directory trying to find a directory name * that doesn't already exist * (we could use unique_name() here...) * * @author Hugues Peeters <*****@*****.**> * @author Bert Vanderkimpen * @param array $_course current course information * @param int $user_id current user id * @param int $session_id * @param int $to_group_id * @param int $to_user_id * @param string $base_work_dir /var/www/chamilo/courses/ABC/document * @param string $desired_dir_name complete path of the desired name * Example: /folder1/folder2 * @param string $title "folder2" * @param int $visibility (0 for invisible, 1 for visible, 2 for deleted) * @param bool $generateNewNameIfExists * @return string actual directory name if it succeeds, * boolean false otherwise */ function create_unexisting_directory($_course, $user_id, $session_id, $to_group_id, $to_user_id, $base_work_dir, $desired_dir_name, $title = null, $visibility = null, $generateNewNameIfExists = false) { $course_id = $_course['real_id']; $session_id = intval($session_id); $folderExists = DocumentManager::folderExists($desired_dir_name, $_course, $session_id, $to_group_id); if ($folderExists == true) { if ($generateNewNameIfExists) { $counter = 1; while (1) { $folderExists = DocumentManager::folderExists($desired_dir_name . '_' . $counter, $_course, $session_id, $to_group_id); if ($folderExists == false) { break; } $counter++; } $desired_dir_name = $desired_dir_name . '_' . $counter; } else { return false; } } $systemFolderName = $desired_dir_name; // Adding suffix $suffix = DocumentManager::getDocumentSuffix($_course, $session_id, $to_group_id); $systemFolderName .= $suffix; if ($title == null) { $title = basename($desired_dir_name); } if (!is_dir($base_work_dir . $systemFolderName)) { $result = mkdir($base_work_dir . $systemFolderName, api_get_permissions_for_new_directories(), true); if ($result) { // Check if pathname already exists inside document table $tbl_document = Database::get_course_table(TABLE_DOCUMENT); $sql = "SELECT id, path FROM {$tbl_document}\n WHERE\n c_id = {$course_id} AND\n (\n path = '" . $systemFolderName . "'\n )\n "; $rs = Database::query($sql); if (Database::num_rows($rs) == 0) { $document_id = add_document($_course, $systemFolderName, 'folder', 0, $title, null, 0, true, $to_group_id); if ($document_id) { // Update document item_property if (!empty($visibility)) { $visibilities = array(0 => 'invisible', 1 => 'visible', 2 => 'delete'); api_item_property_update($_course, TOOL_DOCUMENT, $document_id, $visibilities[$visibility], $user_id, $to_group_id, $to_user_id, null, null, $session_id); } else { api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'FolderCreated', $user_id, $to_group_id, $to_user_id, null, null, $session_id); } $documentData = DocumentManager::get_document_data_by_id($document_id, $_course['code'], false, $session_id); return $documentData; } } else { $document = Database::fetch_array($rs); $documentData = DocumentManager::get_document_data_by_id($document['id'], $_course['code'], false, $session_id); /* This means the folder NOT exist in the filesystem (now this was created) but there is a record in the Database*/ return $documentData; } } } return false; }
function add_docs_to_visio($files = array()) { global $_course; foreach ($files as $file) { list($slide_name,$file_name) = explode('||',$file); // '||' is used as separator between slide name (with accents) and file name (without accents). $slide_name = api_htmlentities($slide_name, ENT_COMPAT, $this->original_charset); $slide_name = str_replace('’', '\'', $slide_name); $slide_name = api_convert_encoding($slide_name, api_get_system_encoding(), $this->original_charset); $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding()); $did = add_document($_course, $this->created_dir.'/'.urlencode($file_name), 'file', filesize($this->base_work_dir.$this->created_dir.'/'.$file_name), $slide_name); if ($did) { api_item_property_update($_course, TOOL_DOCUMENT, $did, 'DocumentAdded', $_SESSION['_uid'], 0, null, null, null, api_get_session_id()); } } }
if (is_dir($item)) { $doc_id = add_document($_course, $chamiloFolder, 'folder', $chamiloFileSize, $chamiloFile); //get Chamilo api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo } elseif (is_file($item)) { $chamiloFileSize = filesize($item); $doc_id = add_document($_course, $chamiloFolder, 'file', $chamiloFileSize, $chamiloFile); //get Chamilo api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo } } } } elseif ($tem['type'] == "file") { $doc_id = add_document($_course, $chamiloFolder, 'file', $chamiloFileSize, $chamiloFile); //get Chamilo api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', api_get_user_id(), $to_group_id, null, null, null, $current_session_id); //get Chamilo } } } //end bridge $manager = null; if ($sessionAction->getAction() == "cut") { $file->delete($doc); } $fileMoved[sizeof($fileMoved)] = $tem; $tem = null; } } else {