Esempio n. 1
0
 /**
  * This function serves exporting data in CSV format.
  * @param array $header         The header labels.
  * @param array $data           The data array.
  * @param string $file_name     The name of the file which contains exported data.
  * @return string mixed             Returns a message (string) if an error occurred.
  */
 function export_csv($header, $data, $file_name = 'export.csv')
 {
     $archive_path = api_get_path(SYS_ARCHIVE_PATH);
     $archive_url = api_get_path(WEB_CODE_PATH) . 'course_info/download.php?archive=';
     if (!($open = fopen($archive_path . $file_name, 'w+'))) {
         $message = get_lang('noOpen');
     } else {
         $info = '';
         foreach ($header as $value) {
             $info .= $value . ';';
         }
         $info .= "\r\n";
         foreach ($data as $row) {
             foreach ($row as $value) {
                 $info .= $value . ';';
             }
             $info .= "\r\n";
         }
         fwrite($open, $info);
         fclose($open);
         @chmod($file_name, api_get_permissions_for_new_files());
         header("Location:" . $archive_url . $file_name);
     }
     return $message;
 }
/**
 * Function to convert from ppt to png
 * This function is used from Chamilo Rapid Lesson
 *
 * @param array $pptData
 * @return string
 */
function wsConvertPpt($pptData)
{
    $fileData = $pptData['file_data'];
    $dataInfo = pathinfo($pptData['file_name']);
    $fileName = basename($pptData['file_name'], '.' . $dataInfo['extension']);
    $fullFileName = $pptData['file_name'];
    $tempArchivePath = api_get_path(SYS_ARCHIVE_PATH);
    $tempPath = $tempArchivePath . 'wsConvert/' . $fileName . '/';
    $tempPathNewFiles = $tempArchivePath . 'wsConvert/' . $fileName . '-n/';
    $perms = api_get_permissions_for_new_directories();
    if (!is_dir($tempPath)) {
        mkdir($tempPath, $perms, true);
    }
    if (!is_dir($tempPathNewFiles)) {
        mkdir($tempPathNewFiles, $perms, true);
    }
    if (!is_dir($tempPathNewFiles . $fileName)) {
        mkdir($tempPathNewFiles . $fileName, $perms, true);
    }
    $file = base64_decode($fileData);
    file_put_contents($tempPath . $fullFileName, $file);
    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 -cp "' . $classPath . '" DokeosConverter';
    } else {
        $converterPath = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png';
        $classPath = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.2.jar:jodconverter-cli-2.2.2.jar';
        $cmd = 'cd ' . $converterPath . ' && java ' . $classPath . ' DokeosConverter';
    }
    $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port');
    $cmd .= ' -w 720 -h 540 -d oogie "' . $tempPath . $fullFileName . '"  "' . $tempPathNewFiles . $fileName . '.html"';
    $perms = api_get_permissions_for_new_files();
    chmod($tempPathNewFiles . $fileName, $perms, true);
    $files = array();
    $return = 0;
    $shell = exec($cmd, $files, $return);
    if ($return === 0) {
        $images = array();
        foreach ($files as $file) {
            $imageData = explode('||', $file);
            $images[$imageData[1]] = base64_encode(file_get_contents($tempPathNewFiles . $fileName . '/' . $imageData[1]));
        }
        $data = array('files' => $files, 'images' => $images);
        deleteDirectory($tempPath);
        deleteDirectory($tempPathNewFiles);
        return serialize($data);
    } else {
        deleteDirectory($tempPath);
        deleteDirectory($tempPathNewFiles);
        return false;
    }
}
Esempio n. 3
0
 $content = Security::remove_XSS($values['content'], COURSEMANAGERLOWSECURITY);
 if (strpos($content, '/css/frames.css') === false) {
     $content = str_replace('</head>', '<style> body{margin:10px;}</style><link rel="stylesheet" href="./css/frames.css" type="text/css" /></head>', $content);
 }
 if ($fp = @fopen($filepath . $filename . '.' . $extension, 'w')) {
     $content = str_replace(api_get_path(WEB_COURSE_PATH), $_configuration['url_append'] . '/courses/', $content);
     // change the path of mp3 to absolute
     // first regexp deals with ../../../ urls
     // Disabled by Ivan Tcholakov.
     //$content = preg_replace("|(flashvars=\"file=)(\.+/)+|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',$content);
     //second regexp deals with audio/ urls
     // Disabled by Ivan Tcholakov.
     //$content = preg_replace("|(flashvars=\"file=)([^/]+)/|","$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',$content);
     fputs($fp, $content);
     fclose($fp);
     chmod($filepath . $filename . '.' . $extension, api_get_permissions_for_new_files());
     if (!is_dir($filepath . 'css')) {
         mkdir($filepath . 'css', api_get_permissions_for_new_directories());
         $doc_id = FileManager::add_document($_course, $dir . 'css', 'folder', 0, 'css');
         api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_user['user_id'], null, null, null, null, $current_session_id);
         api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], 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_CSS_PATH) . 'themes/' . api_get_setting('stylesheets') . '/frames.css', $filepath . 'css/frames.css');
         $doc_id = FileManager::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', $_user['user_id'], null, null, null, null, $current_session_id);
         api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_user['user_id'], null, null, null, null, $current_session_id);
     }
     $file_size = filesize($filepath . $filename . '.' . $extension);
     $save_file_path = $dir . $filename . '.' . $extension;
 /**
  * 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;
 }
Esempio n. 5
0
 /**
  * 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);
     }
 }
Esempio n. 6
0
/**
 * This function displays the requirements for installing Chamilo.
 *
 * @param string $installType
 * @param boolean $badUpdatePath
 * @param boolean $badUpdatePath
 * @param string $updatePath The updatePath given (if given)
 * @param array $update_from_version_8 The different subversions from version 1.9
 *
 * @author unknow
 * @author Patrick Cool <*****@*****.**>, Ghent University
 */
function display_requirements($installType, $badUpdatePath, $updatePath = '', $update_from_version_8 = array())
{
    global $_setting;
    echo '<div class="RequirementHeading"><h2>' . display_step_sequence() . get_lang('Requirements') . "</h2></div>";
    echo '<div class="RequirementText">';
    echo '<strong>' . get_lang('ReadThoroughly') . '</strong><br />';
    echo get_lang('MoreDetails') . ' <a href="../../documentation/installation_guide.html" target="_blank">' . get_lang('ReadTheInstallationGuide') . '</a>.<br />' . "\n";
    if ($installType == 'update') {
        echo get_lang('IfYouPlanToUpgradeFromOlderVersionYouMightWantToHaveAlookAtTheChangelog') . '<br />';
    }
    echo '</div>';
    //  SERVER REQUIREMENTS
    echo '<div class="RequirementHeading"><h4>' . get_lang('ServerRequirements') . '</h4>';
    $timezone = checkPhpSettingExists("date.timezone");
    if (!$timezone) {
        echo "<div class='warning-message'>" . Display::return_icon('warning.png', get_lang('Warning'), '', ICON_SIZE_MEDIUM) . get_lang("DateTimezoneSettingNotSet") . "</div>";
    }
    echo '<div class="RequirementText">' . get_lang('ServerRequirementsInfo') . '</div>';
    echo '<div class="RequirementContent">';
    echo '<table class="table">
            <tr>
                <td class="requirements-item">' . get_lang('PHPVersion') . ' >= ' . REQUIRED_PHP_VERSION . '</td>
                <td class="requirements-value">';
    if (phpversion() < REQUIRED_PHP_VERSION) {
        echo '<strong><font color="red">' . get_lang('PHPVersionError') . '</font></strong>';
    } else {
        echo '<strong><font color="green">' . get_lang('PHPVersionOK') . ' ' . phpversion() . '</font></strong>';
    }
    echo '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('session', get_lang('Yes'), get_lang('ExtensionSessionsNotAvailable')) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.mysql.php" target="_blank">MySQL</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('mysql', get_lang('Yes'), get_lang('ExtensionMySQLNotAvailable')) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('zlib', get_lang('Yes'), get_lang('ExtensionZlibNotAvailable')) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('pcre', get_lang('Yes'), get_lang('ExtensionPCRENotAvailable')) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('xml', get_lang('Yes'), get_lang('No')) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('intl', get_lang('Yes'), get_lang('No')) . '</td>
            </tr>
               <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('json', get_lang('Yes'), get_lang('No')) . '</td>
            </tr>

             <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> ' . get_lang('support') . '</td>
                <td class="requirements-value">' . checkExtension('gd', get_lang('Yes'), get_lang('ExtensionGDNotAvailable')) . '</td>
            </tr>

            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> ' . get_lang('support') . ' (' . get_lang('Optional') . ')</td>
                <td class="requirements-value">' . checkExtension('mbstring', get_lang('Yes'), get_lang('ExtensionMBStringNotAvailable'), true) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> ' . get_lang('support') . ' (' . get_lang('Optional') . ')</td>
                <td class="requirements-value">' . checkExtension('iconv', get_lang('Yes'), get_lang('No'), true) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> ' . get_lang('support') . ' (' . get_lang('Optional') . ')</td>
                <td class="requirements-value">' . checkExtension('ldap', get_lang('Yes'), get_lang('ExtensionLDAPNotAvailable'), true) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> ' . get_lang('support') . ' (' . get_lang('Optional') . ')</td>
                <td class="requirements-value">' . checkExtension('xapian', get_lang('Yes'), get_lang('No'), true) . '</td>
            </tr>

            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a> ' . get_lang('support') . ' (' . get_lang('Optional') . ')</td>
                <td class="requirements-value">' . checkExtension('curl', get_lang('Yes'), get_lang('No'), true) . '</td>
            </tr>

          </table>';
    echo '  </div>';
    echo '</div>';
    // RECOMMENDED SETTINGS
    // Note: these are the settings for Joomla, does this also apply for Chamilo?
    // Note: also add upload_max_filesize here so that large uploads are possible
    echo '<div class="RequirementHeading"><h4>' . get_lang('RecommendedSettings') . '</h4>';
    echo '<div class="RequirementText">' . get_lang('RecommendedSettingsInfo') . '</div>';
    echo '<div class="RequirementContent">';
    echo '<table class="table">
            <tr>
                <th>' . get_lang('Setting') . '</th>
                <th>' . get_lang('Recommended') . '</th>
                <th>' . get_lang('Actual') . '</th>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/features.safe-mode.php">Safe Mode</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('safe_mode', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('display_errors', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
                <td class="requirements-recommended">' . Display::label('ON', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('file_uploads', 'ON') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-gpc">Magic Quotes GPC</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('magic_quotes_gpc', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-runtime">Magic Quotes Runtime</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('magic_quotes_runtime', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/security.globals.php">Register Globals</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('register_globals', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('session.auto_start', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
                <td class="requirements-recommended">' . Display::label('OFF', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('short_open_tag', 'OFF') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">Cookie HTTP Only</a></td>
                <td class="requirements-recommended">' . Display::label('ON', 'success') . '</td>
                <td class="requirements-value">' . checkPhpSetting('session.cookie_httponly', 'ON') . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
                <td class="requirements-recommended">' . Display::label('>= ' . REQUIRED_MIN_UPLOAD_MAX_FILESIZE . 'M', 'success') . '</td>
                <td class="requirements-value">' . compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
                <td class="requirements-recommended">' . Display::label('>= ' . REQUIRED_MIN_POST_MAX_SIZE . 'M', 'success') . '</td>
                <td class="requirements-value">' . compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE) . '</td>
            </tr>
            <tr>
                <td class="requirements-item"><a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">Memory Limit</a></td>
                <td class="requirements-recommended">' . Display::label('>= ' . REQUIRED_MIN_MEMORY_LIMIT . 'M', 'success') . '</td>
                <td class="requirements-value">' . compare_setting_values(ini_get('memory_limit'), REQUIRED_MIN_MEMORY_LIMIT) . '</td>
            </tr>
          </table>';
    echo '  </div>';
    echo '</div>';
    // DIRECTORY AND FILE PERMISSIONS
    echo '<div class="RequirementHeading"><h4>' . get_lang('DirectoryAndFilePermissions') . '</h4>';
    echo '<div class="RequirementText">' . get_lang('DirectoryAndFilePermissionsInfo') . '</div>';
    echo '<div class="RequirementContent">';
    $course_attempt_name = '__XxTestxX__';
    $course_dir = api_get_path(SYS_COURSE_PATH) . $course_attempt_name;
    //Just in case
    @unlink($course_dir . '/test.php');
    @rmdir($course_dir);
    $perms_dir = array(0777, 0755, 0775, 0770, 0750, 0700);
    $perms_fil = array(0666, 0644, 0664, 0660, 0640, 0600);
    $course_test_was_created = false;
    $dir_perm_verified = 0777;
    foreach ($perms_dir as $perm) {
        $r = @mkdir($course_dir, $perm);
        if ($r === true) {
            $dir_perm_verified = $perm;
            $course_test_was_created = true;
            break;
        }
    }
    $fil_perm_verified = 0666;
    $file_course_test_was_created = false;
    if (is_dir($course_dir)) {
        foreach ($perms_fil as $perm) {
            if ($file_course_test_was_created == true) {
                break;
            }
            $r = @touch($course_dir . '/test.php', $perm);
            if ($r === true) {
                $fil_perm_verified = $perm;
                if (check_course_script_interpretation($course_dir, $course_attempt_name, 'test.php')) {
                    $file_course_test_was_created = true;
                }
            }
        }
    }
    @unlink($course_dir . '/test.php');
    @rmdir($course_dir);
    $_SESSION['permissions_for_new_directories'] = $_setting['permissions_for_new_directories'] = $dir_perm_verified;
    $_SESSION['permissions_for_new_files'] = $_setting['permissions_for_new_files'] = $fil_perm_verified;
    $dir_perm = Display::label('0' . decoct($dir_perm_verified), 'info');
    $file_perm = Display::label('0' . decoct($fil_perm_verified), 'info');
    $courseTestLabel = Display::label(get_lang('No'), 'important');
    if ($course_test_was_created && $file_course_test_was_created) {
        $courseTestLabel = Display::label(get_lang('Yes'), 'success');
    }
    if ($course_test_was_created && !$file_course_test_was_created) {
        $courseTestLabel = Display::label(sprintf(get_lang('InstallWarningCouldNotInterpretPHP'), api_get_path(WEB_COURSE_PATH) . $course_attempt_name . '/test.php'), 'warning');
    }
    if (!$course_test_was_created && !$file_course_test_was_created) {
        $courseTestLabel = Display::label(get_lang('No'), 'important');
    }
    $oldConf = '';
    if (file_exists(api_get_path(SYS_CODE_PATH) . 'inc/conf/configuration.php')) {
        $oldConf = '<tr>
            <td class="requirements-item">' . api_get_path(SYS_CODE_PATH) . 'inc/conf</td>
            <td class="requirements-value">' . check_writable(api_get_path(SYS_CODE_PATH) . 'inc/conf') . '</td>
        </tr>';
    }
    echo '<table class="table">
            ' . $oldConf . '
            <tr>
                <td class="requirements-item">' . api_get_path(SYS_APP_PATH) . '</td>
                <td class="requirements-value">' . check_writable(api_get_path(SYS_APP_PATH)) . '</td>
            </tr>
            <tr>
                <td class="requirements-item">' . api_get_path(SYS_CODE_PATH) . 'default_course_document/images/</td>
                <td class="requirements-value">' . check_writable(api_get_path(SYS_CODE_PATH) . 'default_course_document/images/') . '</td>
            </tr>
            <tr>
                <td class="requirements-item">' . api_get_path(SYS_CODE_PATH) . 'lang/</td>
                <td class="requirements-value">' . check_writable(api_get_path(SYS_CODE_PATH) . 'lang/', true) . ' <br />(' . get_lang('SuggestionOnlyToEnableSubLanguageFeature') . ')</td>
            </tr>
            <tr>
                <td class="requirements-item">' . api_get_path(SYS_PATH) . 'vendor/</td>
                <td class="requirements-value">' . checkReadable(api_get_path(SYS_PATH) . 'vendor') . '</td>
            </tr>
            <tr>
                <td class="requirements-item">' . api_get_path(SYS_PUBLIC_PATH) . '</td>
                <td class="requirements-value">' . check_writable(api_get_path(SYS_PUBLIC_PATH)) . '</td>
            </tr>
            <tr>
                <td class="requirements-item">' . get_lang('CourseTestWasCreated') . '</td>
                <td class="requirements-value">' . $courseTestLabel . ' </td>
            </tr>
            <tr>
                <td class="requirements-item">' . get_lang('PermissionsForNewDirs') . '</td>
                <td class="requirements-value">' . $dir_perm . ' </td>
            </tr>
            <tr>
                <td class="requirements-item">' . get_lang('PermissionsForNewFiles') . '</td>
                <td class="requirements-value">' . $file_perm . ' </td>
            </tr>
            ';
    echo '    </table>';
    echo '  </div>';
    echo '</div>';
    if ($installType == 'update' && (empty($updatePath) || $badUpdatePath)) {
        if ($badUpdatePath) {
            ?>
            <div class="alert alert-warning">
                <?php 
            echo get_lang('Error');
            ?>
!<br />
                Chamilo <?php 
            echo implode('|', $update_from_version_8) . ' ' . get_lang('HasNotBeenFoundInThatDir');
            ?>
.
            </div>
        <?php 
        } else {
            echo '<br />';
        }
        ?>
            <div class="row">
                <div class="col-md-12">
                    <p><?php 
        echo get_lang('OldVersionRootPath');
        ?>
:
                        <input type="text" name="updatePath" size="50" value="<?php 
        echo $badUpdatePath && !empty($updatePath) ? htmlentities($updatePath) : api_get_path(SYS_SERVER_ROOT_PATH) . 'old_version/';
        ?>
" />
                    </p>
                    <p>
                        <button type="submit" class="btn btn-default" name="step1" value="<?php 
        echo get_lang('Back');
        ?>
" >
                            <i class="fa fa-backward"> <?php 
        echo get_lang('Back');
        ?>
</i>
                        </button>
                        <input type="hidden" name="is_executable" id="is_executable" value="-" />
                        <button type="submit" class="btn btn-success" name="<?php 
        echo isset($_POST['step2_update_6']) ? 'step2_update_6' : 'step2_update_8';
        ?>
" value="<?php 
        echo get_lang('Next');
        ?>
 &gt;" >
                            <i class="fa fa-forward"> </i> <?php 
        echo get_lang('Next');
        ?>
                        </button>
                    </p>
                </div>
            </div>

        <?php 
    } else {
        $error = false;
        // First, attempt to set writing permissions if we don't have them yet
        $perm = api_get_permissions_for_new_directories();
        $perm_file = api_get_permissions_for_new_files();
        $notWritable = array();
        $checked_writable = api_get_path(SYS_APP_PATH);
        if (!is_writable($checked_writable)) {
            $notWritable[] = $checked_writable;
            @chmod($checked_writable, $perm);
        }
        $checked_writable = api_get_path(SYS_PUBLIC_PATH);
        if (!is_writable($checked_writable)) {
            $notWritable[] = $checked_writable;
            @chmod($checked_writable, $perm);
        }
        $checked_writable = api_get_path(SYS_CODE_PATH) . 'default_course_document/images/';
        if (!is_writable($checked_writable)) {
            $notWritable[] = $checked_writable;
            @chmod($checked_writable, $perm);
        }
        if ($course_test_was_created == false) {
            $error = true;
        }
        $checked_writable = api_get_path(CONFIGURATION_PATH) . 'configuration.php';
        if (file_exists($checked_writable) && !is_writable($checked_writable)) {
            $notWritable[] = $checked_writable;
            @chmod($checked_writable, $perm_file);
        }
        // Second, if this fails, report an error
        //--> The user would have to adjust the permissions manually
        if (count($notWritable) > 0) {
            $error = true;
            echo '<div class="error-message">';
            echo '<center><h3>' . get_lang('Warning') . '</h3></center>';
            printf(get_lang('NoWritePermissionPleaseReadInstallGuide'), '</font>
                <a href="../../documentation/installation_guide.html" target="blank">', '</a> <font color="red">');
            echo '</div>';
            echo '<ul>';
            foreach ($notWritable as $value) {
                echo '<li>' . $value . '</li>';
            }
            echo '</ul>';
        } elseif (file_exists(api_get_path(CONFIGURATION_PATH) . 'configuration.php')) {
            // Check wether a Chamilo configuration file already exists.
            echo '<div class="alert alert-warning"><h4><center>';
            echo get_lang('WarningExistingLMSInstallationDetected');
            echo '</center></h4></div>';
        }
        // And now display the choice buttons (go back or install)
        ?>
        <p align="center" style="padding-top:15px">
        <button type="submit" name="step1" class="btn btn-default" onclick="javascript: window.location='index.php'; return false;" value="<?php 
        echo get_lang('Previous');
        ?>
" >
            <i class="fa fa-backward"> </i> <?php 
        echo get_lang('Previous');
        ?>
        </button>
        <button type="submit" name="step2_install" class="btn btn-success" value="<?php 
        echo get_lang("NewInstallation");
        ?>
" <?php 
        if ($error) {
            echo 'disabled="disabled"';
        }
        ?>
 >
            <i class="fa fa-forward"> </i> <?php 
        echo get_lang('NewInstallation');
        ?>
        </button>
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
        <?php 
        // Real code
        echo '<button type="submit" class="btn btn-default" name="step2_update_8" value="Upgrade from Chamilo 1.9.x"';
        if ($error) {
            echo ' disabled="disabled"';
        }
        echo ' ><i class="fa fa-forward"> </i> ' . get_lang('UpgradeFromLMS19x') . '</button>';
        echo '</p>';
    }
}
 /**
  * Fills the course database with some required content and example content.
  * @param int Course (int) ID
  * @param string Course directory name (e.g. 'ABC')
  * @param string Language used for content (e.g. 'spanish')
  * @param bool Whether to fill the course with example content
  * @return bool False on error, true otherwise
  * @version 1.2
  * @assert (null, '', '', null) === false
  * @assert (1, 'ABC', null, null) === false
  * @assert (1, 'TEST', 'spanish', true) === true
  */
 public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
 {
     if (is_null($fill_with_exemplary_content)) {
         $fill_with_exemplary_content = api_get_setting('course.example_material_course_creation') != 'false';
     }
     $course_id = intval($course_id);
     if (empty($course_id)) {
         return false;
     }
     $entityManager = Database::getManager();
     $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
     $tools = array();
     $settingsManager = CourseManager::getCourseSettingsManager();
     $settingsManager->setCourse($course);
     $toolList = CourseManager::getToolList();
     $toolList = $toolList->getTools();
     /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
     foreach ($toolList as $tool) {
         $visibility = self::string2binary(api_get_setting_in_list('course.active_tools_on_create', $tool->getName()));
         $toolObject = new CTool();
         $toolObject->setName($tool->getName())->setCategory($tool->getCategory())->setLink($tool->getLink())->setImage($tool->getImage())->setVisibility($visibility)->setAdmin(0)->setTarget($tool->getTarget());
         $tools[] = $toolObject;
         $settings = $settingsManager->loadSettings($tool->getName());
         $settingsManager->saveSettings($tool->getName(), $settings);
     }
     $course->setTools($tools);
     $entityManager->persist($course);
     $entityManager->flush($course);
     $courseInfo = api_get_course_info_by_id($course_id);
     $now = api_get_utc_datetime(time());
     $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
     $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
     $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
     $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
     $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
     $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
     $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
     $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
     $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
     $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
     $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $visible_for_all = 1;
     $visible_for_course_admin = 0;
     $visible_for_platform_admin = 2;
     /*    Course tools  */
     $alert = api_get_setting('exercise.email_alert_manager_on_new_quiz');
     if ($alert === 'true') {
         $defaultEmailExerciseAlert = 1;
     } else {
         $defaultEmailExerciseAlert = 0;
     }
     /* course_setting table (courseinfo tool)   */
     $settings = ['email_alert_manager_on_new_doc' => ['default' => 0, 'category' => 'work'], 'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'], 'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'], 'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'], 'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'], 'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'], 'course_theme' => ['default' => '', 'category' => 'theme'], 'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'], 'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'], 'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'], 'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'], 'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'], 'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'], 'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'], 'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'], 'allow_public_certificates' => ['default' => api_get_setting('course.allow_public_certificates') === 'true' ? 1 : '', 'category' => 'certificates'], 'documents_default_visibility' => ['default' => 'visible', 'category' => 'document']];
     /*$counter = 1;
       foreach ($settings as $variable => $setting) {
           Database::query(
               "INSERT INTO $TABLESETTING (id, c_id, variable, value, category)
                VALUES ($counter, $course_id, '".$variable."', '".$setting['default']."', '".$setting['category']."')"
           );
           $counter++;
       }*/
     /* Course homepage tools for platform admin only */
     /* Group tool */
     Database::query("INSERT INTO {$TABLEGROUPCATEGORIES}  (c_id, id, title , description, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)\n             VALUES ({$course_id}, '2', '" . self::lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
     /*    Example Material  */
     $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('language.platform_language');
     // Example material should be in the same language as the course is.
     $language_interface_original = $language_interface;
     $now = api_get_utc_datetime();
     $files = [['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0], ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0]];
     $counter = 1;
     foreach ($files as $file) {
         self::insertDocument($course_id, $counter, $file);
         $counter++;
     }
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
     if (!is_dir($chat_path)) {
         @mkdir($chat_path, api_get_permissions_for_new_directories());
     }
     /*    Documents   */
     if ($fill_with_exemplary_content) {
         $files = [['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0], ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0], ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0], ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0], ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0], ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0]];
         foreach ($files as $file) {
             self::insertDocument($course_id, $counter, $file);
             $counter++;
         }
         // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
         $folders_to_copy_from_default_course = array('images', 'audio', 'flash', 'video', 'certificates');
         $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document/';
         $default_document_array = array();
         foreach ($folders_to_copy_from_default_course as $folder) {
             $default_course_folder_path = $default_course_path . $folder . '/';
             $files = self::browse_folders($default_course_folder_path, array(), $folder);
             $sorted_array = self::sort_pictures($files, 'dir');
             $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
             $default_document_array[$folder] = $sorted_array;
         }
         //Light protection (adding index.html in every document folder)
         $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
         $example_cert_id = 0;
         if (is_array($default_document_array) && count($default_document_array) > 0) {
             foreach ($default_document_array as $media_type => $array_media) {
                 $path_documents = "/{$media_type}/";
                 //hack until feature #5242 is implemented
                 if ($media_type == 'images') {
                     $media_type = 'images/gallery';
                     $images_folder = $sys_course_path . $course_repository . "/document/images/";
                     if (!is_dir($images_folder)) {
                         //Creating index.html
                         mkdir($images_folder, $perm);
                         $fd = fopen($images_folder . 'index.html', 'w');
                         fwrite($fd, $htmlpage);
                         @chmod($images_folder . 'index.html', $perm_file);
                     }
                 }
                 $course_documents_folder = $sys_course_path . $course_repository . "/document/{$media_type}/";
                 $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document' . $path_documents;
                 if (!is_dir($course_documents_folder)) {
                     // Creating index.html
                     mkdir($course_documents_folder, $perm);
                     $fd = fopen($course_documents_folder . 'index.html', 'w');
                     fwrite($fd, $htmlpage);
                     @chmod($course_documents_folder . 'index.html', $perm_file);
                 }
                 if (is_array($array_media) && count($array_media) > 0) {
                     foreach ($array_media as $key => $value) {
                         if (isset($value['dir']) && !empty($value['dir'])) {
                             if (!is_dir($course_documents_folder . $value['dir'])) {
                                 //Creating folder
                                 mkdir($course_documents_folder . $value['dir'], $perm);
                                 //Creating index.html (for light protection)
                                 $index_html = $course_documents_folder . $value['dir'] . '/index.html';
                                 $fd = fopen($index_html, 'w');
                                 fwrite($fd, $htmlpage);
                                 @chmod($index_html, $perm_file);
                                 //Inserting folder in the DB
                                 $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
                                 $temp = explode('/', $folder_path);
                                 $title = $temp[count($temp) - 1];
                                 //hack until feature #5242 is implemented
                                 if ($title == 'gallery') {
                                     $title = get_lang('DefaultCourseImages');
                                 }
                                 if ($media_type == 'images/gallery') {
                                     $folder_path = 'gallery/' . $folder_path;
                                 }
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $folder_path . "','" . $title . "','folder','0')");
                                 $image_id = Database::insert_id();
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                        VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,0)");
                             }
                         }
                         if (isset($value['file']) && !empty($value['file'])) {
                             if (!file_exists($course_documents_folder . $value['file'])) {
                                 //Copying file
                                 copy($default_course_path . $value['file'], $course_documents_folder . $value['file']);
                                 chmod($course_documents_folder . $value['file'], $perm_file);
                                 //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
                                 $temp = explode('/', $value['file']);
                                 $file_size = filesize($course_documents_folder . $value['file']);
                                 //hack until feature #5242 is implemented
                                 if ($media_type == 'images/gallery') {
                                     $value["file"] = 'gallery/' . $value["file"];
                                 }
                                 //Inserting file in the DB
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','{$file_size}')");
                                 $image_id = Database::insert_id();
                                 if ($image_id) {
                                     $sql = "UPDATE {$TABLETOOLDOCUMENT} SET id = iid WHERE iid = {$image_id}";
                                     Database::query($sql);
                                     if ($path_documents . $value['file'] == '/certificates/default.html') {
                                         $example_cert_id = $image_id;
                                     }
                                     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                            VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,1)");
                                     $docId = Database::insert_id();
                                     if ($docId) {
                                         $sql = "UPDATE {$TABLEITEMPROPERTY} SET id = iid WHERE iid = {$docId}";
                                         Database::query($sql);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $agenda = new Agenda();
         $agenda->setType('course');
         $agenda->set_course($courseInfo);
         $agenda->addEvent($now, $now, 0, get_lang('AgendaCreationTitle'), get_lang('AgendaCreationContenu'));
         /*  Links tool */
         $link = new Link();
         $link->setCourse($courseInfo);
         $links = [['c_id' => $course_id, 'url' => 'http://www.google.com', 'title' => 'Google', 'description' => get_lang('Google'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0], ['c_id' => $course_id, 'url' => 'http://www.wikipedia.org', 'title' => 'Wikipedia', 'description' => get_lang('Wikipedia'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0]];
         foreach ($links as $params) {
             $link->save($params);
         }
         /* Announcement tool */
         AnnouncementManager::add_announcement(get_lang('AnnouncementExampleTitle'), get_lang('AnnouncementEx'), ['everyone' => 'everyone'], null, null, $now);
         $manager = Database::getManager();
         /* Introduction text */
         $intro_text = '<p style="text-align: center;">
                         <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
                         <h2>' . self::lang2db(get_lang('IntroductionText')) . '</h2>
                      </p>';
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_COURSE_HOMEPAGE)->setSessionId(0)->setIntroText($intro_text);
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_STUDENTPUBLICATION)->setSessionId(0)->setIntroText(get_lang('IntroductionTwo'));
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_WIKI)->setSessionId(0)->setIntroText(get_lang('IntroductionWiki'));
         $manager->persist($toolIntro);
         $manager->flush();
         /*  Exercise tool */
         $exercise = new Exercise($course_id);
         $exercise->exercise = get_lang('ExerciceEx');
         $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
                     <tr>
                     <td width="110" valign="top" align="left">
                         <img src="' . api_get_path(WEB_CODE_PATH) . 'default_course_document/images/mr_dokeos/thinking.jpg">
                     </td>
                     <td valign="top" align="left">' . get_lang('Antique') . '</td></tr>
                 </table>';
         $exercise->type = 1;
         $exercise->setRandom(0);
         $exercise->active = 1;
         $exercise->results_disabled = 0;
         $exercise->description = $html;
         $exercise->save();
         $exercise_id = $exercise->id;
         $question = new MultipleAnswer();
         $question->question = get_lang('SocraticIrony');
         $question->description = get_lang('ManyAnswers');
         $question->weighting = 10;
         $question->position = 1;
         $question->course = $courseInfo;
         $question->save($exercise_id);
         $questionId = $question->id;
         $answer = new Answer($questionId, $courseInfo['real_id']);
         $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
         $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
         $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
         $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
         $answer->save();
         /* Forum tool */
         require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php';
         $params = ['forum_category_title' => get_lang('ExampleForumCategory'), 'forum_category_comment' => ''];
         $forumCategoryId = store_forumcategory($params, $courseInfo, false);
         $params = ['forum_category' => $forumCategoryId, 'forum_title' => get_lang('ExampleForum'), 'forum_comment' => '', 'default_view_type_group' => ['default_view_type' => 'flat']];
         $forumId = store_forum($params, $courseInfo, true);
         $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
         $params = ['post_title' => get_lang('ExampleThread'), 'forum_id' => $forumId, 'post_text' => get_lang('ExampleThreadContent'), 'calification_notebook_title' => '', 'numeric_calification' => '', 'weight_calification' => '', 'forum_category' => $forumCategoryId, 'thread_peer_qualify' => 0];
         store_thread($forumInfo, $params, $courseInfo, false);
         /* Gradebook tool */
         $course_code = $courseInfo['code'];
         // father gradebook
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',0,100,0,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',{$gbid},100,1,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOKLINK} (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked)\n                VALUES (1,{$exercise_id},1,'{$course_code}',{$gbid},'{$now}',100,1,0)");
     }
     //Installing plugins in course
     $app_plugin = new AppPlugin();
     $app_plugin->install_course_plugins($course_id);
     $language_interface = $language_interface_original;
     return true;
 }
Esempio n. 8
0
 /**
  * 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);
     }
 }
Esempio n. 9
0
/**
 * This function does the save-work for the documents.
 * It handles the uploaded file and adds the properties to the database
 * If unzip=1 and the file is a zipfile, it is extracted
 * If we decide to save ALL kinds of documents in one database,
 * we could extend this with a $type='document', 'scormdocument',...
 *
 * @param array $courseInfo
 * @param array $uploadedFile ($_FILES)
 * array(
 *  'name' => 'picture.jpg',
 *  'tmp_name' => '...', // absolute path
 * );
 * @param string $documentDir Example: /var/www/chamilo/courses/ABC/document
 * @param string $uploadPath Example: /folder1/folder2/
 * @param int $userId
 * @param int $groupId, 0 for everybody
 * @param int $toUserId, NULL for everybody
 * @param int $unzip 1/0
 * @param string $whatIfFileExists overwrite, rename or warn if exists (default)
 * @param boolean $output Optional output parameter.
 * @param bool $onlyUploadFile
 * @param string $comment
 * @param int $sessionId
 *
 * So far only use for unzip_uploaded_document function.
 * If no output wanted on success, set to false.
 * @param string $comment
 * @return string path of the saved file
 */
function handle_uploaded_document($courseInfo, $uploadedFile, $documentDir, $uploadPath, $userId, $groupId = 0, $toUserId = null, $unzip = 0, $whatIfFileExists = '', $output = true, $onlyUploadFile = false, $comment = null, $sessionId = null)
{
    if (!$userId) {
        return false;
    }
    $userInfo = api_get_user_info();
    $uploadedFile['name'] = stripslashes($uploadedFile['name']);
    // Add extension to files without one (if possible)
    $uploadedFile['name'] = add_ext_on_mime($uploadedFile['name'], $uploadedFile['type']);
    if (empty($sessionId)) {
        $sessionId = api_get_session_id();
    } else {
        $sessionId = intval($sessionId);
    }
    // Just in case process_uploaded_file is not called
    $maxSpace = DocumentManager::get_course_quota();
    // Check if there is enough space to save the file
    if (!DocumentManager::enough_space($uploadedFile['size'], $maxSpace)) {
        if ($output) {
            Display::display_error_message(get_lang('UplNotEnoughSpace'));
        }
        return false;
    }
    // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
    if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
        return unzip_uploaded_document($courseInfo, $userInfo, $uploadedFile, $uploadPath, $documentDir, $maxSpace, $sessionId, $groupId, $output);
    } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
        // We can only unzip ZIP files (no gz, tar,...)
        if ($output) {
            Display::display_error_message(get_lang('UplNotAZip') . " " . get_lang('PleaseTryAgain'));
        }
        return false;
    } else {
        // Clean up the name, only ASCII characters should stay. (and strict)
        $cleanName = api_replace_dangerous_char($uploadedFile['name'], 'strict');
        // No "dangerous" files
        $cleanName = disable_dangerous_file($cleanName);
        // Checking file extension
        if (!filter_extension($cleanName)) {
            if ($output) {
                Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
            }
            return false;
        } else {
            // If the upload path differs from / (= root) it will need a slash at the end
            if ($uploadPath != '/') {
                $uploadPath = $uploadPath . '/';
            }
            // Full path to where we want to store the file with trailing slash
            $whereToSave = $documentDir . $uploadPath;
            // At least if the directory doesn't exist, tell so
            if (!is_dir($whereToSave)) {
                if (!mkdir($whereToSave, api_get_permissions_for_new_directories())) {
                    if ($output) {
                        Display::display_error_message(get_lang('DestDirectoryDoesntExist') . ' (' . $uploadPath . ')');
                    }
                    return false;
                }
            }
            // Just upload the file "as is"
            if ($onlyUploadFile) {
                $errorResult = moveUploadedFile($uploadedFile, $whereToSave . $cleanName);
                if ($errorResult) {
                    return $whereToSave . $cleanName;
                } else {
                    return $errorResult;
                }
            }
            /*
                Based in the clean name we generate a new filesystem name
                Using the session_id and group_id if values are not empty
            */
            /*$fileExists = DocumentManager::documentExists(
                  $uploadPath.$cleanName,
                  $courseInfo,
                  $sessionId,
                  $groupId
              );*/
            $fileSystemName = DocumentManager::fixDocumentName($cleanName, 'file', $courseInfo, $sessionId, $groupId);
            // Name of the document without the extension (for the title)
            $documentTitle = get_document_title($uploadedFile['name']);
            // Size of the uploaded file (in bytes)
            $fileSize = $uploadedFile['size'];
            // File permissions
            $filePermissions = api_get_permissions_for_new_files();
            // Example: /var/www/chamilo/courses/xxx/document/folder/picture.jpg
            $fullPath = $whereToSave . $fileSystemName;
            // Example: /folder/picture.jpg
            $filePath = $uploadPath . $fileSystemName;
            $docId = DocumentManager::get_document_id($courseInfo, $filePath, $sessionId);
            $documentList = DocumentManager::getDocumentByPathInCourse($courseInfo, $filePath);
            // This means that the path already exists in this course.
            if (!empty($documentList) && $whatIfFileExists != 'overwrite') {
                //$found = false;
                // Checking if we are talking about the same course + session
                /*foreach ($documentList as $document) {
                      if ($document['session_id'] == $sessionId) {
                          $found = true;
                          break;
                      }
                  }*/
                //if ($found == false) {
                $whatIfFileExists = 'rename';
                //}
            }
            // What to do if the target file exists
            switch ($whatIfFileExists) {
                // Overwrite the file if it exists
                case 'overwrite':
                    // Check if the target file exists, so we can give another message
                    $fileExists = file_exists($fullPath);
                    if (moveUploadedFile($uploadedFile, $fullPath)) {
                        chmod($fullPath, $filePermissions);
                        if ($fileExists && $docId) {
                            // UPDATE DATABASE
                            $documentId = DocumentManager::get_document_id($courseInfo, $filePath);
                            if (is_numeric($documentId)) {
                                // Update file size
                                update_existing_document($courseInfo, $documentId, $uploadedFile['size']);
                                // Update document item_property
                                api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentUpdated', $userId, $groupId, $toUserId, null, null, $sessionId);
                                // Redo visibility
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                            } else {
                                // There might be cases where the file exists on disk but there is no registration of that in the database
                                // In this case, and if we are in overwrite mode, overwrite and create the db record
                                $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                                if ($documentId) {
                                    // Put the document in item_property update
                                    api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                                    // Redo visibility
                                    api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                                }
                            }
                            // If the file is in a folder, we need to update all parent folders
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                            // Display success message with extra info to user
                            if ($output) {
                                Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle . ' ' . get_lang('UplFileOverwritten'), false);
                            }
                            return $filePath;
                        } else {
                            // Put the document data in the database
                            $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                            if ($documentId) {
                                // Put the document in item_property update
                                api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                                // Redo visibility
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                            }
                            // If the file is in a folder, we need to update all parent folders
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                            // Display success message to user
                            if ($output) {
                                Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle, false);
                            }
                            return $filePath;
                        }
                    } else {
                        if ($output) {
                            Display::display_error_message(get_lang('UplUnableToSaveFile'));
                        }
                        return false;
                    }
                    break;
                    // Rename the file if it exists
                // Rename the file if it exists
                case 'rename':
                    // Always rename.
                    $cleanName = DocumentManager::getUniqueFileName($uploadPath, $cleanName, $courseInfo, $sessionId, $groupId);
                    $fileSystemName = DocumentManager::fixDocumentName($cleanName, 'file', $courseInfo, $sessionId, $groupId);
                    $documentTitle = get_document_title($cleanName);
                    $fullPath = $whereToSave . $fileSystemName;
                    $filePath = $uploadPath . $fileSystemName;
                    if (moveUploadedFile($uploadedFile, $fullPath)) {
                        chmod($fullPath, $filePermissions);
                        // Put the document data in the database
                        $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                        if ($documentId) {
                            // Update document item_property
                            api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                            // Redo visibility
                            api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                        }
                        // If the file is in a folder, we need to update all parent folders
                        item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                        // Display success message to user
                        if ($output) {
                            Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') . ' ' . $documentTitle, false);
                        }
                        return $filePath;
                    } else {
                        if ($output) {
                            Display::display_error_message(get_lang('UplUnableToSaveFile'));
                        }
                        return false;
                    }
                    break;
                default:
                    // Only save the file if it doesn't exist or warn user if it does exist
                    if (file_exists($fullPath) && $docId) {
                        if ($output) {
                            Display::display_error_message($cleanName . ' ' . get_lang('UplAlreadyExists'));
                        }
                    } else {
                        if (moveUploadedFile($uploadedFile, $fullPath)) {
                            chmod($fullPath, $filePermissions);
                            // Put the document data in the database
                            $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                            if ($documentId) {
                                // Update document item_property
                                api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                                // Redo visibility
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                            }
                            // If the file is in a folder, we need to update all parent folders
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                            // Display success message to user
                            if ($output) {
                                Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle, false);
                            }
                            return $filePath;
                        } else {
                            if ($output) {
                                Display::display_error_message(get_lang('UplUnableToSaveFile'));
                            }
                            return false;
                        }
                    }
                    break;
            }
        }
    }
}
Esempio n. 10
0
     </div>
       </div>
       </div>';
 // Push the web server to send these strings before we start the real
 // installation process
 flush();
 $f = ob_get_contents();
 if (!empty($f)) {
     ob_flush();
     //#5565
 }
 if ($installType == 'update') {
     remove_memory_and_time_limits();
     $manager = connectToDatabase($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm, $dbPortForm);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     error_log('Starting migration process from ' . $my_old_version . ' (' . time() . ')');
     switch ($my_old_version) {
         case '1.9.0':
         case '1.9.2':
         case '1.9.4':
         case '1.9.6':
         case '1.9.6.1':
         case '1.9.8':
         case '1.9.8.1':
         case '1.9.8.2':
         case '1.9.10':
         case '1.9.10.2':
             // Fix type "enum" before running the migration with Doctrine
             Database::query("ALTER TABLE course_category MODIFY COLUMN auth_course_child VARCHAR(40) DEFAULT 'TRUE'");
             Database::query("ALTER TABLE course_category MODIFY COLUMN auth_cat_child VARCHAR(40) DEFAULT 'TRUE'");
Esempio n. 11
0
 /**
  * Fills the course database with some required content and example content.
  */
 public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
 {
     if (is_null($fill_with_exemplary_content)) {
         $fill_with_exemplary_content = api_get_setting('example_material_course_creation') != 'false';
     }
     $course_id = intval($course_id);
     if (empty($course_id)) {
         return false;
     }
     $now = api_get_utc_datetime(time());
     $toolTable = Database::get_course_table(TABLE_TOOL_LIST);
     $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
     $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
     $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
     $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
     $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
     $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
     $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
     $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
     $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
     $visible_for_all = 1;
     $visible_for_course_admin = 0;
     $visible_for_platform_admin = 2;
     // Move this in a doctrine listener
     $toolList = self::getToolList();
     $toolList = $toolList->getTools();
     /** @var Course $course */
     $entityManager = Database::getManager();
     $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
     // @todo move in a manager.
     /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
     $tools = array();
     $settingsManager = self::getCourseSettingsManager();
     $settingsManager->setCourse($course);
     foreach ($toolList as $tool) {
         $visibility = Text::string2binary(api_get_setting('course.course_create_active_tools', $tool->getName()));
         $toolObject = new CTool();
         $toolObject->setName($tool->getName())->setCategory($tool->getCategory())->setLink($tool->getLink())->setImage($tool->getImage())->setVisibility($visibility)->setAdmin(0)->setTarget($tool->getTarget());
         $tools[] = $toolObject;
         $settings = $settingsManager->loadSettings($tool->getName());
         $settingsManager->saveSettings($tool->getName(), $settings);
     }
     $course->setTools($tools);
     $entityManager->persist($course);
     $entityManager->flush($course);
     /*    Course tools  */
     /*if (api_get_setting('service_visio', 'active') == 'true') {
           $mycheck = api_get_setting('service_visio', 'visio_host');
           if (!empty($mycheck)) {
               //Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '" . TOOL_VISIO_CONFERENCE . "','conference/index.php?type=conference','visio_meeting.gif','1','0','squaregrey.gif','NO','_self','interaction','0', '', '')");
               //Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '" . TOOL_VISIO_CLASSROOM . "','conference/index.php?type=classroom','visio.gif','1','0','squaregrey.gif','NO','_self','authoring','0', '', '')");
           }
       }*/
     /*if (api_get_setting('search_enabled') == 'true') {
           //Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '" . TOOL_SEARCH. "','search/','info.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'enable_search')) . "','0','search.gif','NO','_self','authoring','0', '', '')");
       }*/
     // Blogs (Kevin Van Den Haute :: kevin@develop-it.be)
     /*$sql = "INSERT INTO $toolTable VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . Text::string2binary(api_get_setting('course_create_active_tools', 'blogs')) . "','1','squaregrey.gif','NO','_self','admin','0', '', '')";
       Database::query($sql);*/
     /*  Course homepage tools for course admin only    */
     /*        Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '".TOOL_TRACKING . "','tracking/courseLog.php','statistics.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0', '', '')");
             Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '".TOOL_COURSE_SETTING . "','course_info/infocours.php','reference.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0', '', '')");
             Database::query("INSERT INTO $toolTable VALUES ($course_id, NULL, '".TOOL_COURSE_MAINTENANCE."','course_info/maintenance.php','backup.gif','$visible_for_course_admin','1','','NO','_self', 'admin','0', '', '')");*/
     /* Course_setting table (courseinfo tool)   */
     /*Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_doc',0,'work')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_on_new_doc_dropbox',0,'dropbox')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_agenda',0,'agenda')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_announcement',0,'announcement')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_quiz',1,'quiz')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_image_forum',1,'forum')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'course_theme','','theme')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_learning_path_theme','1','theme')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_open_chat_window',1,'chat')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_to_teacher_on_new_user_in_course',0,'registration')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_view_user_list',1,'user')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'display_info_advance_inside_homecourse',1,'thematic_advance')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_students_on_new_homework',0,'work')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_lp_auto_launch',0,'learning_path')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'pdf_export_watermark_text','','learning_path')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_public_certificates','','certificates')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_fast_exercise_edition', 0 ,'exercise')");
       Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_exercise_auto_launch', 0 ,'exercise')");*/
     /* Course homepage tools for platform admin only */
     /* Group tool */
     Database::query("INSERT INTO {$TABLEGROUPCATEGORIES}  (c_id,  id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order )\n                VALUES ({$course_id}, '2', '" . Database::escape_string(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
     /*    Example Material  */
     $language_interface = Container::getTranslator()->getLocale();
     // Example material should be in the same language as the course is.
     $language_interface_original = $language_interface;
     $language_interface = $language;
     //Share folder
     Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/shared_folder','" . get_lang('UserFolders') . "','folder','0')");
     $example_doc_id = Database::insert_id();
     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                         VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
     //Chat folder
     Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/chat_files','" . get_lang('ChatFiles') . "','folder','0')");
     $example_doc_id = Database::insert_id();
     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
     if (!is_dir($chat_path)) {
         @mkdir($chat_path, api_get_permissions_for_new_directories());
     }
     /*    Documents   */
     if ($fill_with_exemplary_content) {
         Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id,path,title,filetype,size) VALUES ({$course_id},'/images','" . get_lang('Images') . "','folder','0')");
         $example_doc_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
         Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/images/gallery','" . get_lang('DefaultCourseImages') . "','folder','0')");
         $example_doc_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
         Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/audio','" . get_lang('Audio') . "','folder','0')");
         $example_doc_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
         Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/flash','" . get_lang('Flash') . "','folder','0')");
         $example_doc_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
         Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/video','" . get_lang('Video') . "','folder','0')");
         $example_doc_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
         Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'/certificates','" . get_lang('Certificates') . "','folder','0')");
         $example_doc_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$example_doc_id},'DocumentAdded',1,0,NULL,0)");
         // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
         $folders_to_copy_from_default_course = array('images', 'audio', 'flash', 'video', 'certificates');
         $default_course_path = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH);
         $default_document_array = array();
         foreach ($folders_to_copy_from_default_course as $folder) {
             $default_course_folder_path = $default_course_path . $folder . '/';
             $files = self::browse_folders($default_course_folder_path, array(), $folder);
             $sorted_array = self::sort_pictures($files, 'dir');
             $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
             $default_document_array[$folder] = $sorted_array;
         }
         //Light protection (adding index.html in every document folder)
         $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
         $example_cert_id = 0;
         if (is_array($default_document_array) && count($default_document_array) > 0) {
             foreach ($default_document_array as $media_type => $array_media) {
                 $path_documents = "/{$media_type}/";
                 //hack until feature #5242 is implemented
                 if ($media_type == 'images') {
                     $media_type = 'images/gallery';
                     $images_folder = $sys_course_path . $course_repository . "/document/images/";
                     if (!is_dir($images_folder)) {
                         //Creating index.html
                         mkdir($images_folder, $perm);
                         $fd = fopen($images_folder . 'index.html', 'w');
                         fwrite($fd, $htmlpage);
                         @chmod($images_folder . 'index.html', $perm_file);
                     }
                 }
                 $course_documents_folder = $sys_course_path . $course_repository . "/document/{$media_type}/";
                 $default_course_path = api_get_path(SYS_DEFAULT_COURSE_DOCUMENT_PATH) . $path_documents;
                 //echo 'try '.$course_documents_folder; echo '<br />';
                 if (!is_dir($course_documents_folder)) {
                     //Creating index.html
                     mkdir($course_documents_folder, $perm);
                     $fd = fopen($course_documents_folder . 'index.html', 'w');
                     fwrite($fd, $htmlpage);
                     @chmod($course_documents_folder . 'index.html', $perm_file);
                 }
                 if (is_array($array_media) && count($array_media) > 0) {
                     foreach ($array_media as $key => $value) {
                         if (isset($value['dir']) && !empty($value['dir'])) {
                             if (!is_dir($course_documents_folder . $value['dir'])) {
                                 //Creating folder
                                 mkdir($course_documents_folder . $value['dir'], $perm);
                                 //Creating index.html (for light protection)
                                 $index_html = $course_documents_folder . $value['dir'] . '/index.html';
                                 $fd = fopen($index_html, 'w');
                                 fwrite($fd, $htmlpage);
                                 @chmod($index_html, $perm_file);
                                 //Inserting folder in the DB
                                 $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
                                 $temp = explode('/', $folder_path);
                                 $title = $temp[count($temp) - 1];
                                 //hack until feature #5242 is implemented
                                 if ($title == 'gallery') {
                                     $title = get_lang('DefaultCourseImages');
                                 }
                                 if ($media_type == 'images/gallery') {
                                     $folder_path = 'gallery/' . $folder_path;
                                 }
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'{$path_documents}" . $folder_path . "','" . $title . "','folder','0')");
                                 $image_id = Database::insert_id();
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$image_id},'DocumentAdded',1,0,NULL,0)");
                             }
                         }
                         if (isset($value['file']) && !empty($value['file'])) {
                             if (!file_exists($course_documents_folder . $value['file'])) {
                                 //Copying file
                                 copy($default_course_path . $value['file'], $course_documents_folder . $value['file']);
                                 chmod($course_documents_folder . $value['file'], $perm_file);
                                 //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
                                 $temp = explode('/', $value['file']);
                                 $file_size = filesize($course_documents_folder . $value['file']);
                                 //hack until feature #5242 is implemented
                                 if ($media_type == 'images/gallery') {
                                     $value["file"] = 'gallery/' . $value["file"];
                                 }
                                 //Inserting file in the DB
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size) VALUES ({$course_id},'{$path_documents}" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','{$file_size}')");
                                 $image_id = Database::insert_id();
                                 if ($path_documents . $value['file'] == '/certificates/default.html') {
                                     $example_cert_id = $image_id;
                                 }
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id},'document',1,NOW(),NOW(),{$image_id},'DocumentAdded',1,0,NULL,1)");
                             }
                         }
                     }
                 }
             }
         }
         /* Agenda tool */
         Database::query("INSERT INTO {$TABLETOOLAGENDA} VALUES ({$course_id}, NULL, '" . Database::escape_string(get_lang('AgendaCreationTitle')) . "', '" . Database::escape_string(get_lang('AgendaCreationContenu')) . "', now(), now(), NULL, 0, 0)");
         // We need to add the item properties too!
         $insert_id = Database::insert_id();
         $sql = "INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ({$course_id}, '" . TOOL_CALENDAR_EVENT . "',1,NOW(),NOW(),{$insert_id},'AgendaAdded',1,0,NULL,1)";
         Database::query($sql);
         /*  Links tool */
         $add_google_link_sql = "INSERT INTO {$TABLETOOLLINK}  (c_id, url, title, description, category_id, display_order, on_homepage, target)\n                    VALUES ({$course_id}, 'http://www.google.com','Google','" . Database::escape_string(get_lang('Google')) . "','0','0','0','_self')";
         Database::query($add_google_link_sql);
         // We need to add the item properties too!
         $insert_id = Database::insert_id();
         $sql = "INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                    VALUES ({$course_id}, '" . TOOL_LINK . "',1,NOW(),NOW(),{$insert_id},'LinkAdded',1,0,NULL,1)";
         Database::query($sql);
         $add_wikipedia_link_sql = "INSERT INTO {$TABLETOOLLINK}  (c_id, url, title, description, category_id, display_order, on_homepage, target)\n                    VALUES ({$course_id}, 'http://www.wikipedia.org','Wikipedia','" . Database::escape_string(get_lang('Wikipedia')) . "','0','1','0','_self')";
         Database::query($add_wikipedia_link_sql);
         // We need to add the item properties too!
         $insert_id = Database::insert_id();
         $sql = "INSERT INTO {$TABLEITEMPROPERTY}  (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('" . TOOL_LINK . "',1,NOW(),NOW(),{$insert_id},'LinkAdded',1,0,NULL,1)";
         Database::query($sql);
         /* Announcement tool */
         $sql = "INSERT INTO {$TABLETOOLANNOUNCEMENTS}  (c_id, title,content,end_date,display_order,email_sent)\n                    VALUES ({$course_id}, '" . Database::escape_string(get_lang('AnnouncementExampleTitle')) . "', '" . Database::escape_string(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
         Database::query($sql);
         // We need to add the item properties too!
         $insert_id = Database::insert_id();
         $sql = "INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                    VALUES ({$course_id}, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),{$insert_id},'AnnouncementAdded',1,0,NULL,1)";
         Database::query($sql);
         /* Introduction text */
         $intro_text = '<p style="text-align: center;">
                         <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
                         <h2>' . Database::escape_string(get_lang('IntroductionText')) . '</h2>
                      </p>';
         Database::query("INSERT INTO {$TABLEINTROS} VALUES ({$course_id}, '" . TOOL_COURSE_HOMEPAGE . "','" . $intro_text . "', 0)");
         Database::query("INSERT INTO {$TABLEINTROS} VALUES ({$course_id}, '" . TOOL_STUDENTPUBLICATION . "','" . Database::escape_string(get_lang('IntroductionTwo')) . "', 0)");
         // Wiki intro
         $intro_wiki = '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="110" valign="top" align="left"></td><td valign="top" align="left">' . Database::escape_string(get_lang('IntroductionWiki')) . '</td></tr></table>';
         Database::query("INSERT INTO {$TABLEINTROS} VALUES ({$course_id}, '" . TOOL_WIKI . "','" . $intro_wiki . "', 0)");
         /*  Exercise tool */
         $html = Database::escape_string('<table width="100%" border="0" cellpadding="0" cellspacing="0">
                                             <tr><td width="110" valign="top" align="left">
                                             <img src="' . api_get_path(WEB_DEFAULT_COURSE_DOCUMENT_PATH) . 'images/mr_dokeos/thinking.jpg"></td><td valign="top" align="left">' . get_lang('Antique') . '
                                         </td></tr></table>');
         // Insert exercise
         Database::query('INSERT INTO ' . $TABLEQUIZ . ' (c_id, title, description, type, random, random_answers, active, results_disabled ) ' . ' VALUES (' . $course_id . ', "' . Database::escape_string(get_lang('ExerciceEx')) . '", "' . $html . '", "1", "0", "0", "1", "0")');
         $exercise_id = Database::insert_id();
         // Insert question
         Database::query("INSERT INTO {$TABLEQUIZQUESTIONLIST} (c_id, question, description, ponderation, position, type, picture, level)\n                            VALUES ( '.{$course_id}.', '" . Database::escape_string(get_lang('SocraticIrony')) . "', '" . Database::escape_string(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
         $questionId = Database::insert_id();
         Database::query("INSERT INTO {$TABLEQUIZQUESTION}  (c_id, question_id, exercice_id, question_order) VALUES ({$course_id},{$questionId} , {$exercise_id}, 1)");
         // Insert answers
         Database::query("INSERT INTO {$TABLEQUIZANSWERSLIST} (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ({$course_id}, '{$questionId}', '" . Database::escape_string(get_lang('Ridiculise')) . "', '0', '" . Database::escape_string(get_lang('NoPsychology')) . "', '-5', '1')");
         Database::query("INSERT INTO {$TABLEQUIZANSWERSLIST} (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ({$course_id}, '{$questionId}', '" . Database::escape_string(get_lang('AdmitError')) . "', '0', '" . Database::escape_string(get_lang('NoSeduction')) . "', '-5', '2')");
         Database::query("INSERT INTO {$TABLEQUIZANSWERSLIST} (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ({$course_id}, '{$questionId}', '" . Database::escape_string(get_lang('Force')) . "', '1', '" . Database::escape_string(get_lang('Indeed')) . "', '5', '3')");
         Database::query("INSERT INTO {$TABLEQUIZANSWERSLIST} (c_id, question_id, answer, correct, comment, ponderation, position) VALUES ({$course_id}, '{$questionId}', '" . Database::escape_string(get_lang('Contradiction')) . "', '1', '" . Database::escape_string(get_lang('NotFalse')) . "', '5', '4')");
         /* Forum tool */
         Database::query("INSERT INTO {$TABLEFORUMCATEGORIES} VALUES ({$course_id}, 1,'" . Database::escape_string(get_lang('ExampleForumCategory')) . "', '', 1, 0, 0)");
         $insert_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                            VALUES ({$course_id}, 'forum_category',1,NOW(),NOW(),{$insert_id},'ForumCategoryAdded',1,0,NULL,1)");
         Database::query("INSERT INTO {$TABLEFORUMS} (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id )\n                            VALUES ({$course_id}, '" . Database::escape_string(get_lang('ExampleForum')) . "', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
         $insert_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                             VALUES ({$course_id}, '" . TOOL_FORUM . "', 1,NOW(),NOW(),{$insert_id},'ForumAdded',1,0,NULL,1)");
         Database::query("INSERT INTO {$TABLEFORUMTHREADS} (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id)\n                            VALUES ({$course_id}, 1, '" . Database::escape_string(get_lang('ExampleThread')) . "', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
         $insert_id = Database::insert_id();
         Database::query("INSERT INTO {$TABLEITEMPROPERTY}  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                            VALUES ({$course_id}, 'forum_thread',1,NOW(),NOW(),{$insert_id},'ForumThreadAdded',1,0,NULL,1)");
         Database::query("INSERT INTO {$TABLEFORUMPOSTS} VALUES ({$course_id}, 1, '" . Database::escape_string(get_lang('ExampleThread')) . "', '" . Database::escape_string(get_lang('ExampleThreadContent')) . "', 1, 1, 1, '', NOW(), 0, 0, 1)");
         /* Gradebook tool */
         $course = api_get_course_info_by_id($course_id);
         $course_code = $course['code'];
         // father gradebook
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('{$course_code}','',1,'{$course_code}',0,100,0,NULL,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('{$course_code}','',1,'{$course_code}',{$gbid},100,1,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOKLINK} (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked) VALUES (1,{$exercise_id},1,'{$course_code}',{$gbid},'{$now}',100,1,0)");
     }
     //Installing plugins in course
     $app_plugin = new AppPlugin();
     $app_plugin->install_course_plugins($course_id);
     $language_interface = $language_interface_original;
     return true;
 }
Esempio n. 12
0
 /**
  * This function does the save-work for the documents.
  * It handles the uploaded file and adds the properties to the database
  * If unzip=1 and the file is a zipfile, it is extracted
  * If we decide to save ALL kinds of documents in one database,
  * we could extend this with a $type='document', 'scormdocument',...
  *
  * @param array $_course
  * @param array $uploaded_file ($_FILES)
  * @param string $base_work_dir
  * @param string $upload_path
  * @param int $user_id
  * @param int $to_group_id, 0 for everybody
  * @param int $to_user_id, NULL for everybody
  * @param int $unzip 1/0
  * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
  * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
  * @return path of the saved file
  */
 static function handle_uploaded_document($_course, $uploaded_file, $base_work_dir, $upload_path, $user_id, $to_group_id = 0, $to_user_id = null, $unzip = 0, $what_if_file_exists = '', $output = true)
 {
     if (!$user_id) {
         die('Not a valid user.');
     }
     // Strip slashes
     $uploaded_file['name'] = stripslashes($uploaded_file['name']);
     // Add extension to files without one (if possible)
     $uploaded_file['name'] = self::add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
     $current_session_id = api_get_session_id();
     //Just in case process_uploaded_file is not called
     $max_filled_space = DocumentManager::get_course_quota();
     // Check if there is enough space to save the file
     if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
         if ($output) {
             Display::display_error_message(get_lang('UplNotEnoughSpace'));
         }
         return false;
     }
     // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
     if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
         return self::unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output, $to_group_id);
         //display_message('Unzipping file');
     } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
         // We can only unzip ZIP files (no gz, tar,...)
         if ($output) {
             Display::display_error_message(get_lang('UplNotAZip') . " " . get_lang('PleaseTryAgain'));
         }
         return false;
     } else {
         // Clean up the name, only ASCII characters should stay. (and strict)
         $clean_name = api_replace_dangerous_char($uploaded_file['name'], 'strict');
         // No "dangerous" files
         $clean_name = self::disable_dangerous_file($clean_name);
         if (!self::filter_extension($clean_name)) {
             if ($output) {
                 Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
             }
             return false;
         } else {
             // Extension is good
             //echo '<br />clean name = '.$clean_name;
             //echo '<br />upload_path = '.$upload_path;
             // If the upload path differs from / (= root) it will need a slash at the end
             if ($upload_path != '/') {
                 $upload_path = $upload_path . '/';
             }
             //echo '<br />upload_path = '.$upload_path;
             $file_path = $upload_path . $clean_name;
             //echo '<br />file path = '.$file_path;
             // Full path to where we want to store the file with trailing slash
             $where_to_save = $base_work_dir . $upload_path;
             // At least if the directory doesn't exist, tell so
             if (!is_dir($where_to_save)) {
                 if ($output) {
                     Display::display_error_message(get_lang('DestDirectoryDoesntExist') . ' (' . $upload_path . ')');
                 }
                 return false;
             }
             //echo '<br />where to save = '.$where_to_save;
             // Full path of the destination
             $store_path = $where_to_save . $clean_name;
             //echo '<br />store path = '.$store_path;
             // Name of the document without the extension (for the title)
             $document_name = self::get_document_title($uploaded_file['name']);
             // Size of the uploaded file (in bytes)
             $file_size = $uploaded_file['size'];
             $files_perm = api_get_permissions_for_new_files();
             // What to do if the target file exists
             switch ($what_if_file_exists) {
                 // Overwrite the file if it exists
                 case 'overwrite':
                     // Check if the target file exists, so we can give another message
                     $file_exists = file_exists($store_path);
                     if (self::moveUploadedFile($uploaded_file, $store_path)) {
                         chmod($store_path, $files_perm);
                         if ($file_exists) {
                             // UPDATE DATABASE
                             $document_id = DocumentManager::get_document_id($_course, $file_path);
                             if (is_numeric($document_id)) {
                                 // Update filesize
                                 self::update_existing_document($_course, $document_id, $uploaded_file['size']);
                                 // Update document item_property
                                 api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                                 //Redo visibility
                                 api_set_default_visibility($_course, TOOL_DOCUMENT, $document_id);
                             }
                             // If the file is in a folder, we need to update all parent folders
                             self::item_property_update_on_folder($_course, $upload_path, $user_id);
                             // Display success message with extra info to user
                             if ($output) {
                                 Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . $file_path . ' ' . get_lang('UplFileOverwritten'), false);
                             }
                             return $file_path;
                         } else {
                             // Put the document data in the database
                             $document_id = self::add_document($_course, $file_path, 'file', $file_size, $document_name, null, 0, true);
                             if ($document_id) {
                                 // Put the document in item_property update
                                 api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                             }
                             // If the file is in a folder, we need to update all parent folders
                             self::item_property_update_on_folder($_course, $upload_path, $user_id);
                             // Display success message to user
                             if ($output) {
                                 Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . $file_path, false);
                             }
                             return $file_path;
                         }
                     } else {
                         if ($output) {
                             Display::display_error_message(get_lang('UplUnableToSaveFile'));
                         }
                         return false;
                     }
                     break;
                     // Rename the file if it exists
                 // Rename the file if it exists
                 case 'rename':
                     $new_name = self::unique_name($where_to_save, $clean_name);
                     $store_path = $where_to_save . $new_name;
                     $new_file_path = $upload_path . $new_name;
                     if (self::moveUploadedFile($uploaded_file, $store_path)) {
                         chmod($store_path, $files_perm);
                         // Put the document data in the database
                         $document_id = self::add_document($_course, $new_file_path, 'file', $file_size, $document_name, null, 0, true);
                         if ($document_id) {
                             // Update document item_property
                             api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                         }
                         // If the file is in a folder, we need to update all parent folders
                         self::item_property_update_on_folder($_course, $upload_path, $user_id);
                         // Display success message to user
                         if ($output) {
                             Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') . $new_file_path, false);
                         }
                         return $new_file_path;
                     } else {
                         if ($output) {
                             Display::display_error_message(get_lang('UplUnableToSaveFile'));
                         }
                         return false;
                     }
                     break;
                     // Only save the file if it doesn't exist or warn user if it does exist
                 // Only save the file if it doesn't exist or warn user if it does exist
                 default:
                     if (file_exists($store_path)) {
                         if ($output) {
                             Display::display_error_message($clean_name . ' ' . get_lang('UplAlreadyExists'));
                         }
                     } else {
                         if (self::moveUploadedFile($uploaded_file, $store_path)) {
                             chmod($store_path, $files_perm);
                             // Put the document data in the database
                             $document_id = self::add_document($_course, $file_path, 'file', $file_size, $document_name, null, 0, true);
                             if ($document_id) {
                                 // Update document item_property
                                 api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                             }
                             // If the file is in a folder, we need to update all parent folders
                             self::item_property_update_on_folder($_course, $upload_path, $user_id);
                             // Display success message to user
                             if ($output) {
                                 Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . $file_path, false);
                             }
                             return $file_path;
                         } else {
                             if ($output) {
                                 Display::display_error_message(get_lang('UplUnableToSaveFile'));
                             }
                             return false;
                         }
                     }
                     break;
             }
         }
     }
 }