/**
  * Update the file or directory path in the document db document table
  *
  * @author - Hugues Peeters <*****@*****.**>
  * @param  - action (string) - action type require : 'delete' or 'update'
  * @param  - old_path (string) - old path info stored to change
  * @param  - new_path (string) - new path info to substitute
  * @desc Update the file or directory path in the document db document table
  *
  */
 static function update_db_info($action, $old_path, $new_path = '')
 {
     $dbTable = Database::get_course_table(TABLE_DOCUMENT);
     $course_id = api_get_course_int_id();
     /* DELETE */
     if ($action == 'delete') {
         $old_path = Database::escape_string($old_path);
         $to_delete = "WHERE c_id = {$course_id} AND path LIKE BINARY '" . $old_path . "' OR path LIKE BINARY '" . $old_path . "/%'";
         $query = "DELETE FROM {$dbTable} " . $to_delete;
         $result = Database::query("SELECT id FROM {$dbTable} " . $to_delete);
         if (Database::num_rows($result)) {
             require_once api_get_path(INCLUDE_PATH) . '../metadata/md_funcs.php';
             $mdStore = new mdstore(true);
             // create if needed
             $md_type = substr($dbTable, -13) == 'scormdocument' ? 'Scorm' : 'Document';
             while ($row = Database::fetch_array($result)) {
                 $eid = $md_type . '.' . $row['id'];
                 $mdStore->mds_delete($eid);
                 $mdStore->mds_delete_offspring($eid);
             }
         }
     }
     /* UPDATE */
     if ($action == 'update') {
         if ($new_path[0] == '.') {
             $new_path = substr($new_path, 1);
         }
         $new_path = str_replace('//', '/', $new_path);
         // Attempt to update	- tested & working for root	dir
         $new_path = Database::escape_string($new_path);
         $query = "UPDATE {$dbTable}\n            SET path = CONCAT('" . $new_path . "', SUBSTRING(path, LENGTH('" . $old_path . "')+1) )\n            WHERE c_id = {$course_id} AND path LIKE BINARY '" . $old_path . "' OR path LIKE BINARY '" . $old_path . "/%'";
     }
     Database::query($query);
 }
function create_backup_is_admin($_cid)
{
    $this_section = SECTION_COURSES;
    if (isset($_GET['session']) && $_GET['session']) {
        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
        $_cid = true;
        $is_courseAdmin = true;
    } else {
        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
    }
    $archive_file = $_GET['archive'];
    $archive_file = str_replace(array('..', '/', '\\'), '', $archive_file);
    list($extension) = getextension($archive_file);
    if (empty($extension) || !file_exists($archive_path . $archive_file)) {
        return false;
    }
    $extension = strtolower($extension);
    $content_type = '';
    if (in_array($extension, array('xml', 'csv')) && (api_is_platform_admin(true) || api_is_drh())) {
        $content_type = 'application/force-download';
        // TODO: The following unclear condition is commented ant is to be checked. A replacement has been proposed.
        //} elseif (strtolower($extension) == 'zip' || ('html' && $_cid && (api_is_platform_admin(true) || $is_courseAdmin))) {
    } elseif ($extension == 'zip' && $_cid && (api_is_platform_admin(true) || $is_courseAdmin)) {
        //
        $content_type = 'application/force-download';
    }
    if (empty($content_type)) {
        return false;
    }
    return true;
}
 /**
  * @param Request $request
  * @return null|RedirectResponse
  */
 public function onLogoutSuccess(Request $request)
 {
     // Chamilo logout
     $request->getSession()->remove('_locale');
     $request->getSession()->remove('_locale_user');
     if (api_is_global_chat_enabled()) {
         $chat = new \Chat();
         $chat->setUserStatus(0);
     }
     $userId = $this->storage->getToken()->getUser()->getId();
     $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql = "SELECT login_id, login_date\n                FROM {$tbl_track_login}\n                WHERE login_user_id = {$userId}\n                ORDER BY login_date DESC\n                LIMIT 0,1";
     $row = Database::query($sql);
     $loginId = null;
     if (Database::num_rows($row) > 0) {
         $loginId = Database::result($row, 0, "login_id");
     }
     $loginAs = $this->checker->isGranted('ROLE_PREVIOUS_ADMIN');
     if (!$loginAs) {
         $current_date = api_get_utc_datetime();
         $sql = "UPDATE {$tbl_track_login}\n                    SET logout_date='" . $current_date . "'\n        \t\t    WHERE login_id='{$loginId}'";
         Database::query($sql);
     }
     $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $query = "DELETE FROM " . $online_table . " WHERE login_user_id = {$userId}";
     Database::query($query);
     require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
     exit_of_chat($userId);
     $login = $this->router->generate('home');
     $response = new RedirectResponse($login);
     return $response;
 }
Beispiel #4
0
/**
 * Get a list of courses (code, url, title, teacher, language) for a specific
 * user and return to caller
 * Function registered as service. Returns strings in UTF-8.
 * @param string User name in Chamilo
 * @param string Signature (composed of the sha1(username+apikey)
 * @return array Courses list (code=>[title=>'title',url='http://...',teacher=>'...',language=>''],code=>[...],...)
 */
function WSCourseListOfUser($username, $signature)
{
    if (empty($username) or empty($signature)) {
        return -1;
    }
    global $_configuration;
    $info = api_get_user_info_from_username($username);
    $user_id = $info['user_id'];
    $list = UserManager::get_api_keys($user_id, 'dokeos');
    $key = '';
    foreach ($list as $key) {
        break;
    }
    $local_key = $username . $key;
    if (!api_is_valid_secret_key($signature, $local_key)) {
        return -1;
        // The secret key is incorrect.
    }
    $courses_list = array();
    $courses_list_tmp = CourseManager::get_courses_list_by_user_id($user_id);
    foreach ($courses_list_tmp as $index => $course) {
        $course_info = CourseManager::get_course_information($course['code']);
        $courses_list[] = array('code' => $course['code'], 'title' => api_utf8_encode($course_info['title']), 'url' => api_get_path(WEB_COURSE_PATH) . $course_info['directory'] . '/', 'teacher' => api_utf8_encode($course_info['tutor_name']), 'language' => $course_info['course_language']);
    }
    return $courses_list;
}
Beispiel #5
0
/**
 * Garbage collector caller function
 */
function HotPotGC($root_sys, $flag, $userID)
{
    // flag[0,1] - print or delete the HotPotatoes temp files (.t.html)
    $documentPath = $root_sys . "courses";
    require_once api_get_path(LIBRARY_PATH) . "fileManage.lib.php";
    HotPotGCt($documentPath, $flag, $userID);
}
 /**
  * Connect to the database, and create it if it doesn't exist
  */
 function connectDb($path = null, $dbMode = null, $lang = 'english')
 {
     if ($this->db != null) {
         return $this->db;
     }
     if ($dbMode == null) {
         $dbMode = Xapian::DB_CREATE_OR_OPEN;
     }
     if ($path == null) {
         $path = api_get_path(SYS_DATA_PATH) . 'searchdb/';
     }
     try {
         $this->db = new XapianWritableDatabase($path, $dbMode);
         $this->indexer = new XapianTermGenerator();
         if (!in_array($lang, $this->xapian_languages())) {
             $lang = 'english';
         }
         $this->stemmer = new XapianStem($lang);
         $this->indexer->set_stemmer($this->stemmer);
         return $this->db;
     } catch (Exception $e) {
         Display::display_error_message($e->getMessage());
         return 1;
     }
 }
/**
 * Get a list of courses (code, url, title, teacher, language) and return to caller
 * Function registered as service. Returns strings in UTF-8.
 * @param string Security key (the Dokeos install's API key)
 * @param mixed  Array or string. Type of visibility of course (public, public-registered, private, closed)
 * @return array Courses list (code=>[title=>'title',url='http://...',teacher=>'...',language=>''],code=>[...],...)
 */
function courses_list($security_key, $visibilities = 'public')
{
    global $_configuration;
    // Check if this script is launch by server and if security key is ok.
    if ($security_key != $_configuration['security_key']) {
        return array('error_msg' => 'Security check failed');
    }
    $vis = array('public' => '3', 'public-registered' => '2', 'private' => '1', 'closed' => '0');
    $courses_list = array();
    if (!is_array($visibilities)) {
        $tmp = $visibilities;
        $visibilities = array($tmp);
    }
    foreach ($visibilities as $visibility) {
        if (!in_array($visibility, array_keys($vis))) {
            return array('error_msg' => 'Security check failed');
        }
        $courses_list_tmp = CourseManager::get_courses_list(null, null, null, null, $vis[$visibility]);
        foreach ($courses_list_tmp as $index => $course) {
            $course_info = CourseManager::get_course_information($course['code']);
            $courses_list[$course['code']] = array('title' => api_utf8_encode($course_info['title']), 'url' => api_get_path(WEB_COURSE_PATH) . $course_info['directory'] . '/', 'teacher' => api_utf8_encode($course_info['tutor_name']), 'language' => $course_info['course_language']);
        }
    }
    return $courses_list;
}
Beispiel #8
0
 /**
  *
  * Constructor (generates a connection to the API and the Chamilo settings
  * required for the connection to the video conference server)
  * @param string $host
  * @param string $salt
  */
 public function __construct($host = null, $salt = null)
 {
     // Initialize video server settings from global settings
     $plugin = BBBPlugin::create();
     $bbb_plugin = $plugin->get('tool_enable');
     if (empty($host)) {
         $bbb_host = $plugin->get('host');
     } else {
         $bbb_host = $host;
     }
     if (empty($salt)) {
         $bbb_salt = $plugin->get('salt');
     } else {
         $bbb_salt = $salt;
     }
     $this->logout_url = api_get_path(WEB_PLUGIN_PATH) . 'bbb/listing.php?' . api_get_cidreq();
     $this->table = Database::get_main_table('plugin_bbb_meeting');
     if ($bbb_plugin == true) {
         $userInfo = api_get_user_info();
         $this->user_complete_name = $userInfo['complete_name'];
         $this->salt = $bbb_salt;
         $info = parse_url($bbb_host);
         $this->url = $bbb_host . '/bigbluebutton/';
         if (isset($info['scheme'])) {
             $this->protocol = $info['scheme'] . '://';
             $this->url = str_replace($this->protocol, '', $this->url);
         }
         // Setting BBB api
         define('CONFIG_SECURITY_SALT', $this->salt);
         define('CONFIG_SERVER_BASE_URL', $this->url);
         $this->api = new BigBlueButtonBN();
         $this->plugin_enabled = true;
     }
 }
function get_all_php_files($base_path)
{
    $list = scandir($base_path);
    $files = array();
    foreach ($list as $item) {
        if (substr($item, 0, 1) == '.') {
            continue;
        }
        $special_dirs = array(api_get_path(SYS_TEST_PATH), api_get_path(SYS_COURSE_PATH), api_get_path(SYS_LANG_PATH), api_get_path(SYS_ARCHIVE_PATH));
        if (in_array($base_path . $item . '/', $special_dirs)) {
            continue;
        }
        if (is_dir($base_path . $item)) {
            $files = array_merge($files, get_all_php_files($base_path . $item . '/'));
        } else {
            //only analyse php files
            $sub = substr($item, -4);
            if ($sub == '.php' or $sub == '.tpl') {
                $files[] = $base_path . $item;
            }
        }
    }
    $list = null;
    return $files;
}
 /**
  * Create a Shibboleth session for the user ID
  *
  * @param  string $uid - The user ID
  * @return $_user (array) - The user infos array created when the user logs in
  */
 function login($uid)
 {
     /* This must be set for local.inc.php to register correctly the global variables in session
      * This is BAD. Logic should be migrated into a function and stop relying on global variables.
      */
     global $_uid, $is_allowedCreateCourse, $_real_cid, $_courseUser;
     global $is_courseMember, $is_courseTutor, $is_allowed_in_course, $_gid;
     $_uid = $uid;
     //is_allowedCreateCourse
     $user = User::store()->get_by_user_id($uid);
     if (empty($user)) {
         return;
     }
     $this->logout();
     Chamilo::session()->start();
     Session::write('_uid', $_uid);
     global $_user;
     $_user = (array) $user;
     $_SESSION['_user'] = $_user;
     $_SESSION['_user']['user_id'] = $_uid;
     $_SESSION['noredirection'] = true;
     //must be called before 'init_local.inc.php'
     event_login();
     //used in 'init_local.inc.php' this is BAD but and should be changed
     $loginFailed = false;
     $uidReset = true;
     $gidReset = true;
     $cidReset = false;
     //FALSE !!
     $mainDbName = Database::get_main_database();
     $includePath = api_get_path(INCLUDE_PATH);
     $no_redirection = true;
     require "{$includePath}/local.inc.php";
     return $_user;
 }
 /**
  * Create the dummy course
  */
 function create_dummy_course($course_code)
 {
     $this->default_property['insert_user_id'] = '1';
     $this->default_property['insert_date'] = date('Y-m-d H:i:s');
     $this->default_property['lastedit_date'] = date('Y-m-d H:i:s');
     $this->default_property['lastedit_user_id'] = '1';
     $this->default_property['to_group_id'] = '0';
     $this->default_property['to_user_id'] = null;
     $this->default_property['visibility'] = '1';
     $this->default_property['start_visible'] = '0000-00-00 00:00:00';
     $this->default_property['end_visible'] = '0000-00-00 00:00:00';
     $course = Database::get_course_info($course_code);
     $this->course = new Course();
     $tmp_path = api_get_path(SYS_COURSE_PATH) . $course['directory'] . '/document/tmp_' . uniqid('');
     @mkdir($tmp_path, api_get_permissions_for_new_directories(), true);
     $this->course->backup_path = $tmp_path;
     $this->create_dummy_links();
     $this->create_dummy_events();
     $this->create_dummy_forums();
     $this->create_dummy_announcements();
     $this->create_dummy_documents();
     $this->create_dummy_learnpaths();
     $cr = new CourseRestorer($this->course);
     $cr->set_file_option(FILE_OVERWRITE);
     $cr->restore($course_code);
     rmdirr($tmp_path);
 }
Beispiel #12
0
 function mdobject($_course, $eid)
 {
     if (!($dotpos = strpos($eid, '.'))) {
         return;
     }
     $this->mdo_course = $_course;
     $this->mdo_eid = $eid;
     $this->mdo_type = $type = substr($eid, 0, $dotpos);
     $this->mdo_id = $id = substr($eid, $dotpos + 1);
     if ($type == 'Document' || $type == 'Scorm') {
         $table = $type == 'Scorm' ? Database::get_course_table(TABLE_SCORMDOC) : Database::get_course_table(TABLE_DOCUMENT);
         if ($dotpos = strpos($id, '.')) {
             $urlp = '?sid=' . urlencode(substr($id, $dotpos + 1));
             $id = substr($id, 0, $dotpos);
         }
         if ($docinfo = @mysql_fetch_array(Database::query("SELECT path,comment,filetype FROM\n                 {$table} WHERE id='" . addslashes($id) . "'"))) {
             $this->mdo_path = $docinfo['path'];
             $this->mdo_comment = $docinfo['comment'];
             $this->mdo_filetype = $docinfo['filetype'];
             if ($type == 'Scorm') {
                 $this->mdo_base_url = get_course_web() . $this->mdo_course['path'] . '/scorm' . $this->mdo_path;
                 $this->mdo_url = $this->mdo_base_url . '/index.php' . $urlp;
             } else {
                 $this->mdo_url = api_get_path(WEB_PATH) . 'main/document/' . ($this->mdo_filetype == 'file' ? 'download' : 'document') . '.php?' . ($this->mdo_filetype == 'file' ? 'doc_url=' : 'curdirpath=') . urlencode($this->mdo_path);
             }
         }
     } elseif ($type == 'Link') {
         $link_table = Database::get_course_table(TABLE_LINK);
         if ($linkinfo = @mysql_fetch_array(Database::query("SELECT url,title,description,category_id FROM\n                 {$link_table} WHERE id='" . addslashes($id) . "'"))) {
             $this->mdo_url = $linkinfo['url'];
         }
     }
 }
Beispiel #13
0
 /**
  * {@inheritdoc}
  */
 public function getConfiguration()
 {
     if ($this->connector->security->isGranted('ROLE_ADMIN')) {
         $home = api_get_path(SYS_DATA_PATH) . 'home';
         return array('driver' => 'HomeDriver', 'alias' => $this->connector->translator->trans('Portal'), 'path' => $home, 'URL' => api_get_path(WEB_DATA_PATH) . 'home', 'accessControl' => array($this, 'access'));
     }
 }
Beispiel #14
0
 /**
  * Application web root
  */
 public static function www()
 {
     static $result = false;
     if (empty($result)) {
         $result = api_get_path(WEB_PATH);
     }
     return $result;
 }
Beispiel #15
0
 /**
  * {@inheritdoc}
  */
 public function getConfiguration()
 {
     if ($this->allow()) {
         $home = api_get_path(SYS_APP_PATH) . 'home';
         return array('driver' => 'HomeDriver', 'alias' => get_lang('Portal'), 'path' => $home, 'URL' => api_get_path(WEB_PATH) . 'home', 'accessControl' => array($this, 'access'));
     }
     return array();
 }
Beispiel #16
0
 public function getConfig()
 {
     // Original from ckeditor
     /*
             $config['toolbarGroups'] = array(
                 array('name' => 'document',  'groups' =>array('mode', 'document', 'doctools')),
                 array('name' => 'clipboard',    'groups' =>array('clipboard', 'undo', )),
                 array('name' => 'editing',    'groups' =>array('clipboard', 'undo', )),
                 array('name' => 'forms',    'groups' =>array('clipboard', 'undo', )),
                 '/',
                 array('name' => 'basicstyles',    'groups' =>array('basicstyles', 'cleanup', )),
                 array('name' => 'paragraph',    'groups' =>array('list', 'indent', 'blocks', 'align' )),
                 array('name' => 'links'),
                 array('name' => 'insert'),
                 '/',
                 array('name' => 'styles'),
                 array('name' => 'colors'),
                 array('name' => 'tools'),
                 array('name' => 'others'),
                 array('name' => 'about')
             );*/
     $config['toolbarGroups'] = array(array('name' => 'document', 'groups' => array('document', 'doctools')), array('name' => 'clipboard', 'groups' => array('clipboard', 'undo')), array('name' => 'editing', 'groups' => array('clipboard', 'undo')), '/', array('name' => 'basicstyles', 'groups' => array('basicstyles', 'cleanup')), array('name' => 'paragraph', 'groups' => array('list', 'indent', 'blocks', 'align')), array('name' => 'links'), array('name' => 'insert'), '/', array('name' => 'styles'), array('name' => 'colors'), array('name' => 'tools'), array('name' => 'others'), array('name' => 'allMedias'), array('name' => 'mode'));
     // file manager (elfinder)
     // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
     $config['filebrowserBrowseUrl'] = api_get_path(WEB_PUBLIC_PATH) . 'editor/filemanager';
     $config['templates_files'] = array(api_get_path(WEB_PUBLIC_PATH) . 'editor/templates');
     /*filebrowserFlashBrowseUrl
       filebrowserFlashUploadUrl
       filebrowserImageBrowseLinkUrl
       filebrowserImageBrowseUrl
       filebrowserImageUploadUrl
       filebrowserUploadUrl*/
     //$config['extraPlugins'] = 'oembed,video,wordcount';
     $config['extraPlugins'] = 'oembed,video';
     //$config['oembed_maxWidth'] = '560';
     //$config['oembed_maxHeight'] = '315';
     $config['allowedContent'] = true;
     /*$config['wordcount'] = array(
           // Whether or not you want to show the Word Count
           'showWordCount' => true,
           // Whether or not you want to show the Char Count
           'showCharCount' => true,
           // Option to limit the characters in the Editor
           'charLimit' => 'unlimited',
           // Option to limit the words in the Editor
           'wordLimit' => 'unlimited'
       );*/
     //$config['skins'] = 'moono';
     if (isset($this->config)) {
         $this->config = array_merge($config, $this->config);
     } else {
         $this->config = $config;
     }
     //$config['width'] = '100';
     //$config['height'] = '200';
     return $this->config;
 }
 /**
  * @return string
  */
 public function getCourseDocumentWebPath()
 {
     $url = null;
     if (isset($this->connector->course)) {
         $directory = $this->connector->course->getDirectory();
         $url = api_get_path(REL_COURSE_PATH) . $directory . '/document/';
     }
     return $url;
 }
 /**
  * Get the necessary javascript for this datepicker
  */
 private function getElementJS()
 {
     $js = '';
     if (!defined('DATEPICKER_JAVASCRIPT_INCLUDED')) {
         define('DATEPICKER_JAVASCRIPT_INCLUDED', 1);
         $js .= '<script src="' . api_get_path(WEB_CODE_PATH) . 'inc/lib/formvalidator/Element/tbl_change.js.php" type="text/javascript"></script>';
     }
     return $js;
 }
Beispiel #19
0
 public function __construct($path)
 {
     if (empty($path)) {
         return false;
     }
     $this->path = preg_match(VALID_WEB_PATH, $path) ? api_is_internal_path($path) ? api_get_path(TO_SYS, $path) : $path : $path;
     $this->set_image_wrapper();
     //Creates image obj
 }
 /**
  * Get the terms stored at database
  * @return  array Array of terms
  */
 function get_terms_on_db($prefix, $course_code, $tool_id, $ref_id)
 {
     require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
     $terms = get_specific_field_values_list_by_prefix($prefix, $course_code, $tool_id, $ref_id);
     $prefix_terms = array();
     foreach ($terms as $term) {
         $prefix_terms[] = $term['value'];
     }
     return $prefix_terms;
 }
Beispiel #21
0
 /**
  * Room constructor.
  */
 public function __construct()
 {
     $this->table = \Database::get_main_table('plugin_openmeetings');
     $this->name = 'C' . api_get_real_course_id() . '-' . api_get_session_id();
     $accessUrl = api_get_access_url(api_get_current_access_url_id());
     $this->externalRoomType = substr($accessUrl['url'], strpos($accessUrl['url'], '://') + 3, -1);
     if (strcmp($this->externalRoomType, 'localhost') == 0) {
         $this->externalRoomType = substr(api_get_path(WEB_PATH), strpos(api_get_path(WEB_PATH), '://') + 3, -1);
     }
     $this->externalRoomType = 'chamilolms.' . $this->externalRoomType;
 }
/**
 * 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;
    }
}
Beispiel #23
0
/**
 * This function connect to facebook and retrieves the user info
 * If user does not exist in chamilo, it creates it and logs in
 * If user already exists, it updates his info
 */
function facebookConnect()
{
    global $facebook_config;
    global $helper;
    try {
        $helper = new FacebookRedirectLoginHelper($facebook_config['return_url']);
        $session = $helper->getSessionFromRedirect();
        // see if we have a session
        if (isset($session)) {
            // graph api request for user data
            $request = new FacebookRequest($session, 'GET', '/me');
            $response = $request->execute();
            // get response
            $graphObject = $response->getGraphObject();
            $username = changeToValidChamiloLogin($graphObject->getProperty('email'));
            $email = $graphObject->getProperty('email');
            $locale = $graphObject->getProperty('locale');
            $language = facebookPluginGetLanguage($locale);
            if (!$language) {
                $language = 'en_US';
            }
            //Checks if user already exists in chamilo
            $u = array('firstname' => $graphObject->getProperty('first_name'), 'lastname' => $graphObject->getProperty('last_name'), 'status' => STUDENT, 'email' => $graphObject->getProperty('email'), 'username' => $username, 'language' => $language, 'password' => 'facebook', 'auth_source' => 'facebook', 'extra' => array());
            $chamiloUinfo = api_get_user_info_from_email($email);
            if ($chamiloUinfo === false) {
                // we have to create the user
                $chamilo_uid = external_add_user($u);
                if ($chamilo_uid !== false) {
                    $_user['user_id'] = $chamilo_uid;
                    $_user['uidReset'] = true;
                    $_SESSION['_user'] = $_user;
                    header('Location:' . api_get_path(WEB_PATH));
                    exit;
                } else {
                    return false;
                }
            } else {
                // User already exists, update info and login
                $chamilo_uid = $chamiloUinfo['user_id'];
                $u['user_id'] = $chamilo_uid;
                external_update_user($u);
                $_user['user_id'] = $chamilo_uid;
                $_user['uidReset'] = true;
                $_SESSION['_user'] = $_user;
                header('Location:' . api_get_path(WEB_PATH));
                exit;
            }
        }
    } catch (FacebookRequestException $ex) {
        echo $ex;
    } catch (Exception $ex) {
        // When validation fails or other local issues
    }
}
Beispiel #24
0
 public function __construct()
 {
     $this->paths = array('root_sys' => api_get_path(SYS_PATH), 'sys_root' => api_get_path(SYS_PATH), 'sys_course_path' => api_get_path(SYS_COURSE_PATH), 'path.temp' => api_get_path(SYS_ARCHIVE_PATH));
     /*$this->entityManager = $entityManager;
       $this->paths = $paths;
       $this->urlGenerator = $urlGenerator;
       $this->translator = $translator;
       $this->security = $security;*/
     $this->user = api_get_user_info();
     $this->course = api_get_course_info();
     $this->driverList = $this->getDefaultDriverList();
 }
Beispiel #25
0
 public function __construct(EntityManager $entityManager, array $paths, Router $urlGenerator, Translator $translator, SecurityContext $security, $user, $course = null)
 {
     $this->paths = array('root_sys' => api_get_path(SYS_PATH), 'sys_root' => api_get_path(SYS_PATH), 'sys_course_path' => api_get_path(SYS_COURSE_PATH), 'path.temp' => api_get_path(SYS_ARCHIVE_PATH));
     $this->entityManager = $entityManager;
     //$this->paths = $paths;
     $this->urlGenerator = $urlGenerator;
     $this->translator = $translator;
     $this->security = $security;
     $this->user = empty($user) ? api_get_user_info() : $user;
     $this->course = empty($course) ? api_get_course_info() : $course;
     $this->driverList = $this->getDefaultDriverList();
 }
 /**
  * Runs the import process
  */
 public function run()
 {
     $path = api_get_path(SYS_CODE_PATH) . 'cron/incoming/';
     if (!is_dir($path)) {
         echo "The folder! {$path} does not exits";
         exit;
     }
     if ($this->getDumpValues()) {
         $this->dumpDatabaseTables();
     }
     echo "Starting with reading the files: " . PHP_EOL . PHP_EOL;
     $files = scandir($path);
     $fileToProcess = array();
     if (!empty($files)) {
         foreach ($files as $file) {
             $fileInfo = pathinfo($file);
             if ($fileInfo['extension'] == 'csv') {
                 // teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
                 $parts = explode('_', $fileInfo['filename']);
                 $method = 'import' . ucwords($parts[1]);
                 if (method_exists($this, $method)) {
                     $fileToProcess[$parts[1]][] = array('method' => $method, 'file' => $path . $fileInfo['basename']);
                     //$this->$method($path.$fileInfo['basename']);
                 } else {
                     echo "Error - This file '{$file}' can't be processed." . PHP_EOL;
                     echo "The file have to has this format:" . PHP_EOL;
                     echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv " . PHP_EOL;
                     exit;
                 }
             }
         }
         if (empty($fileToProcess)) {
             echo 'Error - no files to process.';
             exit;
         }
         $sections = array('students', 'teachers', 'courses', 'sessions');
         $this->prepareImport();
         foreach ($sections as $section) {
             $this->logger->addInfo("-- Import {$section} --");
             if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
                 $files = $fileToProcess[$section];
                 foreach ($files as $fileInfo) {
                     $method = $fileInfo['method'];
                     $file = $fileInfo['file'];
                     echo 'Reading file: ' . $file . PHP_EOL;
                     $this->logger->addInfo("Reading file: {$file}");
                     $this->{$method}($file);
                 }
             }
         }
     }
 }
    /**
     * getMobilePhoneNumberById (retrieves a user mobile phone number by user id)
     * @param   int User id
     * @return  int User's mobile phone number
     */
    private function getMobilePhoneNumberById($userId)
    {
        require_once api_get_path(LIBRARY_PATH).'extra_field.lib.php';
        require_once api_get_path(LIBRARY_PATH).'extra_field_value.lib.php';

        $mobilePhoneNumberExtraField = new ExtraField('user');
        $mobilePhoneNumberExtraField = $mobilePhoneNumberExtraField->get_handler_field_info_by_field_variable('mobile_phone_number');

        $mobilePhoneNumberExtraFieldValue = new ExtraFieldValue('user');
        $mobilePhoneNumberExtraFieldValue = $mobilePhoneNumberExtraFieldValue->get_values_by_handler_and_field_id($userId, $mobilePhoneNumberExtraField['id']);

        return $mobilePhoneNumberExtraFieldValue['field_value'];
    }
/**
 * Checks total platform size
 * @param bool $debug
 *
 * @return bool
 */
function isTotalPortalSizeBiggerThanLimit($debug = true)
{
    $sizeLimit = api_get_configuration_value('hosting_total_size_limit');
    if (empty($sizeLimit)) {
        return true;
    }
    $updateFile = true;
    $file = api_get_path(SYS_COURSE_PATH) . 'hosting_total_size.php';
    // Default data
    $hostingData = array('frequency' => 86400);
    $log = null;
    // Check if file exists and if it is updated
    if (file_exists($file)) {
        $hostingDataFromFile = (require $file);
        // Check time() is UTC
        if (isset($hostingDataFromFile['updated_at']) && isset($hostingDataFromFile['frequency']) && isset($hostingDataFromFile['size'])) {
            $hostingData = $hostingDataFromFile;
            $time = $hostingData['updated_at'] + $hostingData['frequency'];
            $diff = $time - time();
            if ($time > time()) {
                $log .= "You need to wait {$diff} seconds to update the file \n";
                $updateFile = false;
            }
        }
    }
    // Now get values for total portal size
    $log .= "Frequency loaded: " . $hostingData['frequency'] . "\n";
    if ($updateFile) {
        $log .= "Updating total size ... \n";
        $totalSize = calculateTotalPortalSize($debug);
        $log .= "Total size calculated: {$totalSize} \n";
        $hostingData['updated_at'] = time();
        $hostingData['size'] = $totalSize;
        $writer = new Zend\Config\Writer\PhpArray();
        $phpCode = $writer->toString($hostingData);
        file_put_contents($file, $phpCode);
        $log .= "File saved in {$file} \n";
    } else {
        $log .= "Total size not updated \n";
        $totalSize = $hostingData['size'];
    }
    $result = true;
    if ($totalSize > $sizeLimit) {
        $log .= "Current total size of {$totalSize} MB is bigger than limit: {$sizeLimit} MB \n";
        $result = false;
    }
    if ($debug) {
        echo $log;
    }
    return $result;
}
 /**
  * Redirect to the session "request uri" if it exists.
  * @param bool Whether the user just logged in (in this case, use page_after_login rules)
  */
 static function session_request_uri($logging_in = false, $user_id = null)
 {
     $no_redirection = isset($_SESSION['noredirection']) ? $_SESSION['noredirection'] : false;
     if ($no_redirection) {
         unset($_SESSION['noredirection']);
         return;
     }
     $url = isset($_SESSION['request_uri']) ? $_SESSION['request_uri'] : '';
     unset($_SESSION['request_uri']);
     if (!empty($url)) {
         self::navigate($url);
     } elseif ($logging_in || isset($_REQUEST['sso_referer']) && !empty($_REQUEST['sso_referer'])) {
         if (isset($user_id)) {
             // Make sure we use the appropriate role redirection in case one has been defined
             $user_status = api_get_user_status($user_id);
             switch ($user_status) {
                 case COURSEMANAGER:
                     $redir = api_get_setting('teacher_page_after_login');
                     if (!empty($redir)) {
                         self::navigate(api_get_path(WEB_PATH) . $redir);
                     }
                     break;
                 case STUDENT:
                     $redir = api_get_setting('student_page_after_login');
                     if (!empty($redir)) {
                         self::navigate(api_get_path(WEB_PATH) . $redir);
                     }
                     break;
                 case DRH:
                     $redir = api_get_setting('drh_page_after_login');
                     if (!empty($redir)) {
                         self::navigate(api_get_path(WEB_PATH) . $redir);
                     }
                     break;
                 case SESSIONADMIN:
                     $redir = api_get_setting('sessionadmin_page_after_login');
                     if (!empty($redir)) {
                         self::navigate(api_get_path(WEB_PATH) . $redir);
                     }
                     break;
                 default:
                     break;
             }
         }
         $page_after_login = api_get_setting('page_after_login');
         if (!empty($page_after_login)) {
             self::navigate(api_get_path(WEB_PATH) . $page_after_login);
         }
     }
 }
Beispiel #30
0
/**
 * Checks whether a user has the right to enter on the platform or not
 * @param string The username, as provided in form
 * @param string The cleartext password, as provided in form
 * @param string The WS URL, as provided at the beginning of this script
 */
function loginWSAuthenticate($username, $password, $wsUrl)
{
    // check params
    if (empty($username) or empty($password) or empty($wsUrl)) {
        return false;
    }
    // Create new SOAP client instance
    $client = new SoapClient($wsUrl);
    if (!$client) {
        return false;
    }
    // Include phpseclib methods, because of a bug with AES/CFB in mcrypt
    include_once api_get_path(LIBRARY_PATH) . 'phpseclib/Crypt/AES.php';
    // Define all elements necessary to the encryption
    $key = '-+*%$({[]})$%*+-';
    // Complete password con PKCS7-specific padding
    $blockSize = 16;
    $padding = $blockSize - strlen($password) % $blockSize;
    $password .= str_repeat(chr($padding), $padding);
    $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
    $cipher->setKeyLength(128);
    $cipher->setKey($key);
    $cipher->setIV($key);
    $cipheredPass = $cipher->encrypt($password);
    // Mcrypt call left for documentation purposes - broken, see https://bugs.php.net/bug.php?id=51146
    //$cipheredPass = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $password,  MCRYPT_MODE_CFB, $key);
    // Following lines present for debug purposes only
    /*
    $arr = preg_split('//', $cipheredPass, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($arr as $char) {
        error_log(ord($char));
    }
    */
    // Change to base64 to avoid communication alteration
    $passCrypted = base64_encode($cipheredPass);
    // The call to the webservice will change depending on your definition
    try {
        $response = $client->validateUser(array('user' => $username, 'pass' => $passCrypted, 'system' => 'chamilo'));
    } catch (SoapFault $fault) {
        error_log('Caught something');
        if ($fault->faultstring != 'Could not connect to host') {
            error_log('Not a connection problem');
            throw $fault;
        } else {
            error_log('Could not connect to WS host');
        }
        return 0;
    }
    return $response->validateUserResult;
}