Ejemplo n.º 1
0
 /**
  * Constructor
  * @param int $certificate_id ID of the certificate.
  *
  * If no ID given, take user_id and try to generate one
  */
 public function __construct($certificate_id = null)
 {
     $this->table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $this->certificate_data = null;
     if (isset($certificate_id)) {
         $this->certificate_data = $this->get($certificate_id);
         $this->user_id = $this->certificate_data['user_id'];
     } else {
         //Try with the current user
         $this->user_id = api_get_user_id();
     }
     if ($this->user_id) {
         // Need to be called before any operation
         $this->check_certificate_path();
         // To force certification generation
         if ($this->force_certificate_generation) {
             $this->generate();
         }
         if (isset($this->certificate_data) && $this->certificate_data) {
             if (empty($this->certificate_data['path_certificate'])) {
                 $this->generate();
             }
         }
     }
     //Setting the qr and html variables
     if (isset($certificate_id) && !empty($this->certification_user_path)) {
         $pathinfo = pathinfo($this->certificate_data['path_certificate']);
         $this->html_file = $this->certification_user_path . basename($this->certificate_data['path_certificate']);
         $this->qr_file = $this->certification_user_path . $pathinfo['filename'] . '_qr.png';
     }
 }
Ejemplo n.º 2
0
 /**
  * Setups the folder
  */
 public function setup()
 {
     $userId = api_get_user_id();
     $userInfo = api_get_user_info();
     $sessionId = api_get_session_id();
     $courseInfo = $this->connector->course;
     if (!empty($courseInfo)) {
         $coursePath = api_get_path(SYS_COURSE_PATH);
         $courseDir = $courseInfo['directory'] . '/document';
         $baseDir = $coursePath . $courseDir;
         // Creates shared folder
         if (!file_exists($baseDir . '/shared_folder')) {
             $title = get_lang('UserFolders');
             $folderName = '/shared_folder';
             //$groupId = 0;
             $visibility = 0;
             create_unexisting_directory($courseInfo, $userId, $sessionId, 0, null, $baseDir, $folderName, $title, $visibility);
         }
         // Creates user-course folder
         if (!file_exists($baseDir . '/shared_folder/sf_user_' . $userId)) {
             $title = $userInfo['complete_name'];
             $folderName = '/shared_folder/sf_user_' . $userId;
             $visibility = 1;
             create_unexisting_directory($courseInfo, $userId, $sessionId, 0, null, $baseDir, $folderName, $title, $visibility);
         }
     }
 }
Ejemplo n.º 3
0
function storage_can_set($sv_user) {
	// platform admin can change any user's stored values, other users can only change their own values
	$allowed = ((api_is_platform_admin()) || ($sv_user == api_get_user_id()));
	if (!$allowed) {
		print "ERROR : Not allowed";
	}
	return $allowed;
}
Ejemplo n.º 4
0
 /**
  * Updates an URL access
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param	int 	$url_id The url id
  * @param	string 	$url
  * @param	string  $description The description of the site
  * @param	int		$active is active or not
  * @return 	boolean if success
  */
 public static function update($url_id, $url, $description, $active)
 {
     $url_id = intval($url_id);
     $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
     $sql = "UPDATE {$table}\n                SET url \t= '" . Database::escape_string($url) . "',\n                description = '" . Database::escape_string($description) . "',\n                active \t\t= '" . intval($active) . "',\n                created_by \t= '" . api_get_user_id() . "',\n                tms \t\t= '" . api_get_utc_datetime() . "'\n                WHERE id = '{$url_id}'";
     $result = Database::query($sql);
     return $result;
 }
Ejemplo n.º 5
0
 /**
  * Updates an URL access to Dokeos
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param    int    The url id
  * @param    string  The description of the site
  * @param    int        is active or not
  * @param    int     the user_id of the owner
  * @param    int    The URL type
  * @param    array    Extra parameters for type > 1
  * @return    boolean if success
  */
 public static function update($url_id, $url, $description, $active, $type, $extra_params)
 {
     $url_id = intval($url_id);
     $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
     $tms = time();
     $sql = "UPDATE {$table_access_url}\n                SET url \t= '" . Database::escape_string($url) . "',\n                description = '" . Database::escape_string($description) . "',\n                active \t\t= '" . Database::escape_string($active) . "',\n                created_by \t= '" . api_get_user_id() . "',\n                tms \t\t= FROM_UNIXTIME(" . $tms . ")\n                WHERE id = '{$url_id}'";
     $result = Database::query($sql);
     return $result;
 }
 /**
  * @param Application $app
  * @param string $type courses|sessions|mycoursecategories
  * @param string $filter for the userportal courses page. Only works when setting 'history'
  * @param int $page
  *
  * @return Response|void
  */
 public function indexAction(Application $app, $type = 'courses', $filter = 'current', $page = 1)
 {
     // @todo Use filters like "after/before|finish" to manage user access
     api_block_anonymous_users();
     // Abort request because the user is not allowed here - @todo use filters
     if ($app['allowed'] == false) {
         return $app->abort(403, 'Not allowed');
     }
     // Main courses and session list
     $items = null;
     $type = str_replace('/', '', $type);
     /** @var \PageController $pageController */
     $pageController = $app['page_controller'];
     switch ($type) {
         case 'sessions':
             $items = $pageController->returnSessions(api_get_user_id(), $filter, $page);
             break;
         case 'sessioncategories':
             $items = $pageController->returnSessionsCategories(api_get_user_id(), $filter, $page);
             break;
         case 'courses':
             $items = $pageController->returnCourses(api_get_user_id(), $filter, $page);
             break;
         case 'mycoursecategories':
             $items = $pageController->returnMyCourseCategories(api_get_user_id(), $filter, $page);
             break;
         case 'specialcourses':
             $items = $pageController->returnSpecialCourses(api_get_user_id(), $filter, $page);
             break;
     }
     //Show the chamilo mascot
     if (empty($items) && empty($filter)) {
         $pageController->return_welcome_to_course_block($app['template']);
     }
     /*
             $app['my_main_menu'] = function($app) {
                 $menu = $app['knp_menu.factory']->createItem('root');
                 $menu->addChild('Home', array('route' => api_get_path(WEB_CODE_PATH)));
                 return $menu;
             };
             $app['knp_menu.menus'] = array('main' => 'my_main_menu');*/
     $app['template']->assign('content', $items);
     $pageController->setCourseSessionMenu();
     $pageController->setProfileBlock();
     $pageController->setUserImageBlock();
     $pageController->setCourseBlock($filter);
     $pageController->setSessionBlock();
     $pageController->return_reservation_block();
     $pageController->returnNavigationLinks($app['template']->getNavigationLinks());
     $app['template']->assign('search_block', $pageController->return_search_block());
     $app['template']->assign('classes_block', $pageController->return_classes_block());
     $pageController->returnSkillsLinks();
     // Deleting the session_id.
     Session::erase('session_id');
     $response = $app['template']->render_template('userportal/index.tpl');
     return new Response($response, 200, array());
 }
Ejemplo n.º 7
0
 /**
  * Class constructor. Depending of the type of construction called ('db' or 'manifest'), will create a scormItem
  * object from database records or from the array given as second parameter
  * @param	string	Type of construction needed ('db' or 'config', default = 'config')
  * @param	mixed	Depending on the type given, DB id for the lp_item or parameters array
  */
 function aiccItem($type = 'config', $params)
 {
     if (isset($params)) {
         switch ($type) {
             case 'db':
                 parent::learnpathItem($params, api_get_user_id());
                 $this->aicc_contact = false;
                 //TODO implement this way of metadata object creation
                 return false;
             case 'config':
                 //do the same as the default
             //do the same as the default
             default:
                 //if($first_item->type == XML_ELEMENT_NODE) this is already check prior to the call to this function
                 foreach ($params as $a => $value) {
                     switch ($a) {
                         case 'system_id':
                             $this->identifier = Database::escape_string(strtolower($value));
                             break;
                         case 'type':
                             $this->au_type = Database::escape_string($value);
                             break;
                         case 'command_line':
                             $this->command_line = Database::escape_string($value);
                             break;
                         case 'max_time_allowed':
                             $this->maxtimeallowed = Database::escape_string($value);
                             break;
                         case 'time_limit_action':
                             $this->timelimitaction = Database::escape_string($value);
                             break;
                         case 'max_score':
                             $this->max_score = Database::escape_string($value);
                             break;
                         case 'core_vendor':
                             $this->core_vendor = Database::escape_string($value);
                             break;
                         case 'system_vendor':
                             $this->system_vendor = Database::escape_string($value);
                             break;
                         case 'file_name':
                             $this->path = Database::escape_string($value);
                             break;
                         case 'mastery_score':
                             $this->masteryscore = Database::escape_string($value);
                             break;
                         case 'web_launch':
                             $this->parameters = Database::escape_string($value);
                             break;
                     }
                 }
                 return true;
         }
     }
     return false;
 }
Ejemplo n.º 8
0
 /**
  * Refreshes the chat windows (usually called every x seconds through AJAX)
  * @return void (prints JSON array of chat windows)
  */
 public function heartbeat()
 {
     $to_user_id = api_get_user_id();
     $minutes = 60;
     $now = time() - $minutes * 60;
     $now = api_get_utc_datetime($now);
     //OR  sent > '$now'
     $sql = "SELECT * FROM " . $this->table . "\n                WHERE to_user = '******' AND ( recd  = 0 ) ORDER BY id ASC";
     $result = Database::query($sql);
     $chat_list = array();
     while ($chat = Database::fetch_array($result, 'ASSOC')) {
         $chat_list[$chat['from_user']]['items'][] = $chat;
     }
     $items = array();
     foreach ($chat_list as $from_user_id => $rows) {
         $rows = $rows['items'];
         $user_info = api_get_user_info($from_user_id, true);
         //Cleaning tsChatBoxes
         unset($_SESSION['tsChatBoxes'][$from_user_id]);
         foreach ($rows as $chat) {
             $chat['message'] = Security::remove_XSS($chat['message']);
             $item = array('s' => '0', 'f' => $from_user_id, 'm' => $chat['message'], 'username' => $user_info['complete_name'], 'id' => $chat['id']);
             $items[$from_user_id]['items'][] = $item;
             $items[$from_user_id]['user_info']['user_name'] = $user_info['complete_name'];
             $items[$from_user_id]['user_info']['online'] = $user_info['user_is_online'];
             $_SESSION['openChatBoxes'][$from_user_id] = api_strtotime($chat['sent'], 'UTC');
         }
         $_SESSION['chatHistory'][$from_user_id]['items'][] = $item;
         $_SESSION['chatHistory'][$from_user_id]['user_info']['user_name'] = $user_info['complete_name'];
         $_SESSION['chatHistory'][$from_user_id]['user_info']['online'] = $user_info['user_is_online'];
     }
     if (!empty($_SESSION['openChatBoxes'])) {
         foreach ($_SESSION['openChatBoxes'] as $user_id => $time) {
             if (!isset($_SESSION['tsChatBoxes'][$user_id])) {
                 $now = time() - $time;
                 $time = api_convert_and_format_date($time, DATE_TIME_FORMAT_SHORT_TIME_FIRST);
                 $message = sprintf(get_lang('SentAtX'), $time);
                 if ($now > 180) {
                     $item = array('s' => '2', 'f' => $user_id, 'm' => $message);
                     if (isset($_SESSION['chatHistory'][$user_id])) {
                         $_SESSION['chatHistory'][$user_id]['items'][] = $item;
                     }
                     $_SESSION['tsChatBoxes'][$user_id] = 1;
                 }
             }
         }
     }
     //print_r($_SESSION['chatHistory']);
     $sql = "UPDATE " . $this->table . " SET recd = 1 WHERE to_user = '******' AND recd = 0";
     Database::query($sql);
     if ($items != '') {
         //$items = substr($items, 0, -1);
     }
     echo json_encode(array('items' => $items));
 }
/**
 * Show the form to copy courses
 * @global string $returnLink
 * @global string $courseCode
 */
function displayForm()
{
    global $returnLink, $courseCode;
    $courseInfo = api_get_course_info();
    $sessionId = api_get_session_id();
    $userId = api_get_user_id();
    $sessions = SessionManager::getSessionsCoachedByUser($userId);
    $html = '';
    // Actions
    $html .= '<div class="actions">';
    // Link back to the documents overview
    $html .= '<a href="' . $returnLink . '">' . Display::return_icon('back.png', get_lang('BackTo') . ' ' . get_lang('Maintenance'), '', ICON_SIZE_MEDIUM) . '</a>';
    $html .= '</div>';
    $html .= Display::return_message(get_lang('CopyCourseFromSessionToSessionExplanation'));
    $html .= '<form name="formulaire" method="post" action="' . api_get_self() . '?' . api_get_cidreq() . '" >';
    $html .= '<table border="0" cellpadding="5" cellspacing="0" width="100%">';
    // Source
    $html .= '<tr><td width="15%"><b>' . get_lang('OriginCoursesFromSession') . ':</b></td>';
    $html .= '<td width="10%" align="left">' . api_get_session_name($sessionId) . '</td>';
    $html .= '<td width="50%">';
    $html .= "{$courseInfo['title']} ({$courseInfo['code']})" . '</td></tr>';
    // Destination
    $html .= '<tr><td width="15%"><b>' . get_lang('DestinationCoursesFromSession') . ':</b></td>';
    $html .= '<td width="10%" align="left"><div id="ajax_sessions_list_destination">';
    $html .= '<select name="sessions_list_destination" onchange="javascript: xajax_searchCourses(this.value,\'destination\');">';
    if (empty($sessions)) {
        $html .= '<option value = "0">' . get_lang('ThereIsNotStillASession') . '</option>';
    } else {
        $html .= '<option value = "0">' . get_lang('SelectASession') . '</option>';
        foreach ($sessions as $session) {
            if ($session['id'] == $sessionId) {
                continue;
            }
            if (!SessionManager::sessionHasCourse($session['id'], $courseCode)) {
                continue;
            }
            $html .= '<option value="' . $session['id'] . '">' . $session['name'] . '</option>';
        }
    }
    $html .= '</select ></div></td>';
    $html .= '<td width="50%">';
    $html .= '<div id="ajax_list_courses_destination">';
    $html .= '<select id="destination" name="SessionCoursesListDestination[]" style="width:380px;" ></select></div></td>';
    $html .= '</tr></table>';
    $html .= "<fieldset>";
    $html .= '<legend>' . get_lang('TypeOfCopy') . ' <small>(' . get_lang('CopyOnlySessionItems') . ')</small></legend>';
    $html .= '<label class="radio"><input type="radio" id="copy_option_1" name="copy_option" value="full_copy" checked="checked"/>';
    $html .= get_lang('FullCopy') . '</label>';
    $html .= '<label class="radio"><input type="radio" id="copy_option_2" name="copy_option" value="select_items"/>';
    $html .= ' ' . get_lang('LetMeSelectItems') . '</label><br/>';
    $html .= "</fieldset>";
    $html .= '<button class="save" type="submit" onclick="javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)) . "'" . ')) return false;">' . get_lang('CopyCourse') . '</button>';
    $html .= '</form>';
    echo $html;
}
Ejemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function getConfiguration()
 {
     if (!empty($this->connector->course)) {
         $userId = api_get_user_id();
         $path = 'shared_folder/sf_user_' . $userId;
         $alias = $this->connector->course['code'] . ' ' . get_lang('CourseUserDocument');
         if (!empty($userId)) {
             return array('driver' => 'CourseUserDriver', 'alias' => $alias, 'path' => $this->getCourseDocumentSysPath() . $path, 'URL' => $this->getCourseDocumentRelativeWebPath() . $path, 'accessControl' => 'access');
         }
     }
 }
Ejemplo n.º 11
0
 /**
  * Organize the saving of a link, using the parent's save method and
  * updating the item_property table
  * @param array $params
  * @param boolean $show_query Whether to show the query in logs when
  * calling parent's save method
  *
  * @return bool True if link could be saved, false otherwise
  */
 public function save($params, $show_query = null)
 {
     $course_info = api_get_course_info();
     $params['session_id'] = api_get_session_id();
     $params['category_id'] = isset($params['category_id']) ? $params['category_id'] : 0;
     $id = parent::save($params, $show_query);
     if (!empty($id)) {
         api_item_property_update($course_info, TOOL_LINK, $id, 'LinkAdded', api_get_user_id());
     }
     return $id;
 }
 /**
  * @param Request $request
  * @return null|RedirectResponse
  */
 public function onLogoutSuccess(Request $request)
 {
     $session = $request->getSession();
     \ChamiloSession::setSession($session);
     // Chamilo logout
     $userId = api_get_user_id();
     \Online::logout($userId, false);
     $login = $this->router->generate('index');
     $response = new RedirectResponse($login);
     return $response;
 }
Ejemplo n.º 13
0
function GetFoldersAndFiles($resourceType, $currentFolder)
{
    // Map the virtual path to the local server path.
    $sServerDir = ServerMapFolder($resourceType, $currentFolder, 'GetFoldersAndFiles');
    // Arrays that will hold the folders and files names.
    $aFolders = array();
    $aFiles = array();
    $oCurrentFolder = @opendir($sServerDir);
    $in_group = api_is_in_group();
    if ($currentFolder == '/shared_folder/' || $currentFolder == '/shared_folder_session_' . api_get_session_id() . '/') {
        $in_shared_folder = true;
    } else {
        $in_shared_folder = false;
    }
    $user_id = api_get_user_id();
    if ($oCurrentFolder !== false) {
        while ($sFile = readdir($oCurrentFolder)) {
            $is_dir = @is_dir($sServerDir . $sFile);
            if ($sFile != '.' && $sFile != '..' && strpos($sFile, '_DELETED_') === false && strpos($sFile, 'chat_files') === false && strpos($sFile, 'HotPotatoes_files') === false && ($in_group || !$in_group && strpos($sFile, '_groupdocs') === false) && (!$in_shared_folder || $in_shared_folder && (!$is_dir || $is_dir && $sFile == $user_id)) && $sFile != '.thumbs' && strpos($sFile, '.editor_') === false && $sFile != '.svn') {
                if ($is_dir) {
                    $aFolders[] = '<Folder name="' . ConvertToXmlAttribute($sFile) . '" />';
                } else {
                    $iFileSize = @filesize($sServerDir . $sFile);
                    if (!$iFileSize) {
                        $iFileSize = 0;
                    }
                    if ($iFileSize > 0) {
                        $iFileSize = round($iFileSize / 1024);
                        if ($iFileSize < 1) {
                            $iFileSize = 1;
                        }
                    }
                    $aFiles[] = '<File name="' . ConvertToXmlAttribute($sFile) . '" size="' . $iFileSize . '" />';
                }
            }
        }
        closedir($oCurrentFolder);
    }
    // Send the folders
    natcasesort($aFolders);
    echo '<Folders>';
    foreach ($aFolders as $sFolder) {
        echo $sFolder;
    }
    echo '</Folders>';
    // Send the files
    natcasesort($aFiles);
    echo '<Files>';
    foreach ($aFiles as $sFiles) {
        echo $sFiles;
    }
    echo '</Files>';
}
Ejemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function getConfiguration()
 {
     if ($this->allow()) {
         $userId = api_get_user_id();
         if (!empty($userId)) {
             // Adding user personal files
             $dir = \UserManager::getUserPathById($userId, 'system');
             $dirWeb = \UserManager::getUserPathById($userId, 'web');
             $driver = array('driver' => 'PersonalDriver', 'alias' => get_lang('MyFiles'), 'path' => $dir . 'my_files', 'URL' => $dirWeb . 'my_files', 'accessControl' => array($this, 'access'), 'disabled' => array('duplicate', 'mkfile', 'copy', 'cut', 'paste', 'edit', 'extract', 'archive', 'help', 'resize'));
             return $driver;
         }
     }
     return array();
 }
Ejemplo n.º 15
0
/**
 * Write a log with the current message
 * @param   string Message
 * @param   int    Debug level (if 0, do not log)
 */
function lp_ajax_log($msg, $level) {
    $debug = 0;
    $return = '';
    if ($debug > 0) {error_log('In log('.$msg.')', 0); }
    if ($level == 0) {
        //error_log('Logging level too low, not writing files in '.__FILE__);
        return $return;
    }
    $msg = str_replace('<br />', "\r\n", $msg);
    $file = sys_get_temp_dir().DIRECTORY_SEPARATOR.session_id().'.'.date('Ymd').'-'.api_get_user_id().'.scorm.log';
    $fh = @fopen($file, 'a');
    @fwrite($fh,'['.date('Y-m-d H:m:s').'] '.$msg."\r\n");
    @fclose($fh);
    return $return;
}
Ejemplo n.º 16
0
 /**
 * Updates an URL access
 * @author Julio Montoya <*****@*****.**>,
 *
 * @param	int 	The url id
 * @param	string  The description of the site
 * @param	int		is active or not
 * @return 	boolean if success
 */
 public static function update($url_id, $url, $description, $active)
 {
     $url_id = intval($url_id);
     $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
     $tms = time();
     $sql = "UPDATE $table_access_url
             SET url 	= '".Database::escape_string($url)."',
             description = '".Database::escape_string($description)."',
             active 		= '".intval($active)."',
             created_by 	= '".api_get_user_id()."',
             tms 		= FROM_UNIXTIME(".$tms.")
             WHERE id = '$url_id'";
     $result = Database::query($sql);
     return $result;
 }
Ejemplo n.º 17
0
 /**
  * True if portfolios are enabled. False otherwise.
  * 
  * @return boolean 
  */
 public static function is_enabled()
 {
     if (api_is_anonymous()) {
         return false;
     }
     $user_id = api_get_user_id();
     if (empty($user_id)) {
         return false;
     }
     $portfolios = self::all();
     if (count($portfolios) == 0) {
         return false;
     }
     return true;
 }
Ejemplo n.º 18
0
 /**
  * Limit session resubscription when a Chamilo user is resubscribed to a session
  * @param HookCreateUserEventInterface $hook The hook
  */
 public function hookResubscribe(HookResubscribeEventInterface $hook)
 {
     $data = $hook->getEventData();
     if ($data['type'] === HOOK_EVENT_TYPE_PRE) {
         $resubscriptionLimit = Resubscription::create()->get('resubscription_limit');
         // Initialize variables as a calendar year by default
         $limitDateFormat = 'Y-01-01';
         $limitDate = gmdate($limitDateFormat);
         $resubscriptionOffset = "1 year";
         // No need to use a 'switch' with only two options so an 'if' is enough.
         // However this could change if the number of options increases
         if ($resubscriptionLimit === 'natural_year') {
             $limitDateFormat = 'Y-m-d';
             $limitDate = gmdate($limitDateFormat);
             $limitDate = gmdate($limitDateFormat, strtotime("{$limitDate} -{$resubscriptionOffset}"));
         }
         $join = " INNER JOIN " . Database::get_main_table(TABLE_MAIN_SESSION) . "ON id = session_id";
         // User sessions and courses
         $userSessions = Database::select('session_id, date_end', Database::get_main_table(TABLE_MAIN_SESSION_USER) . $join, array('where' => array('user_id = ? AND date_end >= ?' => array(api_get_user_id(), $limitDate)), 'order' => 'date_end DESC'));
         $userSessionCourses = array();
         foreach ($userSessions as $userSession) {
             $userSessionCourseResult = Database::select('c_id', Database::get_main_table(TABLE_MAIN_SESSION_COURSE), array('where' => array('session_id = ?' => array($userSession['session_id']))));
             foreach ($userSessionCourseResult as $userSessionCourse) {
                 if (!isset($userSessionCourses[$userSessionCourse['c_id']])) {
                     $userSessionCourses[$userSessionCourse['c_id']] = $userSession['date_end'];
                 }
             }
         }
         // Current session and courses
         $currentSessionCourseResult = Database::select('c_id', Database::get_main_table(TABLE_MAIN_SESSION_COURSE), array('where' => array('session_id = ?' => array($data['session_id']))));
         // Check if current course code matches with one of the users
         foreach ($currentSessionCourseResult as $currentSessionCourse) {
             if (isset($userSessionCourses[$currentSessionCourse['c_id']])) {
                 $endDate = $userSessionCourses[$currentSessionCourse['c_id']];
                 $resubscriptionDate = gmdate($limitDateFormat, strtotime($endDate . " +{$resubscriptionOffset}"));
                 $icon = Display::return_icon('students.gif', get_lang('Student'));
                 $canResubscribeFrom = sprintf(get_plugin_lang('CanResubscribeFromX', 'resubscription'), $resubscriptionDate);
                 throw new Exception(Display::label($icon . ' ' . $canResubscribeFrom, "info"));
             }
         }
     }
 }
Ejemplo n.º 19
0
        Display::display_header($nameTools, 'Doc');
        Display::display_error_message(get_lang('Impossible'));
        Display::display_footer();
    }
} else {
    // Interbreadcrumb for the current directory root path
    // Copied from document.php
    $dir_array = explode('/', $dir);
    $array_len = count($dir_array);
    // Interbreadcrumb for the current directory root path
    if (empty($document_data['parents'])) {
        $interbreadcrumb[] = array('url' => '#', 'name' => $document_data['title']);
    } else {
        foreach ($document_data['parents'] as $document_sub_data) {
            $interbreadcrumb[] = array('url' => $document_sub_data['document_url'], 'name' => $document_sub_data['title']);
        }
    }
    $interbreadcrumb[] = array('url' => '#', 'name' => $nameTools);
    Display::display_header($nameTools, "Doc");
    if ($is_certificate_mode) {
        $all_information_by_create_certificate = DocumentManager::get_all_info_to_certificate(api_get_user_id(), api_get_course_id());
        $str_info = '';
        foreach ($all_information_by_create_certificate[0] as $info_value) {
            $str_info .= $info_value . '<br/>';
        }
        $create_certificate = get_lang('CreateCertificateWithTags');
        Display::display_normal_message($create_certificate . ': <br /><br/>' . $str_info, false);
    }
    echo $form->return_form();
    Display::display_footer();
}
Ejemplo n.º 20
0
 *	@author various contributors
 *	@author Roan Embrechts (VUB), partial code cleanup, initial virtual course support
 *	@package chamilo.group
 *	@todo course admin functionality to create groups based on who is in which course (or class).
 */
//require_once '../inc/global.inc.php';
$this_section = SECTION_COURSES;
$current_course_tool = TOOL_GROUP;
// Notice for unauthorized people.
api_protect_course_script(true);
$group_id = api_get_group_id();
$current_group = GroupManager::get_group_properties($group_id);
$nameTools = get_lang('EditGroup');
$interbreadcrumb[] = array('url' => 'group.php', 'name' => get_lang('Groups'));
$interbreadcrumb[] = array('url' => 'group_space.php?' . api_get_cidReq(), 'name' => $current_group['name']);
$is_group_member = GroupManager::is_tutor_of_group(api_get_user_id(), $group_id);
if (!api_is_allowed_to_edit(false, true) && !$is_group_member) {
    api_not_allowed(true);
}
/**
 *  List all users registered to the course
 */
function search_members_keyword($firstname, $lastname, $username, $official_code, $keyword)
{
    if (api_strripos($firstname, $keyword) !== false || api_strripos($lastname, $keyword) !== false || api_strripos($username, $keyword) !== false || api_strripos($official_code, $keyword) !== false) {
        return true;
    } else {
        return false;
    }
}
/**
Ejemplo n.º 21
0
 /**
  * @param string $courseCode
  * @param array $rules
  * @param array $columns
  * @param array $column_model
  * @return array
  */
 public static function getRules($courseCode, &$rules, &$columns, &$column_model, $questionFields, $checkFields = false)
 {
     // sessions
     // course
     // categories
     // exercises
     // difficult
     // type
     if (empty($courseCode)) {
         // Session.
         $sessionList = SessionManager::get_sessions_by_general_coach(api_get_user_id());
         $fields = array();
         if (!empty($sessionList)) {
             $new_options = array();
             $new_options[] = "-1:" . get_lang('All');
             foreach ($sessionList as $session) {
                 $new_options[] = "{$session['id']}:{$session['name']}";
             }
             $string = implode(';', $new_options);
             $fields[] = array('field_display_text' => get_lang('Session'), 'field_variable' => 'session_id', 'field_type' => ExtraField::FIELD_TYPE_SELECT, 'field_default_value' => null, 'field_options' => $string);
         }
     } else {
         // $courseList = array(api_get_course_info());
         //$courseList = CourseManager::get_course_list_of_user_as_course_admin(api_get_user_id());
     }
     // Courses.
     $courseList = CourseManager::get_course_list_of_user_as_course_admin(api_get_user_id());
     if (!empty($courseList)) {
         $new_options = array();
         $new_options[] = "-1:" . get_lang('All');
         foreach ($courseList as $course) {
             $new_options[] = "{$course['id']}:{$course['title']}";
         }
         $string = implode(';', $new_options);
         $fields[] = array('field_display_text' => get_lang('Course'), 'field_variable' => 'c_id', 'field_type' => ExtraField::FIELD_TYPE_SELECT, 'field_default_value' => null, 'field_options' => $string);
     }
     // Categories.
     $string = null;
     if (!empty($courseList)) {
         $new_options = array();
         $new_options[] = "-1:" . get_lang('All');
         // Global categories
         // @todo use tree view
         $categories = Testcategory::getCategoriesIdAndName(0);
         if (!empty($categories)) {
             foreach ($categories as $id => $category) {
                 if (!empty($id)) {
                     $new_options[] = "{$id}:[Global] - " . $category;
                 }
             }
         }
         foreach ($courseList as $course) {
             $categories = Testcategory::getCategoriesIdAndName($course['real_id']);
             if (!empty($categories)) {
                 foreach ($categories as $id => $category) {
                     if (!empty($id)) {
                         $new_options[] = "{$id}:" . $course['title'] . " - " . $category;
                     }
                 }
             }
         }
         $string = implode(';', $new_options);
         $fields[] = array('field_display_text' => get_lang('Category'), 'field_variable' => 'category_id', 'field_type' => ExtraField::FIELD_TYPE_SELECT, 'field_default_value' => null, 'field_options' => $string);
     }
     $course = api_get_course_int_id();
     $sessionId = api_get_session_id();
     // Exercises.
     $exerciseList = ExerciseLib::get_all_exercises_for_course_id($sessionId, $course);
     if (!empty($exerciseList)) {
         $new_options = array();
         $new_options[] = "-1:" . get_lang('All');
         $new_options[] = "0:" . get_lang('Orphan');
         foreach ($exerciseList as $exercise) {
             $new_options[] = "{$exercise['iid']}:{$exercise['title']}";
         }
         $string = implode(';', $new_options);
         $fields[] = array('field_display_text' => get_lang('Exercise'), 'field_variable' => 'exercise_id', 'field_type' => ExtraField::FIELD_TYPE_SELECT, 'field_default_value' => null, 'field_options' => $string);
     }
     // Question type.
     $questionList = Question::get_question_type_list();
     if (!empty($questionList)) {
         $new_options = array();
         $new_options[] = "-1:" . get_lang('All');
         foreach ($questionList as $key => $question) {
             $new_options[] = "{$key}:" . get_lang($question['1']);
         }
         $string = implode(';', $new_options);
         $fields[] = array('field_display_text' => get_lang('AnswerType'), 'field_variable' => 'question_type', 'field_type' => ExtraField::FIELD_TYPE_SELECT, 'field_default_value' => null, 'field_options' => $string);
     }
     // Difficult.
     $levels = Question::get_default_levels();
     if (!empty($levels)) {
         $new_options = array();
         $new_options[] = "-1:" . get_lang('All');
         foreach ($levels as $key => $level) {
             $new_options[] = "{$key}:{$level}";
         }
         $string = implode(';', $new_options);
         $fields[] = array('field_display_text' => get_lang('Difficulty'), 'field_variable' => 'difficulty', 'field_type' => ExtraField::FIELD_TYPE_SELECT, 'field_default_value' => null, 'field_options' => $string);
     }
     $questionFieldsKeys = array();
     if (!empty($questionFields)) {
         foreach ($questionFields as $question) {
             $questionFieldsKeys[] = $question['field'];
         }
     }
     if (!empty($fields)) {
         foreach ($fields as $field) {
             $search_options = array();
             $type = 'text';
             if (in_array($field['field_type'], array(ExtraField::FIELD_TYPE_SELECT, ExtraField::FIELD_TYPE_DOUBLE_SELECT))) {
                 $type = 'select';
                 $search_options['sopt'] = array('eq', 'ne');
                 //equal not equal
                 //$search_options['sopt'] = array('cn', 'nc'); //contains not contains
             } else {
                 $search_options['sopt'] = array('cn', 'nc');
                 //contains not contains
             }
             $search_options['searchhidden'] = 'true';
             $search_options['defaultValue'] = isset($search_options['field_default_value']) ? $search_options['field_default_value'] : null;
             $search_options['value'] = $field['field_options'];
             $column_model[] = array('name' => 'question_' . $field['field_variable'], 'index' => 'question_' . $field['field_variable'], 'width' => '100', 'hidden' => 'true', 'search' => 'true', 'stype' => $type, 'searchoptions' => $search_options);
             $columns[] = $field['field_display_text'];
             $rules[] = array('field' => 'question_' . $field['field_variable'], 'op' => 'eq');
         }
     }
     return $rules;
 }
Ejemplo n.º 22
0
//admins are allowed to download invisible files
$files = array();
$course_id = api_get_course_int_id();
if (api_is_allowed_to_edit()) {
    //Search for all files that are not deleted => visibility != 2
    $sql = "SELECT DISTINCT url, title, description, insert_user_id, insert_date, contains_file\n            FROM {$tbl_student_publication} AS work INNER JOIN {$prop_table} AS props\n                ON (\n                    props.c_id = {$course_id} AND\n                    work.c_id = {$course_id} AND\n                    work.id = props.ref\n                  )\n \t\t\tWHERE   props.tool='work' AND\n \t\t\t        work.parent_id = {$work_id} AND\n \t\t\t        work.filetype = 'file' AND\n \t\t\t        props.visibility<>'2' AND\n \t\t\t        work.active = 1 AND\n \t\t\t        work.post_group_id = {$groupId}\n            ";
} else {
    $courseInfo = api_get_course_info();
    allowOnlySubscribedUser(api_get_user_id(), $work_id, $courseInfo['real_id']);
    $userCondition = null;
    // All users
    if ($courseInfo['show_score'] == 0) {
        // Do another filter
    } else {
        // Only teachers
        $userCondition = " AND props.insert_user_id = " . api_get_user_id();
    }
    //for other users, we need to create a zipfile with only visible files and folders
    $sql = "SELECT DISTINCT url, title, description, insert_user_id, insert_date, contains_file\n            FROM {$tbl_student_publication} AS work INNER JOIN {$prop_table} AS props\n                ON (props.c_id = {$course_id} AND\n                    work.c_id = {$course_id} AND\n                    work.id = props.ref)\n           WHERE\n                    props.tool='work' AND\n                    work.accepted = 1 AND\n                    work.active = 1 AND\n                    work.parent_id = {$work_id} AND\n                    work.filetype = 'file' AND\n                    props.visibility = '1' AND\n                    work.post_group_id = {$groupId}\n                    {$userCondition}\n            ";
}
$query = Database::query($sql);
//add tem to the zip file
while ($not_deleted_file = Database::fetch_assoc($query)) {
    $user_info = api_get_user_info($not_deleted_file['insert_user_id']);
    $insert_date = api_get_local_time($not_deleted_file['insert_date']);
    $insert_date = str_replace(array(':', '-', ' '), '_', $insert_date);
    $filename = $insert_date . '_' . $user_info['username'] . '_' . basename($not_deleted_file['title']);
    if (file_exists($sys_course_path . $_course['path'] . '/' . $not_deleted_file['url']) && !empty($not_deleted_file['url'])) {
        $files[basename($not_deleted_file['url'])] = $filename;
        $zip_folder->add($sys_course_path . $_course['path'] . '/' . $not_deleted_file['url'], PCLZIP_OPT_REMOVE_PATH, $sys_course_path . $_course['path'] . '/work', PCLZIP_CB_PRE_ADD, 'my_pre_add_callback');
    }
    public function make_lp($files = array())
    {
        global $_course;
        $previous = 0;
        $i = 0;

        if (!is_dir($this->base_work_dir.$this->created_dir))
            return false;

        foreach ($files as $file) {
            /* '||' is used as separator between fields:
                slide name (with accents) || file name (without accents) || all slide text (to be indexed).
            */
            list($slide_name, $file_name, $slide_body) = explode('||', $file);

            // Filename is utf8 encoded, but when we decode, some chars are not translated (like quote &rsquo;).
            // so we remove these chars by translating it in htmlentities and the reconvert it in want charset.
            $slide_name = api_htmlentities($slide_name, ENT_COMPAT, $this->original_charset);
            $slide_name = str_replace('&rsquo;', '\'', $slide_name);
            $slide_name = api_convert_encoding($slide_name, api_get_system_encoding(), $this->original_charset);
            $slide_name = api_html_entity_decode($slide_name, ENT_COMPAT, api_get_system_encoding());

            if ($this->take_slide_name === true) {
                $slide_name = str_replace('_', ' ', $slide_name);
                $slide_name = api_ucfirst($slide_name);
            } else {
                $slide_name = 'slide'.str_repeat('0', 2 - strlen($i)).$i;
            }

            $i++;
            // Add the png to documents.
            $document_id = add_document(
                $_course,
                $this->created_dir.'/'.urlencode($file_name),
                'file',
                filesize($this->base_work_dir.$this->created_dir.'/'.$file_name),
                $slide_name
            );

            api_item_property_update(
                $_course,
                TOOL_DOCUMENT,
                $document_id,
                'DocumentAdded',
                api_get_user_id(),
                0,
                0,
                null,
                null,
                api_get_session_id()
            );

            // Generating the thumbnail.
            $image = $this->base_work_dir.$this->created_dir .'/'. $file_name;

            $pattern = '/(\w+)\.png$/';
            $replacement = '${1}_thumb.png';
            $thumb_name = preg_replace($pattern, $replacement, $file_name);

            // Calculate thumbnail size.
            $image_size = api_getimagesize($image);
            $width  = $image_size['width'];
            $height = $image_size['height'];

            $thumb_width = 300;
            $thumb_height = floor($height * ($thumb_width / $width));

            $my_new_image = new Image($image);
            $my_new_image->resize($thumb_width, $thumb_height);
            $my_new_image->send_image($this->base_work_dir.$this->created_dir .'/'. $thumb_name, -1, 'png');

            // Adding the thumbnail to documents.
            $document_id_thumb = add_document(
                $_course,
                $this->created_dir.'/'.urlencode($thumb_name),
                'file',
                filesize($this->base_work_dir.$this->created_dir.'/'.$thumb_name),
                $slide_name
            );

            api_item_property_update($_course, TOOL_THUMBNAIL, $document_id_thumb, 'DocumentAdded', api_get_user_id(), 0, 0);

            // Create an html file.
            $html_file = $file_name.'.html';
            $fp = fopen($this->base_work_dir.$this->created_dir.'/'.$html_file, 'w+');

            $slide_src = api_get_path(REL_COURSE_PATH).$_course['path'].'/document/'.$this->created_dir.'/'.utf8_encode($file_name);
            $slide_src = str_replace('//', '/', $slide_src);
            fwrite($fp,
'<html>
    <head>
    </head>
    <body>
        <img src="'.$slide_src.'" />
    </body>
</html>');  // This indentation is to make the generated html files to look well.

            fclose($fp);
            $document_id = add_document(
                $_course,
                $this->created_dir.'/'.urlencode($html_file),
                'file',
                filesize($this->base_work_dir.$this->created_dir.'/'.$html_file),
                $slide_name
            );

            if ($document_id) {

                // Put the document in item_property update.
                api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id(), 0, 0, null, null, api_get_session_id());

                $previous = $this->add_item(0, $previous, 'document', $document_id, $slide_name, '');
                if ($this->first_item == 0) {
                    $this->first_item = $previous;
                }
            }
            // Code for text indexing.
            if (api_get_setting('search_enabled') == 'true') {

                if (isset($_POST['index_document']) && $_POST['index_document']) {
                    $di = new ChamiloIndexer();
                    isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
                    $di->connectDb(NULL, NULL, $lang);
                    $ic_slide = new IndexableChunk();
                    $ic_slide->addValue('title', $slide_name);
                    $specific_fields = get_specific_field_list();
                    $all_specific_terms = '';
                    foreach ($specific_fields as $specific_field) {
                        if (isset($_REQUEST[$specific_field['code']])) {
                            $sterms = trim($_REQUEST[$specific_field['code']]);
                            $all_specific_terms .= ' '. $sterms;
                            if (!empty($sterms)) {
                                $sterms = explode(',', $sterms);
                                foreach ($sterms as $sterm) {
                                    $ic_slide->addTerm(trim($sterm), $specific_field['code']);
                                }
                            }
                        }
                    }
                    $slide_body = $all_specific_terms .' '. $slide_body;
                    $ic_slide->addValue('content', $slide_body);
                    /* FIXME:  cidReq:lp_id:doc_id al indexar  */
                    // Add a comment to say terms separated by commas.
                    $courseid = api_get_course_id();
                    $ic_slide->addCourseId($courseid);
                    $ic_slide->addToolId(TOOL_LEARNPATH);
                    $lp_id = $this->lp_id;
                    $xapian_data = array(
                        SE_COURSE_ID => $courseid,
                        SE_TOOL_ID => TOOL_LEARNPATH,
                        SE_DATA => array('lp_id' => $lp_id, 'lp_item' => $previous, 'document_id' => $document_id),
                        SE_USER => (int)api_get_user_id(),
                    );
                    $ic_slide->xapian_data = serialize($xapian_data);
                    $di->addChunk($ic_slide);
                    // Index and return search engine document id.
                    $did = $di->index();
                    if ($did) {
                        // Save it to db.
                        $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
                        $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
                            VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
                        $sql = sprintf($sql, $tbl_se_ref, api_get_course_id(), TOOL_LEARNPATH, $lp_id, $previous, $did);
                        Database::query($sql);
                    }
                }
            }
        }
    }
Ejemplo n.º 24
0
        //$pdf->ezImage(api_get_path(SYS_CODE_PATH).'img/dokeos_logo_certif.png',1,400,'','center','');
        $pdf->ezSetY(480);
        $pdf->ezText($certif_text, 28, array('justification' => 'center'));
        //$pdf->ezSetY(750);
        $pdf->ezSetY(50);
        $pdf->ezText($date, 18, array('justification' => 'center'));
        $pdf->ezSetY(580);
        $pdf->ezText($organization_name, 22, array('justification' => 'left'));
        $pdf->ezSetY(580);
        $pdf->ezText($portal_name, 22, array('justification' => 'right'));
        $pdf->ezStream();
    }
    exit;
} else {
    $cats = Category::load($category);
    $stud_id = api_is_allowed_to_edit() ? null : api_get_user_id();
    $allcat = $cats[0]->get_subcategories($stud_id);
    $alleval = $cats[0]->get_evaluations($stud_id);
    $alllink = $cats[0]->get_links($stud_id);
}
$addparams = array('selectcat' => $cats[0]->get_id());
if (isset($_GET['search'])) {
    $addparams['search'] = $keyword;
}
if (isset($_GET['studentoverview'])) {
    $addparams['studentoverview'] = '';
}
if (isset($allcat_info) && count($allcat_info) >= 0 && (isset($_GET['selectcat']) && $_GET['selectcat'] == 0) && isset($_GET['search']) && strlen(trim($_GET['search'])) > 0) {
    $allcat = $allcat_info;
} else {
    $allcat = $allcat;
Ejemplo n.º 25
0
//Autowidth
$extra_params['autowidth'] = 'true';
//height auto
$extra_params['height'] = 'auto';
//With this function we can add actions to the jgrid (edit, delete, etc)
/*
$action_links = 'function action_formatter(cellvalue, options, rowObject) {
     return \'<a href="?action=edit&id=\'+options.rowId+\'">'.Display::return_icon('edit.png',get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>'.
     '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="?sec_token='.$token.'&action=copy&id=\'+options.rowId+\'">'.Display::return_icon('copy.png',get_lang('Copy'),'',ICON_SIZE_SMALL).'</a>'.
     '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="?sec_token='.$token.'&action=delete&id=\'+options.rowId+\'">'.Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>'.
     '\';
 }';*/
$action_links = null;
$room = UserManager::get_extra_user_data_by_field(api_get_user_id(), 'exam_room');
$room = $room['exam_room'];
$schedule = UserManager::get_extra_user_data_by_field(api_get_user_id(), 'exam_schedule');
$schedule = $schedule['exam_schedule'];
echo Display::page_subheader(get_lang('UserList') . ": " . $room . " - " . $schedule);
?>
<script>
$(function() {
<?php 
echo Display::grid_js('user_list', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
?>
    jQuery("#user_list").jqGrid("navGrid","#user_list_pager",{view:false, edit:false, add:false, del:false, search:false, excel:true});
    jQuery("#user_list").jqGrid("navButtonAdd","#user_list_pager",{
       caption:"",
       onClickButton : function () {
           jQuery("#user_list").jqGrid("excelExport",{"url": "<? echo $url?>&export_format=xls"});
    }
});
Ejemplo n.º 26
0
            if (!isset($_POST['group_id'])) {
                $default['users'] = isset($_POST['users']) ? $_POST['users'] : null;
            } else {
                $default['group_id'] = $_POST['group_id'];
            }
            if (isset($_POST['hidden_user'])) {
                $default['users'] = array($_POST['hidden_user']);
            }
            $social_right_content .= manage_form($default);
        } else {
            $social_right_content .= Display::return_message(get_lang('ErrorSendingMessage'), 'error');
        }
    }
}
if (api_get_setting('social.allow_social_tool') == 'true') {
    $social_right_content .= '</div>';
    $social_right_content .= '</div>';
}
//$tpl = new Template(get_lang('ComposeMessage'));
$tpl = \Chamilo\CoreBundle\Framework\Container::getTwig();
// Block Social Avatar
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
if (api_get_setting('social.allow_social_tool') == 'true') {
    $tpl->addGlobal('social_menu_block', $social_menu_block);
    $tpl->addGlobal('social_right_content', $social_right_content);
    echo $tpl->render('@template_style/social/inbox.html.twig');
} else {
    $content = $social_right_content;
    echo $actions;
    echo $content;
}
Ejemplo n.º 27
0
 // Images uploaded by course
 $file_list = '';
 if (is_array($course_list_code) && count($course_list_code) > 0) {
     foreach ($course_list_code as $course) {
         $file_list .= UserManager::get_user_upload_files_by_course($user_id, $course['code'], $resourcetype = 'images');
     }
 }
 $count_pending_invitations = 0;
 if (!isset($_GET['u']) || isset($_GET['u']) && $_GET['u'] == api_get_user_id()) {
     $pending_invitations = SocialManager::get_list_invitation_of_friends_by_user_id(api_get_user_id());
     $list_get_path_web = SocialManager::get_list_web_path_user_invitation_by_user_id(api_get_user_id());
     $count_pending_invitations = count($pending_invitations);
 }
 if (!empty($production_list) || !empty($file_list) || $count_pending_invitations > 0) {
     //Pending invitations
     if (!isset($_GET['u']) || isset($_GET['u']) && $_GET['u'] == api_get_user_id()) {
         if ($count_pending_invitations > 0) {
             $invitations = '<div><h3>' . get_lang('PendingInvitations') . '</h3></div>';
             for ($i = 0; $i < $count_pending_invitations; $i++) {
                 $user_invitation_id = $pending_invitations[$i]['user_sender_id'];
                 $invitations .= '<div id="dpending_' . $user_invitation_id . '" class="friend_invitations">';
                 $invitations .= '<div style="float:left;width:60px;" >';
                 $invitations .= '<img style="margin-bottom:5px;"' . ' src="' . $list_get_path_web[$i]['dir'] . '/' . $list_get_path_web[$i]['file'] . '"' . ' width="60px">';
                 $invitations .= '</div>';
                 $invitations .= '<div style="padding-left:70px;">';
                 $user_invitation_info = api_get_user_info($user_invitation_id);
                 $invitations .= '<a href="' . api_get_path(WEB_PATH) . 'main/social/profile.php' . '?u=' . $user_invitation_id . '">' . api_get_person_name($user_invitation_info['firstname'], $user_invitation_info['lastname']) . '</a>';
                 $invitations .= '<br />';
                 $invitations .= Security::remove_XSS(cut($pending_invitations[$i]['content'], 50), STUDENT, true);
                 $invitations .= '<br />';
                 $invitations .= '<a id="btn_accepted_' . $user_invitation_id . '"' . ' class="btn btn-default" onclick="register_friend(this)" href="javascript:void(0)">' . get_lang('SocialAddToFriends') . '</a>';
Ejemplo n.º 28
0
api_block_anonymous_users();
$htmlHeadXtra[] = api_get_jqgrid_js();
$interbreadcrumb[] = array("url" => "index.php", "name" => get_lang('MySpace'));
Display::display_header(get_lang('Sessions'));
$export_csv = false;
if (isset($_GET['export']) && $_GET['export'] == 'csv') {
    $export_csv = true;
}
/*	MAIN CODE */
if (isset($_GET['id_coach']) && $_GET['id_coach'] != '') {
    $id_coach = intval($_GET['id_coach']);
} else {
    $id_coach = api_get_user_id();
}
if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
    $a_sessions = SessionManager::get_sessions_followed_by_drh(api_get_user_id());
    if (!api_is_session_admin()) {
        $menu_items[] = Display::url(Display::return_icon('stats.png', get_lang('MyStats'), '', ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . "auth/my_progress.php");
        $menu_items[] = Display::url(Display::return_icon('user.png', get_lang('Students'), array(), ICON_SIZE_MEDIUM), "index.php?view=drh_students&amp;display=yourstudents");
        $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
        $menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), 'course.php');
        $menu_items[] = Display::url(Display::return_icon('session_na.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), '#');
    }
    $actionsLeft = '';
    $nb_menu_items = count($menu_items);
    if ($nb_menu_items > 1) {
        foreach ($menu_items as $key => $item) {
            $actionsLeft .= $item;
        }
    }
    $actionsRight = '';
Ejemplo n.º 29
0
 /**
  * @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;
     }
 }
Ejemplo n.º 30
0
/**
 * Handles a given Excel spreadsheets as in the template provided
 */
function lp_upload_quiz_action_handling()
{
    global $debug;
    $_course = api_get_course_info();
    $courseId = $_course['real_id'];
    if (!isset($_POST['submit_upload_quiz'])) {
        return;
    }
    // Get the extension of the document.
    $path_info = pathinfo($_FILES['user_upload_quiz']['name']);
    // Check if the document is an Excel document
    if ($path_info['extension'] != 'xls') {
        return;
    }
    // Read the Excel document
    $data = new Spreadsheet_Excel_Reader();
    // Set output Encoding.
    $data->setOutputEncoding(api_get_system_encoding());
    // Reading the xls document.
    $data->read($_FILES['user_upload_quiz']['tmp_name']);
    $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null;
    $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null;
    $useCustomScore = isset($_POST['user_custom_score']) ? true : false;
    $propagateNegative = 0;
    if ($useCustomScore && !empty($incorrectScore)) {
        if ($incorrectScore < 0) {
            $propagateNegative = 1;
        }
    }
    // Variables
    $quiz_index = 0;
    $question_title_index = array();
    $question_name_index_init = array();
    $question_name_index_end = array();
    $score_index = array();
    $feedback_true_index = array();
    $feedback_false_index = array();
    $number_questions = 0;
    $question_description_index = array();
    // Reading all the first column items sequentially to create breakpoints
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if ($data->sheets[0]['cells'][$i][1] == 'Quiz' && $i == 1) {
            $quiz_index = $i;
            // Quiz title position, only occurs once
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Question') {
            $question_title_index[] = $i;
            // Question title position line
            $question_name_index_init[] = $i + 1;
            // Questions name 1st position line
            $number_questions++;
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Score') {
            $question_name_index_end[] = $i - 1;
            // Question name position
            $score_index[] = $i;
            // Question score position
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackTrue') {
            $feedback_true_index[] = $i;
            // FeedbackTrue position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackFalse') {
            $feedback_false_index[] = $i;
            // FeedbackFalse position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'EnrichQuestion') {
            $question_description_index[] = $i;
        }
    }
    // Variables
    $quiz = array();
    $question = array();
    $new_answer = array();
    $score_list = array();
    $feedback_true_list = array();
    $feedback_false_list = array();
    $question_description = array();
    // Getting questions.
    $k = $z = $q = $l = $m = 0;
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if (is_array($data->sheets[0]['cells'][$i])) {
            $column_data = $data->sheets[0]['cells'][$i];
            // Fill all column with data to have a full array
            for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                if (empty($column_data[$x])) {
                    $data->sheets[0]['cells'][$i][$x] = '';
                }
            }
            // Array filled with data
            $column_data = $data->sheets[0]['cells'][$i];
        } else {
            $column_data = '';
        }
        // Fill quiz data
        if ($quiz_index == $i) {
            // The title always in the first position
            $quiz = $column_data;
        } elseif (in_array($i, $question_title_index)) {
            //a complete line where 1st column is 'Question'
            $question[$k] = $column_data;
            $k++;
        } elseif (in_array($i, $score_index)) {
            //a complete line where 1st column is 'Score'
            $score_list[$z] = $column_data;
            $z++;
        } elseif (in_array($i, $feedback_true_index)) {
            //a complete line where 1st column is 'FeedbackTrue'
            $feedback_true_list[$q] = $column_data;
            $q++;
        } elseif (in_array($i, $feedback_false_index)) {
            //a complete line where 1st column is 'FeedbackFalse' for wrong answers
            $feedback_false_list[$l] = $column_data;
            $l++;
        } elseif (in_array($i, $question_description_index)) {
            //a complete line where 1st column is 'EnrichQuestion'
            $question_description[$m] = $column_data;
            $m++;
        }
    }
    // Get answers
    for ($i = 0; $i < count($question_name_index_init); $i++) {
        for ($j = $question_name_index_init[$i]; $j <= $question_name_index_end[$i]; $j++) {
            if (is_array($data->sheets[0]['cells'][$j])) {
                $column_data = $data->sheets[0]['cells'][$j];
                // Fill all column with data
                for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                    if (empty($column_data[$x])) {
                        $data->sheets[0]['cells'][$j][$x] = '';
                    }
                }
                $column_data = $data->sheets[0]['cells'][$j];
                // Array filled of data
                if (is_array($data->sheets[0]['cells'][$j]) && count($data->sheets[0]['cells'][$j]) > 0) {
                    $new_answer[$i][$j] = $data->sheets[0]['cells'][$j];
                }
            }
        }
    }
    // Quiz title.
    $quiz_title = $quiz[2];
    if ($quiz_title != '') {
        // Variables
        $type = 2;
        $random = $active = $results = $max_attempt = $expired_time = 0;
        // Make sure feedback is enabled (3 to disable), otherwise the fields
        // added to the XLS are not shown, which is confusing
        $feedback = 0;
        // Quiz object
        $exercise = new Exercise();
        //
        $quiz_id = $exercise->createExercise($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback, $propagateNegative);
        if ($quiz_id) {
            // insert into the item_property table
            api_item_property_update($_course, TOOL_QUIZ, $quiz_id, 'QuizAdded', api_get_user_id());
            // Import questions.
            for ($i = 0; $i < $number_questions; $i++) {
                // Question name
                $question_title = $question[$i][2];
                $question_description_text = "<p></p>";
                if (isset($question_description[$i][2])) {
                    // Question description.
                    $question_description_text = "<p>" . $question_description[$i][2] . "</p>";
                }
                // Unique answers are the only question types available for now
                // through xls-format import
                $question_id = null;
                $detectQuestionType = detectQuestionType($new_answer[$i], $score_list);
                /** @var Question $answer */
                switch ($detectQuestionType) {
                    case FREE_ANSWER:
                        $answer = new FreeAnswer();
                        break;
                    case GLOBAL_MULTIPLE_ANSWER:
                        $answer = new GlobalMultipleAnswer();
                        break;
                    case MULTIPLE_ANSWER:
                        $answer = new MultipleAnswer();
                        break;
                    case UNIQUE_ANSWER:
                    default:
                        $answer = new UniqueAnswer();
                        break;
                }
                if ($question_title != '') {
                    $question_id = $answer->create_question($quiz_id, $question_title, $question_description_text, 0, $answer->type);
                }
                $total = 0;
                if (is_array($new_answer[$i]) && !empty($question_id)) {
                    $id = 1;
                    $answers_data = $new_answer[$i];
                    $globalScore = null;
                    $objAnswer = new Answer($question_id, $courseId);
                    $globalScore = $score_list[$i][3];
                    // Calculate the number of correct answers to divide the
                    // score between them when importing from CSV
                    $numberRightAnswers = 0;
                    foreach ($answers_data as $answer_data) {
                        if (strtolower($answer_data[3]) == 'x') {
                            $numberRightAnswers++;
                        }
                    }
                    foreach ($answers_data as $answer_data) {
                        $answerValue = $answer_data[2];
                        $correct = 0;
                        $score = 0;
                        if (strtolower($answer_data[3]) == 'x') {
                            $correct = 1;
                            $score = $score_list[$i][3];
                            $comment = $feedback_true_list[$i][2];
                        } else {
                            $comment = $feedback_false_list[$i][2];
                            $floatVal = (double) $answer_data[3];
                            if (is_numeric($floatVal)) {
                                $score = $answer_data[3];
                            }
                        }
                        if ($useCustomScore) {
                            if ($correct) {
                                $score = $correctScore;
                            } else {
                                $score = $incorrectScore;
                            }
                        }
                        // Fixing scores:
                        switch ($detectQuestionType) {
                            case GLOBAL_MULTIPLE_ANSWER:
                                $score /= $numberRightAnswers;
                                break;
                            case UNIQUE_ANSWER:
                                break;
                            case MULTIPLE_ANSWER:
                                if (!$correct) {
                                    //$total = $total - $score;
                                }
                                break;
                        }
                        $objAnswer->createAnswer($answerValue, $correct, $comment, $score, $id);
                        $total += $score;
                        $id++;
                    }
                    $objAnswer->save();
                    $questionObj = Question::read($question_id, $courseId);
                    switch ($detectQuestionType) {
                        case GLOBAL_MULTIPLE_ANSWER:
                            $questionObj->updateWeighting($globalScore);
                            break;
                        case UNIQUE_ANSWER:
                        case MULTIPLE_ANSWER:
                        default:
                            $questionObj->updateWeighting($total);
                            break;
                    }
                    $questionObj->save();
                } else {
                    if ($detectQuestionType === FREE_ANSWER) {
                        $questionObj = Question::read($question_id, $courseId);
                        $globalScore = $score_list[$i][3];
                        $questionObj->updateWeighting($globalScore);
                        $questionObj->save();
                    }
                }
            }
        }
        if (isset($_SESSION['lpobject'])) {
            if ($debug > 0) {
                error_log('New LP - SESSION[lpobject] is defined', 0);
            }
            $oLP = unserialize($_SESSION['lpobject']);
            if (is_object($oLP)) {
                if ($debug > 0) {
                    error_log('New LP - oLP is object', 0);
                }
                if (empty($oLP->cc) or $oLP->cc != api_get_course_id()) {
                    if ($debug > 0) {
                        error_log('New LP - Course has changed, discard lp object', 0);
                    }
                    $oLP = null;
                    Session::erase('oLP');
                    Session::erase('lpobject');
                } else {
                    $_SESSION['oLP'] = $oLP;
                }
            }
        }
        if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
            $previous = $_SESSION['oLP']->select_previous_item_id();
            $parent = 0;
            // Add a Quiz as Lp Item
            $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quiz_title, '');
            // Redirect to home page for add more content
            header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id']));
            exit;
        } else {
            //  header('location: exercise.php?' . api_get_cidreq());
            echo '<script>window.location.href = "' . api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidReq() . '&exerciseId=' . $quiz_id . '&session_id=' . api_get_session_id() . '"</script>';
        }
    }
}