From 21be70372019d2f630f0dc11184e5c33522df2f3 Mon Sep 17 00:00:00 2001 From: Ivan Tcholakov Date: Fri, 18 Sep 2009 20:08:24 +0300 Subject: [PATCH] Feature #306 - The main API: Cleaning code, some minor optimizations, pass 1. --- main/inc/lib/main_api.lib.php | 2027 ++++++++++++++++----------------- 1 file changed, 984 insertions(+), 1043 deletions(-) diff --git a/main/inc/lib/main_api.lib.php b/main/inc/lib/main_api.lib.php index 92b33dbb43..500a069b7e 100644 --- a/main/inc/lib/main_api.lib.php +++ b/main/inc/lib/main_api.lib.php @@ -15,6 +15,7 @@ Copyright (c) Toon Van Hoecke Copyright (c) Denes Nagy Copyright (c) Isaac Flores + Copyright (c) Ivan Tcholakov For a full list of contributors, see "credits.txt". The full license can be read in "license.txt". @@ -58,7 +59,7 @@ define('DRH', 4); /** global status of a user: human ressource manager */ define('ANONYMOUS', 6); /** global status of a user: low security,it's necessary for inserting data from the teacher */ -define('COURSEMANAGERLOWSECURITY',10); +define('COURSEMANAGERLOWSECURITY', 10); // table of status $_status_list[STUDENT] = 'user'; @@ -111,7 +112,7 @@ define('WEB_LIBRARY_PATH','WEB_LIBRARY_PATH'); //CONSTANTS defining all tools, using the english version /* - When you add a new tool you must add it into function api_get_tools_lists() too + When you add a new tool you must add it into function api_get_tools_lists() too */ define('TOOL_DOCUMENT', 'document'); define('TOOL_THUMBNAIL', 'thumbnail'); @@ -218,6 +219,7 @@ require_once dirname(__FILE__).'/internationalization.lib.php'; use these to protect your scripts ============================================================================== */ + /** * Function used to protect a course script. * The function blocks access when @@ -231,14 +233,13 @@ require_once dirname(__FILE__).'/internationalization.lib.php'; * @todo replace global variable * @author Roan Embrechts */ -function api_protect_course_script($print_headers=false) { +function api_protect_course_script($print_headers = false) { global $is_allowed_in_course; if (!$is_allowed_in_course) { api_not_allowed($print_headers); return false; - } else { - return true; } + return true; } /** @@ -248,14 +249,13 @@ function api_protect_course_script($print_headers=false) { * * @author Roan Embrechts */ -function api_protect_admin_script($allow_sessions_admins=false) { +function api_protect_admin_script($allow_sessions_admins = false) { if (!api_is_platform_admin($allow_sessions_admins)) { - include (api_get_path(INCLUDE_PATH)."header.inc.php"); + include api_get_path(INCLUDE_PATH).'header.inc.php'; api_not_allowed(); return false; - }else{ - return true; } + return true; } /** @@ -265,14 +265,12 @@ function api_protect_admin_script($allow_sessions_admins=false) { */ function api_block_anonymous_users() { global $_user; - - if (!(isset ($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'],true)) { - include (api_get_path(INCLUDE_PATH)."header.inc.php"); + if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)) { + include api_get_path(INCLUDE_PATH).'header.inc.php'; api_not_allowed(); return false; - }else{ - return true; } + return true; } /* @@ -282,6 +280,8 @@ function api_block_anonymous_users() { use these functions instead ============================================================================== */ + +// TODO: Some optimizations are needed here. /** * @return an array with the navigator name and version */ @@ -307,16 +307,17 @@ function api_get_navigator() { } return array ('name' => $navigator, 'version' => $version); } + /** * @return True if user selfregistration is allowed, false otherwise. */ function api_is_self_registration_allowed() { if(isset($GLOBALS['allowSelfReg'])) { return $GLOBALS["allowSelfReg"]; - } else { - return false; } + return false; } + /** * Returns a full path to a certain Dokeos area, which you specify * through a parameter. @@ -324,7 +325,7 @@ function api_is_self_registration_allowed() { * See $_configuration['course_folder'] in the configuration.php * to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters. * -* @param one of the following constants: +* @param one of the following constants (thist list might be increased): * WEB_SERVER_ROOT_PATH, SYS_SERVER_ROOT_PATH, * WEB_PATH, SYS_PATH, REL_PATH, WEB_COURSE_PATH, SYS_COURSE_PATH, * REL_COURSE_PATH, REL_CODE_PATH, WEB_CODE_PATH, SYS_CODE_PATH, @@ -360,17 +361,19 @@ function api_is_self_registration_allowed() { function api_get_path($path_type) { global $_configuration; - if (!isset($_configuration['access_url']) || $_configuration['access_url']==1 || $_configuration['access_url']=='') { + + if (!isset($_configuration['access_url']) || $_configuration['access_url'] == 1 || $_configuration['access_url'] == '') { //by default we call the $_configuration['root_web'] we don't query to the DB //$url_info= api_get_access_url(1); //$root_web = $url_info['url']; - if(isset($_configuration['root_web'])) + if (isset($_configuration['root_web'])) { $root_web = $_configuration['root_web']; + } } else { //we look into the DB the function api_get_access_url //this funcion have a problem because we can't called to the Database:: functions - $url_info= api_get_access_url($_configuration['access_url']); - if ($url_info['active']==1) { + $url_info = api_get_access_url($_configuration['access_url']); + if ($url_info['active'] == 1) { $root_web = $url_info['url']; } else { $root_web = $_configuration['root_web']; @@ -384,121 +387,97 @@ function api_get_path($path_type) { $result = preg_replace('@'.api_get_path(REL_PATH).'$@', '', api_get_path(WEB_PATH)); if (substr($result, -1) == '/') { return $result; - } else { - return $result.'/'; } - break; + return $result.'/'; case SYS_SERVER_ROOT_PATH: $result = preg_replace('@'.api_get_path(REL_PATH).'$@', '', api_get_path(SYS_PATH)); if (substr($result, -1) == '/') { return $result; - } else { - return $result.'/'; } - break; + return $result.'/'; case WEB_PATH : // example: http://www.mydokeos.com/ or http://www.mydokeos.com/dokeos/ if you're using // a subdirectory of your document root for Dokeos - if (substr($root_web,-1) == '/') { + if (substr($root_web, -1) == '/') { return $root_web; - } else { - return $root_web.'/'; } - break; + return $root_web.'/'; case SYS_PATH : // example: /var/www/dokeos/ - if (substr($_configuration['root_sys'],-1) == '/') { + if (substr($_configuration['root_sys'], -1) == '/') { return $_configuration['root_sys']; - } else { - return $_configuration['root_sys'].'/'; } - break; + return $_configuration['root_sys'].'/'; case REL_PATH : // example: dokeos/ if (substr($_configuration['url_append'], -1) === '/') { return $_configuration['url_append']; - } else { - return $_configuration['url_append'].'/'; } - break; + return $_configuration['url_append'].'/'; case WEB_COURSE_PATH : // example: http://www.mydokeos.com/courses/ return $root_web.$_configuration['course_folder']; - break; case SYS_COURSE_PATH : // example: /var/www/dokeos/courses/ return $_configuration['root_sys'].$_configuration['course_folder']; - break; case REL_COURSE_PATH : // example: courses/ or dokeos/courses/ return api_get_path(REL_PATH).$_configuration['course_folder']; - break; case REL_CODE_PATH : // example: main/ or dokeos/main/ return api_get_path(REL_PATH).$_configuration['code_append']; - break; case WEB_CODE_PATH : // example: http://www.mydokeos.com/main/ //return $GLOBALS['clarolineRepositoryWeb']; // this was changed return $root_web.$_configuration['code_append']; - break; case SYS_CODE_PATH : // example: /var/www/dokeos/main/ return $GLOBALS['clarolineRepositorySys']; - break; case SYS_LANG_PATH : // example: /var/www/dokeos/main/lang/ return api_get_path(SYS_CODE_PATH).'lang/'; - break; case WEB_IMG_PATH : // example: http://www.mydokeos.com/main/img/ return api_get_path(WEB_CODE_PATH).'img/'; - break; case SYS_PLUGIN_PATH : // example: /var/www/dokeos/plugin/ return api_get_path(SYS_PATH).'plugin/'; - break; case WEB_PLUGIN_PATH : // example: http://www.mydokeos.com/plugin/ return api_get_path(WEB_PATH).'plugin/'; - break; - case GARBAGE_PATH : //now set to be same as archive + case GARBAGE_PATH : //now set to be same as archive case SYS_ARCHIVE_PATH : // example: /var/www/dokeos/archive/ return api_get_path(SYS_PATH).'archive/'; - break; case WEB_ARCHIVE_PATH : // example: http://www.mydokeos.com/archive/ return api_get_path(WEB_PATH).'archive/'; - break; case INCLUDE_PATH : // Generated by main/inc/global.inc.php // example: /var/www/dokeos/main/inc/ - $incpath = realpath(dirname(__FILE__).'/../'); - return str_replace('\\', '/', $incpath).'/'; - break; + $incpath = realpath(dirname(__FILE__).'/../'); + return str_replace('\\', '/', $incpath).'/'; case LIBRARY_PATH : // example: /var/www/dokeos/main/inc/lib/ return api_get_path(INCLUDE_PATH).'lib/'; - break; case WEB_LIBRARY_PATH : // example: http://www.mydokeos.com/main/inc/lib/ @@ -508,11 +487,9 @@ function api_get_path($path_type) { case CONFIGURATION_PATH : // example: /var/www/dokeos/main/inc/conf/ return api_get_path(INCLUDE_PATH).'conf/'; - break; default : - return; - break; + return null; } } @@ -529,13 +506,14 @@ function api_get_user_id() { } return $GLOBALS['_user']['user_id']; } + /** * Get the list of courses a specific user is subscribed to * @param int User ID * @param boolean Whether to get session courses or not - NOT YET IMPLEMENTED * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d) */ -function api_get_user_courses($userid,$fetch_session=true) { +function api_get_user_courses($userid, $fetch_session = true) { if ($userid != strval(intval($userid))) { return array(); } //get out if not integer $t_course = Database::get_main_table(TABLE_MAIN_COURSE); $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); @@ -549,14 +527,14 @@ function api_get_user_courses($userid,$fetch_session=true) { WHERE cc.code = cu.course_code AND cu.user_id = '".$userid."'"; $result = api_sql_query($sql_select_courses); - if ($result===false) { return array(); } - while ($row = Database::fetch_array($result)) - { + if ($result === false) { return array(); } + while ($row = Database::fetch_array($result)) { // we only need the database name of the course $courses[] = $row; } return $courses; } + /** * Find all the information about a user. If no paramater is passed you find all the information about the current user. * @param $user_id (integer): the id of the user @@ -568,30 +546,30 @@ function api_get_user_info($user_id = '') { global $tbl_user; if ($user_id == '') { return $GLOBALS["_user"]; - } else { - $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id='".Database::escape_string($user_id)."'"; - $result = api_sql_query($sql, __FILE__, __LINE__); - if(Database::num_rows($result) > 0) { - $result_array = Database::fetch_array($result); - // this is done so that it returns the same array-index-names - // ideally the names of the fields of the user table are renamed so that they match $_user (or vice versa) - // $_user should also contain every field of the user table (except password maybe). This would make the - // following lines obsolete (and the code cleaner and slimmer !!! - $user_info['firstName'] = $result_array['firstname']; - $user_info['lastName'] = $result_array['lastname']; - $user_info['mail'] = $result_array['email']; - $user_info['picture_uri'] = $result_array['picture_uri']; - $user_info['user_id'] = $result_array['user_id']; - $user_info['official_code'] = $result_array['official_code']; - $user_info['status'] = $result_array['status']; - $user_info['auth_source'] = $result_array['auth_source']; - $user_info['username'] = $result_array['username']; - $user_info['theme'] = $result_array['theme']; - return $user_info; - } - return false; } + $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id='".Database::escape_string($user_id)."'"; + $result = api_sql_query($sql, __FILE__, __LINE__); + if (Database::num_rows($result) > 0) { + $result_array = Database::fetch_array($result); + // this is done so that it returns the same array-index-names + // ideally the names of the fields of the user table are renamed so that they match $_user (or vice versa) + // $_user should also contain every field of the user table (except password maybe). This would make the + // following lines obsolete (and the code cleaner and slimmer !!! + $user_info['firstName'] = $result_array['firstname']; + $user_info['lastName'] = $result_array['lastname']; + $user_info['mail'] = $result_array['email']; + $user_info['picture_uri'] = $result_array['picture_uri']; + $user_info['user_id'] = $result_array['user_id']; + $user_info['official_code'] = $result_array['official_code']; + $user_info['status'] = $result_array['status']; + $user_info['auth_source'] = $result_array['auth_source']; + $user_info['username'] = $result_array['username']; + $user_info['theme'] = $result_array['theme']; + return $user_info; + } + return false; } + /** * Find all the information about a user from username instead of user id * @param $username (string): the username @@ -599,36 +577,38 @@ function api_get_user_info($user_id = '') { * @author Yannick Warnier */ function api_get_user_info_from_username($username = '') { - if (empty($username)) { return false; } - global $tbl_user; - $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE username='".Database::escape_string($username)."'"; - $result = api_sql_query($sql, __FILE__, __LINE__); - if (Database::num_rows($result) > 0) { - $result_array = Database::fetch_array($result); - // this is done so that it returns the same array-index-names - // ideally the names of the fields of the user table are renamed so that they match $_user (or vice versa) - // $_user should also contain every field of the user table (except password maybe). This would make the - // following lines obsolete (and the code cleaner and slimmer !!! - $user_info['firstName'] = $result_array['firstname']; - $user_info['lastName'] = $result_array['lastname']; - $user_info['mail'] = $result_array['email']; - $user_info['picture_uri'] = $result_array['picture_uri']; - $user_info['user_id'] = $result_array['user_id']; - $user_info['official_code'] = $result_array['official_code']; - $user_info['status'] = $result_array['status']; - $user_info['auth_source'] = $result_array['auth_source']; - $user_info['username'] = $result_array['username']; - $user_info['theme'] = $result_array['theme']; - return $user_info; - } - return false; + if (empty($username)) { return false; } + global $tbl_user; + $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE username='".Database::escape_string($username)."'"; + $result = api_sql_query($sql, __FILE__, __LINE__); + if (Database::num_rows($result) > 0) { + $result_array = Database::fetch_array($result); + // this is done so that it returns the same array-index-names + // ideally the names of the fields of the user table are renamed so that they match $_user (or vice versa) + // $_user should also contain every field of the user table (except password maybe). This would make the + // following lines obsolete (and the code cleaner and slimmer !!! + $user_info['firstName'] = $result_array['firstname']; + $user_info['lastName'] = $result_array['lastname']; + $user_info['mail'] = $result_array['email']; + $user_info['picture_uri'] = $result_array['picture_uri']; + $user_info['user_id'] = $result_array['user_id']; + $user_info['official_code'] = $result_array['official_code']; + $user_info['status'] = $result_array['status']; + $user_info['auth_source'] = $result_array['auth_source']; + $user_info['username'] = $result_array['username']; + $user_info['theme'] = $result_array['theme']; + return $user_info; + } + return false; } + /** * Returns the current course id (integer) */ function api_get_course_id() { - return $GLOBALS["_cid"]; + return $GLOBALS['_cid']; } + /** * Returns the current course directory * @@ -637,14 +617,15 @@ function api_get_course_id() { * @return string The directory where the course is located inside the Dokeos "courses" directory * @author Yannick Warnier */ -function api_get_course_path($course_code=null) { - if(!empty($course_code)) { +function api_get_course_path($course_code = null) { + if (!empty($course_code)) { $info = api_get_course_info($course_code); } else { $info = api_get_course_info(); } return $info['path']; } + /** * Gets a course setting from the current course_setting table. Try always using integer values. * @param string The name of the setting we want from the table @@ -653,20 +634,21 @@ function api_get_course_path($course_code=null) { */ function api_get_course_setting($setting_name, $course_code = null) { if (!empty($course_code)) { - $c = api_get_course_info($course_code); - $table = Database::get_course_table(TABLE_COURSE_SETTING,$c['dbName']); + $course_info = api_get_course_info($course_code); + $table = Database::get_course_table(TABLE_COURSE_SETTING, $course_info['dbName']); } else { $table = Database::get_course_table(TABLE_COURSE_SETTING); } $setting_name = Database::escape_string($setting_name); $sql = "SELECT * FROM $table WHERE variable = '$setting_name'"; - $res = api_sql_query($sql,__FILE__,__LINE__); - if (Database::num_rows($res)>0) { + $res = api_sql_query($sql, __FILE__, __LINE__); + if (Database::num_rows($res) > 0) { $row = Database::fetch_array($res); return $row['value']; } return -1; } + /** * Gets an anonymous user ID * @@ -679,25 +661,26 @@ function api_get_course_setting($setting_name, $course_code = null) { function api_get_anonymous_id() { $table = Database::get_main_table(TABLE_MAIN_USER); $sql = "SELECT user_id FROM $table WHERE status = 6"; - $res = api_sql_query($sql,__FILE__,__LINE__); - if (Database::num_rows($res)>0) { + $res = api_sql_query($sql, __FILE__, __LINE__); + if (Database::num_rows($res) > 0) { $row = Database::fetch_array($res); - //error_log('api_get_anonymous_id() returns '.$row['user_id'],0); + //error_log('api_get_anonymous_id() returns '.$row['user_id'], 0); return $row['user_id']; - } else {//no anonymous user was found - return 0; } + //no anonymous user was found + return 0; } /** * Returns the cidreq parameter name + current course id */ function api_get_cidreq() { - if (!empty ($GLOBALS["_cid"])) { - return 'cidReq='.htmlspecialchars($GLOBALS["_cid"]); + if (!empty ($GLOBALS['_cid'])) { + return 'cidReq='.htmlspecialchars($GLOBALS['_cid']); } return ''; } + /** * Returns the current course info array. * Note: this array is only defined if the user is inside a course. @@ -718,44 +701,43 @@ function api_get_cidreq() { * particular course, not specially the current one. * @todo same behaviour as api_get_user_info so that api_get_course_id becomes absolete too */ -function api_get_course_info($course_code=null) { +function api_get_course_info($course_code = null) { if (!empty($course_code)) { $course_code = Database::escape_string($course_code); $course_table = Database::get_main_table(TABLE_MAIN_COURSE); - $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY); - $sql = "SELECT `course`.*, `course_category`.`code` `faCode`, `course_category`.`name` `faName` + $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY); + $sql = "SELECT `course`.*, `course_category`.`code` `faCode`, `course_category`.`name` `faName` FROM $course_table LEFT JOIN $course_cat_table ON `course`.`category_code` = `course_category`.`code` WHERE `course`.`code` = '$course_code'"; - $result = api_sql_query($sql,__FILE__,__LINE__); - $_course = array(); - if (Database::num_rows($result)>0) { - global $_configuration; - $cData = Database::fetch_array($result); - $_course['id' ] = $cData['code' ]; //auto-assigned integer - $_course['name' ] = $cData['title' ]; - $_course['official_code'] = $cData['visual_code' ]; // use in echo - $_course['sysCode' ] = $cData['code' ]; // use as key in db - $_course['path' ] = $cData['directory' ]; // use as key in path - $_course['dbName' ] = $cData['db_name' ]; // use as key in db list - $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $cData['db_name'] . $_configuration['db_glue']; // use in all queries - $_course['titular' ] = $cData['tutor_name' ]; - $_course['language' ] = $cData['course_language' ]; - $_course['extLink' ]['url' ] = $cData['department_url' ]; - $_course['extLink' ]['name'] = $cData['department_name']; - $_course['categoryCode'] = $cData['faCode' ]; - $_course['categoryName'] = $cData['faName' ]; - - $_course['visibility' ] = $cData['visibility']; - $_course['subscribe_allowed'] = $cData['subscribe']; - $_course['unubscribe_allowed'] = $cData['unsubscribe']; - } - return $_course; - } else { - global $_course; + $result = api_sql_query($sql, __FILE__, __LINE__); + $_course = array(); + if (Database::num_rows($result) > 0) { + global $_configuration; + $cData = Database::fetch_array($result); + $_course['id' ] = $cData['code' ]; //auto-assigned integer + $_course['name' ] = $cData['title' ]; + $_course['official_code'] = $cData['visual_code' ]; // use in echo + $_course['sysCode' ] = $cData['code' ]; // use as key in db + $_course['path' ] = $cData['directory' ]; // use as key in path + $_course['dbName' ] = $cData['db_name' ]; // use as key in db list + $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $cData['db_name'] . $_configuration['db_glue']; // use in all queries + $_course['titular' ] = $cData['tutor_name' ]; + $_course['language' ] = $cData['course_language']; + $_course['extLink' ]['url' ] = $cData['department_url' ]; + $_course['extLink' ]['name'] = $cData['department_name']; + $_course['categoryCode' ] = $cData['faCode' ]; + $_course['categoryName' ] = $cData['faName' ]; + + $_course['visibility' ] = $cData['visibility' ]; + $_course['subscribe_allowed'] = $cData['subscribe' ]; + $_course['unubscribe_allowed'] = $cData['unsubscribe' ]; + } return $_course; } + global $_course; + return $_course; } /* @@ -763,6 +745,7 @@ function api_get_course_info($course_code=null) { DATABASE QUERY MANAGEMENT ============================================================================== */ + /** * Executes an SQL query * You have to use addslashes() on each value that you want to record into the database @@ -772,6 +755,7 @@ function api_get_course_info($course_code=null) { * @param string $file - optional, the file path and name of the error (__FILE__) * @param string $line - optional, the line of the error (__LINE__) * @return resource - the return value of the query + * Note: Database::query method is preferable for use. */ function api_sql_query($query, $file = '', $line = 0) { $result = @mysql_query($query); @@ -796,6 +780,8 @@ function api_sql_query($query, $file = '', $line = 0) { } return $result; } + +// TODO: To be moved to Database class. /** * Store the result of a query into an array * @@ -804,11 +790,13 @@ function api_sql_query($query, $file = '', $line = 0) { * @return array - the value returned by the query */ function api_store_result($result) { - $tab = array (); - while ($row = Database::fetch_array($result)) { - $tab[] = $row; + $array = array(); + if ($result !== false) { // For isolation from database engine's behaviour. + while ($row = Database::fetch_array($result)) { + $array[] = $row; + } } - return $tab; + return $array; } /* @@ -816,6 +804,7 @@ function api_store_result($result) { SESSION MANAGEMENT ============================================================================== */ + /** * Start the Dokeos session. * @@ -846,9 +835,9 @@ function api_session_start($already_installed = true) { $storeSessionInDb = false; } if ($storeSessionInDb && function_exists('session_set_save_handler')) { - include_once (api_get_path(LIBRARY_PATH).'session_handler.class.php'); + include_once api_get_path(LIBRARY_PATH).'session_handler.class.php'; $session_handler = new session_handler(); - @ session_set_save_handler(array (& $session_handler, 'open'), array (& $session_handler, 'close'), array (& $session_handler, 'read'), array (& $session_handler, 'write'), array (& $session_handler, 'destroy'), array (& $session_handler, 'garbage')); + @session_set_save_handler(array(& $session_handler, 'open'), array(& $session_handler, 'close'), array(& $session_handler, 'read'), array(& $session_handler, 'write'), array(& $session_handler, 'destroy'), array(& $session_handler, 'garbage')); } session_name('dk_sid'); session_start(); @@ -860,6 +849,7 @@ function api_session_start($already_installed = true) { } } } + /** * save a variable into the session * @@ -873,6 +863,7 @@ function api_session_register($variable) { session_register($variable); $_SESSION[$variable] = $$variable; } + /** * Remove a variable from the session. * @@ -881,15 +872,15 @@ function api_session_register($variable) { */ function api_session_unregister($variable) { $variable = strval($variable); - if(isset($GLOBALS[$variable])) { + if (isset($GLOBALS[$variable])) { unset ($GLOBALS[$variable]); } - if(isset($_SESSION[$variable])) { $_SESSION[$variable] = null; session_unregister($variable); } } + /** * Clear the session * @@ -900,6 +891,7 @@ function api_session_clear() { session_unset(); $_SESSION = array (); } + /** * Destroy the session * @@ -916,6 +908,7 @@ function api_session_destroy() { STRING MANAGEMENT ============================================================================== */ + /** * Add a parameter to the existing URL. If this parameter already exists, * just replace it with the new value @@ -924,7 +917,7 @@ function api_session_destroy() { * @param boolean Whether to filter XSS or not * @return string The URL with the added parameter */ -function api_add_url_param($url, $param, $filter_xss=true) { +function api_add_url_param($url, $param, $filter_xss = true) { if (empty ($param)) { return $url; } @@ -952,11 +945,13 @@ function api_add_url_param($url, $param, $filter_xss=true) { } else { $url = $url.'?'.$param; } - if ($filter_xss === true) { - $url = Security::remove_XSS(urldecode($url)); - } + if ($filter_xss === true) { + $url = Security::remove_XSS(urldecode($url)); + } return $url; } + +// TODO: To be moved to the UserManager? /** * Returns a difficult to guess password. * @param int $length, the length of the password @@ -973,41 +968,45 @@ function api_generate_password($length = 8) { } return $password; } + +// TODO: To be moved to the UserManager? +// TODO: Multibyte support to be implemented. /** * Checks a password to see wether it is OK to use. * @param string $password * @return true if the password is acceptable, false otherwise */ function api_check_password($password) { - $lengthPass = strlen($password); - if ($lengthPass < 5) { + $length_pass = strlen($password); + if ($length_pass < 5) { return false; } - $passLower = strtolower($password); - $cptLettres = $cptChiffres = 0; - $consecutif = 0; - $codeCharPrev = 0; - for ($i = 0; $i < $lengthPass; $i ++) { - $codeCharCur = ord($passLower[$i]); - if ($i && abs($codeCharCur - $codeCharPrev) <= 1) { - $consecutif ++; - if ($consecutif == 3) { + $pass_lower = strtolower($password); + $nb_lettres = $nb_digits = 0; + $nb_sequent_chars = 0; + $char_code_previous = 0; + for ($i = 0; $i < $length_pass; $i ++) { + $char_code_current = ord($pass_lower[$i]); + if ($i && abs($char_code_current - $char_code_previous) <= 1) { + $nb_sequent_chars ++; + if ($nb_sequent_chars == 3) { return false; } } else { - $consecutif = 1; + $nb_sequent_chars = 1; } - if ($codeCharCur >= 97 && $codeCharCur <= 122) { - $cptLettres ++; - } elseif ($codeCharCur >= 48 && $codeCharCur <= 57) { - $cptChiffres ++; + if ($char_code_current >= 97 && $char_code_current <= 122) { + $nb_lettres ++; + } elseif ($char_code_current >= 48 && $char_code_current <= 57) { + $nb_digits ++; } else { return false; } - $codeCharPrev = $codeCharCur; + $char_code_previous = $char_code_current; } - return ($cptLettres >= 3 && $cptChiffres >= 2) ? true : false; + return $nb_lettres >= 3 && $nb_digits >= 2; } + /** * Clear the user ID from the session if it was the anonymous user. Generally * used on out-of-tools pages to remove a user ID that could otherwise be used @@ -1017,17 +1016,18 @@ function api_check_password($password) { * @param bool database check switch - passed to api_is_anonymous() * @return bool true if succesfully unregistered, false if not anonymous. */ -function api_clear_anonymous($db_check=false) { +function api_clear_anonymous($db_check = false) { global $_user; - if (api_is_anonymous($_user['user_id'],$db_check)) { + if (api_is_anonymous($_user['user_id'], $db_check)) { unset($_user['user_id']); api_session_unregister('_uid'); return true; - } else { - return false; } + return false; } +// TODO: To be moved in text.lib.php +// TODO: Multibyte capability to be checked. /** * truncates a string * @@ -1042,12 +1042,14 @@ function api_trunc_str($text, $length = 30, $endStr = '...', $middle = false) { return $text; } if ($middle) { - $text = rtrim(api_substr($text, 0, round($length / 2))).$endStr.ltrim(api_substr($text, -round($length / 2))); + $text = rtrim(api_substr($text, 0, round($length / 2))).$endStr.ltrim(api_substr($text, - round($length / 2))); } else { $text = rtrim(api_substr($text, 0, $length)).$endStr; } return $text; } + +// TODO: Multibyte capability to be added anyway. // deprecated, use api_trunc_str() instead function shorten($input, $length = 15) { $length = intval($length); @@ -1056,6 +1058,8 @@ function shorten($input, $length = 15) { } return api_trunc_str($input, $length); } + +// TODO: To be moved in text.lib.php /** * handling simple and double apostrofe in order that strings be stored properly in database * @@ -1069,6 +1073,7 @@ function domesticate($input) { return ($input); } + /** * Returns the status string corresponding to the status code * @author Noel Dieschburg @@ -1077,16 +1082,16 @@ function domesticate($input) { function get_status_from_code($status_code) { switch ($status_code) { case STUDENT: - return get_lang('Student'); + return get_lang('Student', ''); case TEACHER: - return get_lang('Teacher'); + return get_lang('Teacher', ''); case COURSEMANAGER: - return get_lang('Manager'); + return get_lang('Manager', ''); case SESSIONADMIN: - return get_lang('SessionsAdmin'); + return get_lang('SessionsAdmin', ''); case DRH: - return get_lang('Drh'); - } + return get_lang('Drh', ''); + } } /* @@ -1099,11 +1104,13 @@ function get_status_from_code($status_code) { * The Failure Management module is here to compensate * the absence of an 'exception' device in PHP 4. */ + /** * $api_failureList - array containing all the failure recorded * in order of arrival. */ $api_failureList = array (); + /** * Fills a global array called $api_failureList * This array collects all the failure occuring during the script runs @@ -1130,21 +1137,19 @@ function api_set_failure($failureType) { */ function api_set_anonymous() { global $_user; - if(!empty($_user['user_id'])) { + if (!empty($_user['user_id'])) { + return false; + } + $user_id = api_get_anonymous_id(); + if ($user_id == 0) { return false; - } else { - $user_id = api_get_anonymous_id(); - if($user_id == 0) { - return false; - } else { - api_session_unregister('_user'); - $_user['user_id'] = $user_id; - $_user['is_anonymous'] = true; - api_session_register('_user'); - $GLOBALS['_user'] = $_user; - return true; - } } + api_session_unregister('_user'); + $_user['user_id'] = $user_id; + $_user['is_anonymous'] = true; + api_session_register('_user'); + $GLOBALS['_user'] = $_user; + return true; } /** @@ -1158,6 +1163,7 @@ function api_get_last_failure() { global $api_failureList; return $api_failureList[count($api_failureList) - 1]; } + /** * collects and manage failures occuring during script execution * The main purpose is allowing to manage the display messages externaly @@ -1166,8 +1172,9 @@ function api_get_last_failure() { * @author Hugues Peeters * @package dokeos.library */ -class api_failure -{ +class api_failure { + + // TODO: $api_failureList to be hidden from global scope. /* * IMPLEMENTATION NOTE : For now the $api_failureList list is set to the * global scope, as PHP 4 is unable to manage static variable in class. But @@ -1176,6 +1183,7 @@ class api_failure * change. */ public $api_failureList = array (); + /** * Pile the last failure in the failure list * @@ -1189,6 +1197,7 @@ class api_failure $api_failureList[] = $failureType; return false; } + /** * get the last failure stored * @@ -1198,7 +1207,7 @@ class api_failure */ function get_last_failure() { global $api_failureList; - if(count($api_failureList)==0){return '';} + if (count($api_failureList) == 0) { return ''; } return $api_failureList[count($api_failureList) - 1]; } } @@ -1225,31 +1234,32 @@ function get_setting($variable, $key = NULL) { function api_get_session_id() { if (empty($_SESSION['id_session'])) { return 0; - } else { - return (int) $_SESSION['id_session']; } + return (int) $_SESSION['id_session']; } + /** * Gets the current or given session name * @param int Session ID (optional) * @return string The session name, or null if unfound */ function api_get_session_name($session_id) { - if (empty($session_id)) { - $session_id = api_get_session_id(); - if (empty($session_id)) {return null;} - } - $t = Database::get_main_table(TABLE_MAIN_SESSION); - $s = "SELECT name FROM $t WHERE id = ".(int)$session_id; - $r = api_sql_query($s,__FILE__,__LINE__); - $c = Database::num_rows($r); - if ($c > 0) { - //technically, there can be only one, but anyway we take the first - $rec = Database::fetch_array($r); - return $rec['name']; - } - return null; + if (empty($session_id)) { + $session_id = api_get_session_id(); + if (empty($session_id)) { return null; } + } + $t = Database::get_main_table(TABLE_MAIN_SESSION); + $s = "SELECT name FROM $t WHERE id = ".(int)$session_id; + $r = api_sql_query($s, __FILE__, __LINE__); + $c = Database::num_rows($r); + if ($c > 0) { + //technically, there can be only one, but anyway we take the first + $rec = Database::fetch_array($r); + return $rec['name']; + } + return null; } + /** * Returns the value of a setting from the web-adjustable admin config settings. * @@ -1262,9 +1272,9 @@ function api_get_session_name($session_id) { * @author Rene Haentjens * @author Bart Mollet */ -function api_get_setting($variable, $key = NULL) { +function api_get_setting($variable, $key = null) { global $_setting; - return is_null($key) ? (!empty($_setting[$variable])?$_setting[$variable]:null) : $_setting[$variable][$key]; + return is_null($key) ? (!empty($_setting[$variable]) ? $_setting[$variable] : null) : $_setting[$variable][$key]; } /** @@ -1290,29 +1300,31 @@ function api_get_self() { function api_is_platform_admin($allow_sessions_admins = false) { if($_SESSION['is_platformAdmin']) { return true; - } else { - global $_user; - if ($allow_sessions_admins && $_user['status']==SESSIONADMIN) { - return true; - } + } + global $_user; + if ($allow_sessions_admins && $_user['status'] == SESSIONADMIN) { + return true; } return false; } + /** * Check if current user is allowed to create courses * @return boolean True if the user has course creation rights, * false otherwise. */ function api_is_allowed_to_create_course() { - return $_SESSION["is_allowedCreateCourse"]; + return $_SESSION['is_allowedCreateCourse']; } + /** * Check if the current user is a course administrator * @return boolean True if current user is a course administrator */ function api_is_course_admin() { - return $_SESSION["is_courseAdmin"]; + return $_SESSION['is_courseAdmin']; } + /** * Check if the current user is a course coach * @return bool True if current user is a course coach @@ -1320,6 +1332,7 @@ function api_is_course_admin() { function api_is_course_coach() { return $_SESSION['is_courseCoach']; } + /** * Check if the current user is a course tutor * @return bool True if current user is a course tutor @@ -1327,6 +1340,7 @@ function api_is_course_coach() { function api_is_course_tutor() { return $_SESSION['is_courseTutor']; } + /** * Check if the current user is a course or session coach * @return boolean True if current user is a course or session coach @@ -1340,21 +1354,17 @@ function api_is_coach() { INNER JOIN session_rel_course ON session_rel_course.id_coach = '".Database::escape_string($_user['user_id'])."' ORDER BY date_start, date_end, name"; - $result = api_sql_query($sql,__FILE__,__LINE__); + $result = api_sql_query($sql, __FILE__, __LINE__); $sessionIsCoach = api_store_result($result); $sql = "SELECT DISTINCT id, name, date_start, date_end FROM session WHERE session.id_coach = '".Database::escape_string($_user['user_id'])."' ORDER BY date_start, date_end, name"; - $result = api_sql_query($sql,__FILE__,__LINE__); - $sessionIsCoach = array_merge($sessionIsCoach , api_store_result($result)); + $result = api_sql_query($sql, __FILE__, __LINE__); + $sessionIsCoach = array_merge($sessionIsCoach, api_store_result($result)); - if(count($sessionIsCoach) > 0) { - return true; - } else { - return false; - } + return count($sessionIsCoach) > 0; } /** @@ -1363,11 +1373,7 @@ function api_is_coach() { */ function api_is_session_admin() { global $_user; - if ($_user['status']==SESSIONADMIN) { - return true; - } else{ - return false; - } + return $_user['status'] == SESSIONADMIN; } /* @@ -1376,6 +1382,8 @@ function api_is_session_admin() { student view, title, message boxes,... ============================================================================== */ + +// TODO: To be moved to Display class. /** * Displays the title of a tool. * Normal use: parameter is a string: @@ -1416,6 +1424,8 @@ function api_display_tool_title($titleElement) { } echo ''; } + +// TODO: To be moved to Display class. /** * Display options to switch between student view and course manager view * @@ -1440,73 +1450,79 @@ function api_display_tool_title($titleElement) { * @todo rewrite code so it is easier to understand */ function api_display_tool_view_option() { - if (api_get_setting('student_view_enabled') != "true") { + + if (api_get_setting('student_view_enabled') != 'true') { return ''; } - $output_string=''; + + $output_string = ''; $sourceurl = ''; $is_framed = false; // Exceptions apply for all multi-frames pages - if (strpos($_SERVER['REQUEST_URI'],'chat/chat_banner.php')!==false) { //the chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link + if (strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php') !== false) { //the chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link $is_framed = true; return ''; } + // Uncomment to remove student view link from document view page - if (strpos($_SERVER['REQUEST_URI'],'document/headerpage.php')!==false) { - $sourceurl = str_replace('document/headerpage.php','document/showinframes.php',$_SERVER['REQUEST_URI']); + if (strpos($_SERVER['REQUEST_URI'], 'document/headerpage.php') !== false) { + $sourceurl = str_replace('document/headerpage.php', 'document/showinframes.php', $_SERVER['REQUEST_URI']); + //showinframes doesn't handle student view anyway... + //return ''; + $is_framed = true; + } + + // Uncomment to remove student view link from document view page + if (strpos($_SERVER['REQUEST_URI'], 'newscorm/lp_header.php') !== false) { + if (empty($_GET['lp_id'])) { + return ''; + } + $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')); + $sourceurl = str_replace('newscorm/lp_header.php', 'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview']=='studentview' ? 'false' : 'true'), $sourceurl); //showinframes doesn't handle student view anyway... //return ''; $is_framed = true; } - // Uncomment to remove student view link from document view page - if (strpos($_SERVER['REQUEST_URI'],'newscorm/lp_header.php')!==false) { - if (empty($_GET['lp_id'])) { - return ''; - } - $sourceurl = substr($_SERVER['REQUEST_URI'],0,strpos($_SERVER['REQUEST_URI'],'?')); - $sourceurl = str_replace('newscorm/lp_header.php','newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview']=='studentview'?'false':'true'),$sourceurl); - //showinframes doesn't handle student view anyway... - //return ''; - $is_framed = true; - } // check if the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark) if (!$is_framed) { - if (!strstr($_SERVER['REQUEST_URI'], "?")) { - $sourceurl = api_get_self()."?".api_get_cidreq(); + if (!strstr($_SERVER['REQUEST_URI'], '?')) { + $sourceurl = api_get_self().'?'.api_get_cidreq(); } else { $sourceurl = $_SERVER['REQUEST_URI']; //$sourceurl = str_replace('&', '&', $sourceurl); } } - if(!empty($_SESSION['studentview'])) { - if ($_SESSION['studentview']=='studentview') { + if (!empty($_SESSION['studentview'])) { + if ($_SESSION['studentview'] == 'studentview') { // we have to remove the isStudentView=true from the $sourceurl $sourceurl = str_replace('&isStudentView=true', '', $sourceurl); $sourceurl = str_replace('&isStudentView=false', '', $sourceurl); - $output_string .= ''.get_lang("CourseManagerview").''; - } elseif ($_SESSION['studentview']=='teacherview') { + $output_string .= ''.get_lang('CourseManagerview').''; + } elseif ($_SESSION['studentview'] == 'teacherview') { //switching to teacherview $sourceurl = str_replace('&isStudentView=true', '', $sourceurl); $sourceurl = str_replace('&isStudentView=false', '', $sourceurl); - $output_string .= ''.get_lang("StudentView").''; + $output_string .= ''.get_lang('StudentView').''; } } else { - $output_string .= ''.get_lang("StudentView").''; + $output_string .= ''.get_lang('StudentView').''; } echo $output_string; } + /** * Displays the contents of an array in a messagebox. * @param array $info_array An array with the messages to show */ function api_display_array($info_array) { foreach ($info_array as $element) { - $message .= $element."
"; + $message .= $element.'
'; } Display :: display_normal_message($message); } + /** * Displays debug info * @param string $debug_info The message to display @@ -1514,10 +1530,11 @@ function api_display_array($info_array) { * @version 1.1, March 2004 */ function api_display_debug_info($debug_info) { - $message = "Debug info
"; + $message = 'Debug info
'; $message .= $debug_info; Display :: display_normal_message($message); } + /** * @deprecated, use api_is_allowed_to_edit() instead */ @@ -1525,6 +1542,7 @@ function is_allowed_to_edit() { return api_is_allowed_to_edit(); } +// TODO: This is for the permission section. /** * Function that removes the need to directly use is_courseAdmin global in * tool scripts. It returns true or false depending on the user's rights in @@ -1539,7 +1557,7 @@ function is_allowed_to_edit() { * @version 1.1, February 2004 * @return boolean, true: the user has the rights to edit, false: he does not */ -function api_is_allowed_to_edit($tutor=false,$coach=false) { +function api_is_allowed_to_edit($tutor = false, $coach = false) { $is_courseAdmin = api_is_course_admin() || api_is_platform_admin(); if (!$is_courseAdmin && $tutor == true) { //if we also want to check if the user is a tutor... $is_courseAdmin = $is_courseAdmin || api_is_course_tutor(); @@ -1548,12 +1566,10 @@ function api_is_allowed_to_edit($tutor=false,$coach=false) { $is_courseAdmin = $is_courseAdmin || api_is_course_coach(); } if (api_get_setting('student_view_enabled') == 'true') { //check if the student_view is enabled, and if so, if it is activated - $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != "studentview"; + $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview'; return $is_allowed; - } else { - return $is_courseAdmin; } - + return $is_courseAdmin; } /** @@ -1571,9 +1587,9 @@ function api_is_allowed($tool, $action, $task_id = 0) { return true; } //if(!$_SESSION['total_permissions'][$_course['code']] and $_course) - if (is_array($_course) and count($_course)>0) { - require_once(api_get_path(SYS_CODE_PATH) . 'permissions/permissions_functions.inc.php'); - require_once(api_get_path(LIBRARY_PATH) . "/groupmanager.lib.php"); + if (is_array($_course) and count($_course) > 0) { + require_once api_get_path(SYS_CODE_PATH).'permissions/permissions_functions.inc.php'; + require_once api_get_path(LIBRARY_PATH).'/groupmanager.lib.php'; // getting the permissions of this user if ($task_id == 0) { @@ -1623,12 +1639,10 @@ function api_is_allowed($tool, $action, $task_id = 0) { // so there is no need to requery everything. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]); if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) { - if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) { - return true; - } else { - return false; - } + return in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool]); } + + // TODO: Here the finction returns null. Is this intended behaviour? } /** @@ -1637,30 +1651,29 @@ function api_is_allowed($tool, $action, $task_id = 0) { * @param bool Whether to check in the database (true) or simply in the session (false) to see if the current user is the anonymous user * @return bool true if this user is anonymous, false otherwise */ -function api_is_anonymous($user_id=null,$db_check=false) { - if(!isset($user_id)) { +function api_is_anonymous($user_id = null, $db_check = false) { + if (!isset($user_id)) { $user_id = api_get_user_id(); } - if($db_check) { + if ($db_check) { $info = api_get_user_info($user_id); - if($info['status'] == 6) { - return true; - } - } else { - global $_user; - if (!isset($_user)) { - //in some cases, api_set_anonymous doesn't seem to be - //triggered in local.inc.php. Make sure it is. - //Occurs in agenda for admin links - YW - global $use_anonymous; - if (isset($use_anonymous) && $use_anonymous == true) { - api_set_anonymous(); - } + if ($info['status'] == 6) { return true; } - if (isset($_user['is_anonymous']) and $_user['is_anonymous'] === true) { - return true; + } + global $_user; + if (!isset($_user)) { + //in some cases, api_set_anonymous doesn't seem to be + //triggered in local.inc.php. Make sure it is. + //Occurs in agenda for admin links - YW + global $use_anonymous; + if (isset($use_anonymous) && $use_anonymous == true) { + api_set_anonymous(); } + return true; + } + if (isset($_user['is_anonymous']) and $_user['is_anonymous'] === true) { + return true; } return false; } @@ -1677,15 +1690,15 @@ function api_is_anonymous($user_id=null,$db_check=false) { * @version dokeos 1.8, August 2006 */ function api_not_allowed($print_headers = false) { + $home_url = api_get_path(WEB_PATH); $user = api_get_user_id(); $course = api_get_course_id(); - global $this_section; + global $this_section; - $origin = isset($_GET['origin'])?$_GET['origin']:''; + $origin = isset($_GET['origin']) ? $_GET['origin'] : ''; if ($origin == 'learnpath') { - echo ' '; } - if ((isset($user) && !api_is_anonymous()) - && (!isset($course) || $course==-1) - && empty($_GET['cidReq'])) - {//if the access is not authorized and there is some login information - // but the cidReq is not found, assume we are missing course data and send the user - // to the user_portal - if ((!headers_sent() or $print_headers) && $origin != 'learnpath'){Display::display_header('');} + if ((isset($user) && !api_is_anonymous()) && (!isset($course) || $course == -1) && empty($_GET['cidReq'])) { + //if the access is not authorized and there is some login information + // but the cidReq is not found, assume we are missing course data and send the user + // to the user_portal + if ((!headers_sent() or $print_headers) && $origin != 'learnpath') { Display::display_header(''); } echo '
'; - Display::display_error_message(get_lang('NotAllowedClickBack').'

'.get_lang('BackToPreviousPage').'
',false); + Display::display_error_message(get_lang('NotAllowedClickBack').'

'.get_lang('BackToPreviousPage').'
', false); echo '
'; - if ($print_headers && $origin != 'learnpath'){Display::display_footer();} + if ($print_headers && $origin != 'learnpath') { Display::display_footer(); } die(); - } elseif (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE)) { + } + if (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE)) { //only display form and return to the previous URL if there was a course ID included if (!empty($user) && !api_is_anonymous()) { - if ((!headers_sent() or $print_headers) && $origin != 'learnpath') { Display::display_header('');} + if ((!headers_sent() || $print_headers) && $origin != 'learnpath') { Display::display_header(''); } echo '
'; - Display::display_error_message(get_lang('NotAllowedClickBack').'

'.get_lang('BackToPreviousPage').'
',false); + Display::display_error_message(get_lang('NotAllowedClickBack').'

'.get_lang('BackToPreviousPage').'
', false); echo '
'; - if ($print_headers && $origin != 'learnpath') {Display::display_footer();} - die(); - } else { - include_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php'); - $form = new FormValidator('formLogin','post',api_get_self().'?'.$_SERVER['QUERY_STRING']); - $form->addElement('static',null,null,'Username'); - $form->addElement('text','login','',array('size'=>15)); - $form->addElement('static',null,null,'Password'); - $form->addElement('password','password','',array('size'=>15)); - $form->addElement('style_submit_button','submitAuth',get_lang('Enter'),'class="login"'); - $test ='

'.$form->return_form();'
'; - - if((!headers_sent() or $print_headers) && $origin != 'learnpath'){Display::display_header('');} - Display::display_error_message(''.get_lang('NotAllowed').'
'.get_lang('PleaseLoginAgainFromFormBelow').'
'.$test.'
',false); - $_SESSION['request_uri'] = $_SERVER['REQUEST_URI']; - if ($print_headers && $origin != 'learnpath') {Display::display_footer();} - die(); - } - } else { - if (!empty($user) && !api_is_anonymous()) { - if ((!headers_sent() or $print_headers) && $origin != 'learnpath') {Display::display_header('');} - echo '
'; - Display::display_error_message(get_lang('NotAllowedClickBack').'

'.get_lang('BackToPreviousPage').'
',false); - echo '
'; - if ($print_headers && $origin != 'learnpath') {Display::display_footer();} - die(); - } else { - //if no course ID was included in the requested URL, redirect to homepage - if ($print_headers && $origin != 'learnpath') {Display::display_header('');} - echo '
'; - Display::display_error_message(get_lang('NotAllowed').'

'.get_lang('PleaseLoginAgainFromHomepage').'
',false); - echo '
'; - if ($print_headers && $origin != 'learnpath') {Display::display_footer();} + if ($print_headers && $origin != 'learnpath') { Display::display_footer(); } die(); } + include_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php'; + $form = new FormValidator('formLogin', 'post', api_get_self().'?'.$_SERVER['QUERY_STRING']); + $form->addElement('static', null, null, 'Username'); + $form->addElement('text', 'login', '', array('size' => USERNAME_MAX_LENGTH)); + $form->addElement('static', null, null, 'Password'); + $form->addElement('password', 'password', '', array('size' => 15)); + $form->addElement('style_submit_button', 'submitAuth', get_lang('Enter'),'class="login"'); + $test ='

'.$form->return_form().'
'; + + if ((!headers_sent() || $print_headers) && $origin != 'learnpath') { Display::display_header(''); } + Display::display_error_message(''.get_lang('NotAllowed').'
'.get_lang('PleaseLoginAgainFromFormBelow').'
'.$test.'
', false); + $_SESSION['request_uri'] = $_SERVER['REQUEST_URI']; + if ($print_headers && $origin != 'learnpath') { Display::display_footer(); } + die(); + } + if (!empty($user) && !api_is_anonymous()) { + if ((!headers_sent() or $print_headers) && $origin != 'learnpath') { Display::display_header(''); } + echo '
'; + Display::display_error_message(get_lang('NotAllowedClickBack').'

'.get_lang('BackToPreviousPage').'
', false); + echo '
'; + if ($print_headers && $origin != 'learnpath') {Display::display_footer();} + die(); } + //if no course ID was included in the requested URL, redirect to homepage + if ($print_headers && $origin != 'learnpath') { Display::display_header(''); } + echo '
'; + Display::display_error_message(get_lang('NotAllowed').'

'.get_lang('PleaseLoginAgainFromHomepage').'
', false); + echo '
'; + if ($print_headers && $origin != 'learnpath') { Display::display_footer(); } + die(); } /* @@ -1767,9 +1776,9 @@ function api_not_allowed($print_headers = false) { * @desc convert sql date to unix timestamp */ function convert_mysql_date($last_post_datetime) { - list ($last_post_date, $last_post_time) = split(" ", $last_post_datetime); - list ($year, $month, $day) = explode("-", $last_post_date); - list ($hour, $min, $sec) = explode(":", $last_post_time); + list ($last_post_date, $last_post_time) = split(' ', $last_post_datetime); + list ($year, $month, $day) = explode('-', $last_post_date); + list ($hour, $min, $sec) = explode(':', $last_post_time); $announceDate = mktime((int)$hour, (int)$min, (int)$sec, (int)$month, (int)$day, (int)$year); return $announceDate; } @@ -1778,9 +1787,9 @@ function convert_mysql_date($last_post_datetime) { * @param int UNIX timestamp, as generated by the time() function. Will be generated if parameter not provided * @return string MySQL datetime format, like '2009-01-30 12:23:34' */ -function api_get_datetime($time=null) { - if (!isset($time)) { $time = time();} - return date('Y-m-d H:i:s', $time); +function api_get_datetime($time = null) { + if (!isset($time)) { $time = time(); } + return date('Y-m-d H:i:s', $time); } /** @@ -1790,14 +1799,14 @@ function api_get_datetime($time=null) { * @param int The item ID in the given tool * @return int -1 on error, 0 if invisible, 1 if visible */ -function api_get_item_visibility($_course,$tool,$id) { - if (!is_array($_course) or count($_course)==0 or empty($tool) or empty($id)) return -1; +function api_get_item_visibility($_course, $tool, $id) { + if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) { return -1; } $tool = Database::escape_string($tool); $id = Database::escape_string($id); - $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY,$_course['dbName']); + $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']); $sql = "SELECT * FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref = $id"; $res = api_sql_query($sql); - if($res === false or Database::num_rows($res)==0) return -1; + if ($res === false || Database::num_rows($res) ==0 ) { return -1; } $row = Database::fetch_array($res); return $row['visibility']; } @@ -1830,15 +1839,15 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us $to_user_id = Database::escape_string($to_user_id); $start_visible = Database::escape_string($start_visible); $end_visible = Database::escape_string($end_visible); - $to_filter = ""; + $to_filter = ''; $time = time(); - $time = date("Y-m-d H:i:s", $time); - $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY,$_course['dbName']); + $time = date('Y-m-d H:i:s', $time); + $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']); if ($to_user_id <= 0) { $to_user_id = NULL; //no to_user_id set } - $start_visible = ($start_visible == 0) ? "0000-00-00 00:00:00" : $start_visible; - $end_visible = ($end_visible == 0) ? "0000-00-00 00:00:00" : $end_visible; + $start_visible = ($start_visible == 0) ? '0000-00-00 00:00:00' : $start_visible; + $end_visible = ($end_visible == 0) ? '0000-00-00 00:00:00' : $end_visible; // set filters for $to_user_id and $to_group_id, with priority for $to_user_id $filter = "tool='$tool' AND ref='$item_id'"; if ($item_id == "*") { @@ -1857,21 +1866,21 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us } } // update if possible - $set_type = ""; + $set_type = ''; switch ($lastedit_type) { - case "delete" : // delete = make item only visible for the platform admin + case 'delete' : // delete = make item only visible for the platform admin $visibility = '2'; $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type WHERE $filter"; break; - case "visible" : // change item to visible + case 'visible' : // change item to visible $visibility = '1'; $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type WHERE $filter"; break; - case "invisible" : // change item to invisible + case 'invisible' : // change item to invisible $visibility = '0'; $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type @@ -1891,11 +1900,11 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us if (mysql_affected_rows() == 0) { if (!is_null($to_user_id)) { // $to_user_id has more priority than $to_group_id - $to_field = "to_user_id"; + $to_field = 'to_user_id'; $to_value = $to_user_id; } else { // $to_user_id is not set - $to_field = "to_group_id"; + $to_field = 'to_group_id'; $to_value = $to_group_id; } $sql = "INSERT INTO $TABLE_ITEMPROPERTY @@ -1903,10 +1912,10 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us VALUES ('$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value','$visibility','$start_visible','$end_visible')"; $res = mysql_query($sql); if (!$res) { - return FALSE; + return false; } } - return TRUE; + return true; } /* @@ -1914,91 +1923,93 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us Language Dropdown ============================================================================== */ + +// TODO: To be moved to Display calss. /** * Displays a combobox so the user can select his/her preferred language. * @param string The desired name= value for the select * @return string */ -function api_get_languages_combo($name="language") { - $ret = ""; +function api_get_languages_combo($name = 'language') { + + $ret = ''; $platformLanguage = api_get_setting('platformLanguage'); - /* retrieve a complete list of all the languages. */ + /* retrieve a complete list of all the languages. */ $language_list = api_get_languages(); - if (count($language_list['name']) < 2) { - return $ret; - } + if (count($language_list['name']) < 2) { + return $ret; + } /* the the current language of the user so that his/her language occurs as - * selected in the dropdown menu */ - if(isset($_SESSION['user_language_choice'])) + * selected in the dropdown menu */ + if (isset($_SESSION['user_language_choice'])) { $default = $_SESSION['user_language_choice']; - else + } else { $default = $platformLanguage; + } - $languages = $language_list['name']; + $languages = $language_list['name']; $folder = $language_list['folder']; - $ret .= ''; foreach ($languages as $key => $value) { - if ($folder[$key] == $default) - $selected = ' selected="selected"'; - else - $selected = ''; - - $ret .= sprintf(''."\n", - $folder[$key], $selected, $value); + if ($folder[$key] == $default) { + $selected = ' selected="selected"'; + } else { + $selected = ''; + } + $ret .= sprintf(''."\n", $folder[$key], $selected, $value); } $ret .= ''; - return $ret; + return $ret; } +// TODO: To be moved to Display calss. /** * Displays a form (drop down menu) so the user can select his/her preferred language. * The form works with or without javascript * @param boolean Hide form if only one language available (defaults to false = show the box anyway) * @return void Display the box directly */ -function api_display_language_form($hide_if_no_choice=false) { +function api_display_language_form($hide_if_no_choice = false) { $platformLanguage = api_get_setting('platformLanguage'); - $dirname = api_get_path(SYS_PATH)."main/lang/"; // this line is probably no longer needed + $dirname = api_get_path(SYS_PATH).'main/lang/'; // TODO: this line is probably no longer needed // retrieve a complete list of all the languages. $language_list = api_get_languages(); - if (count($language_list['name'])<=1 && $hide_if_no_choice == true) { - return; //don't show any form - } + if (count($language_list['name']) <= 1 && $hide_if_no_choice) { + return; //don't show any form + } // the the current language of the user so that his/her language occurs as selected in the dropdown menu - if(isset($_SESSION['user_language_choice'])) - { + if (isset($_SESSION['user_language_choice'])) { $user_selected_language = $_SESSION['user_language_choice']; } - if (!isset ($user_selected_language)) + if (!isset($user_selected_language)) { $user_selected_language = $platformLanguage; + } $original_languages = $language_list['name']; $folder = $language_list['folder']; // this line is probably no longer needed ?> - - ", ""; + foreach ($original_languages as $key => $value) { + if ($folder[$key] == $user_selected_language) { $option_end = " selected=\"selected\" >"; - else + } else { $option_end = ">"; + } echo "