Example #1
0
 /**
  * @return bool
  */
 public function create_user_folder()
 {
     // COURSE123/exercises/session_id/exercise_id/question_id/user_id
     if (empty($this->store_path)) {
         return false;
     }
     //@todo use an array to create folders
     $folders_to_create = array();
     // Trying to create the courses/COURSE123/exercises/ dir just in case.
     $directoryPermissions = api_get_permissions_for_new_directories();
     if (!is_dir($this->store_path)) {
         mkdir($this->store_path, $directoryPermissions);
     }
     if (!is_dir($this->store_path . $this->session_id)) {
         mkdir($this->store_path . $this->session_id, $directoryPermissions);
     }
     if (!is_dir($this->store_path . $this->session_id . '/' . $this->exercise_id)) {
         mkdir($this->store_path . $this->session_id . '/' . $this->exercise_id, $directoryPermissions);
     }
     if (!is_dir($this->store_path . $this->session_id . '/' . $this->exercise_id . '/' . $this->question_id)) {
         mkdir($this->store_path . $this->session_id . '/' . $this->exercise_id . '/' . $this->question_id, $directoryPermissions);
     }
     if (!empty($this->user_id) && !is_dir($this->store_path . $this->session_id . '/' . $this->exercise_id . '/' . $this->question_id . '/' . $this->user_id)) {
         mkdir($this->store_path . $this->session_id . '/' . $this->exercise_id . '/' . $this->question_id . '/' . $this->user_id, $directoryPermissions);
     }
 }
/**
 * 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;
    }
}
Example #3
0
 /**
  *
  * @param int $c_id
  * @param string $sub_path 
  * @return FileStore 
  */
 static function course($c_id, $sub_path = '')
 {
     $sys_path = api_get_path(SYS_COURSE_PATH);
     $course = api_get_course_info_by_id($c_id);
     $course_path = $course['path'];
     $path = $sys_path . $course_path . $sub_path;
     if (!is_dir($path)) {
         $mode = api_get_permissions_for_new_directories();
         $success = mkdir($path, $mode, true);
         if (!$success) {
             return false;
         }
     }
     return new self($path);
 }
 /**
  * @param Console\Input\InputInterface $input
  * @param Console\Output\OutputInterface $output
  * @return integer|null|boolean|void
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     /** @var \Silex\Application $app */
     $app = $this->getApplication()->getSilexApplication();
     $theme = $input->getArgument('theme');
     // Get all themes
     if ($app['assetic.enabled'] == false || !isset($app['assetic.enabled'])) {
         $output->writeln("<info>Assetic is not enabled. Change this value to true:</info> <comment>assetic.enabled = true</comment>");
         return false;
     }
     $themes = $app['template']->getStyleSheetFolderList();
     //$themes = array('chamilo', 'public_admin');
     if (empty($theme)) {
         $dialog = $this->getHelperSet()->get('dialog');
         if (!$dialog->askConfirmation($output, '<question>Are you sure you want to dump css/js of all themes?</question>(y/N)', false)) {
             return;
         }
     } else {
         $themes = array($theme);
     }
     if (!is_dir($app['assetic.path_to_web'])) {
         mkdir($app['assetic.path_to_web'], api_get_permissions_for_new_directories());
         $output->writeln("<info>Creating folder in: </info><comment>" . $app['assetic.path_to_web'] . "</comment>");
     }
     foreach ($themes as $theme) {
         if (is_dir($app['root_sys'] . 'main/css/' . $theme) && file_exists($app['root_sys'] . 'main/css/' . $theme . '/default.css')) {
             $output->writeln("<info>Dumping theme: {$theme}</info>");
             /** @var \SilexAssetic\Assetic\Dumper $dumper */
             $dumper = $app['assetic.dumper'];
             $app['assetic.output.path_to_css'] = 'css/' . $theme . '/style.css';
             $params = array($app['root_sys'] . 'main/css/' . $theme => $app['assetic.input.path_to_assets'] . '/css/' . $theme);
             $app['chamilo.filesystem']->copyFolders($params, $output);
             if (isset($app['twig'])) {
                 //$dumper->addTwigAssets();
             }
             $dumper->dumpAssets();
         } else {
             $output->writeln("<info>Seems that theme: <comment>{$theme}</comment> doesn't have a <comment>{$theme}/default.css</comment> file. Skipping dump.</info>");
         }
     }
     $output->writeln('<info>Dump finished</info>');
     return true;
 }
/**
 * Creates a hotpotato directory.
 *
 * If a directory of that name already exists, don't create any. If a file of that name exists, remove it and create a directory.
 * @param   string      Wanted path
 * @return  boolean     Always true so far
 */
function hotpotatoes_init($base_work_dir)
{
    //global $_course, $_user;
    $document_path = $base_work_dir . '/';
    if (!is_dir($document_path)) {
        if (is_file($document_path)) {
            @unlink($document_path);
        }
        @mkdir($document_path, api_get_permissions_for_new_directories());
        return true;
    } else {
        return false;
    }
    //why create a .htaccess here?
    //if (!is_file($document_path.".htacces"))
    //{
    //        if (!($fp = fopen($document_path.".htaccess", "w"))) {
    //    }
    //    $str = "order deny,allow\nallow from all";
    //    if (!fwrite($fp,$str)) { }
    //}
}
Example #6
0
     $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;
     $document_id = FileManager::add_document($_course, $save_file_path, 'file', $file_size, $title, null, $readonly);
     if ($document_id) {
Example #7
0
            }
            $tpl->assign('displayCookieUsageWarning', true);
        }
    }
}
$tpl->assign('web_admin_ajax_url', $admin_ajax_url);
$tpl->assign('blocks', $blocks);
if (api_is_platform_admin()) {
    $extraContentForm = new FormValidator('block_extra_data', 'post', '#', null, array('id' => 'block-extra-data', 'class' => ''), FormValidator::LAYOUT_BOX_NO_LABEL);
    $extraContentFormRenderer = $extraContentForm->getDefaultRenderer();
    if ($extraContentForm->validate()) {
        $extraData = $extraContentForm->getSubmitValues();
        $extraData = array_map(['Security', 'remove_XSS'], $extraData);
        if (!empty($extraData['block'])) {
            if (!is_dir($adminExtraContentDir)) {
                mkdir($adminExtraContentDir, api_get_permissions_for_new_directories(), true);
            }
            if (!is_writable($adminExtraContentDir)) {
                die;
            }
            $fullFilePath = $adminExtraContentDir . $extraData['block'];
            $fullFilePath .= "_extra.html";
            file_put_contents($fullFilePath, $extraData['extra_content']);
            Header::location(api_get_self());
        }
    }
    $extraContentForm->addTextarea('extra_content', null, ['id' => 'extra_content']);
    $extraContentFormRenderer->setElementTemplate('<div class="form-group">{element}</div>', 'extra_content');
    $extraContentForm->addElement('hidden', 'block', null, array('id' => 'extra-block'));
    $extraContentForm->addButtonExport(get_lang('Save'), 'submit_extra_content');
    $tpl->assign('extraDataForm', $extraContentForm->returnForm());
Example #8
0
 /**
  * Creates new group pictures in various sizes of a user, or deletes user pfotos.
  * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
  * @param	int	The group id
  * @param	string $file			The common file name for the newly created photos.
  * It will be checked and modified for compatibility with the file system.
  * If full name is provided, path component is ignored.
  * If an empty name is provided, then old user photos are deleted only,
  * @see UserManager::delete_user_picture() as the prefered way for deletion.
  * @param	string		$source_file	The full system name of the image from which user photos will be created.
  * @return	string/bool	Returns the resulting common file name of created images which usually should be stored in database.
  * When an image is removed the function returns an empty string. In case of internal error or negative validation it returns FALSE.
  */
 public function update_group_picture($group_id, $file = null, $source_file = null)
 {
     // Validation 1.
     if (empty($group_id)) {
         return false;
     }
     $delete = empty($file);
     if (empty($source_file)) {
         $source_file = $file;
     }
     // User-reserved directory where photos have to be placed.
     $path_info = self::get_group_picture_path_by_id($group_id, 'system', true);
     $path = $path_info['dir'];
     // If this directory does not exist - we create it.
     if (!file_exists($path)) {
         @mkdir($path, api_get_permissions_for_new_directories(), true);
     }
     // The old photos (if any).
     $old_file = $path_info['file'];
     // Let us delete them.
     if (!empty($old_file)) {
         if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
             $prefix = 'saved_' . date('Y_m_d_H_i_s') . '_' . uniqid('') . '_';
             @rename($path . 'small_' . $old_file, $path . $prefix . 'small_' . $old_file);
             @rename($path . 'medium_' . $old_file, $path . $prefix . 'medium_' . $old_file);
             @rename($path . 'big_' . $old_file, $path . $prefix . 'big_' . $old_file);
             @rename($path . $old_file, $path . $prefix . $old_file);
         } else {
             @unlink($path . 'small_' . $old_file);
             @unlink($path . 'medium_' . $old_file);
             @unlink($path . 'big_' . $old_file);
             @unlink($path . $old_file);
         }
     }
     // Exit if only deletion has been requested. Return an empty picture name.
     if ($delete) {
         return '';
     }
     // Validation 2.
     $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
     $file = str_replace('\\', '/', $file);
     $filename = ($pos = strrpos($file, '/')) !== false ? substr($file, $pos + 1) : $file;
     $extension = strtolower(substr(strrchr($filename, '.'), 1));
     if (!in_array($extension, $allowed_types)) {
         return false;
     }
     // This is the common name for the new photos.
     if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
         $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
         $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
         $filename = substr($filename, -1) == '.' ? $filename . $extension : $filename . '.' . $extension;
     } else {
         $filename = api_replace_dangerous_char($filename);
         if (PREFIX_IMAGE_FILENAME_WITH_UID) {
             $filename = uniqid('') . '_' . $filename;
         }
         // We always prefix user photos with user ids, so on setting
         // api_get_setting('split_users_upload_directory') === 'true'
         // the correspondent directories to be found successfully.
         $filename = $group_id . '_' . $filename;
     }
     // Storing the new photos in 4 versions with various sizes.
     /*$image->resize(
       // get original size and set width (widen) or height (heighten).
       // width or height will be set maintaining aspect ratio.
           $image->getSize()->widen( 700 )
       );*/
     // Usign the Imagine service
     $imagine = new Imagine\Gd\Imagine();
     $image = $imagine->open($source_file);
     $options = array('quality' => 90);
     //$image->resize(new Imagine\Image\Box(200, 200))->save($path.'big_'.$filename);
     $image->resize($image->getSize()->widen(200))->save($path . 'big_' . $filename, $options);
     $image = $imagine->open($source_file);
     $image->resize(new Imagine\Image\Box(85, 85))->save($path . 'medium_' . $filename, $options);
     $image = $imagine->open($source_file);
     $image->resize(new Imagine\Image\Box(22, 22))->save($path . 'small_' . $filename);
     /*
             $small  = self::resize_picture($source_file, 22);
             $medium = self::resize_picture($source_file, 85);
             $normal = self::resize_picture($source_file, 200);
     
             $big = new Image($source_file); // This is the original picture.
             $ok = $small && $small->send_image($path.'small_'.$filename)
                 && $medium && $medium->send_image($path.'medium_'.$filename)
                 && $normal && $normal->send_image($path.'big_'.$filename)
                 && $big && $big->send_image($path.$filename);
             return $ok ? $filename : false;*/
     return $filename;
 }
 /**
  * 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;
 }
 /**
  * Restore Work
  */
 function restore_works($session_id = 0)
 {
     $perm = api_get_permissions_for_new_directories();
     if ($this->course->has_resources(RESOURCE_WORK)) {
         $table_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
         $table_work_assignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
         $resources = $this->course->resources;
         foreach ($resources[RESOURCE_WORK] as $id => $obj) {
             // check resources inside html from fckeditor tool and copy correct urls into recipient course
             $obj->params['description'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($obj->params['description'], $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']);
             $obj->params['id'] = null;
             $obj->params['c_id'] = $this->destination_course_id;
             $last_id = Database::insert($table_work, $obj->params);
             // re-create dir
             // @todo check security against injection of dir in crafted course backup here!
             $path = $obj->params['url'];
             $path = '/' . str_replace('/', '', substr($path, 1));
             $destination_path = api_get_path(SYS_COURSE_PATH) . $this->course->destination_path . '/work' . $path;
             $r = @mkdir($destination_path, $perm);
             if ($r === false) {
                 error_log('Failed creating directory ' . $destination_path . ' in course restore for work tool');
             }
             if (is_numeric($last_id)) {
                 api_item_property_update($this->destination_course_info, 'work', $last_id, "DirectoryCreated", api_get_user_id());
             }
         }
     }
 }
 /**
  * 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;
 }
Example #12
0
 /**
  * Replace urls inside content html from a copy course
  * @param string        content html
  * @param string        origin course code
  * @param string        destination course directory
  * @return string    new content html with replaced urls or return false if content is not a string
  */
 static function replace_urls_inside_content_html_from_copy_course($content_html, $origin_course_code, $destination_course_directory, $origin_course_path_from_zip = null, $origin_course_info_path = null)
 {
     if (empty($content_html)) {
         return false;
     }
     $orig_source_html = DocumentManager::get_resources_from_source_html($content_html);
     $orig_course_info = api_get_course_info($origin_course_code);
     //Course does not exist in the current DB probably this cames from a zip file?
     if (empty($orig_course_info)) {
         if (!empty($origin_course_path_from_zip)) {
             $orig_course_path = $origin_course_path_from_zip . '/';
             $orig_course_info_path = $origin_course_info_path;
         }
     } else {
         $orig_course_path = api_get_path(SYS_PATH) . 'courses/' . $orig_course_info['path'] . '/';
         $orig_course_info_path = $orig_course_info['path'];
     }
     $destination_course_code = CourseManager::get_course_id_from_path($destination_course_directory);
     $destination_course_info = api_get_course_info($destination_course_code);
     $dest_course_path = api_get_path(SYS_COURSE_PATH) . $destination_course_directory . '/';
     $user_id = api_get_user_id();
     if (!empty($orig_source_html)) {
         foreach ($orig_source_html as $source) {
             // get information about source url
             $real_orig_url = $source[0];
             // url
             $scope_url = $source[1];
             // scope (local, remote)
             $type_url = $source[2];
             // tyle (rel, abs, url)
             // Get path and query from origin url
             $orig_parse_url = parse_url($real_orig_url);
             $real_orig_path = isset($orig_parse_url['path']) ? $orig_parse_url['path'] : null;
             $real_orig_query = isset($orig_parse_url['query']) ? $orig_parse_url['query'] : null;
             // Replace origin course code by destination course code from origin url query
             $dest_url_query = '';
             if (!empty($real_orig_query)) {
                 $dest_url_query = '?' . $real_orig_query;
                 if (strpos($dest_url_query, $origin_course_code) !== false) {
                     $dest_url_query = str_replace($origin_course_code, $destination_course_code, $dest_url_query);
                 }
             }
             if ($scope_url == 'local') {
                 if ($type_url == 'abs' || $type_url == 'rel') {
                     $document_file = strstr($real_orig_path, 'document');
                     if (strpos($real_orig_path, $document_file) !== false) {
                         $origin_filepath = $orig_course_path . $document_file;
                         $destination_filepath = $dest_course_path . $document_file;
                         // copy origin file inside destination course
                         if (file_exists($origin_filepath)) {
                             $filepath_dir = dirname($destination_filepath);
                             if (!is_dir($filepath_dir)) {
                                 $perm = api_get_permissions_for_new_directories();
                                 $result = @mkdir($filepath_dir, $perm, true);
                                 if ($result) {
                                     $filepath_to_add = str_replace(array($dest_course_path, 'document'), '', $filepath_dir);
                                     //Add to item properties to the new folder
                                     $doc_id = FileManager::add_document($destination_course_info, $filepath_to_add, 'folder', 0, basename($filepath_to_add));
                                     api_item_property_update($destination_course_info, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $user_id, null, null, null, null);
                                 }
                             }
                             if (!file_exists($destination_filepath)) {
                                 $result = @copy($origin_filepath, $destination_filepath);
                                 if ($result) {
                                     $filepath_to_add = str_replace(array($dest_course_path, 'document'), '', $destination_filepath);
                                     $size = filesize($destination_filepath);
                                     //Add to item properties to the file
                                     $doc_id = FileManager::add_document($destination_course_info, $filepath_to_add, 'file', $size, basename($filepath_to_add));
                                     api_item_property_update($destination_course_info, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $user_id, null, null, null, null);
                                 }
                             }
                         }
                         // Replace origin course path by destination course path
                         if (strpos($content_html, $real_orig_url) !== false) {
                             //$origin_course_code
                             $url_course_path = str_replace($orig_course_info_path . '/' . $document_file, '', $real_orig_path);
                             $destination_url = $url_course_path . $destination_course_directory . '/' . $document_file . $dest_url_query;
                             //If the course code doesn't exist in the path? what we do? Nothing! see BT#1985
                             if (strpos($real_orig_path, $origin_course_code) === false) {
                                 $url_course_path = $real_orig_path;
                                 $destination_url = $real_orig_path;
                             }
                             $content_html = str_replace($real_orig_url, $destination_url, $content_html);
                         }
                     }
                     // replace origin course code by destination course code  from origin url
                     if (strpos($real_orig_url, '?') === 0) {
                         $dest_url = str_replace($origin_course_code, $destination_course_code, $real_orig_url);
                         $content_html = str_replace($real_orig_url, $dest_url, $content_html);
                     }
                 } else {
                     if ($type_url == 'url') {
                     }
                 }
             }
         }
     }
     return $content_html;
 }
 /**
  * Create dummy documents
  */
 function create_dummy_documents()
 {
     $course = api_get_course_info();
     $course_doc_path = $this->course->backup_path . '/document/';
     $number_of_documents = rand(10, 30);
     $extensions = array('html', 'doc');
     $directories = array();
     $property = $this->default_property;
     $property['lastedit_type'] = 'DocumentAdded';
     $property['tool'] = TOOL_DOCUMENT;
     $doc_id = 0;
     for ($doc_id = 1; $doc_id < $number_of_documents; $doc_id++) {
         $path = '';
         $doc_type = rand(0, count($extensions) - 1);
         $extension = $extensions[$doc_type];
         $filename = $this->get_dummy_content('title') . '_' . $doc_id . '.' . $extension;
         $content = $this->get_dummy_content('text');
         $dirs = rand(0, 3);
         for ($i = 0; $i < $dirs; $i++) {
             $path .= 'directory/';
             $directories[$path] = 1;
         }
         $dir_to_make = $course_doc_path . $path;
         if (!is_dir($dir_to_make)) {
             @mkdir($dir_to_make, api_get_permissions_for_new_directories(), true);
         }
         $file = $course_doc_path . $path . $filename;
         $fp = fopen($file, 'w');
         fwrite($fp, $content);
         fclose($fp);
         $size = filesize($file);
         $document = new Document($doc_id, '/' . $path . $filename, $this->get_dummy_content('description'), $this->get_dummy_content('title'), 'file', $size);
         $document->item_properties[] = $property;
         $this->course->add_resource($document);
     }
     foreach ($directories as $path => $flag) {
         $path = substr($path, 0, strlen($path) - 1);
         $document = new Document($doc_id++, '/' . $path, $this->get_dummy_content('description'), $this->get_dummy_content('title'), 'folder', 0);
         $property['lastedit_type'] = 'FolderCreated';
         $document->item_properties[] = $property;
         $this->course->add_resource($document);
     }
 }
Example #14
0
/**
 * Create a new empty directory with index.html file
 * @param string $name The new directory name
 * @param string $parentDirectory Directory parent directory name
 * @return boolean Return true if the directory was create. Otherwise return false
 */
function api_create_protected_dir($name, $parentDirectory)
{
    $isCreated = false;
    if (!is_writable($parentDirectory)) {
        return false;
    }
    $fullPath = $parentDirectory . api_replace_dangerous_char($name);
    if (mkdir($fullPath, api_get_permissions_for_new_directories(), true)) {
        $fp = fopen($fullPath . '/index.html', 'w');
        if ($fp) {
            if (fwrite($fp, '<html><head></head><body></body></html>')) {
                $isCreated = true;
            }
        }
        fclose($fp);
    }
    return $isCreated;
}
function create_zip()
{
    $path = '';
    if (empty($path)) {
        $path = '/';
    }
    $remove_dir = $path != '/' ? substr($path, 0, strlen($path) - strlen(basename($path))) : '/';
    $sys_archive_path = api_get_path(SYS_ARCHIVE_PATH);
    $sys_course_path = api_get_path(SYS_COURSE_PATH);
    $temp_zip_dir = $sys_archive_path . "temp";
    if (!is_dir($temp_zip_dir)) {
        mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
    } else {
        $handle = opendir($temp_zip_dir);
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $Diff = (time() - filemtime("{$temp_zip_dir}/{$file}")) / 60 / 60;
                //the "age" of the file in hours
                if ($Diff > 4) {
                    unlink("{$temp_zip_dir}/{$file}");
                }
                //delete files older than 4 hours
            }
        }
        closedir($handle);
    }
    $temp_zip_file = $temp_zip_dir . "/" . md5(time()) . ".zip";
    //create zipfile of given directory
    return array('PATH' => $path, 'PATH_TEMP_ARCHIVE' => $temp_zip_dir, 'PATH_COURSE' => $sys_course_path, 'TEMP_FILE_ZIP' => $temp_zip_file, 'PATH_REMOVE' => $remove_dir);
}
Example #16
0
 /**
  * Saves a message attachment files
  * @param  array 	$file_attach $_FILES['name']
  * @param  string  	a comment about the uploaded file
  * @param  int		message id
  * @param  int		receiver user id (optional)
  * @param  int		sender user id (optional)
  * @param  int		group id (optional)
  * @return void
  */
 public static function save_message_attachment_file($file_attach, $file_comment, $message_id, $receiver_user_id = 0, $sender_user_id = 0, $group_id = 0)
 {
     $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
     // Try to add an extension to the file if it hasn't one
     $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $file_attach['type']);
     // user's file name
     $file_name = $file_attach['name'];
     if (!filter_extension($new_file_name)) {
         Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
     } else {
         $new_file_name = uniqid('');
         if (!empty($receiver_user_id)) {
             $message_user_id = $receiver_user_id;
         } else {
             $message_user_id = $sender_user_id;
         }
         // User-reserved directory where photos have to be placed.*
         $userGroup = new UserGroup();
         if (!empty($group_id)) {
             $path_user_info = $userGroup->get_group_picture_path_by_id($group_id, 'system', true);
         } else {
             $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
         }
         $path_message_attach = $path_user_info['dir'] . 'message_attachments/';
         // If this directory does not exist - we create it.
         if (!file_exists($path_message_attach)) {
             @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
         }
         $new_path = $path_message_attach . $new_file_name;
         if (is_uploaded_file($file_attach['tmp_name'])) {
             @copy($file_attach['tmp_name'], $new_path);
         }
         // Storing the attachments if any
         $params = ['filename' => $file_name, 'comment' => $file_comment, 'path' => $new_file_name, 'message_id' => $message_id, 'size' => $file_attach['size']];
         Database::insert($tbl_message_attach, $params);
     }
 }
 /**
  * Update User extra field file type into {user_folder}/{$extra_field}
  * @param int $user_id          The user internal identification number
  * @param string $extra_field   The $extra_field The extra field name
  * @param null $file            The filename
  * @param null $source_file     The temporal filename
  * @return bool|null            return filename if success, but false
  */
 public static function update_user_extra_file($user_id, $extra_field = '', $file = null, $source_file = null)
 {
     // Add Filter
     $source_file = Security::filter_filename($source_file);
     $file = Security::filter_filename($file);
     if (empty($user_id)) {
         return false;
     }
     if (empty($source_file)) {
         $source_file = $file;
     }
     // User-reserved directory where extra file have to be placed.
     $path_info = self::get_user_picture_path_by_id($user_id, 'system');
     $path = $path_info['dir'];
     if (!empty($extra_field)) {
         $path .= $extra_field . '/';
     }
     // If this directory does not exist - we create it.
     if (!file_exists($path)) {
         @mkdir($path, api_get_permissions_for_new_directories(), true);
     }
     if (filter_extension($file)) {
         if (@move_uploaded_file($source_file, $path . $file)) {
             if ($extra_field) {
                 return $extra_field . '/' . $file;
             } else {
                 return $file;
             }
         }
     }
     return false;
     // this should be returned if anything went wrong with the upload
 }
 function add_audio()
 {
     $course_info = api_get_course_info();
     $filepath = api_get_path(SYS_COURSE_PATH) . $course_info['path'] . '/document/';
     if (!is_dir($filepath . 'audio')) {
         mkdir($filepath . 'audio', api_get_permissions_for_new_directories());
         $audio_id = FileManager::add_document($course_info, '/audio', 'folder', 0, 'audio');
         api_item_property_update($course_info, TOOL_DOCUMENT, $audio_id, 'FolderCreated', api_get_user_id(), null, null, null, null, api_get_session_id());
         api_item_property_update($course_info, TOOL_DOCUMENT, $audio_id, 'invisible', api_get_user_id(), null, null, null, null, api_get_session_id());
     }
     $key = 'file';
     if (!isset($_FILES[$key]['name']) || !isset($_FILES[$key]['tmp_name'])) {
         return false;
     }
     $result = DocumentManager::upload_document($_FILES, '/audio', null, null, 0, 'rename', false, false);
     $file_path = null;
     if ($result) {
         $file_path = basename($result['path']);
         // Store the mp3 file in the lp_item table.
         $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
         $sql_insert_audio = "UPDATE {$tbl_lp_item} SET audio = '" . Database::escape_string($file_path) . "'\n                                WHERE c_id = {$course_info['real_id']} AND id = '" . Database::escape_string($this->db_id) . "'";
         Database::query($sql_insert_audio);
     }
     return $file_path;
 }
Example #19
0
 /**
  * @param array $folderList
  * @param OutputInterface $output
  */
 public function copyFolders(array $folderList, OutputInterface $output = null)
 {
     if (!empty($folderList)) {
         foreach ($folderList as $folderSource => $folderDestination) {
             $this->fs->mirror($folderSource, $folderDestination);
             $finder = new Finder();
             $files = $finder->files()->in($folderDestination);
             $this->fs->chmod($files, api_get_permissions_for_new_directories());
             if ($output) {
                 $output->writeln("Contents were copied from <comment>{$folderSource}</comment> to <comment>{$folderDestination}</comment>");
             }
         }
     }
 }
Example #20
0
 $png_compression = 0;
 //0(none)-9
 $jpg_quality = 75;
 //from 0 to 100 (default is 75). More quality less compression
 $directory_thumbnails = $sys_course_path . $_course['path'] . '/document' . $folder . '.thumbs/';
 //Other parameters only for show tumbnails
 $row_items = 4;
 //only in slideshow.php
 $number_image = 7;
 //num icons cols to show
 $thumbnail_width_frame = $max_thumbnail_width;
 //optional $max_thumbnail_width+x
 $thumbnail_height_frame = $max_thumbnail_height;
 // Create the template_thumbnails folder (if no exist)
 if (!file_exists($directory_thumbnails)) {
     @mkdir($directory_thumbnails, api_get_permissions_for_new_directories());
 }
 // check files and thumbnails
 if (is_array($image_files_only)) {
     foreach ($image_files_only as $one_image_file) {
         $image = $sys_course_path . $_course['path'] . '/document' . $folder . $one_image_file;
         $image_thumbnail = $directory_thumbnails . '.' . $one_image_file;
         if (file_exists($image)) {
             //check thumbnail
             $imagetype = explode(".", $image);
             //or check $imagetype = image_type_to_extension(exif_imagetype($image), false);
             $imagetype = strtolower($imagetype[count($imagetype) - 1]);
             if (in_array($imagetype, $allowed_thumbnail_types)) {
                 if (!file_exists($image_thumbnail)) {
                     //run each once we view thumbnails is too heavy, then need move into  !file_exists($image_thumbnail, and only run when haven't the thumbnail
                     $original_image_size = api_getimagesize($image);
         }
     }
     $result = Database::query($sql);
 } else {
     $sql = "SELECT s.id,name,username,access_start_date,access_end_date,visibility,session_category_id\n\t\t\t\tFROM {$tbl_session} s\n\t\t\t\tINNER JOIN {$tbl_user}\n\t\t\t\t\tON {$tbl_user}.user_id = s.id_coach\n\t\t\t\tWHERE id='{$session_id}'";
     $result = Database::query($sql);
 }
 if (Database::num_rows($result)) {
     $sessionListToExport = [];
     if (in_array($file_type, ['csv', 'xls'])) {
         $archiveFile = 'export_sessions_' . $session_id . '_' . api_get_local_time();
         $cvs = true;
         $sessionListToExport[] = ['SessionName', 'Coach', 'DateStart', 'DateEnd', 'Visibility', 'SessionCategory', 'Users', 'Courses'];
     } else {
         if (!file_exists($archivePath)) {
             mkdir($archivePath, api_get_permissions_for_new_directories(), true);
         }
         if (!file_exists($archivePath . 'index.html')) {
             $fp = fopen($archivePath . 'index.html', 'w');
             fputs($fp, '<html><head></head><body></body></html>');
             fclose($fp);
         }
         $archiveFile = 'export_sessions_' . $session_id . '_' . api_get_local_time() . '.' . $file_type;
         while (file_exists($archivePath . $archiveFile)) {
             $archiveFile = 'export_users_' . $session_id . '_' . api_get_local_time() . '_' . uniqid('') . '.' . $file_type;
         }
         $cvs = false;
         $fp = fopen($archivePath . $archiveFile, 'w');
         fputs($fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Sessions>\n");
     }
     while ($row = Database::fetch_array($result)) {
Example #22
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>';
    }
}
 /**
  * Save the extra fields values
  * In order to save this function needs a item_id (user id, course id, etc)
  * This function is used with $extraField->addElements()
  * @param array $params array for the insertion into the *_field_values table
  *
  * @return mixed false on empty params, void otherwise
  * @assert (array()) === false
  */
 public function saveFieldValues($params)
 {
     foreach ($params as $key => $value) {
         $found = strpos($key, '__persist__');
         if ($found) {
             $tempKey = str_replace('__persist__', '', $key);
             if (!isset($params[$tempKey])) {
                 $params[$tempKey] = array();
             }
         }
     }
     if (empty($params['item_id'])) {
         return false;
     }
     $type = $this->getExtraField()->getExtraFieldType();
     // Parse params.
     foreach ($params as $key => $value) {
         if (substr($key, 0, 6) == 'extra_' || substr($key, 0, 7) == '_extra_') {
             // An extra field.
             $field_variable = substr($key, 6);
             $extraFieldInfo = $this->getExtraField()->get_handler_field_info_by_field_variable($field_variable);
             if ($extraFieldInfo) {
                 $commentVariable = 'extra_' . $field_variable . '_comment';
                 $comment = isset($params[$commentVariable]) ? $params[$commentVariable] : null;
                 switch ($extraFieldInfo['field_type']) {
                     case ExtraField::FIELD_TYPE_TAG:
                         if ($type == EntityExtraField::USER_FIELD_TYPE) {
                             UserManager::delete_user_tags($params['item_id'], $extraFieldInfo['id']);
                             UserManager::process_tags($value, $params['item_id'], $extraFieldInfo['id']);
                         } else {
                             $em = Database::getManager();
                             $tagValues = is_array($value) ? $value : [$value];
                             $tags = [];
                             foreach ($tagValues as $tagValue) {
                                 $tagsResult = $em->getRepository('ChamiloCoreBundle:Tag')->findBy(['tag' => $tagValue, 'fieldId' => $extraFieldInfo['id']]);
                                 if (empty($tagsResult)) {
                                     $tag = new \Chamilo\CoreBundle\Entity\Tag();
                                     $tag->setCount(0);
                                     $tag->setFieldId($extraFieldInfo['id']);
                                     $tag->setTag($tagValue);
                                     $tags[] = $tag;
                                 } else {
                                     $tags = array_merge($tags, $tagsResult);
                                 }
                             }
                             foreach ($tags as $tag) {
                                 $fieldTags = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')->findBy(['fieldId' => $extraFieldInfo['id'], 'itemId' => $params['item_id'], 'tagId' => $tag->getId()]);
                                 foreach ($fieldTags as $fieldTag) {
                                     $em->remove($fieldTag);
                                     $tag->setCount($tag->getCount() - 1);
                                     $em->persist($tag);
                                     $em->flush();
                                 }
                                 $tag->setCount($tag->getCount() + 1);
                                 $em->persist($tag);
                                 $em->flush();
                                 $fieldRelTag = new Chamilo\CoreBundle\Entity\ExtraFieldRelTag();
                                 $fieldRelTag->setFieldId($extraFieldInfo['id']);
                                 $fieldRelTag->setItemId($params['item_id']);
                                 $fieldRelTag->setTagId($tag->getId());
                                 $em->persist($fieldRelTag);
                                 $em->flush();
                             }
                         }
                         break;
                     case ExtraField::FIELD_TYPE_FILE_IMAGE:
                         $dirPermissions = api_get_permissions_for_new_directories();
                         switch ($this->type) {
                             case 'course':
                                 $fileDir = api_get_path(SYS_UPLOAD_PATH) . "courses/";
                                 $fileDirStored = "courses/";
                                 break;
                             case 'session':
                                 $fileDir = api_get_path(SYS_UPLOAD_PATH) . "sessions/";
                                 $fileDirStored = "sessions/";
                                 break;
                             case 'user':
                                 $fileDir = UserManager::getUserPathById($params['item_id'], 'system');
                                 $fileDirStored = UserManager::getUserPathById($params['item_id'], 'last');
                                 break;
                         }
                         $fileName = ExtraField::FIELD_TYPE_FILE_IMAGE . "_{$params['item_id']}.png";
                         if (!file_exists($fileDir)) {
                             mkdir($fileDir, $dirPermissions, true);
                         }
                         if ($value['error'] == 0) {
                             $imageExtraField = new Image($value['tmp_name']);
                             $imageExtraField->send_image($fileDir . $fileName, -1, 'png');
                             $newParams = array('item_id' => $params['item_id'], 'field_id' => $extraFieldInfo['id'], 'value' => $fileDirStored . $fileName, 'comment' => $comment);
                             self::save($newParams);
                         }
                         break;
                     case ExtraField::FIELD_TYPE_FILE:
                         $dirPermissions = api_get_permissions_for_new_directories();
                         switch ($this->type) {
                             case 'course':
                                 $fileDir = api_get_path(SYS_UPLOAD_PATH) . "courses/";
                                 $fileDirStored = "courses/";
                                 break;
                             case 'session':
                                 $fileDir = api_get_path(SYS_UPLOAD_PATH) . "sessions/";
                                 $fileDirStored = "sessions/";
                                 break;
                             case 'user':
                                 $fileDir = UserManager::getUserPathById($params['item_id'], 'system');
                                 $fileDirStored = UserManager::getUserPathById($params['item_id'], 'last');
                                 break;
                         }
                         $cleanedName = api_replace_dangerous_char($value['name']);
                         $fileName = ExtraField::FIELD_TYPE_FILE . "_{$params['item_id']}_{$cleanedName}";
                         if (!file_exists($fileDir)) {
                             mkdir($fileDir, $dirPermissions, true);
                         }
                         if ($value['error'] == 0) {
                             moveUploadedFile($value, $fileDir . $fileName);
                             $new_params = array('item_id' => $params['item_id'], 'field_id' => $extraFieldInfo['id'], 'value' => $fileDirStored . $fileName);
                             if ($this->type !== 'session' && $this->type !== 'course') {
                                 $new_params['comment'] = $comment;
                             }
                             self::save($new_params);
                         }
                         break;
                     default:
                         $newParams = array('item_id' => $params['item_id'], 'field_id' => $extraFieldInfo['id'], 'value' => $value, 'comment' => $comment);
                         self::save($newParams);
                 }
             }
         }
     }
 }
 /**
  * Read a course-object from a zip-file
  * @return course The course
  * @param boolean $delete Delete the file after reading the course?
  * @todo Check if the archive is a correct Chamilo-export
  */
 static function read_course($filename, $delete = false)
 {
     CourseArchiver::clean_backup_dir();
     // Create a temp directory
     $tmp_dir_name = 'CourseArchiver_' . uniqid('');
     $unzip_dir = api_get_path(SYS_ARCHIVE_PATH) . $tmp_dir_name;
     mkdir($unzip_dir, api_get_permissions_for_new_directories(), true);
     copy(api_get_path(SYS_ARCHIVE_PATH) . $filename, $unzip_dir . '/backup.zip');
     // unzip the archive
     $zip = new PclZip($unzip_dir . '/backup.zip');
     chdir($unzip_dir);
     $list = $zip->extract(PCLZIP_OPT_TEMP_FILE_ON);
     if ($list == 0) {
         /*global $app;
           $errorMessage = $zip->errorInfo(true);
           $app['session']->getFlashBag()->add('warning', $errorMessage);*/
     }
     // remove the archive-file
     if ($delete) {
         if (file_exists(api_get_path(SYS_ARCHIVE_PATH) . $filename)) {
             unlink(api_get_path(SYS_ARCHIVE_PATH) . $filename);
         }
     }
     // Read the course
     if (!is_file('course_info.dat')) {
         return new Course();
     }
     $contents = file_get_contents('course_info.dat');
     // CourseCopyLearnpath class appeared in Chamilo 1.8.7, it is the former Learnpath class in the "Copy course" tool.
     // For backward comaptibility with archives created on Chamilo 1.8.6.2 or older systems, we have to do the following:
     // Before unserialization, if class name "Learnpath" was found, it should be renamed as "CourseCopyLearnpath".
     $course = unserialize(str_replace('O:9:"Learnpath":', 'O:19:"CourseCopyLearnpath":', base64_decode($contents)));
     if (get_class($course) != 'Course') {
         return new Course();
     }
     $course->backup_path = $unzip_dir;
     return $course;
 }
Example #25
0
    /**
     * @param string $title
     * @param bool $show_header
     * @param bool $show_footer
     * @param bool $show_learnpath
     * @param bool $hide_global_chat
     * @param bool $load_plugins
     */
    public function __construct(
        $title = '',
        $show_header = true,
        $show_footer = true,
        $show_learnpath = false,
        $hide_global_chat = false,
        $load_plugins = true
    ) {
        // Page title
        $this->title            = $title;
        $this->show_learnpath   = $show_learnpath;
        $this->hide_global_chat = $hide_global_chat;
        $this->load_plugins     = $load_plugins;

        // Twig settings
        Twig_Autoloader::register();

        $template_paths = array(
            api_get_path(SYS_CODE_PATH).'template', //template folder
            api_get_path(SYS_PLUGIN_PATH) //plugin folder
        );

        $cache_folder = api_get_path(SYS_ARCHIVE_PATH).'twig';

        if (!is_dir($cache_folder)) {
            mkdir($cache_folder, api_get_permissions_for_new_directories());
        }

        $loader = new Twig_Loader_Filesystem($template_paths);

        //Setting Twig options depending on the server see http://twig.sensiolabs.org/doc/api.html#environment-options
        if (api_get_setting('server_type') == 'test') {
            $options = array(
                //'cache' => api_get_path(SYS_ARCHIVE_PATH), //path to the cache folder
                'autoescape'       => false,
                'debug'            => true,
                'auto_reload'      => true,
                'optimizations'    => 0, // turn on optimizations with -1
                'strict_variables' => false, //If set to false, Twig will silently ignore invalid variables
            );
        } else {
            $options = array(
                'cache'            => $cache_folder, //path to the cache folder
                'autoescape'       => false,
                'debug'            => false,
                'auto_reload'      => false,
                'optimizations'    => -1, // turn on optimizations with -1
                'strict_variables' => false //If set to false, Twig will silently ignore invalid variables
            );
        }

        $this->twig = new Twig_Environment($loader, $options);

        $this->twig->addFilter('get_plugin_lang', new Twig_Filter_Function('get_plugin_lang'));
        $this->twig->addFilter('get_lang', new Twig_Filter_Function('get_lang'));
        $this->twig->addFilter('get_path', new Twig_Filter_Function('api_get_path'));
        $this->twig->addFilter('get_setting', new Twig_Filter_Function('api_get_setting'));
        $this->twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
        $this->twig->addFilter('return_message', new Twig_Filter_Function('Display::return_message_and_translate'));
        $this->twig->addFilter('display_page_header', new Twig_Filter_Function('Display::page_header_and_translate'));
        $this->twig->addFilter(
            'display_page_subheader',
            new Twig_Filter_Function('Display::page_subheader_and_translate')
        );
        $this->twig->addFilter('icon', new Twig_Filter_Function('Template::get_icon_path'));
        $this->twig->addFilter('format_date', new Twig_Filter_Function('Template::format_date'));
        $this->twig->addFilter('api_get_local_time', new Twig_Filter_Function('api_get_local_time'));

        /*
          $lexer = new Twig_Lexer($this->twig, array(
          //'tag_comment'  => array('{*', '*}'),
          //'tag_comment'  => array('{#', '#}'),
          //'tag_block'    => array('{', '}'),
          //'tag_variable' => array('{$', '}'),
          ));
          $this->twig->setLexer($lexer); */

        //Setting system variables
        $this->set_system_parameters();

        //Setting user variables
        $this->set_user_parameters();

        //Setting course variables
        $this->set_course_parameters();

        //header and footer are showed by default
        $this->set_footer($show_footer);
        $this->set_header($show_header);

        $this->set_header_parameters();
        $this->set_footer_parameters();

        $defaultStyle = api_get_configuration_value('default_template');
        if (!empty($defaultStyle)) {
            $this->templateFolder = $defaultStyle;
        }

        $this->assign('template', $this->templateFolder);
        $this->assign('css_styles', $this->theme);
        $this->assign('login_class', null);

        // Chamilo plugins
        if ($this->show_header) {
            if ($this->load_plugins) {

                $this->plugin = new AppPlugin();

                //1. Showing installed plugins in regions
                $plugin_regions = $this->plugin->get_plugin_regions();
                foreach ($plugin_regions as $region) {
                    $this->set_plugin_region($region);
                }

                //2. Loading the course plugin info
                global $course_plugin;
                if (isset($course_plugin) && !empty($course_plugin) && !empty($this->course_id)) {
                    //Load plugin get_langs
                    $this->plugin->load_plugin_lang_variables($course_plugin);
                }
            }
        }
    }
Example #26
0
 /**
  * Exports the current SCORM object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath()
  * @param    integer    Learnpath ID (optional, taken from object context if not defined)
  */
 function export_zip($lp_id = null)
 {
     if ($this->debug > 0) {
         error_log('In scorm::export_zip method(' . $lp_id . ')', 0);
     }
     if (empty($lp_id)) {
         if (!is_object($this)) {
             return false;
         } else {
             $id = $this->get_id();
             if (empty($id)) {
                 return false;
             } else {
                 $lp_id = $this->get_id();
             }
         }
     }
     //error_log('New LP - in export_zip()',0);
     //zip everything that is in the corresponding scorm dir
     //write the zip file somewhere (might be too big to return)
     require_once 'learnpath_functions.inc.php';
     $course_id = api_get_course_int_id();
     $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
     $_course = api_get_course_info(api_get_course_id());
     $sql = "SELECT * FROM {$tbl_lp} WHERE c_id = " . $course_id . " AND id=" . $lp_id;
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
     $LPname = $row['path'];
     $list = split('/', $LPname);
     $LPnamesafe = $list[0];
     //$zipfoldername = '/tmp';
     //$zipfoldername = '../../courses/'.$_course['directory'].'/temp/'.$LPnamesafe;
     $zipfoldername = api_get_path(SYS_COURSE_PATH) . $_course['directory'] . '/temp/' . $LPnamesafe;
     $scormfoldername = api_get_path(SYS_COURSE_PATH) . $_course['directory'] . '/scorm/' . $LPnamesafe;
     $zipfilename = $zipfoldername . '/' . $LPnamesafe . '.zip';
     // Get a temporary dir for creating the zip file.
     //error_log('New LP - cleaning dir '.$zipfoldername, 0);
     deldir($zipfoldername);
     // Make sure the temp dir is cleared.
     $res = mkdir($zipfoldername, api_get_permissions_for_new_directories());
     //error_log('New LP - made dir '.$zipfoldername, 0);
     // Create zipfile of given directory.
     $zip_folder = new PclZip($zipfilename);
     $zip_folder->create($scormfoldername . '/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername . '/');
     //$zipfilename = '/var/www/chamilo/courses/TEST2/scorm/example_document.html';
     //This file sending implies removing the default mime-type from php.ini
     //DocumentManager :: file_send_for_download($zipfilename, true, $LPnamesafe.'.zip');
     DocumentManager::file_send_for_download($zipfilename, true);
     // Delete the temporary zip file and directory in fileManager.lib.php
     FileManager::my_delete($zipfilename);
     FileManager::my_delete($zipfoldername);
     return true;
 }
Example #27
0
 /**
  * Adds a picture to the question
  *
  * @author Olivier Brouckaert
  * @param string $Picture - temporary path of the picture to upload
  * @param string $PictureName - Name of the picture
  * @param string
  * @return bool - true if uploaded, otherwise false
  */
 public function uploadPicture($Picture, $PictureName, $picturePath = null)
 {
     if (empty($picturePath)) {
         global $picturePath;
     }
     if (!file_exists($picturePath)) {
         if (mkdir($picturePath, api_get_permissions_for_new_directories())) {
             // document path
             $documentPath = api_get_path(SYS_COURSE_PATH) . $this->course['path'] . "/document";
             $path = str_replace($documentPath, '', $picturePath);
             $title_path = basename($picturePath);
             $doc_id = FileManager::add_document($this->course, $path, 'folder', 0, $title_path);
             api_item_property_update($this->course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
         }
     }
     // if the question has got an ID
     if ($this->id) {
         $extension = pathinfo($PictureName, PATHINFO_EXTENSION);
         $this->picture = 'quiz-' . $this->id . '.jpg';
         $o_img = new Image($Picture);
         $o_img->send_image($picturePath . '/' . $this->picture, -1, 'jpg');
         $document_id = FileManager::add_document($this->course, '/images/' . $this->picture, 'file', filesize($picturePath . '/' . $this->picture), $this->picture);
         if ($document_id) {
             return api_item_property_update($this->course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id());
         }
     }
     return false;
 }
Example #28
0
 /**
  * Temp function to be moved in main_api or the best place around for this. Creates a file path
  * if it doesn't exist
  */
 public function create_path($path)
 {
     $path_bits = explode('/', dirname($path));
     // IS_WINDOWS_OS has been defined in api.lib.php
     $path_built = IS_WINDOWS_OS ? '' : '/';
     foreach ($path_bits as $bit) {
         if (!empty($bit)) {
             $new_path = $path_built . $bit;
             if (is_dir($new_path)) {
                 $path_built = $new_path . '/';
             } else {
                 mkdir($new_path, api_get_permissions_for_new_directories());
                 $path_built = $new_path . '/';
             }
         }
     }
 }
 /**
  * @param array $values
  * @param array $file $_FILES['uploaded_file']
  * @param bool  $deleteFile
  */
 public function save($values, $file = array(), $deleteFile = false)
 {
     $table = Database::get_main_table('session_rel_course_legal');
     $courseId = $values['c_id'];
     $sessionId = $values['session_id'];
     $conditions = array('c_id' => $courseId, 'session_id' => $sessionId);
     $course = api_get_course_info_by_id($courseId);
     $legalData = $this->getData($courseId, $sessionId);
     $coursePath = api_get_path(SYS_COURSE_PATH) . $course['directory'] . '/courselegal';
     $uploadResult = $coursePath . '/' . $legalData['filename'];
     if (!is_dir($coursePath)) {
         mkdir($coursePath, api_get_permissions_for_new_directories());
     }
     $uploadOk = process_uploaded_file($file, false);
     $fileName = null;
     if ($uploadOk) {
         $uploadResult = handle_uploaded_document($course, $file, $coursePath, '/', api_get_user_id(), api_get_group_id(), null, false, false, false, true);
         if ($uploadResult) {
             $fileName = basename($uploadResult);
             // Delete old one if exists.
             if ($legalData) {
                 if (!empty($legalData['filename'])) {
                     $fileToDelete = $coursePath . '/' . $legalData['filename'];
                     if (file_exists($fileToDelete)) {
                         unlink($fileToDelete);
                     }
                 }
             }
         }
     }
     $conditions['content'] = $values['content'];
     $conditions['filename'] = $fileName;
     if (empty($legalData)) {
         $id = Database::insert($table, $conditions);
     } else {
         $id = $legalData['id'];
         $updateParams = array('content' => $values['content']);
         if (!empty($fileName)) {
             $updateParams['filename'] = $fileName;
         }
         Database::update($table, $updateParams, array('id = ? ' => $id));
     }
     if ($deleteFile) {
         Database::update($table, array('filename' => ''), array('id = ? ' => $id));
         if (!empty($legalData['filename'])) {
             $fileToDelete = $coursePath . '/' . $legalData['filename'];
             if (file_exists($fileToDelete)) {
                 unlink($fileToDelete);
             }
         }
     }
     if (isset($values['remove_previous_agreements']) && !empty($values['remove_previous_agreements'])) {
         $this->removePreviousAgreements($courseId, $sessionId);
     }
     $warnUsers = isset($values['warn_users_by_email']) ? $values['warn_users_by_email'] : null;
     switch ($warnUsers) {
         case '1':
             // Nothing
             break;
         case '2':
             // Send mail
             $this->warnUsersByEmail($courseId, $sessionId);
             break;
         case '3':
             // Send mail + attachment if exists.
             if (!empty($legalData['filename'])) {
                 $this->warnUsersByEmail($courseId, $sessionId, $uploadResult);
             }
             break;
     }
 }
Example #30
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);
     }
 }