public function export() { $postsList = $this->loadTopic($this->getTopicId()); $topicInfo = get_topic_settings($this->getTopicId()); $this->createPDF($topicInfo['topic_title']); $this->pdf->AddPage(); $htmlContent = '<p>' . "\n" . '<table cellspacing="0" cellpadding="2" border="1">' . "\n" . '<tbody>' . "\n" . '<tr>' . "\n" . '<th colspan="2" style="font-weight: bold; background-color: #EDF1E3; color: #669933; border-bottom: 1px solid #96BB7A;">' . claro_utf8_encode($topicInfo['topic_title']) . '</th>' . '</tr>' . "\n"; foreach ($postsList as $post) { $htmlContent .= '<tr>' . "\n" . '<td style="width: 150px; background-color: #EEEEEE;">' . "\n" . '<div style="font-weight: bold;">' . claro_utf8_encode($post['firstname'] . ' ' . $post['lastname'], get_conf('charset')) . '</div>' . "\n" . '<small>' . claro_html_localised_date(get_locale('dateTimeFormatLong'), datetime_to_timestamp($post['post_time'])) . '</small>' . "\n" . '</td>' . "\n" . '<td style="width: 354px;">' . claro_utf8_encode(claro_parse_user_text(strip_tags($post['post_text'])), get_conf('charset')) . '</td>' . "\n" . '</tr>' . "\n"; } $htmlContent .= '</tbody>' . "\n" . '</table>' . "\n" . '</p>'; //exit( claro_utf8_decode($htmlContent) ); $this->pdf->writeHTML($htmlContent, true, 0, true, 0); switch ($this->output) { case 'screen': $this->pdf->Output(claro_utf8_encode($topicInfo['topic_id'] . '_' . $topicInfo['topic_title'] . '.pdf'), 'D'); break; default: $path = get_conf('rootSys') . get_conf('tmpPathSys') . '/forum_export/'; claro_mkdir($path); $this->pdf->Output($path . claro_utf8_encode(replace_dangerous_char($topicInfo['topic_id'] . '_' . $topicInfo['topic_title']) . '.pdf'), 'F'); break; } return true; }
public function export() { $postsList = $this->loadTopic($this->getTopicId()); $topicInfo = get_topic_settings($this->getTopicId()); $css = $this->importCss(); $form = new PhpTemplate(get_module_path('CLFRM') . '/templates/forum_export.tpl.php'); $form->assign('forum_id', $topicInfo['forum_id']); $form->assign('topic_id', $topicInfo['topic_id']); $form->assign('notification_bloc', false); $form->assign('topic_subject', $topicInfo['topic_title']); $form->assign('postList', $postsList); $form->assign('claro_notifier', false); $form->assign('is_allowedToEdit', false); $form->assign('date', null); $out = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . "\n" . '<html>' . "\n" . '<head>' . "\n" . '<meta http-equiv="Content-Type" content="text/HTML; charset=' . get_conf('charset') . '" />' . "\n" . '<style type="text/css">' . $css . '</style>' . "\n" . '<title>' . $topicInfo['topic_title'] . '</title>' . "\n" . '</head>' . "\n" . '<body><div id="forumExport">' . "\n"; $out .= $form->render(); $out .= '</div></body>' . "\n" . '</html>'; $path = get_conf('rootSys') . get_conf('tmpPathSys') . '/forum_export/'; $filename = $path . replace_dangerous_char(str_replace(' ', '_', $topicInfo['topic_title']) . '_' . $topicInfo['topic_id']) . '.html'; claro_mkdir($path); file_put_contents($filename, $out); switch ($this->output) { case 'screen': header('Content-Description: File Transfer'); header('Content-Type: application/force-download'); header('Content-Length: ' . filesize($filename)); header('Content-Disposition: attachment; filename=' . basename($filename)); readfile($filename); claro_delete_file($filename); break; case 'file': break; } return true; }
/** * 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); } }
//put the uploaded files in the new directory and get the paths $paths_to_replace_in_file = move_uploaded_file_collection_into_directory($_course, $_FILES['img_file'],$base_work_dir,$missing_files_dir,$_user['user_id'],$to_group_id,$to_user_id,$max_filled_space); //open the html file and replace the paths replace_img_path_in_html_file( $_POST['img_file_path'], $paths_to_replace_in_file, $base_work_dir . $_POST['related_file'] ); //update parent folders item_property_update_on_folder($_course,$_POST['curdirpath'],$_user['user_id']); } } //they want to create a directory if (isset($_POST['create_dir']) && $_POST['dirname']!='') { $added_slash = ($path=='/')?'':'/'; $dir_name = $path.$added_slash.replace_dangerous_char($_POST['dirname']); $created_dir = create_unexisting_directory($_course,$_user['user_id'],api_get_session_id(), $to_group_id,$to_user_id,$base_work_dir,$dir_name,$_POST['dirname']); if ($created_dir) { Display::display_normal_message(get_lang('DirCr')); $path = $created_dir; } else { display_error(get_lang('CannotCreateDir')); } } if (isset($_GET['createdir'])) { //create the form that asks for the directory name $new_folder_text = '<form action="'.api_get_self().'" method="POST">'; $new_folder_text .= '<input type="hidden" name="curdirpath" value="'.$path.'"/>'; $new_folder_text .= get_lang('NewDir') .' '; $new_folder_text .= '<input type="text" name="dirname"/>';
/** * Fetch info from the database * * @return False on error, true otherwise. * @author Thanos Kyritsis <*****@*****.**> * @author Amand Tihon <*****@*****.**> */ function fetch() { global $webDir, $course_code, $course_id, $langLearningPathNotFound, $langLearningPathEmpty; /* Get general infos about the learning path */ $lp = Database::get()->querySingle("SELECT `name`, `comment` FROM `lp_learnPath` WHERE `learnPath_id` = ?d AND `course_id` = ?d", $this->id, $course_id); if (!$lp) { $this->error[] = $langLearningPathNotFound; return false; } $this->name = $lp->name; $this->comment = $lp->comment; /* Build various directories' names */ // Replace ',' too, because pclzip doesn't support it. $this->destDir = $webDir . "/courses/" . $course_code . '/temp/' . str_replace(',', '_', replace_dangerous_char($this->name)); $this->srcDirDocument = $webDir . "/courses/" . $course_code . "/document"; $this->srcDirExercise = $webDir . "/courses/" . $course_code . "/exercise"; $this->srcDirScorm = $webDir . "/courses/" . $course_code . "/scormPackages/path_" . $this->id; $this->srcDirVideo = $webDir . "/video/" . $course_code; /* Now, get the complete list of modules, etc... */ $sql = 'SELECT LPM.`learnPath_module_id` ID, LPM.`lock`, LPM.`visible`, LPM.`rank`, LPM.`parent`, LPM.`raw_to_pass`, LPM.`specificComment` itemComment, M.`name`, M.`contentType`, M.`comment` resourceComment, A.`path` FROM `lp_rel_learnPath_module` AS LPM LEFT JOIN `lp_module` AS M ON LPM.`module_id` = M.`module_id` LEFT JOIN `lp_asset` AS A ON M.`startAsset_id` = A.`asset_id` WHERE LPM.`learnPath_id` = ?d AND M.`course_id` = ?d ORDER BY LPM.`parent`, LPM.`rank`'; $result = Database::get()->queryArray($sql, $this->id, $course_id); if (!$result) { $this->error[] = $langLearningPathEmpty; return false; } $module = array(); foreach ($result as $modobj) { $module['ID'] = $modobj->ID; $module['lock'] = $modobj->lock; $module['visible'] = $modobj->visible; $module['rank'] = $modobj->rank; $module['parent'] = $modobj->parent; $module['raw_to_pass'] = $modobj->raw_to_pass; $module['itemComment'] = $modobj->itemComment; $module['name'] = $modobj->name; $module['contentType'] = $modobj->contentType; $module['resourceComment'] = $modobj->resourceComment; $module['path'] = $modobj->path; // Check for SCORM content. If at least one module is SCORM, we need to export the existing SCORM package if ($module['contentType'] == 'SCORM' || $module['contentType'] == 'SCORM_ASSET') { $this->fromScorm = true; } // If it is an exercise, create a filename for it. if ($module['contentType'] == 'EXERCISE') { $module['fileName'] = 'quiz_' . $module['path'] . '.html'; } // Only for clarity : $id = $module['ID']; $parent = $module['parent']; // Add to the flat resource map $this->resourceMap[$id] = $module; // Build Item tree, only keeping visible modules if ($module['visible'] == 1) { if (!$parent) { // parent is 0, item is at root $this->itemTree[$id] = &$this->resourceMap[$id]; } else { /* item has a parent. Add it to the list of its children. Note that references are used, not copies. */ $this->resourceMap[$parent]['children'][] = &$this->resourceMap[$id]; } } } return true; }
/** * Check if a document width the chosen filename already exists */ function document_exists($filename) { global $dir; // Clean up the name, only ASCII characters should stay. (and strict) $cleanName = replace_dangerous_char($filename, 'strict'); // No "dangerous" files $cleanName = disable_dangerous_file($cleanName); return !DocumentManager::documentExists($dir . $cleanName . '.html', api_get_course_info(), api_get_session_id(), api_get_group_id()); /*$filename = addslashes(trim($filename)); $filename = Security::remove_XSS($filename); $filename = replace_dangerous_char($filename); $filename = disable_dangerous_file($filename); return !file_exists($filepath.$filename.'.html');*/ }
claro_mkdir($pathSys); } /* * Init request vars */ if (!empty($_REQUEST['relativePath']) && $_REQUEST['relativePath'] != '/' && $_REQUEST['relativePath'] != '.') { $relativePath = str_replace('..', '', $_REQUEST['relativePath']) . '/'; } else { $relativePath = '/'; } /* * Handle upload */ if ($is_allowedToEdit && isset($_FILES['sentFile']['tmp_name']) && is_uploaded_file($_FILES['sentFile']['tmp_name'])) { $imgFile = $_FILES['sentFile']; $imgFile['name'] = replace_dangerous_char($imgFile['name'], 'strict'); $imgFile['name'] = get_secure_file_name($imgFile['name']); if (claro_is_in_a_course()) { $enoughSize = enough_size($_FILES['sentFile']['size'], $pathSys, $maxFilledSpace); } else { $enoughSize = true; } if (is_image($imgFile['name']) && $enoughSize) { // rename if file already exists if (file_exists($pathSys . $relativePath . $imgFile['name'])) { $pieceList = explode('.', $imgFile['name']); $base = $pieceList[0]; $ext = $pieceList[1]; $i = 1; while (file_exists($pathSys . $relativePath . $base . '_' . $i . '.' . $ext)) { $i++;
/** * @param array $params * * @return int */ public function saveOptions($params, $show_query = false) { $optionInfo = self::get_field_option_by_field_and_option($params['field_id'], $params['option_value']); // Use URLify only for new items //$optionValue = URLify::filter($params['option_value']); $optionValue = replace_dangerous_char($params['option_value']); $option = $params['option_value']; if ($optionInfo == false) { $order = self::get_max_order($params['field_id']); $new_params = array('field_id' => $params['field_id'], 'option_value' => trim($optionValue), 'option_display_text' => trim($option), 'option_order' => $order, 'tms' => api_get_utc_datetime()); return parent::save($new_params, $show_query); } return false; }
/** * Rename a file or a directory * * @param - $filePath (string) - complete path of the file or the directory * @param - $newFileName (string) - new name for the file or the directory * @return - string - new file path if it succeeds * - boolean - false otherwise * @see - rename() uses the check_name_exist() and php2phps() functions */ function claro_rename_file($oldFilePath, $newFilePath) { if (realpath($oldFilePath) == realpath($newFilePath)) { return true; } /* CHECK IF THE NEW NAME HAS AN EXTENSION */ if (!is_dir($oldFilePath)) { $ext_new = get_file_extension($newFilePath); $ext_old = get_file_extension($oldFilePath); if (empty($ext_new) && !empty($ext_old)) { $newFilePath .= '.' . $ext_old; } } /* PREVENT FILE NAME WITH PHP EXTENSION */ $newFilePath = get_secure_file_name($newFilePath); /* REPLACE CHARACTER POTENTIALY DANGEROUS FOR THE SYSTEM */ $newFilePath = dirname($newFilePath) . '/' . replace_dangerous_char(basename($newFilePath)); if (check_name_exist($newFilePath) && $newFilePath != $oldFilePath) { return false; } else { if (check_name_exist($oldFilePath)) { if (rename($oldFilePath, $newFilePath)) { return $newFilePath; } else { return false; } } else { return false; } } }
function return_menu() { $navigation = return_navigation_array(); $navigation = $navigation['navigation']; // Displaying the tabs $lang = ''; //el for "Edit Language" if (!empty($_SESSION['user_language_choice'])) { $lang = $_SESSION['user_language_choice']; } elseif (!empty($_SESSION['_user']['language'])) { $lang = $_SESSION['_user']['language']; } else { $lang = get_setting('platformLanguage'); } //Preparing home folder for multiple urls if (api_get_multiple_access_url()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url_info = api_get_access_url($access_url_id); $url = api_remove_trailing_slash(preg_replace('/https?:\\/\\//i', '', $url_info['url'])); $clean_url = replace_dangerous_char($url); $clean_url = str_replace('/', '-', $clean_url); $clean_url .= '/'; $homep = api_get_path(SYS_PATH) . 'home/' . $clean_url; //homep for Home Path //we create the new dir for the new sites if (!is_dir($homep)) { mkdir($homep, api_get_permissions_for_new_directories()); } } } else { $homep = api_get_path(SYS_PATH) . 'home/'; } $ext = '.html'; $menutabs = 'home_tabs'; $mtloggedin = 'home_tabs_logged_in'; $home_top = ''; if (is_file($homep . $menutabs . '_' . $lang . $ext) && is_readable($homep . $menutabs . '_' . $lang . $ext)) { $home_top = @(string) file_get_contents($homep . $menutabs . '_' . $lang . $ext); } elseif (is_file($homep . $menutabs . $lang . $ext) && is_readable($homep . $menutabs . $lang . $ext)) { $home_top = @(string) file_get_contents($homep . $menutabs . $lang . $ext); } else { //$errorMsg = get_lang('HomePageFilesNotReadable'); } $home_top = api_to_system_encoding($home_top, api_detect_encoding(strip_tags($home_top))); $open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top); $open = api_to_system_encoding($open, api_detect_encoding(strip_tags($open))); $open_mtloggedin = ''; if (api_get_user_id() && !api_is_anonymous()) { if (is_file($homep . $mtloggedin . '_' . $lang . $ext) && is_readable($homep . $mtloggedin . '_' . $lang . $ext)) { $home_top = @(string) file_get_contents($homep . $mtloggedin . '_' . $lang . $ext); $home_top = str_replace('::private', '', $home_top); } elseif (is_file($homep . $mtloggedin . $lang . $ext) && is_readable($homep . $mtloggedin . $lang . $ext)) { $home_top = @(string) file_get_contents($homep . $mtloggedin . $lang . $ext); $home_top = str_replace('::private', '', $home_top); } else { //$errorMsg = get_lang('HomePageFilesNotReadable'); } $home_top = api_to_system_encoding($home_top, api_detect_encoding(strip_tags($home_top))); $open_mtloggedin = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top); $open_mtloggedin = api_to_system_encoding($open_mtloggedin, api_detect_encoding(strip_tags($open_mtloggedin))); } $lis = ''; if (!empty($open) or !empty($open_mtloggedin)) { if (strpos($open . $open_mtloggedin, 'show_menu') === false) { if (api_is_anonymous()) { $navigation[SECTION_CAMPUS] = null; } } else { //$lis .= Display::tag('li', $open); if (api_get_user_id() && !api_is_anonymous()) { $lis .= $open_mtloggedin; } else { $lis .= $open; } } } if (count($navigation) > 0 || !empty($lis)) { $pre_lis = ''; foreach ($navigation as $section => $navigation_info) { $key = !empty($navigation_info['key']) ? 'tab-' . $navigation_info['key'] : ''; if (isset($GLOBALS['this_section'])) { $current = $section == $GLOBALS['this_section'] ? ' id="current" class="active ' . $key . '" ' : ' class="' . $key . '"'; } else { $current = ''; } if (!empty($navigation_info['title'])) { $pre_lis .= '<li' . $current . '><a href="' . $navigation_info['url'] . '" target="_top">' . $navigation_info['title'] . '</a></li>'; } } $lis = $pre_lis . $lis; } $menu = null; if (!empty($lis)) { $menu .= $lis; } return $menu; }
/** * @param string $file * @param string $action_after_conversion * @return bool|int */ public function convert_document($file, $action_after_conversion = 'make_lp') { global $_course; $this->file_name = pathinfo($file['name'], PATHINFO_FILENAME); // Create the directory $result = $this->generate_lp_folder($_course, $this->file_name); // Create the directory $this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'; ///learning_path/ppt_dirname directory $this->created_dir = substr($result['dir'], 0, strlen($result['dir']) -1); $this->file_path = $this->created_dir.'/'.replace_dangerous_char($file['name'], 'strict'); //var_dump($this->file_name, $this->file_path, $this->base_work_dir, $this->created_dir); /* * Original code global $_course, $_user, $_configuration; $this->file_name = (strrpos($file['name'], '.') > 0 ? substr($file['name'], 0, strrpos($file['name'], '.')) : $file['name']); $this->file_name = replace_dangerous_char($this->file_name, 'strict'); $this->file_name = strtolower($this->file_name); $visio_dir = ($action_after_conversion == 'add_docs_to_visio') ? VIDEOCONF_UPLOAD_PATH : ''; $this->file_path = $visio_dir.'/'.$this->file_name.'.'.pathinfo($file['name'], PATHINFO_EXTENSION); $dir_name = $visio_dir.'/'.$this->file_name; // Create the directory. $this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'; $this->created_dir = create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), 0, 0, $this->base_work_dir, $dir_name); var_dump($this->file_name, $this->file_path, $this->base_work_dir, $this->created_dir); */ $ppt2lp_host = api_get_setting('service_ppt2lp', 'host'); if ($ppt2lp_host == 'localhost') { move_uploaded_file($file['tmp_name'], $this->base_work_dir.'/'.$this->file_path); //var_dump( $this->base_work_dir.$this->created_dir.$this->file_path); $perm = api_get_setting('permissions_for_new_files'); if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php $converter_path = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png'); $class_path = $converter_path . ';' . $converter_path . '/jodconverter-2.2.2.jar;' . $converter_path . '/jodconverter-cli-2.2.2.jar'; //$cmd = 'java -cp "'.$class_path.'" DokeosConverter'; $cmd = 'java -Dfile.encoding=UTF-8 -cp "' . $class_path . '" DokeosConverter'; } else { $converter_path = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png'; //$class_path = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar'; $class_path = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.2.jar:jodconverter-cli-2.2.2.jar'; $cmd = 'cd ' . $converter_path . ' && java ' . $class_path . ' DokeosConverter'; } $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port'); // Call to the function implemented by child. $cmd .= $this->add_command_parameters(); // To allow openoffice to manipulate docs. @chmod($this->base_work_dir, 0777); @chmod($this->base_work_dir.$this->created_dir, 0777); @chmod($this->base_work_dir.$this->file_path, 0777); $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); 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. case 2: $this->error = get_lang('OogieConversionFailed'); break; // 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 { // get result from webservices $result = $this->_get_remote_ppt2lp_files($file); $result = unserialize($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 (!empty($files)) { // Create lp $this->lp_id = learnpath::add_lp($_course['id'], $this->file_name, '', 'guess', 'manual'); // Call to the function implemented by child following action_after_conversion parameter. switch ($action_after_conversion) { case 'make_lp': $this->make_lp($files); break; case 'add_docs_to_visio': $this->add_docs_to_visio($files); break; } chmod($this->base_work_dir, api_get_permissions_for_new_directories()); } return $this->first_item; }
Display::display_footer(); exit; } } } $tool_name = get_lang('Registration', null, !empty($_POST['language']) ? $_POST['language'] : $_user['language']); if (api_get_setting('allow_terms_conditions') == 'true' && $user_already_registered_show_terms) { $tool_name = get_lang('TermsAndConditions'); } $home = api_get_path(SYS_PATH) . 'home/'; if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url_info = api_get_access_url($access_url_id); $url = api_remove_trailing_slash(preg_replace('/https?:\\/\\//i', '', $url_info['url'])); $clean_url = replace_dangerous_char($url); $clean_url = str_replace('/', '-', $clean_url); $clean_url .= '/'; $home_old = api_get_path(SYS_PATH) . 'home/'; $home = api_get_path(SYS_PATH) . 'home/' . $clean_url; } } if (file_exists($home . 'register_top_' . $user_selected_language . '.html')) { $home_top_temp = @(string) file_get_contents($home . 'register_top_' . $user_selected_language . '.html'); $open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp); $open = api_to_system_encoding($open, api_detect_encoding(strip_tags($open))); if (!empty($open)) { $content = '<div class="well_border">' . $open . '</div>'; } } // Forbidden to self-register
/** * Downloads all user files per user * @param int $userId * @param array $courseInfo * @return bool */ function downloadAllFilesPerUser($userId, $courseInfo) { $userInfo = api_get_user_info($userId); if (empty($userInfo) || empty($courseInfo)) { return false; } require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php'; $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip"; $coursePath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/work/'; $zip = new PclZip($tempZipFile); $workPerUser = getWorkPerUser($userId); if (!empty($workPerUser)) { $files = array(); foreach ($workPerUser as $work) { $work = $work['work']; foreach ($work->user_results as $userResult) { if (empty($userResult['url']) || empty($userResult['contains_file'])) { continue; } $data = getFileContents($userResult['id'], $courseInfo); if (!empty($data) && isset($data['path'])) { $files[basename($data['path'])] = array( 'title' => $data['title'], 'path' => $data['path'] ); } } } if (!empty($files)) { Session::write('files', $files); foreach ($files as $data) { $zip->add( $data['path'], PCLZIP_OPT_REMOVE_PATH, $coursePath, PCLZIP_CB_PRE_ADD, 'preAddAllWorkStudentCallback' ); } } // Start download of created file $name = basename(replace_dangerous_char($userInfo['complete_name'])).'.zip'; event_download($name.'.zip (folder)'); if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) { DocumentManager::file_send_for_download($tempZipFile, true, $name); @unlink($tempZipFile); exit; } } exit; }
$work_temp = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().'_'.$filename; file_put_contents($work_temp, $not_deleted_file['description']); $files[basename($work_temp)] = $filename; $addStatus = $zip_folder->add( $work_temp, PCLZIP_OPT_REMOVE_PATH, api_get_path(SYS_ARCHIVE_PATH), PCLZIP_CB_PRE_ADD, 'my_pre_add_callback' ); @unlink($work_temp); } } if (!empty($files)) { $fileName = replace_dangerous_char($work_data['title']); // Logging event_download($fileName .'.zip (folder)'); //start download of created file $name = $fileName .'.zip'; if (Security::check_abs_path($temp_zip_file, api_get_path(SYS_ARCHIVE_PATH))) { DocumentManager::file_send_for_download($temp_zip_file, true, $name); @unlink($temp_zip_file); exit; } } else { exit; } /* Extra function (only used here) */
/** * @return array|null|string */ function store_add_dropbox() { $_course = api_get_course_info(); $_user = api_get_user_info(); $dropbox_cnf = getDropboxConf(); // Validating the form data // there are no recipients selected if (!isset($_POST['recipients']) || count($_POST['recipients']) <= 0) { return get_lang('YouMustSelectAtLeastOneDestinee'); } else { // Check if all the recipients are valid $thisIsAMailing = false; $thisIsJustUpload = false; foreach ($_POST['recipients'] as $rec) { if ($rec == 'mailing') { $thisIsAMailing = true; } elseif ($rec == 'upload') { $thisIsJustUpload = true; } elseif (strpos($rec, 'user_') === 0 && !isCourseMember(substr($rec, strlen('user_')))) { return get_lang('InvalideUserDetected'); } elseif (strpos($rec, 'group_') !== 0 && strpos($rec, 'user_') !== 0) { return get_lang('InvalideGroupDetected'); } } } // we are doing a mailing but an additional recipient is selected if ($thisIsAMailing && count($_POST['recipients']) != 1) { return get_lang('MailingSelectNoOther'); } // we are doing a just upload but an additional recipient is selected. // note: why can't this be valid? It is like sending a document to yourself AND to a different person (I do this quite often with my e-mails) if ($thisIsJustUpload && count($_POST['recipients']) != 1) { return get_lang('MailingJustUploadSelectNoOther'); } if (empty($_FILES['file']['name'])) { $error = true; return get_lang('NoFileSpecified'); } // are we overwriting a previous file or sending a new one $dropbox_overwrite = false; if (isset($_POST['cb_overwrite']) && $_POST['cb_overwrite']) { $dropbox_overwrite = true; } // doing the upload $dropbox_filename = $_FILES['file']['name']; $dropbox_filesize = $_FILES['file']['size']; $dropbox_filetype = $_FILES['file']['type']; $dropbox_filetmpname = $_FILES['file']['tmp_name']; // check if the filesize does not exceed the allowed size. if ($dropbox_filesize <= 0 || $dropbox_filesize > $dropbox_cnf['maxFilesize']) { return get_lang('DropboxFileTooBig'); // TODO: The "too big" message does not fit in the case of uploading zero-sized file. } // check if the file is actually uploaded if (!is_uploaded_file($dropbox_filetmpname)) { // check user fraud : no clean error msg. return get_lang('TheFileIsNotUploaded'); } $upload_ok = process_uploaded_file($_FILES['file'], true); if (!$upload_ok) { return null; } // Try to add an extension to the file if it hasn't got one $dropbox_filename = add_ext_on_mime($dropbox_filename, $dropbox_filetype); // Replace dangerous characters $dropbox_filename = replace_dangerous_char($dropbox_filename); // Transform any .php file in .phps fo security $dropbox_filename = php2phps($dropbox_filename); //filter extension if (!filter_extension($dropbox_filename)) { return get_lang('UplUnableToSaveFileFilteredExtension'); } // set title $dropbox_title = $dropbox_filename; // set author if (!isset($_POST['authors'])) { $_POST['authors'] = getUserNameFromId($_user['user_id']); } // note: I think we could better migrate everything from here on to separate functions: store_new_dropbox, store_new_mailing, store_just_upload if ($dropbox_overwrite) { $dropbox_person = new Dropbox_Person($_user['user_id'], api_is_course_admin(), api_is_course_tutor()); foreach ($dropbox_person->sentWork as $w) { if ($w->title == $dropbox_filename) { if ($w->recipients[0]['id'] > dropbox_cnf('mailingIdBase') xor $thisIsAMailing) { return get_lang('MailingNonMailingError'); } if ($w->recipients[0]['id'] == $_user['user_id'] xor $thisIsJustUpload) { return get_lang('MailingJustUploadSelectNoOther'); } $dropbox_filename = $w->filename; $found = true; // note: do we still need this? break; } } } else { // rename file to login_filename_uniqueId format $dropbox_filename = getLoginFromId($_user['user_id']) . "_" . $dropbox_filename . "_" . uniqid(''); } // creating the array that contains all the users who will receive the file $new_work_recipients = array(); foreach ($_POST['recipients'] as $rec) { if (strpos($rec, 'user_') === 0) { $new_work_recipients[] = substr($rec, strlen('user_')); } elseif (strpos($rec, 'group_') === 0) { $userList = GroupManager::get_subscribed_users(substr($rec, strlen('group_'))); foreach ($userList as $usr) { if (!in_array($usr['user_id'], $new_work_recipients) && $usr['user_id'] != $_user['user_id']) { $new_work_recipients[] = $usr['user_id']; } } } } @move_uploaded_file($dropbox_filetmpname, dropbox_cnf('sysPath') . '/' . $dropbox_filename); $b_send_mail = api_get_course_setting('email_alert_on_new_doc_dropbox'); if ($b_send_mail) { foreach ($new_work_recipients as $recipient_id) { $recipent_temp = UserManager::get_user_info_by_id($recipient_id); $additionalParameters = array('smsType' => ClockworksmsPlugin::NEW_FILE_SHARED_COURSE_BY, 'userId' => $recipient_id, 'courseTitle' => $_course['title'], 'userUsername' => $recipent_temp['username']); api_mail_html(api_get_person_name($recipent_temp['firstname'] . ' ' . $recipent_temp['lastname'], null, PERSON_NAME_EMAIL_ADDRESS), $recipent_temp['email'], get_lang('NewDropboxFileUploaded'), get_lang('NewDropboxFileUploadedContent') . ' ' . api_get_path(WEB_CODE_PATH) . 'dropbox/index.php?cidReq=' . $_course['sysCode'] . "\n\n" . api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS) . "\n" . get_lang('Email') . " : " . $_user['mail'], api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS), $_user['mail'], null, null, null, $additionalParameters); } } new Dropbox_SentWork($_user['user_id'], $dropbox_title, $_POST['description'], strip_tags($_POST['authors']), $dropbox_filename, $dropbox_filesize, $new_work_recipients); Security::clear_token(); return get_lang('FileUploadSucces'); }
/** * Send a zip file for download, * * @param string name of the downloaded file (without extension) * @param * * @return boolean result of operation */ function sendZip($archiveName, $archiveContent, $removedPath) { // TODO find a better solution for removedPath if (!is_array($archiveContent) || empty($archiveContent)) { return false; } $downloadPlace = get_path('rootSys') . get_conf('tmpPathSys'); $downloadArchivePath = $downloadPlace . '' . uniqid('') . '.zip'; $downloadArchiveName = empty($archiveName) ? 'archive' : $archiveName; $downloadArchiveName = str_replace(',', '_', replace_dangerous_char($downloadArchiveName)); $downloadArchiveName = $downloadArchiveName . '.zip'; $downloadArchive = new PclZip($downloadArchivePath); $downloadArchive->add($archiveContent, PCLZIP_OPT_REMOVE_PATH, $removedPath); if (file_exists($downloadArchivePath)) { if (claro_send_file($downloadArchivePath, $downloadArchiveName)) { unlink($downloadArchivePath); return true; } else { unlink($downloadArchivePath); return false; } } else { return false; } }
function SanitizeFileName($sNewFileName, $sMimeType = null) { global $Config; if (empty($sMimeType)) { $sNewFileName = stripslashes($sNewFileName); } else { $sNewFileName = add_ext_on_mime(stripslashes($sNewFileName), $sMimeType); } // Replace dots in the name with underscores (only one dot can be there... security issue). if ($Config['ForceSingleExtension']) { $sNewFileName = preg_replace('/\\.(?![^.]*$)/', '_', $sNewFileName); } // Remove \ / | : ? * " < > //$sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ; $sNewFileName = replace_dangerous_char($sNewFileName, 'strict'); $sNewFileName = php2phps($sNewFileName); return $sNewFileName; }
/** * Executes all the necessary operation to upload the file in the document tool * * @author Hugues Peeters <*****@*****.**> * * @param array $uploadedFile - follows the $_FILES Structure * @param string $baseWorkDir - base working directory of the module * @param string $uploadPath - destination of the upload. * This path is to append to $baseWorkDir * @param int $maxFilledSpace - amount of bytes to not exceed in the base * working directory * @param string $uncompress - whether 'unzip' and file is a zip; * extract the content. * @param string $allowPHP - if set to true, then there is no security check for .php files (works for zip archives only) * @return boolean : true if it succeds, false otherwise */ function treat_uploaded_file($uploadedFile, $baseWorkDir, $uploadPath, $maxFilledSpace, $uncompress = '', $allowPHP = false) { if (file_upload_failed($uploadedFile)) { $failureStr = get_file_upload_error_message($uploadedFile); return claro_failure::set_failure($failureStr); } if (!enough_size($uploadedFile['size'], $baseWorkDir, $maxFilledSpace)) { return claro_failure::set_failure(get_lang('The upload has failed. There is not enough space in your directory')); } if ($uncompress == 'unzip' && preg_match('/.zip$/i', $uploadedFile['name'])) { return treat_secure_uploaded_file_unzip($uploadedFile, $uploadPath, $baseWorkDir, $maxFilledSpace, $allowPHP); } else { /* TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION */ $fileName = $uploadedFile['name'] . add_extension_for_uploaded_file($uploadedFile); $fileName = trim($uploadedFile['name']); /* CHECK FOR NO DESIRED CHARACTERS */ $fileName = replace_dangerous_char($fileName); /* HANDLE DANGEROUS FILE NAME FOR SERVER SECURITY */ $fileName = get_secure_file_name($fileName); /* COPY THE FILE TO THE DESIRED DESTINATION */ if (move_uploaded_file($uploadedFile['tmp_name'], $baseWorkDir . $uploadPath . '/' . $fileName)) { chmod($baseWorkDir . $uploadPath . '/' . $fileName, CLARO_FILE_PERMISSIONS); return $fileName; } else { return claro_failure::set_failure(get_lang('File upload failed')); } } }
$form->addElement('html', '</div>'); $form->addElement('checkbox', 'type1', null, get_lang('EnableExpiryDate'), array('id' => 'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option2').style.display='block';}else{document.getElementById('option2').style.display='none';}")); $form->addElement('html', '<div id="option2" style="display: none;">'); $form->addElement('advanced_settings', draw_date_picker('expires')); $form->addElement('html', '</div>'); $form->addElement('checkbox', 'type2', null, get_lang('EnableEndDate'), array('id' => 'make_calification_id', 'onclick' => "javascript: if(this.checked){document.getElementById('option3').style.display='block';}else{document.getElementById('option3').style.display='none';}")); $form->addElement('html', '<div id="option3" style="display: none;">'); $form->addElement('advanced_settings', draw_date_picker('ends')); $form->addElement('html', '</div>'); $form->addElement('checkbox', 'add_to_calendar', null, get_lang('AddToCalendar')); $form->addElement('checkbox', 'allow_text_assignment', null, get_lang('AllowTextAssignments')); $form->addElement('html', '</div>'); $form->addElement('style_submit_button', 'submit', get_lang('CreateDirectory')); if ($form->validate()) { $directory = Security::remove_XSS($_POST['new_dir']); $directory = replace_dangerous_char($directory); $directory = disable_dangerous_file($directory); $dir_name = $curdirpath . $directory; $created_dir = create_unexisting_work_directory($base_work_dir, $dir_name); // we insert here the directory in the table $work_table $dir_name_sql = ''; if (!empty($created_dir)) { if ($curdirpath == '/') { $dir_name_sql = $created_dir; } else { $dir_name_sql = '/' . $created_dir; } $time = time(); $today = api_get_utc_datetime($time); $sql_add_publication = "INSERT INTO " . $work_table . " SET\n c_id\t\t\t\t= {$course_id},\n url \t\t= '" . Database::escape_string($dir_name_sql) . "',\n title = '" . Database::escape_string($_POST['new_dir']) . "',\n description \t\t= '" . Database::escape_string($_POST['description']) . "',\n author \t\t= '',\n active = '1',\n accepted\t\t\t= '1',\n filetype = 'folder',\n post_group_id = '" . $group_id . "',\n sent_date = '" . $today . "',\n qualification = '" . ($_POST['qualification_value'] != '' ? Database::escape_string($_POST['qualification_value']) : '') . "',\n parent_id = '',\n qualificator_id = '',\n date_of_qualification\t= '0000-00-00 00:00:00',\n weight = '" . Database::escape_string($_POST['weight']) . "',\n session_id = '" . intval($id_session) . "',\n allow_text_assignment = '" . Database::escape_string($_POST['allow_text_assignment']) . "',\n contains_file = 0,\n user_id \t\t\t= '" . $user_id . "'"; Database::query($sql_add_publication);
$wamidir = $params['wamidir']; $wamiuserid = $params['wamiuserid']; } else { api_not_allowed(); die(); } if ($wamiuserid != api_get_user_id() || api_get_user_id() == 0 || $wamiuserid == 0) { api_not_allowed(); die(); } // Clean $waminame = Security::remove_XSS($waminame); $waminame = Database::escape_string($waminame); $waminame = replace_dangerous_char($waminame, 'strict'); $waminame = disable_dangerous_file($waminame); $wamidir = Security::remove_XSS($wamidir); $content = file_get_contents('php://input'); if (empty($content)) { exit; } $ext = explode('.', $waminame); $ext = strtolower($ext[sizeof($ext) - 1]); if ($ext != 'wav') { die(); }
/** * This function cleans up a given path * by eliminating dangerous file names and cleaning them * * @param string $path * @return $path * @see disable_dangerous_file() * @see replace_dangerous_char() */ function clean_up_path(&$path) { // Split the path in folders and files $path_array = explode('/', $path); // Clean up every foler and filename in the path foreach ($path_array as $key => &$val) { // We don't want to lose the dots in ././folder/file (cfr. zipfile) if ($val != '.') { $val = disable_dangerous_file(replace_dangerous_char($val)); } } // Join the "cleaned" path (modified in-place as passed by reference) $path = implode('/', $path_array); $res = filter_extension($path); return $res; }
function edit_assignment($id) { global $tool_content, $langBackAssignment, $langEditSuccess, $m, $langTheField, $langEditError, $course_code, $works_url, $course_id, $uid, $workPath, $langFormErrors; $v = new Valitron\Validator($_POST); $v->rule('required', array('title', 'max_grade')); $v->rule('numeric', array('max_grade')); $v->labels(array('title' => "{$langTheField} {$m['title']}", 'max_grade' => "{$langTheField} {$m['max_grade']}")); if ($v->validate()) { $row = Database::get()->querySingle("SELECT * FROM assignment WHERE id = ?d", $id); $title = $_POST['title']; $desc = purify($_POST['desc']); $deadline = trim($_POST['WorkEnd']) == FALSE ? '0000-00-00 00:00' : date('Y-m-d H:i', strtotime($_POST['WorkEnd'])); $late_submission = isset($_POST['late_submission']) && trim($_POST['WorkEnd']) != FALSE ? 1 : 0; $group_submissions = $_POST['group_submissions']; $max_grade = filter_input(INPUT_POST, 'max_grade', FILTER_VALIDATE_FLOAT); $assign_to_specific = filter_input(INPUT_POST, 'assign_to_specific', FILTER_VALIDATE_INT); $assigned_to = filter_input(INPUT_POST, 'ingroup', FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY); $auto_judge = filter_input(INPUT_POST, 'auto_judge', FILTER_VALIDATE_INT); $auto_judge_scenarios = serialize($_POST['auto_judge_scenarios']); $lang = filter_input(INPUT_POST, 'lang'); if ($assign_to_specific == 1 && empty($assigned_to)) { $assign_to_specific = 0; } if (!isset($_POST['comments'])) { $comments = ''; } else { $comments = purify($_POST['comments']); } if (!isset($_FILES) || !$_FILES['userfile']['size']) { $_FILES['userfile']['name'] = ''; $_FILES['userfile']['tmp_name'] = ''; $filename = $row->file_path; $file_name = $row->file_name; } else { validateUploadedFile($_FILES['userfile']['name'], 2); if (preg_match('/\\.(ade|adp|bas|bat|chm|cmd|com|cpl|crt|exe|hlp|hta|' . 'inf|ins|isp|jse|lnk|mdb|mde|msc|msi|msp|mst|pcd|pif|reg|scr|sct|shs|' . 'shb|url|vbe|vbs|wsc|wsf|wsh)$/', $_FILES['userfile']['name'])) { $tool_content .= "<p class=\"caution\">{$langUnwantedFiletype}: {$_FILES['userfile']['name']}<br />"; $tool_content .= "<a href=\"{$_SERVER['SCRIPT_NAME']}?course={$course_code}&id={$id}\">{$langBack}</a></p><br />"; return; } $local_name = uid_to_name($uid); $am = Database::get()->querySingle("SELECT am FROM user WHERE id = ?d", $uid)->am; if (!empty($am)) { $local_name .= $am; } $local_name = greek_to_latin($local_name); $local_name = replace_dangerous_char($local_name); $secret = $row->secret_directory; $ext = get_file_extension($_FILES['userfile']['name']); $filename = "{$secret}/{$local_name}" . (empty($ext) ? '' : '.' . $ext); if (move_uploaded_file($_FILES['userfile']['tmp_name'], "{$workPath}/admin_files/{$filename}")) { @chmod("{$workPath}/admin_files/{$filename}", 0644); $file_name = $_FILES['userfile']['name']; } } Database::get()->query("UPDATE assignment SET title = ?s, description = ?s, deadline = ?t, late_submission = ?d, comments = ?s,\n group_submissions = ?d, max_grade = ?d, assign_to_specific = ?d, file_path = ?s, file_name = ?s,\n auto_judge = ?d, auto_judge_scenarios = ?s, lang = ?s WHERE course_id = ?d AND id = ?d", $title, $desc, $deadline, $late_submission, $comments, $group_submissions, $max_grade, $assign_to_specific, $filename, $file_name, $auto_judge, $auto_judge_scenarios, $lang, $course_id, $id); Database::get()->query("DELETE FROM assignment_to_specific WHERE assignment_id = ?d", $id); if ($assign_to_specific && !empty($assigned_to)) { if ($group_submissions == 1) { $column = 'group_id'; $other_column = 'user_id'; } else { $column = 'user_id'; $other_column = 'group_id'; } foreach ($assigned_to as $assignee_id) { Database::get()->query("INSERT INTO assignment_to_specific ({$column}, {$other_column}, assignment_id) VALUES (?d, ?d, ?d)", $assignee_id, 0, $id); } } Log::record($course_id, MODULE_ID_ASSIGN, LOG_MODIFY, array('id' => $id, 'title' => $title, 'description' => $desc, 'deadline' => $deadline, 'group' => $group_submissions)); \Session::Messages($langEditSuccess, 'alert-success'); redirect_to_home_page("modules/work/index.php?course={$course_code}"); } else { // $new_or_modify = isset($_GET['NewExercise']) ? "&NewExercise=Yes" : "&exerciseId=$_GET[exerciseId]&modifyExercise=yes"; Session::flashPost()->Messages($langFormErrors)->Errors($v->errors()); redirect_to_home_page("modules/work/index.php?course={$course_code}&id={$id}&choice=edit"); } }
/** * Converts an html string to PDF * @param string $document_html valid html * @param string $css CSS content of a CSS file * @param string $pdf_name pdf name * @param string $course_code course code * (if you are using html that are located in the document tool you must provide this) * @return string Web path */ public function content_to_pdf( $document_html, $css = '', $pdf_name = '', $course_code = null ) { global $_configuration; if (empty($document_html)) { return false; } //clean styles and javascript document $clean_search = array ( '@<script[^>]*?>.*?</script>@si', '@<style[^>]*?>.*?</style>@siU' ); // Formatting the pdf $course_data = api_get_course_info($course_code); self::format_pdf($course_data); $document_html = preg_replace($clean_search, '', $document_html); //absolute path for frames.css //TODO: necessary? $absolute_css_path = api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css'; $document_html = str_replace('href="./css/frames.css"','href="'.$absolute_css_path.'"', $document_html); //$document_html=str_replace('<link rel="stylesheet" http://my.chamilo.net/main/css/chamilo/frames.css type="text/css" />','', $document_html); $document_html= str_replace('../../','',$document_html); $document_html= str_replace('../','',$document_html); $document_html= str_replace((empty($_configuration['url_append'])?'':$_configuration['url_append'].'/').'courses/'.$course_code.'/document/','',$document_html); if (!empty($course_data['path'])) { $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/'; $doc = new DOMDocument(); $result = @$doc->loadHTML($document_html); //Fixing only images @todo do the same thing with other elements $elements = $doc->getElementsByTagName('img'); if (!empty($elements)) { foreach ($elements as $item) { $old_src = $item->getAttribute('src'); //$old_src= str_replace('../','',$old_src); if (strpos($old_src, 'http') === false) { if (strpos($old_src, '/main/default_course_document') === false) { if (strpos($old_src, '/main/inc/lib/') === false) { $old_src_fixed = str_replace('/courses/'.$course_data['path'].'/document/', '', $old_src); $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src_fixed); $new_path = $document_path.$old_src_fixed; $document_html= str_replace($old_src, $new_path, $document_html); } } } } } } //replace relative path by absolute path for resources //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply //$document_html= str_replace('src="/', 'temp_template_path', $document_html);// before save src templates not apply //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply //$src_http_www= 'src="'.api_get_path(WEB_COURSE_PATH).$course_data['path'].'/document/'; //$document_html= str_replace('src="',$src_http_www, $document_html); //$document_html= str_replace('temp_template_path', 'src="/main/default_course_document/', $document_html);// restore src templates api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8'); // TODO: Maybe it is better idea the title to be passed through // $_GET[] too, as it is done with file name. // At the moment the title is retrieved from the html document itself. if (!empty($css)) { $this->pdf->WriteHTML($css, 1); } $this->pdf->WriteHTML($document_html, 2); if (empty($pdf_name)) { $output_file = 'pdf_'.date('Y-m-d-his').'.pdf'; } else { $pdf_name = replace_dangerous_char($pdf_name); $output_file = $pdf_name.'.pdf'; } $this->pdf->Output($output_file, 'D'); // F to save the pdf in a file exit; }
/** * Create a group * @param string $name The name for this group * @param int $category_id * @param int $tutor The user-id of the group's tutor * @param int $places How many people can subscribe to the new group */ public static function create_group($name, $category_id, $tutor, $places) { $_course = api_get_course_info(); $session_id = api_get_session_id(); $course_id = api_get_course_int_id(); $currentCourseRepository = $_course['path']; $category = self::get_category($category_id); $places = intval($places); if ($places == 0) { //if the amount of users per group is not filled in, use the setting from the category $places = $category['max_student']; } else { if ($places > $category['max_student'] && $category['max_student'] != 0) { $places = $category['max_student']; } } $table_group = Database::get_course_table(TABLE_GROUP); $sql = "INSERT INTO " . $table_group . " SET\n c_id = {$course_id} ,\n category_id='" . Database::escape_string($category_id) . "',\n max_student = '" . $places . "',\n doc_state = '" . $category['doc_state'] . "',\n calendar_state = '" . $category['calendar_state'] . "',\n work_state = '" . $category['work_state'] . "',\n announcements_state = '" . $category['announcements_state'] . "',\n forum_state = '" . $category['forum_state'] . "',\n wiki_state = '" . $category['wiki_state'] . "',\n chat_state = '" . $category['chat_state'] . "',\n self_registration_allowed = '" . $category['self_reg_allowed'] . "',\n self_unregistration_allowed = '" . $category['self_unreg_allowed'] . "',\n session_id='" . Database::escape_string($session_id) . "'"; Database::query($sql); $lastId = Database::insert_id(); if ($lastId) { $desired_dir_name = '/' . replace_dangerous_char($name, 'strict') . '_groupdocs'; $my_path = api_get_path(SYS_COURSE_PATH) . $currentCourseRepository . '/document'; $newFolderData = create_unexisting_directory($_course, api_get_user_id(), $session_id, $lastId, null, $my_path, $desired_dir_name, null, 1); $unique_name = $newFolderData['path']; /* Stores the directory path into the group table */ $sql = "UPDATE " . $table_group . " SET\n name = '" . Database::escape_string($name) . "',\n secret_directory = '" . $unique_name . "'\n WHERE c_id = {$course_id} AND id ='" . $lastId . "'"; Database::query($sql); // create a forum if needed if ($category['forum_state'] >= 0) { require_once api_get_path(SYS_CODE_PATH) . 'forum/forumconfig.inc.php'; require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php'; $forum_categories = get_forum_categories(); $values = array(); $values['forum_title'] = $name; $values['group_id'] = $lastId; $counter = 0; foreach ($forum_categories as $key => $value) { if ($counter == 0) { $forum_category_id = $key; } $counter++; } // A sanity check. if (empty($forum_category_id)) { $forum_category_id = 0; } $values['forum_category'] = $forum_category_id; $values['allow_anonymous_group']['allow_anonymous'] = 0; $values['students_can_edit_group']['students_can_edit'] = 0; $values['approval_direct_group']['approval_direct'] = 0; $values['allow_attachments_group']['allow_attachments'] = 1; $values['allow_new_threads_group']['allow_new_threads'] = 1; $values['default_view_type_group']['default_view_type'] = api_get_setting('default_forum_view'); $values['group_forum'] = $lastId; if ($category['forum_state'] == '1') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'public'; } elseif ($category['forum_state'] == '2') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'private'; } elseif ($category['forum_state'] == '0') { $values['public_private_group_forum_group']['public_private_group_forum'] = 'unavailable'; } store_forum($values); } } return $lastId; }
/** * Imports a zip file (presumably AICC) into the Dokeos structure * @param string Zip file info as given by $_FILES['userFile'] * @return string Absolute path to the AICC config files directory or empty string on error */ function import_package($zip_file_info, $current_dir = '') { if ($this->debug > 0) { error_log('In aicc::import_package(' . print_r($zip_file_info, true) . ',"' . $current_dir . '") method', 0); } //ini_set('error_log','E_ALL'); $maxFilledSpace = 1000000000; $zip_file_path = $zip_file_info['tmp_name']; $zip_file_name = $zip_file_info['name']; if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0); } $course_rel_dir = api_get_course_path() . '/scorm'; //scorm dir web path starting from /courses $course_sys_dir = api_get_path(SYS_COURSE_PATH) . $course_rel_dir; //absolute system path for this course $current_dir = replace_dangerous_char(trim($current_dir), 'strict'); //current dir we are in, inside scorm/ if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Current_dir = ' . $current_dir, 0); } //$uploaded_filename = $_FILES['userFile']['name']; //get name of the zip file without the extension if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Received zip file name: ' . $zip_file_path, 0); } $file_info = pathinfo($zip_file_name); $filename = $file_info['basename']; $extension = $file_info['extension']; $file_base_name = str_replace('.' . $extension, '', $filename); //filename without its extension $this->zipname = $file_base_name; //save for later in case we don't have a title if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Base file name is : ' . $file_base_name, 0); } $new_dir = replace_dangerous_char(trim($file_base_name), 'strict'); $this->subdir = $new_dir; if ($this->debug > 0) { error_log('New LP - aicc::import_package() - Subdir is first set to : ' . $this->subdir, 0); } /* if( check_name_exist($course_sys_dir.$current_dir."/".$new_dir) ) { $dialogBox = get_lang('FileExists'); $stopping_error = true; } */ $zipFile = new pclZip($zip_file_path); // Check the zip content (real size and file extension) $zipContentArray = $zipFile->listContent(); $package_type = ''; //the type of the package. Should be 'aicc' after the next few lines $package = ''; //the basename of the config files (if 'courses.crs' => 'courses') $at_root = false; //check if the config files are at zip root $config_dir = ''; //the directory in which the config files are. May remain empty $files_found = array(); $subdir_isset = false; //the following loop should be stopped as soon as we found the right config files (.crs, .au, .des and .cst) foreach ($zipContentArray as $thisContent) { if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) { //if a php file is found, do not authorize (security risk) if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found unauthorized file: ' . $thisContent['filename'], 0); } return api_failure::set_failure('php_file_in_zip_file'); } elseif (preg_match('?.*/aicc/$?', $thisContent['filename'])) { //if a directory named 'aicc' is found, package type = aicc, but continue //because we need to find the right AICC files if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found aicc directory: ' . $thisContent['filename'], 0); } $package_type = 'aicc'; } else { //else, look for one of the files we're searching for (something.crs case insensitive) $res = array(); if (preg_match('?^(.*)\\.(crs|au|des|cst|ore|pre|cmp)$?i', $thisContent['filename'], $res)) { if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found AICC config file: ' . $thisContent['filename'] . '. Now splitting: ' . $res[1] . ' and ' . $res[2], 0); } if ($thisContent['filename'] == basename($thisContent['filename'])) { if ($this->debug > 2) { error_log('New LP - aicc::import_package() - ' . $thisContent['filename'] . ' is at root level', 0); } $at_root = true; if (!is_array($files_found[$res[1]])) { $files_found[$res[1]] = $this->config_exts; //initialise list of expected extensions (defined in class definition) } $files_found[$res[1]][strtolower($res[2])] = $thisContent['filename']; $subdir_isset = true; } else { if (!$subdir_isset) { if (preg_match('?^.*/aicc$?i', dirname($thisContent['filename']))) { //echo "Cutting subdir<br/>"; $this->subdir .= '/' . substr(dirname($thisContent['filename']), 0, -5); } else { //echo "Not cutting subdir<br/>"; $this->subdir .= '/' . dirname($thisContent['filename']); } $subdir_isset = true; } if ($this->debug > 2) { error_log('New LP - aicc::import_package() - ' . $thisContent['filename'] . ' is not at root level - recording subdir ' . $this->subdir, 0); } $config_dir = dirname($thisContent['filename']); //just the relative directory inside scorm/ if (!is_array($files_found[basename($res[1])])) { $files_found[basename($res[1])] = $this->config_exts; } $files_found[basename($res[1])][strtolower($res[2])] = basename($thisContent['filename']); } $package_type = 'aicc'; } else { if ($this->debug > 3) { error_log('New LP - aicc::import_package() - File ' . $thisContent['filename'] . ' didnt match any check', 0); } } } $realFileSize += $thisContent['size']; } if ($this->debug > 2) { error_log('New LP - aicc::import_package() - $files_found: ' . print_r($files_found, true), 0); } if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Package type is now ' . $package_type, 0); } $mandatory = false; foreach ($files_found as $file_name => $file_exts) { $temp = (!empty($files_found[$file_name]['crs']) and !empty($files_found[$file_name]['au']) and !empty($files_found[$file_name]['des']) and !empty($files_found[$file_name]['cst'])); if ($temp) { if ($this->debug > 1) { error_log('New LP - aicc::import_package() - Found all config files for ' . $file_name, 0); } $mandatory = true; $package = $file_name; //store base config file name for reuse in parse_config_files() $this->config_basename = $file_name; //store filenames for reuse in parse_config_files() $this->config_files = $files_found[$file_name]; //get out, we only want one config files set break; } } if ($package_type == '' or $mandatory != true) { return api_failure::set_failure('not_aicc_content'); } if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) { return api_failure::set_failure('not_enough_space'); } // it happens on Linux that $new_dir sometimes doesn't start with '/' if ($new_dir[0] != '/') { $new_dir = '/' . $new_dir; } //cut trailing slash if ($new_dir[strlen($new_dir) - 1] == '/') { $new_dir = substr($new_dir, 0, -1); } /* -------------------------------------- Uncompressing phase -------------------------------------- */ /* We need to process each individual file in the zip archive to - add it to the database - parse & change relative html links - make sure the filenames are secure (filter funny characters or php extensions) */ if (is_dir($course_sys_dir . $new_dir) or @mkdir($course_sys_dir . $new_dir)) { // PHP method - slower... if ($this->debug >= 1) { error_log('New LP - Changing dir to ' . $course_sys_dir . $new_dir, 0); } $saved_dir = getcwd(); chdir($course_sys_dir . $new_dir); $unzippingState = $zipFile->extract(); for ($j = 0; $j < count($unzippingState); $j++) { $state = $unzippingState[$j]; //TODO fix relative links in html files (?) $extension = strrchr($state["stored_filename"], "."); //if($this->debug>1){error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'],0);} } if (!empty($new_dir)) { $new_dir = $new_dir . '/'; } //rename files, for example with \\ in it if ($dir = @opendir($course_sys_dir . $new_dir)) { if ($this->debug == 1) { error_log('New LP - Opened dir ' . $course_sys_dir . $new_dir, 0); } while ($file = readdir($dir)) { if ($file != '.' && $file != '..') { $filetype = "file"; if (is_dir($course_sys_dir . $new_dir . $file)) { $filetype = "folder"; } //TODO RENAMING FILES CAN BE VERY DANGEROUS AICC-WISE, avoid that as much as possible! //$safe_file=replace_dangerous_char($file,'strict'); $find_str = array('\\', '.php', '.phtml'); $repl_str = array('/', '.txt', '.txt'); $safe_file = str_replace($find_str, $repl_str, $file); if ($safe_file != $file) { //@rename($course_sys_dir.$new_dir,$course_sys_dir.'/'.$safe_file); $mydir = dirname($course_sys_dir . $new_dir . $safe_file); if (!is_dir($mydir)) { $mysubdirs = split('/', $mydir); $mybasedir = '/'; foreach ($mysubdirs as $mysubdir) { if (!empty($mysubdir)) { $mybasedir = $mybasedir . $mysubdir . '/'; if (!is_dir($mybasedir)) { @mkdir($mybasedir); if ($this->debug == 1) { error_log('New LP - Dir ' . $mybasedir . ' doesnt exist. Creating.', 0); } } } } } @rename($course_sys_dir . $new_dir . $file, $course_sys_dir . $new_dir . $safe_file); if ($this->debug == 1) { error_log('New LP - Renaming ' . $course_sys_dir . $new_dir . $file . ' to ' . $course_sys_dir . $new_dir . $safe_file, 0); } } //set_default_settings($course_sys_dir,$safe_file,$filetype); } } closedir($dir); chdir($saved_dir); } } else { return ''; } return $course_sys_dir . $new_dir . $config_dir; }
$dialogBox->error($message); $action = 'error'; } else { $wiki = $wikiStore->loadWiki($wikiId); $wikiTitle = $wiki->getTitle(); $renderer = new WikiToSingleHTMLExporter($wiki); $contents = $renderer->export(); if (0 != $groupId) { $groupPart = '_group' . (int) $groupId; } else { $groupPart = ''; } require_once get_conf('includePath') . '/lib/fileUpload.lib.php'; // TODO : use function wich return get_conf('coursesRepositorySys') . '/' . $_course['path'] $exportDir = get_conf('coursesRepositorySys') . '/' . claro_get_course_path() . '/document'; $exportFile = replace_dangerous_char($wikiTitle, 'strict') . $groupPart; $i = 1; while (file_exists($exportDir . '/' . $exportFile . '_' . $i . '.html')) { $i++; } $wikiFileName = $exportFile . '_' . $i . '.html'; $exportPath = $exportDir . '/' . $wikiFileName; file_put_contents($exportPath, $contents); } break; case 'exSearch': require_once "lib/class.wikisearchengine.php"; $pattern = isset($_REQUEST['searchPattern']) ? trim($_REQUEST['searchPattern']) : null; if (!empty($pattern)) { $searchEngine = new WikiSearchEngine($con, $config); $searchResult = $searchEngine->searchAllWiki($pattern, $groupId, CLWIKI_SEARCH_ANY);
/** * Create a new document //still needs some finetuning * * @param array $_course * @return string */ function create_document($_course) { 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 (!is_dir($filepath)) { $filepath = api_get_path('SYS_COURSE_PATH') . $_course['path'] . '/document/'; $dir = '/'; } //stripslashes before calling replace_dangerous_char() because $_POST['title'] //is already escaped twice when it gets here $tmp_title = stripslashes($_POST['title']); $title = 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(text_filter($content)); $content = str_replace(api_get_path('WEB_COURSE_PATH'), api_get_path(REL_PATH) . 'courses/', $content); // change the path of mp3 to absolute // first regexp deals with ../../../ urls $content = preg_replace("|(flashvars=\"file=)(\\.+/)+|", "\$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/', $content); //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_title . '.html'); 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()); //update parent folders //item_property_update_on_folder($_course, $_GET['dir'], $_user['user_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='" . $new_comment . "'"; } if ($new_title) { $ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset)) . ".html\t'"; } $sql_update = "\n\t\t\t\t\t\t\t\t\t\t\t\t\tUPDATE " . $tbl_doc . "\n\t\t\t\t\t\t\t\t\t\t\t\t\tSET " . substr($ct, 1) . "\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE id = " . $document_id; Database::query($sql_update, __FILE__, __LINE__); } } return $document_id; } } }
/** * Imports a zip file into the Chamilo structure * @param string $zip_file_info Zip file info as given by $_FILES['userFile'] * @return string $current_dir Absolute path to the imsmanifest.xml file or empty string on error */ public function import_package($zip_file_info, $current_dir = '') { if ($this->debug > 0) { error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); } $maxFilledSpace = DocumentManager :: get_course_quota(); $zip_file_path = $zip_file_info['tmp_name']; $zip_file_name = $zip_file_info['name']; if ($this->debug > 1) { error_log('New LP - import_package() - zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0); } $course_rel_dir = api_get_course_path().'/scorm'; // scorm dir web path starting from /courses $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // Absolute system path for this course. $current_dir = replace_dangerous_char(trim($current_dir),'strict'); // Current dir we are in, inside scorm/ if ($this->debug > 1) { error_log( 'New LP - import_package() - current_dir = ' . $current_dir, 0); } // Get name of the zip file without the extension. if ($this->debug > 1) { error_log('New LP - Received zip file name: '.$zip_file_path, 0); } $file_info = pathinfo($zip_file_name); $filename = $file_info['basename']; $extension = $file_info['extension']; $file_base_name = str_replace('.'.$extension,'',$filename); // Filename without its extension. $this->zipname = $file_base_name; // Save for later in case we don't have a title. if ($this->debug > 1) { error_log("New LP - base file name is : ".$file_base_name, 0); } $new_dir = replace_dangerous_char(trim($file_base_name),'strict'); $this->subdir = $new_dir; if ($this->debug > 1) { error_log("New LP - subdir is first set to : ".$this->subdir, 0); } $zipFile = new PclZip($zip_file_path); // Check the zip content (real size and file extension). $zipContentArray = $zipFile->listContent(); $package_type = ''; $at_root = false; $manifest = ''; $manifest_list = array(); // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?). $realFileSize = 0; foreach ($zipContentArray as $thisContent) { $thisContent['filename']; if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) { $file = $thisContent['filename']; $this->set_error_msg("File $file contains a PHP script"); } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) { //error_log('Found imsmanifest at '.$thisContent['filename'], 0); if ($thisContent['filename'] == basename($thisContent['filename'])) { $at_root = true; } else { if ($this->debug > 2) { error_log("New LP - subdir is now ".$this->subdir, 0); } } $package_type = 'scorm'; $manifest_list[] = $thisContent['filename']; $manifest = $thisContent['filename']; //just the relative directory inside scorm/ } else { // Do nothing, if it has not been set as scorm somewhere else, it stays as '' default. } $realFileSize += $thisContent['size']; } // Now get the shortest path (basically, the imsmanifest that is the closest to the root). $shortest_path = $manifest_list[0]; $slash_count = substr_count($shortest_path, '/'); foreach ($manifest_list as $manifest_path) { $tmp_slash_count = substr_count($manifest_path, '/'); if ($tmp_slash_count<$slash_count) { $shortest_path = $manifest_path; $slash_count = $tmp_slash_count; } } $this->subdir .= '/'.dirname($shortest_path); // Do not concatenate because already done above. $manifest = $shortest_path; if ($this->debug > 1) { error_log('New LP - Package type is now '.$package_type, 0); } if ($package_type== '') { // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM) if ($this->debug > 1) { error_log('New LP - Package type is empty', 0); } return api_failure::set_failure('not_scorm_content'); } if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) { if ($this->debug > 1) { error_log('New LP - Not enough space to store package', 0); } return api_failure::set_failure('not_enough_space'); } // It happens on Linux that $new_dir sometimes doesn't start with '/' if ($new_dir[0] != '/') { $new_dir = '/'.$new_dir; } if ($new_dir[strlen($new_dir)-1] == '/') { $new_dir = substr($new_dir,0,-1); } /* Uncompressing phase */ /* We need to process each individual file in the zip archive to - add it to the database - parse & change relative html links - make sure the filenames are secure (filter funny characters or php extensions) */ if (is_dir($course_sys_dir.$new_dir) OR @mkdir($course_sys_dir.$new_dir, api_get_permissions_for_new_directories()) ) { // PHP method - slower... if ($this->debug >= 1) { error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0); } $saved_dir = getcwd(); chdir($course_sys_dir.$new_dir); $unzippingState = $zipFile->extract(); for ($j = 0; $j < count($unzippingState); $j++) { $state = $unzippingState[$j]; // TODO: Fix relative links in html files (?) $extension = strrchr($state['stored_filename'], '.'); if ($this->debug >= 1) { error_log('New LP - found extension '.$extension.' in '.$state['stored_filename'], 0); } } if (!empty($new_dir)) { $new_dir = $new_dir.'/'; } // Rename files, for example with \\ in it. if ($this->debug >= 1) { error_log('New LP - try to open: '.$course_sys_dir.$new_dir, 0); } if ($dir = @opendir($course_sys_dir.$new_dir)) { if ($this->debug >= 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); } while ($file = readdir($dir)) { if ($file != '.' && $file != '..') { $filetype = 'file'; if (is_dir($course_sys_dir . $new_dir . $file)) { $filetype = 'folder'; } // TODO: RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible! //$safe_file = replace_dangerous_char($file, 'strict'); $find_str = array('\\', '.php', '.phtml'); $repl_str = array('/', '.txt', '.txt'); $safe_file = str_replace($find_str, $repl_str, $file); if ($this->debug >= 1) { error_log('Comparing: '.$safe_file, 0); } if ($this->debug >= 1) { error_log('and: '.$file, 0); } if ($safe_file != $file) { $mydir = dirname($course_sys_dir.$new_dir.$safe_file); if (!is_dir($mydir)) { $mysubdirs = explode('/', $mydir); $mybasedir = '/'; foreach ($mysubdirs as $mysubdir) { if (!empty($mysubdir)) { $mybasedir = $mybasedir.$mysubdir.'/'; if (!is_dir($mybasedir)) { @mkdir($mybasedir, api_get_permissions_for_new_directories()); if ($this->debug >= 1) { error_log('New LP - Dir '.$mybasedir.' doesnt exist. Creating.', 0); } } } } } @rename($course_sys_dir.$new_dir.$file,$course_sys_dir.$new_dir.$safe_file); if ($this->debug >= 1) { error_log('New LP - Renaming '.$course_sys_dir.$new_dir.$file.' to '.$course_sys_dir.$new_dir.$safe_file, 0); } } } } closedir($dir); chdir($saved_dir); api_chmod_R($course_sys_dir.$new_dir, api_get_permissions_for_new_directories()); if ($this->debug > 1) { error_log('New LP - changed back to init dir: '.$course_sys_dir.$new_dir, 0); } } } else { return ''; } return $course_sys_dir.$new_dir.$manifest; }
/** * Set header parameters */ private function set_header_parameters() { global $httpHeadXtra, $_course, $interbreadcrumb, $language_file, $noPHP_SELF, $_configuration, $this_section; $help = $this->help; $nameTools = $this->title; $navigation = return_navigation_array(); $this->menu_navigation = $navigation['menu_navigation']; $this->assign('system_charset', api_get_system_encoding()); if (isset($httpHeadXtra) && $httpHeadXtra) { foreach ($httpHeadXtra as & $thisHttpHead) { header($thisHttpHead); } } $this->assign('online_button', Display::return_icon('online.png')); $this->assign('offline_button',Display::return_icon('offline.png')); // Get language iso-code for this page - ignore errors $this->assign('document_language', api_get_language_isocode()); $course_title = isset($_course['name']) ? $_course['name'] : null; $title_list = array(); $title_list[] = api_get_setting('Institution'); $title_list[] = api_get_setting('siteName'); if (!empty($course_title)) { $title_list[] = $course_title; } if ($nameTools != '') { $title_list[] = $nameTools; } $title_string = ''; for ($i = 0; $i < count($title_list); $i++) { $title_string .= $title_list[$i]; if (isset($title_list[$i + 1])) { $item = trim($title_list[$i + 1]); if (!empty($item)) { $title_string .= ' - '; } } } $this->assign('title_string', $title_string); //Setting the theme and CSS files $this->set_css_files(); $this->set_js_files(); //$this->set_js_files_post(); $browser = api_browser_support('check_browser'); if ($browser[0] == 'Internet Explorer' && $browser[1] >= '11') { $browser_head = '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />'; $this->assign('browser_specific_head', $browser_head); } // Implementation of prefetch. // See http://cdn.chamilo.org/main/img/online.png for details $prefetch = ''; if (!empty($_configuration['cdn_enable'])) { $prefetch .= '<meta http-equiv="x-dns-prefetch-control" content="on">'; foreach ($_configuration['cdn'] as $host => $exts) { $prefetch .= '<link rel="dns-prefetch" href="'.$host.'">'; } } $this->assign('prefetch', $prefetch); $this->assign('text_direction', api_get_text_direction()); $this->assign('section_name', 'section-'.$this_section); $favico = '<link rel="shortcut icon" href="'.api_get_path(WEB_PATH).'favicon.ico" type="image/x-icon" />'; if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url_info = api_get_access_url($access_url_id); $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url'])); $clean_url = replace_dangerous_char($url); $clean_url = str_replace('/', '-', $clean_url); $clean_url .= '/'; $homep = api_get_path(REL_PATH).'home/'.$clean_url; //homep for Home Path $icon_real_homep = api_get_path(SYS_PATH).'home/'.$clean_url; //we create the new dir for the new sites if (is_file($icon_real_homep.'favicon.ico')) { $favico = '<link rel="shortcut icon" href="'.$homep.'favicon.ico" type="image/x-icon" />'; } } } $this->assign('favico', $favico); $this->set_help(); //@todo move this in the template $bug_notification_link = ''; if (api_get_setting('show_link_bug_notification') == 'true' && $this->user_is_logged_in) { $bug_notification_link = '<li class="report"> <a href="http://support.chamilo.org/projects/chamilo-18/wiki/How_to_report_bugs" target="_blank"> <img src="'.api_get_path(WEB_IMG_PATH).'bug.large.png" style="vertical-align: middle;" alt="'.get_lang('ReportABug').'" title="'.get_lang( 'ReportABug' ).'"/></a> </li>'; } $this->assign('bug_notification_link', $bug_notification_link); $notification = return_notification_menu(); $this->assign('notification_menu', $notification); //Preparing values for the menu //Logout link if (isset($_configuration['hide_logout_button']) && $_configuration['hide_logout_button'] == 'true') { $this->assign('logout_link', null); } else { $this->assign('logout_link', api_get_path(WEB_PATH).'index.php?logout=logout&uid='.api_get_user_id()); } //Profile link if (api_get_setting('allow_social_tool') == 'true') { $profile_url = api_get_path(WEB_CODE_PATH).'social/home.php'; $profile_link = Display::url(get_lang('Profile'), $profile_url); } else { $profile_url = api_get_path(WEB_CODE_PATH).'auth/profile.php'; $profile_link = Display::url(get_lang('Profile'), $profile_url); } $this->assign('profile_link', $profile_link); $this->assign('profile_url', $profile_url); //Message link $message_link = null; $message_url = null; if (api_get_setting('allow_message_tool') == 'true') { $message_url = api_get_path(WEB_CODE_PATH).'messages/inbox.php'; $message_link = '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.get_lang('Inbox').'</a>'; } $this->assign('message_link', $message_link); $this->assign('message_url', $message_url); $institution = api_get_setting('Institution'); $portal_name = empty($institution) ? api_get_setting('siteName') : $institution; $this->assign('portal_name', $portal_name); //Menu $menu = return_menu(); $this->assign('menu', $menu); //Setting notifications $count_unread_message = 0; if (api_get_setting('allow_message_tool') == 'true') { // get count unread message and total invitations $count_unread_message = MessageManager::get_number_of_messages(true); } $total_invitations = 0; if (api_get_setting('allow_social_tool') == 'true') { $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id( api_get_user_id() ); $group_pending_invitations = GroupPortalManager::get_groups_by_user( api_get_user_id(), GROUP_USER_PERMISSION_PENDING_INVITATION, false ); $group_pending_invitations = 0; if (!empty($group_pending_invitations)) { $group_pending_invitations = count($group_pending_invitations); } $total_invitations = intval($number_of_new_messages_of_friend) + $group_pending_invitations + intval( $count_unread_message ); } $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : null); $this->assign('user_notifications', $total_invitations); //Breadcrumb $breadcrumb = return_breadcrumb($interbreadcrumb, $language_file, $nameTools); $this->assign('breadcrumb', $breadcrumb); //Extra content $extra_header = null; if (!api_is_platform_admin()) { $extra_header = trim(api_get_setting('header_extra_content')); } $this->assign('header_extra_content', $extra_header); //if ($this->show_header == 1) { header('Content-Type: text/html; charset='.api_get_system_encoding()); header( 'X-Powered-By: '.$_configuration['software_name'].' '.substr($_configuration['system_version'], 0, 1) ); //} }
$dialogBox->form($form); } // end if cmd == rqEdit /*= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CREATE DIRECTORY = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */ /* * The code begin with STEP 2 * so it allows to return to STEP 1 * if STEP 2 unsucceds */ /*------------------------------------------------------------------------ STEP 2 ------------------------------------------------------------------------*/ if ('exMkDir' == $cmd) { $newDirName = replace_dangerous_char(trim($_REQUEST['newName'])); $cwd = secure_file_path($cwd); if (check_name_exist($baseWorkDir . $cwd . '/' . $newDirName)) { $dialogBox->error(get_lang('A file with this name already exists.')); $cmd = 'rqMkDir'; } else { claro_mkdir($baseWorkDir . $cwd . '/' . $newDirName, CLARO_FILE_PERMISSIONS); $comment = isset($_REQUEST['comment']) ? trim($_REQUEST['comment']) : ''; if (!empty($comment) && $courseContext) { update_db_info('update', $cwd . '/' . $newDirName, array('comment' => $comment)); } $dialogBox->success(get_lang("Directory created")); $eventNotifier->notifyCourseEvent("document_file_added", claro_get_current_course_id(), claro_get_current_tool_id(), $cwd . '/' . $newDirName, claro_get_current_group_id(), "0"); } } /*------------------------------------------------------------------------