dokeos-library
[ class tree: dokeos-library ] [ index: dokeos-library ] [ all elements ]

Source for file main_api.lib.php

Documentation is available at main_api.lib.php

  1. <?php
  2. /*
  3. ===============================================================================
  4.     Dokeos - elearning and course management software
  5.  
  6.     Copyright (c) 2004-2008 Dokeos S.A.
  7.     Copyright (c) 2003 Ghent University (UGent)
  8.     Copyright (c) 2001 Universite catholique de Louvain (UCL)
  9.     Copyright (c) Hugues Peeters
  10.     Copyright (c) Christophe Gesche
  11.     Copyright (c) Roan Embrechts (Vrije Universiteit Brussel)
  12.     Copyright (c) Patrick Cool
  13.     Copyright (c) Olivier Brouckaert
  14.     Copyright (c) Toon Van Hoecke
  15.     Copyright (c) Denes Nagy
  16.  
  17.     For a full list of contributors, see "credits.txt".
  18.     The full license can be read in "license.txt".
  19.  
  20.     This program is free software; you can redistribute it and/or
  21.     modify it under the terms of the GNU General Public License
  22.     as published by the Free Software Foundation; either version 2
  23.     of the License, or (at your option) any later version.
  24.  
  25.     See the GNU General Public License for more details.
  26.  
  27.     Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium    
  28.     Mail: info@dokeos.com
  29. ===============================================================================
  30. */
  31. /**
  32. ==============================================================================
  33. *    This is a code library for Dokeos.
  34. *    It is included by default in every Dokeos file
  35. *    (through including the global.inc.php)
  36. *
  37. *    @package dokeos.library
  38. ==============================================================================
  39. */
  40. /*
  41. ==============================================================================
  42.         CONSTANTS
  43. ==============================================================================
  44. */
  45.  
  46. //USER STATUS CONSTANTS
  47. /** global status of a user: student */
  48. define('STUDENT'5);
  49. /** global status of a user: course manager */
  50. define('COURSEMANAGER'1);
  51. /** global status of a user: session admin */
  52. define('SESSIONADMIN'3);
  53. /** global status of a user: human ressource manager */
  54. define('DRH'4);
  55. /** global status of a user: human ressource manager */
  56. define('ANONYMOUS'6);
  57.  
  58. // table of status
  59. $_status_list[STUDENT'user';
  60. $_status_list[COURSEMANAGER'teacher';
  61. $_status_list[SESSIONADMIN'session_admin';
  62. $_status_list[DRH'drh';
  63. $_status_list[ANONYMOUS'anonymous';
  64.  
  65.  
  66. //COURSE VISIBILITY CONSTANTS
  67. /** only visible for course admin */
  68. define('COURSE_VISIBILITY_CLOSED'0);
  69. /** only visible for users registered in the course*/
  70. define('COURSE_VISIBILITY_REGISTERED'1);
  71. /** open for all registered users on the platform */
  72. define('COURSE_VISIBILITY_OPEN_PLATFORM'2);
  73. /** open for the whole world */
  74. define('COURSE_VISIBILITY_OPEN_WORLD'3);
  75.  
  76. define('SUBSCRIBE_ALLOWED'1);
  77. define('SUBSCRIBE_NOT_ALLOWED'0);
  78. define('UNSUBSCRIBE_ALLOWED'1);
  79. define('UNSUBSCRIBE_NOT_ALLOWED'0);
  80.  
  81. //CONSTANTS FOR api_get_path FUNCTION
  82. define('WEB_PATH''WEB_PATH');
  83. define('SYS_PATH''SYS_PATH');
  84. define('REL_PATH''REL_PATH');
  85. define('WEB_COURSE_PATH''WEB_COURSE_PATH');
  86. define('SYS_COURSE_PATH''SYS_COURSE_PATH');
  87. define('REL_COURSE_PATH''REL_COURSE_PATH');
  88. define('REL_CODE_PATH''REL_CODE_PATH');
  89. define('WEB_CODE_PATH''WEB_CODE_PATH');
  90. define('SYS_CODE_PATH''SYS_CODE_PATH');
  91. define('SYS_LANG_PATH''SYS_LANG_PATH');
  92. define('WEB_IMG_PATH''WEB_IMG_PATH');
  93. define('WEB_CSS_PATH''WEB_CSS_PATH');
  94. define('GARBAGE_PATH''GARBAGE_PATH');
  95. define('SYS_PLUGIN_PATH''SYS_PLUGIN_PATH');
  96. define('PLUGIN_PATH''PLUGIN_PATH');
  97. define('WEB_PLUGIN_PATH''WEB_PLUGIN_PATH');
  98. define('SYS_ARCHIVE_PATH''SYS_ARCHIVE_PATH');
  99. define('INCLUDE_PATH''INCLUDE_PATH');
  100. define('LIBRARY_PATH''LIBRARY_PATH');
  101. define('CONFIGURATION_PATH''CONFIGURATION_PATH');
  102. define('WEB_LIBRARY_PATH','WEB_LIBRARY_PATH');
  103.  
  104. //CONSTANTS defining all tools, using the english version
  105. define('TOOL_DOCUMENT''document');
  106. define('TOOL_HOTPOTATOES''hotpotatoes');
  107. define('TOOL_CALENDAR_EVENT''calendar_event');
  108. define('TOOL_LINK''link');
  109. define('TOOL_COURSE_DESCRIPTION''course_description');
  110. define('TOOL_LEARNPATH''learnpath');
  111. define('TOOL_ANNOUNCEMENT''announcement');
  112. define('TOOL_FORUM''forum');
  113. define('TOOL_THREAD''thread');
  114. define('TOOL_POST''post');
  115. define('TOOL_DROPBOX''dropbox');
  116. define('TOOL_QUIZ''quiz');
  117. define('TOOL_USER''user');
  118. define('TOOL_GROUP''group');
  119. define('TOOL_BLOGS''blog_management')// Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be)
  120. define('TOOL_CHAT''chat');
  121. define('TOOL_CONFERENCE''conference');
  122. define('TOOL_STUDENTPUBLICATION''student_publication');
  123. define('TOOL_TRACKING''tracking');
  124. define('TOOL_HOMEPAGE_LINK''homepage_link');
  125. define('TOOL_COURSE_SETTING''course_setting');
  126. define('TOOL_BACKUP''backup');
  127. define('TOOL_COPY_COURSE_CONTENT''copy_course_content');
  128. define('TOOL_RECYCLE_COURSE''recycle_course');
  129. define('TOOL_COURSE_HOMEPAGE''course_homepage');
  130. define('TOOL_COURSE_RIGHTS_OVERVIEW''course_rights');
  131. define('TOOL_UPLOAD','file_upload');
  132. define('TOOL_COURSE_MAINTENANCE','course_maintenance');
  133. define('TOOL_VISIO','visio');
  134. define('TOOL_VISIO_CONFERENCE','visio_conference');
  135. define('TOOL_VISIO_CLASSROOM','visio_classroom');
  136. define('TOOL_SURVEY','survey');
  137.  
  138. // CONSTANTS defining dokeos sections
  139. define('SECTION_CAMPUS''mycampus');
  140. define('SECTION_COURSES''mycourses');
  141. define('SECTION_MYPROFILE''myprofile');
  142. define('SECTION_MYAGENDA''myagenda');
  143. define('SECTION_COURSE_ADMIN''course_admin');
  144. define('SECTION_PLATFORM_ADMIN''platform_admin');
  145. define('SECTION_MYGRADEBOOK''mygradebook');
  146.  
  147. // CONSTANT name for local authentication source
  148. define('PLATFORM_AUTH_SOURCE''platform');
  149.  
  150. //CONSTANT defining the default HotPotatoes files directory
  151. define('DIR_HOTPOTATOES','/HotPotatoes_files');
  152.  
  153. /*
  154. ==============================================================================
  155.         PROTECTION FUNCTIONS
  156.         use these to protect your scripts
  157. ==============================================================================
  158. */
  159. /**
  160. * Function used to protect a course script.
  161. * The function blocks access when
  162. * - there is no $_SESSION["_course"] defined; or
  163. * - $is_allowed_in_course is set to false (this depends on the course
  164. * visibility and user status).
  165. *
  166. * This is only the first proposal, test and improve!
  167. @param    boolean    Option to print headers when displaying error message. Default: false
  168. @todo replace global variable
  169. @author Roan Embrechts
  170. */
  171. function api_protect_course_script($print_headers=false)
  172. {    
  173.      global $is_allowed_in_course;               
  174.     //if (!isset ($_SESSION["_course"]) || !$is_allowed_in_course)    
  175.     if (!$is_allowed_in_course)
  176.     {            
  177.         api_not_allowed($print_headers);
  178.     }
  179. }
  180.  
  181.  
  182.  
  183.  
  184. /**
  185. * Function used to protect an admin script.
  186. * The function blocks access when the user has no platform admin rights.
  187. * This is only the first proposal, test and improve!
  188. *
  189. @author Roan Embrechts
  190. */
  191. function api_protect_admin_script($allow_sessions_admins=false)
  192. {
  193.     if (!api_is_platform_admin($allow_sessions_admins))
  194.     {
  195.         include (api_get_path(INCLUDE_PATH)."header.inc.php");
  196.         api_not_allowed();
  197.     }
  198. }
  199.  
  200. /**
  201. * Function used to prevent anonymous users from accessing a script.
  202. *
  203. @author Roan Embrechts
  204. */
  205. {
  206.     global $_user;
  207.  
  208.     if (!(isset ($_user['user_id']&& $_user['user_id']|| api_is_anonymous($_user['user_id'],true))
  209.     {
  210.         include (api_get_path(INCLUDE_PATH)."header.inc.php");
  211.         api_not_allowed();
  212.     }
  213. }
  214.  
  215. /*
  216. ==============================================================================
  217.         ACCESSOR FUNCTIONS
  218.         don't access kernel variables directly,
  219.         use these functions instead
  220. ==============================================================================
  221. */
  222. /**
  223. *    @return an array with the navigator name and version
  224. */
  225. function api_get_navigator()
  226. {
  227.     $navigator 'Unknown';
  228.     $version 0;
  229.     if (strstr($_SERVER['HTTP_USER_AGENT']'Opera'))
  230.     {
  231.         $navigator 'Opera';
  232.         list ($versionexplode('Opera'$_SERVER['HTTP_USER_AGENT']);
  233.     }
  234.     elseif (strstr($_SERVER['HTTP_USER_AGENT']'MSIE'))
  235.     {
  236.         $navigator 'Internet Explorer';
  237.         list ($versionexplode('MSIE'$_SERVER['HTTP_USER_AGENT']);
  238.     }
  239.     elseif (strstr($_SERVER['HTTP_USER_AGENT']'Gecko'))
  240.     {
  241.         $navigator 'Mozilla';
  242.         list ($versionexplode('; rv:'$_SERVER['HTTP_USER_AGENT']);
  243.     }
  244.     elseif (strstr($_SERVER['HTTP_USER_AGENT']'Netscape'))
  245.     {
  246.         $navigator 'Netscape';
  247.         list ($versionexplode('Netscape'$_SERVER['HTTP_USER_AGENT']);
  248.     }
  249.     $version doubleval($version);
  250.     if (!strstr($version'.'))
  251.     {
  252.         $version number_format(doubleval($version)1);
  253.     }
  254.     return array ('name' => $navigator'version' => $version);
  255. }
  256. /**
  257. *    @return True if user selfregistration is allowed, false otherwise.
  258. */
  259. {
  260.     if(isset($GLOBALS['allowSelfReg']))
  261.     {
  262.         return $GLOBALS["allowSelfReg"];
  263.     }
  264.     else
  265.     {
  266.         return false;
  267.     }
  268. }
  269. /**
  270. *    Returns a full path to a certain Dokeos area, which you specify
  271. *    through a parameter.
  272. *
  273. *    See $_configuration['course_folder'] in the configuration.php
  274. *    to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  275. *
  276. *    @param one of the following constants:
  277. *     WEB_PATH, SYS_PATH, REL_PATH, WEB_COURSE_PATH, SYS_COURSE_PATH,
  278. *     REL_COURSE_PATH, REL_CODE_PATH, WEB_CODE_PATH, SYS_CODE_PATH,
  279. *     SYS_LANG_PATH, WEB_IMG_PATH, GARBAGE_PATH, PLUGIN_PATH, SYS_ARCHIVE_PATH,
  280. *     INCLUDE_PATH, LIBRARY_PATH, CONFIGURATION_PATH
  281. *
  282. *     @example assume that your server root is /var/www/ dokeos is installed in a subfolder dokeos/ and the URL of your campus is http://www.mydokeos.com
  283. *      The other configuration paramaters have not been changed.
  284. *      The different api_get_paths will give
  285. *      WEB_PATH            http://www.mydokeos.com
  286. *      SYS_PATH            /var/www/
  287. *      REL_PATH            dokeos/
  288. *      WEB_COURSE_PATH        http://www.mydokeos.com/courses/
  289. *      SYS_COURSE_PATH        /var/www/dokeos/courses/
  290. *     REL_COURSE_PATH
  291. *      REL_CODE_PATH
  292. *      WEB_CODE_PATH
  293. *      SYS_CODE_PATH
  294. *      SYS_LANG_PATH
  295. *      WEB_IMG_PATH
  296. *      GARBAGE_PATH
  297. *      PLUGIN_PATH
  298. *      SYS_ARCHIVE_PATH
  299. *     INCLUDE_PATH
  300. *      LIBRARY_PATH
  301. *      CONFIGURATION_PATH
  302. */
  303. function api_get_path($path_type)
  304. {
  305.     global $_configuration;
  306.  
  307.     switch ($path_type)
  308.     {
  309.         case WEB_PATH :
  310.             // example: http://www.mydokeos.com/ or http://www.mydokeos.com/portal/ if you're using
  311.             // a subdirectory of your document root for Dokeos
  312.             if(substr($_configuration['root_web'],-1== '/')
  313.             {
  314.                 return $_configuration['root_web'];
  315.             }
  316.             else
  317.             {
  318.                 return $_configuration['root_web'].'/';
  319.             }
  320.             break;
  321.  
  322.         case SYS_PATH :
  323.             // example: /var/www/
  324.             if(substr($_configuration['root_sys'],-1== '/')
  325.             {
  326.                 return $_configuration['root_sys'];
  327.             }
  328.             else
  329.             {
  330.                 return $_configuration['root_sys'].'/';                
  331.             }
  332.             break;
  333.  
  334.         case REL_PATH :
  335.             // example: dokeos/
  336.             if (substr($_configuration['url_append']-1=== '/')
  337.             {
  338.                 return $_configuration['url_append'];
  339.             }
  340.             else
  341.             {
  342.                 return $_configuration['url_append'].'/';
  343.             }
  344.             break;
  345.  
  346.         case WEB_COURSE_PATH :
  347.             // example: http://www.mydokeos.com/courses/
  348.             return $_configuration['root_web'].$_configuration['course_folder'];
  349.             break;
  350.  
  351.         case SYS_COURSE_PATH :
  352.             // example: /var/www/dokeos/courses/
  353.             return $_configuration['root_sys'].$_configuration['course_folder'];
  354.             break;
  355.  
  356.         case REL_COURSE_PATH :
  357.             // example: courses/ or dokeos/courses/
  358.             return api_get_path(REL_PATH).$_configuration['course_folder'];
  359.             break;
  360.         case REL_CODE_PATH :
  361.             // example: main/ or dokeos/main/
  362.             return api_get_path(REL_PATH).$_configuration['code_append'];
  363.             break;
  364.         case WEB_CODE_PATH :
  365.             // example: http://www.mydokeos.com/main/
  366.             return $GLOBALS['clarolineRepositoryWeb'];
  367.             break;
  368.         case SYS_CODE_PATH :
  369.             // example: /var/www/dokeos/main/
  370.             return $GLOBALS['clarolineRepositorySys'];
  371.             break;
  372.         case SYS_LANG_PATH :
  373.             // example: /var/www/dokeos/main/lang/
  374.             return api_get_path(SYS_CODE_PATH).'lang/';
  375.             break;
  376.         case WEB_IMG_PATH :
  377.             // example: http://www.mydokeos.com/main/img/
  378.             return api_get_path(WEB_CODE_PATH).'img/';
  379.             break;
  380.         case GARBAGE_PATH :
  381.             // example: /var/www/dokeos/main/garbage/
  382.             return $GLOBALS['garbageRepositorySys'];
  383.             break;
  384.         case SYS_PLUGIN_PATH :
  385.             // example: /var/www/dokeos/plugin/
  386.             return api_get_path(SYS_PATH).'plugin/';
  387.             break;
  388.         case WEB_PLUGIN_PATH :
  389.             // example: http://www.mydokeos.com/plugin/
  390.             return api_get_path(WEB_PATH).'plugin/';
  391.             break;
  392.         case SYS_ARCHIVE_PATH :
  393.             // example: /var/www/dokeos/archive/
  394.             return api_get_path(SYS_PATH).'archive/';
  395.             break;
  396.         case INCLUDE_PATH :
  397.             // Generated by main/inc/global.inc.php 
  398.             // example: /var/www/dokeos/main/inc/
  399.             return str_replace('\\''/'$GLOBALS['includePath']).'/';
  400.             break;
  401.         case LIBRARY_PATH :
  402.             // example: /var/www/dokeos/main/inc/lib/
  403.             return api_get_path(INCLUDE_PATH).'lib/';
  404.             break;
  405.         case WEB_LIBRARY_PATH :
  406.             // example: http://www.mydokeos.com/main/inc/lib/
  407.             return api_get_path(WEB_CODE_PATH).'inc/lib/';
  408.             break;
  409.         case CONFIGURATION_PATH :
  410.             // example: /var/www/dokeos/main/inc/conf/
  411.             return api_get_path(INCLUDE_PATH).'conf/';
  412.             break;
  413.         default :
  414.             return;
  415.             break;
  416.     }
  417. }
  418.  
  419. /**
  420. * This function returns the id of the user which is stored in the $_user array.
  421. *
  422. @example The function can be used to check if a user is logged in
  423. *              if (api_get_user_id())
  424. @return integer the id of the current user
  425. */
  426. function api_get_user_id()
  427. {
  428.     if(empty($GLOBALS['_user']['user_id']))
  429.     {
  430.         return 0;
  431.     }
  432.     return $GLOBALS['_user']['user_id'];
  433. }
  434. /**
  435.  * @param $user_id (integer): the id of the user
  436.  * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  437.  * @author Patrick Cool <patrick.cool@UGent.be>
  438.  * @version 21 September 2004
  439.  * @desc find all the information about a user. If no paramater is passed you find all the information about the current user.
  440. */
  441. function api_get_user_info($user_id '')
  442. {
  443.     global $tbl_user;
  444.     if ($user_id == '')
  445.     {
  446.         return $GLOBALS["_user"];
  447.     }
  448.     else
  449.     {
  450.         $sql "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id='".mysql_real_escape_string($user_id)."'";
  451.         $result api_sql_query($sql__FILE____LINE__);
  452.         if(mysql_num_rows($result0)
  453.         {
  454.             $result_array mysql_fetch_array($result);
  455.             // this is done so that it returns the same array-index-names
  456.             // ideally the names of the fields of the user table are renamed so that they match $_user (or vice versa)
  457.             // $_user should also contain every field of the user table (except password maybe). This would make the
  458.             // following lines obsolete (and the code cleaner and slimmer !!!
  459.             $user_info['firstName'$result_array['firstname'];
  460.             $user_info['lastName'$result_array['lastname'];
  461.             $user_info['mail'$result_array['email'];
  462.             $user_info['picture_uri'$result_array['picture_uri'];
  463.             $user_info['user_id'$result_array['user_id'];
  464.             $user_info['official_code'$result_array['official_code'];
  465.             $user_info['status'$result_array['status'];
  466.             $user_info['auth_source'$result_array['auth_source'];
  467.             $user_info['username'$result_array['username'];
  468.             $user_info['theme'$result_array['theme'];
  469.             return $user_info;
  470.         }
  471.         return false;
  472.     }
  473. }
  474. /**
  475.  * Returns the current course id (integer)
  476. */
  477. function api_get_course_id()
  478. {
  479.     return $GLOBALS["_cid"];
  480. }
  481. /**
  482.  * Returns the current course directory
  483.  *
  484.  * This function relies on api_get_course_info()
  485.  * @param    string    The course code - optional (takes it from session if not given)
  486.  * @return    string    The directory where the course is located inside the Dokeos "courses" directory
  487.  * @author    Yannick Warnier <yannick.warnier@dokeos.com>
  488. */
  489. function api_get_course_path($course_code=null)
  490. {
  491.     if(!empty($course_code))
  492.     {
  493.         $info api_get_course_info($course_code);
  494.     }
  495.     else
  496.     {
  497.         $info api_get_course_info();
  498.     }
  499.     return $info['path'];
  500. }
  501. /**
  502.  * Gets a course setting from the current course_setting table. Try always using integer values.
  503.  * @param    string    The name of the setting we want from the table
  504.  * @return    mixed    The value of that setting in that table. Return -1 if not found.
  505.  */
  506. function api_get_course_setting($setting_name)
  507. {
  508.     $setting_name mysql_real_escape_string($setting_name);
  509.     $sql "SELECT * FROM $table WHERE variable = '$setting_name'";
  510.     $res api_sql_query($sql,__FILE__,__LINE__);
  511.     if(Database::num_rows($res)>0){
  512.         $row Database::fetch_array($res);
  513.         return $row['value'];
  514.     }
  515.     return -1;
  516. }
  517. /**
  518.  * Gets an anonymous user ID
  519.  * 
  520.  * For some tools that need tracking, like the learnpath tool, it is necessary
  521.  * to have a usable user-id to enable some kind of tracking, even if not
  522.  * perfect. An anonymous ID is taken from the users table by looking for a
  523.  * status of "6" (anonymous).
  524.  * @return    int    User ID of the anonymous user, or O if no anonymous user found
  525.  */
  526. {
  527.     $sql "SELECT user_id FROM $table WHERE status = 6";
  528.     $res api_sql_query($sql,__FILE__,__LINE__);
  529.     if(Database::num_rows($res)>0)
  530.     {
  531.         $row Database::fetch_array($res);
  532.         //error_log('api_get_anonymous_id() returns '.$row['user_id'],0);
  533.         return $row['user_id'];
  534.     }
  535.     else //no anonymous user was found
  536.     {
  537.         return 0;
  538.     }
  539. }
  540.  
  541. /**
  542.  * Returns the cidreq parameter name + current course id
  543. */
  544. function api_get_cidreq()
  545. {
  546.     if (!empty ($GLOBALS["_cid"]))
  547.     {
  548.         return 'cidReq='.htmlspecialchars($GLOBALS["_cid"]);
  549.     }
  550.     return '';
  551. }
  552. /**
  553. *    Returns the current course info array.
  554. *    Note: this array is only defined if the user is inside a course.
  555. *    Array elements:
  556. *    ['name']
  557. *    ['official_code']
  558. *    ['sysCode']
  559. *    ['path']
  560. *    ['dbName']
  561. *    ['dbNameGlu']
  562. *    ['titular']
  563. *    ['language']
  564. *    ['extLink']['url' ]
  565. *    ['extLink']['name']
  566. *    ['categoryCode']
  567. *    ['categoryName']
  568. *    Now if the course_code is given, the returned array gives info about that
  569. *   particular course, not specially the current one.
  570. @todo    same behaviour as api_get_user_info so that api_get_course_id becomes absolete too
  571. */
  572. function api_get_course_info($course_code=null)
  573. {
  574.     if(!empty($course_code))
  575.     {
  576.         $course_code Database::escape_string($course_code);
  577.         $course_table Database::get_main_table(TABLE_MAIN_COURSE);
  578.         $course_cat_table Database::get_main_table(TABLE_MAIN_CATEGORY);
  579.         $sql =    "SELECT `course`.*, `course_category`.`code` `faCode`, `course_category`.`name` `faName`
  580.                  FROM $course_table
  581.                  LEFT JOIN $course_cat_table
  582.                  ON `course`.`category_code` =  `course_category`.`code`
  583.                  WHERE `course`.`code` = '$course_code'";
  584.         $result api_sql_query($sql,__FILE__,__LINE__);
  585.         $_course array();
  586.         if (Database::num_rows($result)>0)
  587.         {
  588.             global $_configuration;
  589.             $cData Database::fetch_array($result);
  590.             $_course['id'          ]         $cData['code'             ]//auto-assigned integer
  591.             $_course['name'        ]         $cData['title'         ];
  592.             $_course['official_code']         $cData['visual_code'        ]// use in echo
  593.             $_course['sysCode'     ]         $cData['code'             ]// use as key in db
  594.             $_course['path'        ]         $cData['directory'        ]// use as key in path
  595.             $_course['dbName'      ]         $cData['db_name'           ]// use as key in db list
  596.             $_course['dbNameGlu'   ]         $_configuration['table_prefix'$cData['db_name'$_configuration['db_glue']// use in all queries
  597.             $_course['titular'     ]         $cData['tutor_name'       ];
  598.             $_course['language'    ]         $cData['course_language'   ];
  599.             $_course['extLink'     ]['url' $cData['department_url'    ];
  600.             $_course['extLink'     ]['name'$cData['department_name'];
  601.             $_course['categoryCode']         $cData['faCode'           ];
  602.             $_course['categoryName']         $cData['faName'           ];
  603.  
  604.             $_course['visibility'  ]         $cData['visibility'];
  605.             $_course['subscribe_allowed']    $cData['subscribe'];
  606.             $_course['unubscribe_allowed']   $cData['unsubscribe'];
  607.         }
  608.         return $_course;            
  609.     }
  610.     else
  611.     {
  612.         global $_course;
  613.         return $_course;
  614.     }
  615. }
  616.  
  617. /*
  618. ==============================================================================
  619.         DATABASE QUERY MANAGEMENT
  620. ==============================================================================
  621. */
  622. /**
  623.  * Executes an SQL query
  624.  * You have to use addslashes() on each value that you want to record into the database
  625.  *
  626.  * @author Olivier Brouckaert
  627.  * @param  string $query - SQL query
  628.  * @param  string $file - optional, the file path and name of the error (__FILE__)
  629.  * @param  string $line - optional, the line of the error (__LINE__)
  630.  * @return resource - the return value of the query
  631.  */
  632. function api_sql_query($query$file ''$line 0)
  633. {
  634.     $result @mysql_query($query);
  635.  
  636.     if ($line && !$result)
  637.     {
  638.             $info '<pre>';
  639.             $info .= '<b>MYSQL ERROR :</b><br/> ';
  640.             $info .= mysql_error();
  641.             $info .= '<br/>';
  642.             $info .= '<b>QUERY       :</b><br/> ';
  643.             $info .= $query;
  644.             $info .= '<br/>';
  645.             $info .= '<b>FILE        :</b><br/> ';
  646.             $info .= ($file == '' ' unknown ' $file);
  647.             $info .= '<br/>';
  648.             $info .= '<b>LINE        :</b><br/> ';
  649.             $info .= ($line == ' unknown ' $line);
  650.             $info .= '</pre>';
  651.             //@ mysql_close();
  652.             //die($info);
  653.             echo $info;
  654.     }
  655.     return $result;
  656. }
  657. /**
  658.  * Store the result of a query into an array
  659.  *
  660.  * @author Olivier Brouckaert
  661.  * @param  resource $result - the return value of the query
  662.  * @return array - the value returned by the query
  663.  */
  664. function api_store_result($result)
  665. {
  666.     $tab array ();
  667.     while ($row mysql_fetch_array($result))
  668.     {
  669.         $tab[$row;
  670.     }
  671.     return $tab;
  672. }
  673.  
  674. /*
  675. ==============================================================================
  676.         SESSION MANAGEMENT
  677. ==============================================================================
  678. */
  679. /**
  680.  * Start the Dokeos session.
  681.  * 
  682.  * The default lifetime for session is set here. It is not possible to have it
  683.  * as a database setting as it is used before the database connection has been made.
  684.  * It is taken from the configuration file, and if it doesn't exist there, it is set
  685.  * to 360000 seconds
  686.  *
  687.  * @author Olivier Brouckaert
  688.  * @param  string variable - the variable name to save into the session
  689.  */
  690. function api_session_start($already_installed true)
  691. {
  692.     global $storeSessionInDb;
  693.     global $_configuration;
  694.     
  695.     /* causes too many problems and is not configurable dynamically
  696.      * 
  697.     if($already_installed){
  698.         $session_lifetime = 360000;
  699.         if(isset($_configuration['session_lifetime']))
  700.         {
  701.             $session_lifetime = $_configuration['session_lifetime'];    
  702.         }
  703.         session_set_cookie_params($session_lifetime,api_get_path(REL_PATH));
  704.         
  705.     }*/
  706.     if (is_null($storeSessionInDb))
  707.     {
  708.         $storeSessionInDb false;
  709.     }
  710.     if ($storeSessionInDb && function_exists('session_set_save_handler'))
  711.     {
  712.         include_once (api_get_path(LIBRARY_PATH).'session_handler.class.php');
  713.         $session_handler new session_handler();
  714.         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'));
  715.     }
  716.     session_name('dk_sid');
  717.     session_start();
  718.     if ($already_installed)
  719.     {
  720.         if (empty ($_SESSION['checkDokeosURL']))
  721.         {
  722.             $_SESSION['checkDokeosURL'api_get_path(WEB_PATH);
  723.         }
  724.         elseif ($_SESSION['checkDokeosURL'!= api_get_path(WEB_PATH))
  725.         {
  726.             api_session_clear();
  727.         }
  728.     }
  729. }
  730. /**
  731.  * save a variable into the session
  732.  *
  733.  * BUG: function works only with global variables
  734.  *
  735.  * @author Olivier Brouckaert
  736.  * @param  string variable - the variable name to save into the session
  737.  */
  738. function api_session_register($variable)
  739. {
  740.     global $$variable;
  741.     session_register($variable);
  742.     $_SESSION[$variable= $$variable;
  743. }
  744. /**
  745.  * Remove a variable from the session.
  746.  *
  747.  * @author Olivier Brouckaert
  748.  * @param  string variable - the variable name to remove from the session
  749.  */
  750. function api_session_unregister($variable)
  751. {
  752.     if(isset($GLOBALS[$variable]))
  753.     {
  754.         unset ($GLOBALS[$variable]);
  755.     }
  756.     
  757.     if(isset($_SESSION[$variable]))
  758.     {
  759.         $_SESSION[$variablenull;
  760.         session_unregister($variable);        
  761.     }    
  762. }
  763. /**
  764.  * Clear the session
  765.  *
  766.  * @author Olivier Brouckaert
  767.  */
  768. function api_session_clear()
  769. {
  770.     session_unset();
  771.     $_SESSION array ();
  772. }
  773. /**
  774.  * Destroy the session
  775.  *
  776.  * @author Olivier Brouckaert
  777.  */
  778. {
  779.     session_unset();
  780.     $_SESSION array ();
  781.     session_destroy();
  782. }
  783.  
  784. /*
  785. ==============================================================================
  786.         STRING MANAGEMENT
  787. ==============================================================================
  788. */
  789. function api_add_url_param($url$param)
  790. {
  791.     if (empty ($param))
  792.     {
  793.         return $url;
  794.     }
  795.     if (strstr($url'?'))
  796.     {
  797.         if ($param[0!= '&')
  798.         {
  799.             $param '&'.$param;
  800.         }
  801.         list ($query_stringexplode('?'$url);
  802.         $param_list1 explode('&'$param);
  803.         $param_list2 explode('&'$query_string);
  804.         $param_list1_keys $param_list1_vals array ();
  805.         foreach ($param_list1 as $key => $enreg)
  806.         {
  807.             list ($param_list1_keys[$key]$param_list1_vals[$key]explode('='$enreg);
  808.         }
  809.         $param_list1 array ('keys' => $param_list1_keys'vals' => $param_list1_vals);
  810.         foreach ($param_list2 as $enreg)
  811.         {
  812.             $enreg explode('='$enreg);
  813.             $key array_search($enreg[0]$param_list1['keys']);
  814.             if (!is_null($key&& !is_bool($key))
  815.             {
  816.                 $url str_replace($enreg[0].'='.$enreg[1]$enreg[0].'='.$param_list1['vals'][$key]$url);
  817.                 $param str_replace('&'.$enreg[0].'='.$param_list1['vals'][$key]''$param);
  818.             }
  819.         }
  820.         $url .= $param;
  821.     }
  822.     else
  823.     {
  824.         $url $url.'?'.$param;
  825.     }
  826.     return $url;
  827. }
  828. /**
  829. * Returns a difficult to guess password.
  830. @param int $length, the length of the password
  831. @return string the generated password
  832. */
  833. function api_generate_password($length 8)
  834. {
  835.     $characters 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  836.     if ($length 2)
  837.     {
  838.         $length 2;
  839.     }
  840.     $password '';
  841.     for ($i 0$i $length$i ++)
  842.     {
  843.         $password .= $characters[rand(strlen($characters)];
  844.     }
  845.     return $password;
  846. }
  847. /**
  848. * Checks a password to see wether it is OK to use.
  849. @param string $password 
  850. @return true if the password is acceptable, false otherwise
  851. */
  852. function api_check_password($password)
  853. {
  854.     $lengthPass strlen($password);
  855.     if ($lengthPass 5)
  856.     {
  857.         return false;
  858.     }
  859.     $passLower strtolower($password);
  860.     $cptLettres $cptChiffres 0;
  861.     $consecutif 0;
  862.     $codeCharPrev 0;
  863.     for ($i 0$i $lengthPass$i ++)
  864.     {
  865.         $codeCharCur ord($passLower[$i]);
  866.         if ($i && abs($codeCharCur $codeCharPrev<= 1)
  867.         {
  868.             $consecutif ++;
  869.             if ($consecutif == 3)
  870.             {
  871.                 return false;
  872.             }
  873.         }
  874.         else
  875.         {
  876.             $consecutif 1;
  877.         }
  878.         if ($codeCharCur >= 97 && $codeCharCur <= 122)
  879.         {
  880.             $cptLettres ++;
  881.         }
  882.         elseif ($codeCharCur >= 48 && $codeCharCur <= 57)
  883.         {
  884.             $cptChiffres ++;
  885.         }
  886.         else
  887.         {
  888.             return false;
  889.         }
  890.         $codeCharPrev $codeCharCur;
  891.     }
  892.     return ($cptLettres >= && $cptChiffres >= 2true false;
  893. }
  894. /**
  895.  * Clear the user ID from the session if it was the anonymous user. Generally
  896.  * used on out-of-tools pages to remove a user ID that could otherwise be used
  897.  * in the wrong context.
  898.  * This function is to be used in conjunction with the api_set_anonymous()
  899.  * function to simulate the user existence in case of an anonymous visit.
  900.  * @param    bool    database check switch - passed to api_is_anonymous()
  901.  * @return    bool    true if succesfully unregistered, false if not anonymous.
  902.  */
  903. function api_clear_anonymous($db_check=false)
  904. {
  905.     global $_user;
  906.     if(api_is_anonymous($_user['user_id'],$db_check))
  907.     {
  908.         unset($_user['user_id']);
  909.         api_session_unregister('_uid');
  910.         return true;
  911.     }
  912.     else
  913.     {
  914.         return false;
  915.     }
  916. }
  917.  
  918. /**
  919.  * truncates a string
  920.  *
  921.  * @author Brouckaert Olivier
  922.  * @param  string text - text to truncate
  923.  * @param  integer length - length of the truncated text
  924.  * @param  string endStr - suffix
  925.  * @param  boolean middle - if true, truncates on string middle
  926.  */
  927. function api_trunc_str($text$length 30$endStr '...'$middle false)
  928. {
  929.     if (strlen($text<= $length)
  930.     {
  931.         return $text;
  932.     }
  933.     if ($middle)
  934.     {
  935.         $text rtrim(substr($text0round($length 2))).$endStr.ltrim(substr($text-round($length 2)));
  936.     }
  937.     else
  938.     {
  939.         $text rtrim(substr($text0$length)).$endStr;
  940.     }
  941.     return $text;
  942. }
  943. // deprecated, use api_trunc_str() instead
  944. function shorten($input$length 15)
  945. {
  946.     $length intval($length);
  947.     if (!$length)
  948.     {
  949.         $length 15;
  950.     }
  951.     return api_trunc_str($input$length);
  952. }
  953. /**
  954.  * handling simple and double apostrofe in order that strings be stored properly in database
  955.  *
  956.  * @author Denes Nagy
  957.  * @param  string variable - the variable to be revised
  958.  */
  959. function domesticate($input)
  960. {
  961.     $input stripslashes($input);
  962.     $input str_replace("'""''"$input);
  963.     $input str_replace('"'"''"$input);
  964.     return ($input);
  965. }
  966.  
  967. /*
  968. ==============================================================================
  969.         FAILURE MANAGEMENT
  970. ==============================================================================
  971. */
  972.  
  973. /*
  974.  * The Failure Management module is here to compensate
  975.  * the absence of an 'exception' device in PHP 4.
  976.  */
  977. /**
  978.  * $api_failureList - array containing all the failure recorded
  979.  * in order of arrival.
  980.  */
  981. $api_failureList array ();
  982. /**
  983.  * Fills a global array called $api_failureList
  984.  * This array collects all the failure occuring during the script runs
  985.  * The main purpose is allowing to manage the display messages externaly
  986.  * from the functions or objects. This strengthens encupsalation principle
  987.  *
  988.  * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  989.  * @param  string $failureType - the type of failure
  990.  * @global array $api_failureList 
  991.  * @return bolean false to stay consistent with the main script
  992.  */
  993. function api_set_failure($failureType)
  994. {
  995.     global $api_failureList;
  996.     $api_failureList[$failureType;
  997.     return false;
  998. }
  999.  
  1000. /**
  1001.  * Sets the current user as anonymous if it hasn't been identified yet. This
  1002.  * function should be used inside a tool only. The function api_clear_anonymous()
  1003.  * acts in the opposite direction by clearing the anonymous user's data every
  1004.  * time we get on a course homepage or on a neutral page (index, admin, my space)
  1005.  * @return    bool    true if set user as anonymous, false if user was already logged in or anonymous id could not be found
  1006.  */
  1007. function api_set_anonymous()
  1008. {
  1009.     global $_user;
  1010.     if(!empty($_user['user_id']))
  1011.     {
  1012.         return false;
  1013.     }
  1014.     else
  1015.     {
  1016.         $user_id api_get_anonymous_id();
  1017.         if($user_id == 0)
  1018.         {
  1019.             return false;
  1020.         }
  1021.         else
  1022.         {
  1023.             api_session_unregister('_user');
  1024.             $_user['user_id'$user_id;
  1025.             $_user['is_anonymous'true;
  1026.             api_session_register('_user');
  1027.             $GLOBALS['_user'$_user;
  1028.             return true;
  1029.         }
  1030.     }
  1031. }
  1032.  
  1033. /**
  1034.  * get the last failure stored in $api_failureList;
  1035.  *
  1036.  * @author Hugues Peeters <hugues.peeters@claroline.net>
  1037.  * @param void 
  1038.  * @return string - the last failure stored
  1039.  */
  1040. {
  1041.     global $api_failureList;
  1042.     return $api_failureList[count($api_failureList1];
  1043. }
  1044. /**
  1045.  * collects and manage failures occuring during script execution
  1046.  * The main purpose is allowing to manage the display messages externaly
  1047.  * from functions or objects. This strengthens encupsalation principle
  1048.  *
  1049.  * @author Hugues Peeters <hugues.peeters@claroline.net>
  1050.  * @package dokeos.library
  1051.  */
  1052. {
  1053.     /*
  1054.      * IMPLEMENTATION NOTE : For now the $api_failureList list is set to the
  1055.      * global scope, as PHP 4 is unable to manage static variable in class. But
  1056.      * this feature is awaited in PHP 5. The class is already written to minize
  1057.      * the change when static class variable will be possible. And the API won't
  1058.      * change.
  1059.      */
  1060.     public $api_failureList = array ();
  1061.     /**
  1062.      * Pile the last failure in the failure list
  1063.      *
  1064.      * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  1065.      * @param  string $failureType - the type of failure
  1066.      * @global array  $api_failureList 
  1067.      * @return bolean false to stay consistent with the main script
  1068.      */
  1069.     function set_failure($failureType)
  1070.     {
  1071.         global $api_failureList;
  1072.         $api_failureList[$failureType;
  1073.         return false;
  1074.     }
  1075.     /**
  1076.      * get the last failure stored
  1077.      *
  1078.      * @author Hugues Peeters <hugues.peeters@claroline.net>
  1079.      * @param void 
  1080.      * @return string - the last failure stored
  1081.      */
  1082.     function get_last_failure()
  1083.     {
  1084.         global $api_failureList;
  1085.         return $api_failureList[count($api_failureList1];
  1086.     }
  1087. }
  1088.  
  1089. /*
  1090. ==============================================================================
  1091.         CONFIGURATION SETTINGS
  1092. ==============================================================================
  1093. */
  1094. /**
  1095. * DEPRECATED, use api_get_setting instead
  1096. */
  1097. function get_setting($variable$key NULL)
  1098. {
  1099.     global $_setting;
  1100.     return api_get_setting($variable$key);
  1101. }
  1102.  
  1103.  
  1104. /**
  1105. * Returns the value of a setting from the web-adjustable admin config settings.
  1106. *
  1107. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  1108. * if(api_get_setting("show_navigation_menu") == "true") //CORRECT
  1109. * instead of
  1110. * if(api_get_setting("show_navigation_menu") == true) //INCORRECT
  1111. @param    string    The variable name
  1112. @param    string    The subkey (sub-variable) if any. Defaults to NULL
  1113. @author Rene Haentjens
  1114. @author Bart Mollet
  1115. */
  1116. function api_get_setting($variable$key NULL)
  1117. {
  1118.     global $_setting;
  1119.     return is_null($key(!empty($_setting[$variable])?$_setting[$variable]:null$_setting[$variable][$key];
  1120. }
  1121.  
  1122. /**
  1123.  * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection
  1124.  * @return    string    Escaped version of $_SERVER['PHP_SELF']
  1125.  */
  1126. function api_get_self()
  1127. {
  1128.     return htmlentities($_SERVER['PHP_SELF']);
  1129. }
  1130.  
  1131. /*
  1132. ==============================================================================
  1133.         LANGUAGE SUPPORT
  1134. ==============================================================================
  1135. */
  1136.  
  1137. /**
  1138. * Whenever the server type in the Dokeos Config settings is
  1139. * set to test/development server you will get an indication that a language variable
  1140. * is not translated and a link to a suggestions form of DLTT.
  1141. *
  1142. @return language variable '$lang'.$variable or language variable $variable.
  1143. *
  1144. @author Roan Embrechts
  1145. @author Patrick Cool
  1146. */
  1147. function get_lang($variable$notrans 'DLTT')
  1148. {
  1149.     $ot '[='//opening tag for missing vars
  1150.     $ct '=]'//closing tag for missing vars
  1151.     if(api_get_setting('hide_dltt_markup'== 'true')
  1152.     {
  1153.         $ot '';
  1154.         $ct '';
  1155.     }
  1156.     if (api_get_setting('server_type'!= 'test')
  1157.     {
  1158.         $lvv = isset ($GLOBALS['lang'.$variable]$GLOBALS['lang'.$variable(isset ($GLOBALS[$variable]$GLOBALS[$variable$ot.$variable.$ct);
  1159.         if (!is_string($lvv))
  1160.             return $lvv;
  1161.         return str_replace("\\'""'"$lvv);
  1162.     }
  1163.     if (!is_string($variable))
  1164.         return $ot.'get_lang(?)'.$ct;
  1165.     global $language_interface$language_files;
  1166.     //language file specified in tool
  1167.     $langpath api_get_path(SYS_CODE_PATH).'lang/';
  1168.     if (isset ($language_files))
  1169.     {
  1170.         if (!is_array($language_files))
  1171.         {
  1172.             @include ($langpath.$language_interface.'/'.$language_files.'.inc.php');
  1173.         }
  1174.         else
  1175.         {
  1176.             foreach ($language_files as $index => $language_file)
  1177.             {
  1178.                 @include ($langpath.$language_interface.'/'.$language_file.'.inc.php');
  1179.             }
  1180.         }
  1181.     }
  1182.     eval ('$langvar = $'.$variable.';')// Note (RH): $$var doesn't work with arrays, see PHP doc
  1183.     if (isset ($langvar&& is_string($langvar&& strlen($langvar0)
  1184.     {
  1185.         return str_replace("\\'""'"$langvar);
  1186.     }
  1187.     eval ('$langvar = $lang'.$variable.';');
  1188.     if (isset ($langvar&& is_string($langvar&& strlen($langvar0)
  1189.     {
  1190.         return str_replace("\\'""'"$langvar);
  1191.     }
  1192.     if ($notrans != 'DLTT')
  1193.         return $ot.$variable.$ct;
  1194.     if (!is_array($language_files))
  1195.     {
  1196.         $language_file $language_files;
  1197.     }
  1198.     else
  1199.     {
  1200.         $language_file implode('.inc.php',$language_files);
  1201.     }
  1202.     return $ot.$variable.$ct."<a href=\"http://www.dokeos.com/DLTT/suggestion.php?file=".$language_file.".inc.php&amp;variable=$".$variable."&amp;language=".$language_interface."\" style=\"color:#FF0000\"><strong>#</strong></a>";
  1203. }
  1204.  
  1205. /**
  1206.  * Gets the current interface language
  1207.  * @return string The current language of the interface
  1208.  */
  1209. {
  1210.     global     $language_interface;
  1211.     return $language_interface;
  1212. }
  1213.  
  1214. /*
  1215. ==============================================================================
  1216.         USER PERMISSIONS
  1217. ==============================================================================
  1218. */
  1219. /**
  1220. * Check if current user is a platform administrator
  1221. @return boolean True if the user has platform admin rights,
  1222. *  false otherwise.
  1223. */
  1224. function api_is_platform_admin($allow_sessions_admins false)
  1225. {
  1226.     if($_SESSION['is_platformAdmin'])
  1227.         return true;
  1228.     else
  1229.     {
  1230.         global $_user;
  1231.         if($allow_sessions_admins && $_user['status']==SESSIONADMIN)
  1232.             return true;
  1233.     }
  1234.     return false;
  1235. }
  1236. /**
  1237.  * Check if current user is allowed to create courses
  1238. @return boolean True if the user has course creation rights,
  1239. *  false otherwise.
  1240. */
  1241. {
  1242.     return $_SESSION["is_allowedCreateCourse"];
  1243. }
  1244. /**
  1245.  * Check if the current user is a course administrator
  1246.  * @return boolean True if current user is a course administrator
  1247.  */
  1248. {
  1249.     return $_SESSION["is_courseAdmin"];
  1250. }
  1251. /**
  1252.  * Check if the current user is a course coach
  1253.  * @return    bool    True if current user is a course coach
  1254.  */
  1255. {
  1256.     return $_SESSION['is_courseCoach'];
  1257. }
  1258. /**
  1259.  * Check if the current user is a course tutor
  1260.  * @return     bool    True if current user is a course tutor
  1261.  */
  1262. {
  1263.     return $_SESSION['is_courseTutor'];
  1264. }
  1265. /**
  1266.  * Check if the current user is a course or session coach
  1267.  * @return boolean True if current user is a course or session coach
  1268.  */
  1269. function api_is_coach()
  1270. {
  1271.     global $_user;
  1272.     global $sessionIsCoach;
  1273.  
  1274.     $sql "SELECT DISTINCT id, name, date_start, date_end
  1275.                             FROM session
  1276.                             INNER JOIN session_rel_course
  1277.                                 ON session_rel_course.id_coach = '".mysql_real_escape_string($_user['user_id'])."'
  1278.                             ORDER BY date_start, date_end, name";
  1279.     $result api_sql_query($sql,__FILE__,__LINE__);
  1280.     $sessionIsCoach api_store_result($result);
  1281.  
  1282.     $sql "SELECT DISTINCT id, name, date_start, date_end
  1283.                             FROM session
  1284.                             WHERE session.id_coach =  '".mysql_real_escape_string($_user['user_id'])."'
  1285.                             ORDER BY date_start, date_end, name";
  1286.     $result api_sql_query($sql,__FILE__,__LINE__);
  1287.     $sessionIsCoach array_merge($sessionIsCoach api_store_result($result));
  1288.  
  1289.     if(count($sessionIsCoach0)
  1290.     {
  1291.         return true;
  1292.     }
  1293.     else
  1294.     {
  1295.         return false;
  1296.     }
  1297. }
  1298. /*
  1299. ==============================================================================
  1300.         DISPLAY OPTIONS
  1301.         student view, title, message boxes,...
  1302. ==============================================================================
  1303. */
  1304. /**
  1305.  * Displays the title of a tool.
  1306.  * Normal use: parameter is a string:
  1307.  * api_display_tool_title("My Tool")
  1308.  *
  1309.  * Optionally, there can be a subtitle below
  1310.  * the normal title, and / or a supra title above the normal title.
  1311.  *
  1312.  * e.g. supra title:
  1313.  * group
  1314.  * GROUP PROPERTIES
  1315.  *
  1316.  * e.g. subtitle:
  1317.  * AGENDA
  1318.  * calender & events tool
  1319.  *
  1320.  * @author Hugues Peeters <hugues.peeters@claroline.net>
  1321.  * @param  mixed $titleElement - it could either be a string or an array
  1322.  *                                containing 'supraTitle', 'mainTitle',
  1323.  *                                'subTitle'
  1324.  * @return void 
  1325.  */
  1326. function api_display_tool_title($titleElement)
  1327. {
  1328.     if (is_string($titleElement))
  1329.     {
  1330.         $tit $titleElement;
  1331.         unset ($titleElement);
  1332.         $titleElement['mainTitle'$tit;
  1333.     }
  1334.     echo '<h3>';
  1335.     if (!empty($titleElement['supraTitle']))
  1336.     {
  1337.         echo '<small>'.$titleElement['supraTitle'].'</small><br>';
  1338.     }
  1339.     if (!empty($titleElement['mainTitle']))
  1340.     {
  1341.         echo $titleElement['mainTitle'];
  1342.     }
  1343.     if (!empty($titleElement['subTitle']))
  1344.     {
  1345.         echo '<br><small>'.$titleElement['subTitle'].'</small>';
  1346.     }
  1347.     echo '</h3>';
  1348. }
  1349. /**
  1350. *    Display options to switch between student view and course manager view
  1351. *
  1352. *    Changes in version 1.2 (Patrick Cool)
  1353. *    Student view switch now behaves as a real switch. It maintains its current state until the state
  1354. *    is changed explicitly
  1355. *
  1356. *    Changes in version 1.1 (Patrick Cool)
  1357. *    student view now works correctly in subfolders of the document tool
  1358. *    student view works correctly in the new links tool
  1359. *
  1360. *    Example code for using this in your tools:
  1361. *    //if ( $is_courseAdmin && api_get_setting('student_view_enabled') == 'true' )
  1362. *    //{
  1363. *    //    display_tool_view_option($isStudentView);
  1364. *    //}
  1365. *    //and in later sections, use api_is_allowed_to_edit()
  1366. *
  1367.     @author Roan Embrechts
  1368. *    @author Patrick Cool
  1369. *    @version 1.2
  1370. *    @todo rewrite code so it is easier to understand
  1371. */
  1372. {
  1373.     if (api_get_setting('student_view_enabled'!= "true")
  1374.     {
  1375.         return '';
  1376.     }
  1377.     $output_string='';
  1378.  
  1379.     $sourceurl '';
  1380.     $is_framed false;
  1381.     // Exceptions apply for all multi-frames pages
  1382.     if (strpos($_SERVER['REQUEST_URI'],'chat/chat_banner.php')!==false)
  1383.     {    //the chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
  1384.         $is_framed true;
  1385.         return '';
  1386.     }
  1387.     // Uncomment to remove student view link from document view page
  1388.     if(strpos($_SERVER['REQUEST_URI'],'document/headerpage.php')!==false)
  1389.     {
  1390.         $sourceurl str_replace('document/headerpage.php','document/showinframes.php',$_SERVER['REQUEST_URI']);
  1391.         //showinframes doesn't handle student view anyway...
  1392.         //return '';
  1393.         $is_framed true;
  1394.     }
  1395.     // Uncomment to remove student view link from document view page
  1396.     if(strpos($_SERVER['REQUEST_URI'],'newscorm/lp_header.php')!==false)
  1397.     {
  1398.         if(empty($_GET['lp_id']))
  1399.         {
  1400.             return '';
  1401.         }
  1402.         $sourceurl substr($_SERVER['REQUEST_URI'],0,strpos($_SERVER['REQUEST_URI'],'?'));
  1403.         $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);
  1404.         //showinframes doesn't handle student view anyway...
  1405.         //return '';
  1406.         $is_framed true;
  1407.     }
  1408.  
  1409.     // check if the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  1410.     if(!$is_framed)
  1411.     {
  1412.         if (!strstr($_SERVER['REQUEST_URI']"?"))
  1413.         {
  1414.             $sourceurl api_get_self()."?".api_get_cidreq();
  1415.         }
  1416.         else
  1417.         {
  1418.             $sourceurl $_SERVER['REQUEST_URI'];
  1419.             //$sourceurl = str_replace('&', '&amp;', $sourceurl);
  1420.         }
  1421.     }
  1422.     if(!empty($_SESSION['studentview']))
  1423.     {
  1424.         if ($_SESSION['studentview']=='studentview')
  1425.         {
  1426.             // we have to remove the isStudentView=true from the $sourceurl
  1427.             $sourceurl str_replace('&isStudentView=true'''$sourceurl);
  1428.             $sourceurl str_replace('&isStudentView=false'''$sourceurl);
  1429.             $output_string .= '<a href="'.$sourceurl.'&isStudentView=false" target="_top">'.get_lang("CourseManagerview").'</a>';
  1430.         }
  1431.         elseif ($_SESSION['studentview']=='teacherview')
  1432.         {
  1433.             //switching to teacherview
  1434.             $sourceurl str_replace('&isStudentView=true'''$sourceurl);
  1435.             $sourceurl str_replace('&isStudentView=false'''$sourceurl);
  1436.             $output_string .= '<a href="'.$sourceurl.'&isStudentView=true" target="_top">'.get_lang("StudentView").'</a>';
  1437.         }
  1438.     }
  1439.     else
  1440.     {
  1441.         $output_string .= '<a href="'.$sourceurl.'&isStudentView=true" target="_top">'.get_lang("StudentView").'</a>';
  1442.     }
  1443.     echo $output_string;
  1444. }
  1445. /**
  1446.  * Displays the contents of an array in a messagebox.
  1447.  * @param array $info_array An array with the messages to show
  1448.  */
  1449. function api_display_array($info_array)
  1450. {
  1451.     foreach ($info_array as $element)
  1452.     {
  1453.         $message .= $element."<br>";
  1454.     }
  1455.     Display :: display_normal_message($message);
  1456. }
  1457. /**
  1458. *    Displays debug info
  1459. @param string $debug_info The message to display
  1460. *    @author Roan Embrechts
  1461. *    @version 1.1, March 2004
  1462. */
  1463. function api_display_debug_info($debug_info)
  1464. {
  1465.     $message "<i>Debug info</i><br>";
  1466.     $message .= $debug_info;
  1467.     Display :: display_normal_message($message);
  1468. }
  1469. /**
  1470. *    @deprecated, use api_is_allowed_to_edit() instead
  1471. */
  1472. function is_allowed_to_edit()
  1473. {
  1474.     return api_is_allowed_to_edit();
  1475. }
  1476.  
  1477. /**
  1478. *    Function that removes the need to directly use is_courseAdmin global in
  1479. *    tool scripts. It returns true or false depending on the user's rights in
  1480. *    this particular course.
  1481. *    Optionally checking for tutor and coach roles here allows us to use the
  1482. *    student_view feature altogether with these roles as well.
  1483. *    @param    bool    Whether to check if the user has the tutor role
  1484. *    @param    bool    Whether to check if the user has the coach role
  1485. *
  1486. *    @author Roan Embrechts
  1487. *    @author Patrick Cool
  1488. *    @version 1.1, February 2004
  1489. *    @return boolean, true: the user has the rights to edit, false: he does not
  1490. */
  1491. function api_is_allowed_to_edit($tutor=false,$coach=false)
  1492. {
  1493.     $is_courseAdmin api_is_course_admin(|| api_is_platform_admin();
  1494.     if(!$is_courseAdmin && $tutor == true)
  1495.     {    //if we also want to check if the user is a tutor...
  1496.         $is_courseAdmin $is_courseAdmin || api_is_course_tutor();
  1497.     }
  1498.     if(!$is_courseAdmin && $coach == true)
  1499.     {    //if we also want to check if the user is a coach...
  1500.         $is_courseAdmin $is_courseAdmin || api_is_course_coach();
  1501.     }    
  1502.     if(api_get_setting('student_view_enabled'== 'true')
  1503.     {    //check if the student_view is enabled, and if so, if it is activated
  1504.         $is_allowed $is_courseAdmin && $_SESSION['studentview'!= "studentview";
  1505.         return $is_allowed;
  1506.     }
  1507.     else
  1508.         return $is_courseAdmin;
  1509. }
  1510.  
  1511. /**
  1512. * this fun
  1513. @param $tool the tool we are checking ifthe user has a certain permission
  1514. @param $action the action we are checking (add, edit, delete, move, visibility)
  1515. @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1516. @version 1.0
  1517. */
  1518. function api_is_allowed($tool$action$task_id 0)
  1519. {
  1520.     global $_course;
  1521.     global $_user;
  1522.  
  1523.     if(api_is_course_admin())
  1524.         return true;
  1525.  
  1526.     //if(!$_SESSION['total_permissions'][$_course['code']] and $_course)
  1527.     if($_course)
  1528.     {
  1529.         require_once(api_get_path(SYS_CODE_PATH'permissions/permissions_functions.inc.php');
  1530.         require_once(api_get_path(LIBRARY_PATH"/groupmanager.lib.php");
  1531.  
  1532.         // getting the permissions of this user
  1533.         if($task_id == 0)
  1534.         {
  1535.             $user_permissions get_permissions('user'$_user['user_id']);
  1536.             $_SESSION['total_permissions'][$_course['code']] $user_permissions;
  1537.         }
  1538.  
  1539.         // getting the permissions of the task
  1540.         if($task_id != 0)
  1541.         {
  1542.             $task_permissions get_permissions('task'$task_id);
  1543.             /* !!! */$_SESSION['total_permissions'][$_course['code']] $task_permissions;
  1544.         }
  1545.         //print_r($_SESSION['total_permissions']);
  1546.  
  1547.         // getting the permissions of the groups of the user
  1548.         //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  1549.  
  1550.         //foreach($groups_of_user as $group)
  1551.             //$this_group_permissions = get_permissions('group', $group);
  1552.  
  1553.         // getting the permissions of the courseroles of the user
  1554.         $user_courserole_permissions get_roles_permissions('user'$_user['user_id']);
  1555.  
  1556.         // getting the permissions of the platformroles of the user
  1557.         //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  1558.  
  1559.         // getting the permissions of the roles of the groups of the user
  1560.         //foreach($groups_of_user as $group)
  1561.             //$this_group_courserole_permissions = get_roles_permissions('group', $group);
  1562.  
  1563.         // getting the permissions of the platformroles of the groups of the user
  1564.         //foreach($groups_of_user as $group)
  1565.             //$this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  1566.     }
  1567.  
  1568.     // ifthe permissions are limited we have to map the extended ones to the limited ones
  1569.     if(api_get_setting('permissions'== 'limited')
  1570.     {
  1571.         if($action == 'Visibility')
  1572.             $action 'Edit';
  1573.  
  1574.         if($action == 'Move')
  1575.             $action 'Edit';
  1576.     }
  1577.  
  1578.     // the session that contains all the permissions already exists for this course
  1579.     // so there is no need to requery everything.
  1580.     //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  1581.     if(in_array($action$_SESSION['total_permissions'][$_course['code']][$tool]))
  1582.         return true;
  1583.     else
  1584.         return false;
  1585. }
  1586.  
  1587. /**
  1588.  * Tells whether this user is an anonymous user
  1589.  * @param    int        User ID (optional, will take session ID if not provided)
  1590.  * @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
  1591.  * @return    bool    true if this user is anonymous, false otherwise
  1592.  */
  1593. function api_is_anonymous($user_id=null,$db_check=false)
  1594. {
  1595.     if(!isset($user_id))
  1596.     {
  1597.         $user_id api_get_user_id();
  1598.     }
  1599.     if($db_check)
  1600.     {
  1601.         $info api_get_user_info($user_id);
  1602.         if($info['status'== 6)
  1603.         {
  1604.             return true;
  1605.         }
  1606.     }
  1607.     else
  1608.     {
  1609.         global $_user;
  1610.         if(!isset($_user)){
  1611.             //in some cases, api_set_anonymous doesn't seem to be
  1612.             //triggered in local.inc.php. Make sure it is.    
  1613.             //Occurs in agenda for admin links - YW
  1614.             global $use_anonymous;
  1615.                         if(isset($use_anonymous&& $use_anonymous == true)
  1616.                         {
  1617.                                 api_set_anonymous();
  1618.                         }
  1619.             return true;
  1620.         }
  1621.         if(isset($_user['is_anonymous']and $_user['is_anonymous'=== true)
  1622.         {
  1623.             return true;
  1624.         }
  1625.     }
  1626.     return false;
  1627. }
  1628.  
  1629. /**
  1630.  * Displays message "You are not allowed here..." and exits the entire script.
  1631.  * @param    bool    Whether or not to print headers (default = false -> does not print them)
  1632.  *
  1633.  * @author Roan Embrechts
  1634.  * @author Yannick Warnier
  1635.  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1636. *
  1637.  * @version 1.0, February 2004
  1638.  * @version dokeos 1.8, August 2006
  1639. */
  1640. function api_not_allowed($print_headers false)
  1641. {
  1642.     $home_url api_get_path(WEB_PATH);
  1643.     $user api_get_user_id();
  1644.     $course api_get_course_id();
  1645.     if((isset($user&& !api_is_anonymous()) 
  1646.         && (!isset($course|| $course==-1
  1647.         && empty($_GET['cidReq']))
  1648.     {//if the access is not authorized and there is some login information 
  1649.      // but the cidReq is not found, assume we are missing course data and send the user
  1650.      // to the user_portal            
  1651.          if(!headers_sent(or $print_headers){Display::display_header('');}
  1652.         echo '<div align="center">';
  1653.         Display :: display_error_message(get_lang('NotAllowedClickBack').'<br/><br/><a href="'.$_SERVER['HTTP_REFERRER'].'">'.get_lang('BackToPreviousPage').'</a><br/>',false);
  1654.         echo '</div>';
  1655.         if($print_headers){Display::display_footer();}
  1656.         die();
  1657.     }
  1658.     elseif(!empty($_SERVER['REQUEST_URI']&& !empty($_GET['cidReq']))
  1659.     {
  1660.         //only display form and return to the previous URL if there was a course ID included
  1661.         if(!empty($user&& !api_is_anonymous())
  1662.         {
  1663.             if(!headers_sent(or $print_headers){Display::display_header('');}
  1664.             echo '<div align="center">';
  1665.             Display :: display_error_message(get_lang('NotAllowedClickBack').'<br/><br/><a href="'.$_SERVER['HTTP_REFERRER'].'">'.get_lang('BackToPreviousPage').'</a><br/>',false);
  1666.             echo '</div>';
  1667.             if($print_headers){Display::display_footer();}
  1668.             die();            
  1669.         }
  1670.         else
  1671.         {
  1672.             include_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');$form new FormValidator('formLogin','post',api_get_self().'?'.$_SERVER['QUERY_STRING']);
  1673.             $form->addElement('static',null,null,'Username');
  1674.             $form->addElement('text','login','',array('size'=>15));
  1675.             $form->addElement('static',null,null,'Password');
  1676.             $form->addElement('password','password','',array('size'=>15));
  1677.             $form->addElement('submit','submitAuth',get_lang('Ok'));
  1678.             $test $form->return_form();
  1679.             if(!headers_sent(or $print_headers){Display::display_header('');}
  1680.             echo '<div align="center">';
  1681.             Display :: display_error_message(get_lang('NotAllowed').'<br/><br/>'.get_lang('PleaseLoginAgainFromFormBelow').'<br/>'.$test,false);
  1682.             echo '</div>';
  1683.             $_SESSION['request_uri'$_SERVER['REQUEST_URI'];
  1684.             if($print_headers){Display::display_footer();}
  1685.             die();
  1686.         }
  1687.     }
  1688.     else
  1689.     {
  1690.         if(!empty($user&& !api_is_anonymous())
  1691.         {
  1692.             if(!headers_sent(or $print_headers){Display::display_header('');}
  1693.             echo '<div align="center">';
  1694.             Display :: display_error_message(get_lang('NotAllowedClickBack').'<br/><br/><a href="'.$_SERVER['HTTP_REFERRER'].'">'.get_lang('BackToPreviousPage').'</a><br/>',false);
  1695.             echo '</div>';
  1696.             if($print_headers){Display::display_footer();}
  1697.             die();            
  1698.         }
  1699.         else
  1700.         {
  1701.             //if no course ID was included in the requested URL, redirect to homepage
  1702.             if($print_headers){Display::display_header('');}
  1703.             echo '<div align="center">';
  1704.             Display :: display_error_message(get_lang('NotAllowed').'<br/><br/><a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br/>',false);
  1705.             echo '</div>';
  1706.             if($print_headers){Display::display_footer();}
  1707.             die();
  1708.         }
  1709.     }
  1710. }
  1711.  
  1712. /*
  1713. ==============================================================================
  1714.         WHAT'S NEW
  1715.         functions for the what's new icons
  1716.         in the user course list
  1717. ==============================================================================
  1718. */
  1719. /**
  1720.  * @param $last_post_datetime standard output date in a sql query
  1721.  * @return unix timestamp
  1722.  * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  1723.  * @version October 2003
  1724.  * @desc convert sql date to unix timestamp
  1725. */
  1726. function convert_mysql_date($last_post_datetime)
  1727. {
  1728.     list ($last_post_date$last_post_timesplit(" "$last_post_datetime);
  1729.     list ($year$month$dayexplode("-"$last_post_date);
  1730.     list ($hour$min$secexplode(":"$last_post_time);
  1731.     $announceDate mktime($hour$min$sec$month$day$year);
  1732.     return $announceDate;
  1733. }
  1734.  
  1735. /**
  1736.  * Gets item visibility from the item_property table
  1737.  * @param    array    Course properties array (result of api_get_course_info())
  1738.  * @param    string    Tool (learnpath, document, etc)
  1739.  * @param    int        The item ID in the given tool
  1740.  * @return    int        -1 on error, 0 if invisible, 1 if visible
  1741.  */
  1742. function api_get_item_visibility($_course,$tool,$id)
  1743. {
  1744.     if(!is_array($_courseor count($_course)==or empty($toolor empty($id)) return -1;
  1745.     $tool Database::escape_string($tool);
  1746.     $id Database::escape_string($id);
  1747.     $TABLE_ITEMPROPERTY Database :: get_course_table(TABLE_ITEM_PROPERTY,$_course['dbName']);
  1748.     $sql "SELECT * FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref = $id";
  1749.     $res api_sql_query($sql);
  1750.     if($res === false or Database::num_rows($res)==0return -1;
  1751.     $row Database::fetch_array($res);
  1752.     return $row['visibility'];      
  1753. }
  1754.  
  1755. /**
  1756.  * Updates or adds item properties to the Item_propetry table
  1757.  * Tool and lastedit_type are language independant strings (langvars->get_lang!)
  1758.  *
  1759.  * @param $_course : array with course properties
  1760.  * @param $tool : tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  1761.  * @param $item_id : id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  1762.  * @param $lastedit_type : add or update action (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  1763.  *                                                  (2) "delete"; (3) "visible"; (4) "invisible";
  1764.  * @param $user_id : id of the editing/adding user
  1765.  * @param $to_group_id : id of the intended group ( 0 = for everybody), only relevant for $type (1)
  1766.  * @param $to_user_id : id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  1767.  * @param string $start_visible 0000-00-00 00:00:00 format
  1768.  * @param unknown_type $end_visible 0000-00-00 00:00:00 format
  1769.  * @return boolean False if update fails.
  1770.  * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  1771.  * @version January 2005
  1772.  * @desc update the item_properties table (if entry not exists, insert) of the course
  1773.  */
  1774. function api_item_property_update($_course$tool$item_id$lastedit_type$user_id$to_group_id 0$to_user_id NULL$start_visible 0$end_visible 0)
  1775. {
  1776.     $tool Database::escape_string($tool);
  1777.     $item_id Database::escape_string($item_id);
  1778.     $lastedit_type Database::escape_string($lastedit_type);
  1779.     $user_id Database::escape_string($user_id);
  1780.     $to_group_id Database::escape_string($to_group_id);
  1781.     $to_user_id Database::escape_string($to_user_id);
  1782.     $start_visible Database::escape_string($start_visible);
  1783.     $end_visible Database::escape_string($end_visible);
  1784.  
  1785.     $time time();
  1786.     $time date("Y-m-d H:i:s"$time);
  1787.     $TABLE_ITEMPROPERTY Database :: get_course_table(TABLE_ITEM_PROPERTY,$_course['dbName']);
  1788.     if ($to_user_id <= 0)
  1789.         $to_user_id NULL//no to_user_id set
  1790.     $start_visible ($start_visible == 0"0000-00-00 00:00:00" $start_visible;
  1791.     $end_visible ($end_visible == 0"0000-00-00 00:00:00" $end_visible;
  1792.     // set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  1793.     $filter "tool='$tool' AND ref='$item_id'";
  1794.     if ($item_id == "*")
  1795.         $filter "tool='$tool' AND visibility<>'2'"// for all (not deleted) items of the tool
  1796.     // check if $to_user_id and $to_group_id are passed in the function call
  1797.     // if both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  1798.     if (is_null($to_user_id&& is_null($to_group_id))
  1799.         $to_group_id 0;
  1800.     if (!is_null($to_user_id))
  1801.         $to_filter " AND to_user_id='$to_user_id'"// set filter to intended user
  1802.     else
  1803.         if (!is_null($to_group_idand $to_group_id == strval(intval($to_group_id)))
  1804.             $to_filter " AND to_group_id='$to_group_id'"// set filter to intended group
  1805.     // update if possible
  1806.     $set_type "";
  1807.     switch ($lastedit_type)
  1808.     {
  1809.         case "delete" // delete = make item only visible for the platform admin
  1810.             $visibility '2';
  1811.             $sql "UPDATE $TABLE_ITEMPROPERTY
  1812.                                         SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility$set_type
  1813.                                         WHERE $filter";
  1814.             break;
  1815.         case "visible" // change item to visible
  1816.             $visibility '1';
  1817.             $sql "UPDATE $TABLE_ITEMPROPERTY
  1818.                                         SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility$set_type
  1819.                                         WHERE $filter";
  1820.             break;
  1821.         case "invisible" // change item to invisible
  1822.             $visibility '0';
  1823.             $sql "UPDATE $TABLE_ITEMPROPERTY
  1824.                                         SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility$set_type
  1825.                                         WHERE $filter";
  1826.             break;
  1827.         default // item will be added or updated
  1828.             $set_type ", lastedit_type='$lastedit_type";
  1829.             $visibility '1';
  1830.             $filter .= $to_filter;
  1831.             $sql "UPDATE $TABLE_ITEMPROPERTY
  1832.                                         SET lastedit_date='$time', lastedit_user_id='$user_id$set_type
  1833.                                         WHERE $filter";
  1834.     }
  1835.  
  1836.     $res mysql_query($sql);
  1837.     // insert if no entries are found (can only happen in case of $lastedit_type switch is 'default')
  1838.     if (mysql_affected_rows(== 0)
  1839.     {
  1840.         if (!is_null($to_user_id)) // $to_user_id has more priority than $to_group_id
  1841.         {
  1842.             $to_field "to_user_id";
  1843.             $to_value $to_user_id;
  1844.         }
  1845.         else // $to_user_id is not set
  1846.             {
  1847.             $to_field "to_group_id";
  1848.             $to_value $to_group_id;
  1849.         }
  1850.         $sql "INSERT INTO $TABLE_ITEMPROPERTY
  1851.                                                  (tool,   ref,       insert_date,insert_user_id,lastedit_date,lastedit_type,   lastedit_user_id,$to_field,  visibility,   start_visible,   end_visible)
  1852.                                      VALUES     ('$tool','$item_id','$time',    '$user_id',       '$time',         '$lastedit_type','$user_id',       '$to_value','$visibility','$start_visible','$end_visible')";
  1853.         $res mysql_query($sql);
  1854.         if (!$res)
  1855.             return FALSE;
  1856.     }
  1857.     return TRUE;
  1858. }
  1859.  
  1860. /*
  1861. ==============================================================================
  1862.         Language Dropdown
  1863. ==============================================================================
  1864. */
  1865. /**
  1866. *    Displays a form (drop down menu) so the user can select his/her preferred language.
  1867. *    The form works with or without javascript
  1868. */
  1869. {
  1870.     $platformLanguage api_get_setting('platformLanguage');
  1871.     $dirname api_get_path(SYS_PATH)."main/lang/"// this line is probably no longer needed
  1872.     // retrieve a complete list of all the languages.
  1873.     $language_list api_get_languages();
  1874.     // the the current language of the user so that his/her language occurs as selected in the dropdown menu
  1875.     if(isset($_SESSION['user_language_choice']))
  1876.     {
  1877.         $user_selected_language $_SESSION['user_language_choice'];
  1878.     }
  1879.     if (!isset ($user_selected_language))
  1880.         $user_selected_language $platformLanguage;
  1881.     $original_languages $language_list['name'];
  1882.     $folder $language_list['folder']// this line is probably no longer needed
  1883. ?>
  1884.     <script language="JavaScript" type="text/JavaScript">
  1885.     <!--
  1886.     function jumpMenu(targ,selObj,restore){ //v3.0
  1887.       eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  1888.       if (restore) selObj.selectedIndex=0;
  1889.     }
  1890.     //-->
  1891.     </script>
  1892.     <?php
  1893.  
  1894.  
  1895.     echo "<form id=\"lang_form\" name=\"lang_form\" method=\"post\" action=\"".api_get_self()."\">""<select name=\"language_list\"  onchange=\"jumpMenu('parent',this,0)\">";
  1896.     foreach ($original_languages as $key => $value)
  1897.     {
  1898.         if ($folder[$key== $user_selected_language)
  1899.             $option_end " selected=\"selected\" >";
  1900.         else
  1901.             $option_end ">";
  1902.         echo "<option value=\"".api_get_self()."?language=".$folder[$key]."\"$option_end";
  1903.         #echo substr($value,0,16); #cut string to keep 800x600 aspect
  1904.         echo $value;
  1905.         echo "</option>\n";
  1906.     }
  1907.     echo "</select>";
  1908.     echo "<noscript><input type=\"submit\" name=\"user_select_language\" value=\"".get_lang("Ok")."\" /></noscript>";
  1909.     echo "</form>";
  1910. }
  1911. /**
  1912. * Return a list of all the languages that are made available by the admin.
  1913. @return array An array with all languages. Structure of the array is
  1914. *   array['name'] = An array with the name of every language
  1915. *   array['folder'] = An array with the corresponding dokeos-folder
  1916. */
  1917. function api_get_languages()
  1918. {
  1919.     $tbl_language Database :: get_main_table(TABLE_MAIN_LANGUAGE);
  1920.     $sql "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  1921.     $result api_sql_query($sql__FILE____LINE__);
  1922.     while ($row mysql_fetch_array($result))
  1923.     {
  1924.         $language_list['name'][$row['original_name'];
  1925.         $language_list['folder'][$row['dokeos_folder'];
  1926.     }
  1927.     return $language_list;
  1928. }
  1929. /**
  1930.  * Get language isocode column from the language table, taking the current language as a query
  1931.  * @return    string    The isocode (two-letters code or 5 letters code, fr or fr-BE) or null if error
  1932.  */
  1933. {
  1934.     $tbl_language Database::get_main_table(TABLE_MAIN_LANGUAGE);
  1935.     $sql "SELECT isocode FROM $tbl_language WHERE dokeos_folder = '".api_get_interface_language()."'";
  1936.     $res api_sql_query($sql,__FILE__,__LINE__);
  1937.     if(mysql_num_rows($res))
  1938.     {
  1939.         $row mysql_fetch_array($res);
  1940.         return $row['isocode'];
  1941.     }
  1942.     return null;
  1943. }
  1944. /**
  1945.  * Returns a list of CSS themes currently available in the CSS folder
  1946.  * @return    array    List of themes directories from the css folder
  1947.  */
  1948. function api_get_themes()
  1949. {
  1950.     $cssdir api_get_path(SYS_PATH).'main/css/';
  1951.     $list_dirarray();
  1952.     $list_namearray();
  1953.     
  1954.     if (@is_dir($cssdir))
  1955.     {
  1956.         $themes @scandir($cssdir);
  1957.         
  1958.         if (is_array($themes))
  1959.         {
  1960.             if($themes !== false)
  1961.             {
  1962.                 sort($themes);
  1963.                 
  1964.                 foreach($themes as $theme)
  1965.                 {
  1966.                     if(substr($theme,0,1)=='.')
  1967.                     {
  1968.                         //ignore
  1969.                         continue;
  1970.                     }
  1971.                     else
  1972.                     {
  1973.                         if(@is_dir($cssdir.$theme))
  1974.                         {
  1975.                             $list_dir[$theme;
  1976.                             $list_name[ucwords(str_replace('_',' ',$theme));
  1977.                         }    
  1978.                     }
  1979.                 }
  1980.             }
  1981.         }        
  1982.     }
  1983.     $return=array();
  1984.     $return[]=$list_dir;
  1985.     $return[]=$list_name;    
  1986.     return $return;
  1987. }
  1988.  
  1989. /*
  1990. ==============================================================================
  1991.         WYSIWYG HTML AREA
  1992.         functions for the WYSIWYG html editor, TeX parsing...
  1993. ==============================================================================
  1994. */
  1995. /**
  1996. * Displays the FckEditor WYSIWYG editor for online editing of html
  1997. @param string $name The name of the form-element
  1998. @param string $content The default content of the html-editor
  1999. @param int $height The height of the form element
  2000. @param int $width The width of the form element
  2001. @param string $optAttrib optional attributes for the form element
  2002. */
  2003. function api_disp_html_area($name$content ''$height ''$width '100%'$optAttrib '')
  2004. {
  2005.     global $_configuration$_course$fck_attribute;
  2006.     require_once(dirname(__FILE__).'/formvalidator/Element/html_editor.php');
  2007.     $editor new HTML_QuickForm_html_editor($name);
  2008.     $editor->setValue($content);
  2009.     if$height != '')
  2010.     {
  2011.         $fck_attribute['Height'$height;
  2012.     }
  2013.     if$width != '')
  2014.     {
  2015.         $fck_attribute['Width'$width;
  2016.     }
  2017.     echo $editor->toHtml();
  2018. }
  2019. function api_return_html_area($name$content ''$height ''$width '100%'$optAttrib '')
  2020. {
  2021.     global $_configuration$_course$fck_attribute;
  2022.     require_once(dirname(__FILE__).'/formvalidator/Element/html_editor.php');
  2023.     $editor new HTML_QuickForm_html_editor($name);
  2024.     $editor->setValue($content);
  2025.     if$height != '')
  2026.     {
  2027.         $fck_attribute['Height'$height;
  2028.     }
  2029.     if$width != '')
  2030.     {
  2031.         $fck_attribute['Width'$width;
  2032.     }
  2033.     return $editor->toHtml();
  2034. }
  2035.  
  2036. /**
  2037.  * Send an email.
  2038.  *
  2039.  * Wrapper function for the standard php mail() function. Change this function
  2040.  * to your needs. The parameters must follow the same rules as the standard php
  2041.  * mail() function. Please look at the documentation on http: //www. php.
  2042.  * net/manual/en/function. mail.php
  2043.  * @param string $to 
  2044.  * @param string $subject 
  2045.  * @param string $message 
  2046.  * @param string $additional_headers 
  2047.  * @param string $additional_parameters 
  2048.  */
  2049. function api_send_mail($to$subject$message$additional_headers null$additional_parameters null)
  2050. {
  2051.     return mail($to$subject$message$additional_headers$additional_parameters);
  2052. }
  2053.  
  2054. /**
  2055.  * Find the largest sort value in a given user_course_category
  2056.  * This function is used when we are moving a course to a different category
  2057.  * and also when a user subscribes to a courses (the new courses is added to the end
  2058.  * of the main category
  2059.  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2060.  * @param int $user_course_category: the id of the user_course_category
  2061.  * @return int the value of the highest sort of the user_course_category
  2062. */
  2063. function api_max_sort_value($user_course_category$user_id)
  2064. {
  2065.  
  2066.     $tbl_course_user Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  2067.  
  2068.     $sql_max "SELECT max(sort) as max_sort FROM $tbl_course_user WHERE user_id='".$user_id."' AND user_course_cat='".$user_course_category."'";
  2069.     $result_max mysql_query($sql_maxor die(mysql_error());
  2070.     if (mysql_num_rows($result_max== 1)
  2071.     {
  2072.         $row_max mysql_fetch_array($result_max);
  2073.         $max_sort $row_max['max_sort'];
  2074.     }
  2075.     else
  2076.     {
  2077.         $max_sort 0;
  2078.     }
  2079.  
  2080.     return $max_sort;
  2081. }
  2082.  
  2083. /**
  2084.  * This function converts the string "true" or "false" to a boolean true or false.
  2085.  * This function is in the first place written for the Dokeos Config Settings (also named AWACS)
  2086.  * @param string "true" or "false"
  2087.  * @return boolean true or false
  2088.  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2089.  */
  2090. function string_2_boolean($string)
  2091. {
  2092.     if ($string == "true")
  2093.     {
  2094.         return true;
  2095.     }
  2096.     if ($string == "false")
  2097.     {
  2098.         return false;
  2099.     }
  2100. }
  2101.  
  2102. /**
  2103.  * Determines the number of plugins installed for a given location
  2104.  */
  2105. function api_number_of_plugins($location)
  2106. {
  2107.     global $_plugins;
  2108.     if (isset($_plugins[$location]&& is_array($_plugins[$location]))
  2109.     {
  2110.         return count($_plugins[$location]);
  2111.     }
  2112.     return 0;
  2113. }
  2114.  
  2115. /**
  2116.  * including the necessary plugins
  2117.  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2118. */
  2119. function api_plugin($location)
  2120. {
  2121.     global $_plugins;
  2122.  
  2123.     if (isset($_plugins[$location]&& is_array($_plugins[$location]))
  2124.     {
  2125.         foreach ($_plugins[$locationas $this_plugin)
  2126.         {
  2127.             include (api_get_path(SYS_PLUGIN_PATH)."$this_plugin/index.php");
  2128.         }
  2129.     }
  2130. }
  2131.  
  2132. /**
  2133. * Checks to see wether a certain plugin is installed.
  2134. @return boolean true if the plugin is installed, false otherwise.
  2135. */
  2136. function api_is_plugin_installed($plugin_list$plugin_name)
  2137. {
  2138.     foreach ($plugin_list as $plugin_location)
  2139.     {
  2140.         if array_search($plugin_name$plugin_location!== false return true;
  2141.     }
  2142.     return false;
  2143. }
  2144.  
  2145. /**
  2146.  * Apply parsing to content to parse tex commandos that are seperated by [tex]
  2147.  * [/tex] to make it readable for techexplorer plugin.
  2148.  * @param string $text The text to parse
  2149.  * @return string The text after parsing.
  2150.  * @author Patrick Cool <patrick.cool@UGent.be>
  2151.  * @version June 2004
  2152. */
  2153. function api_parse_tex($textext)
  2154. {
  2155.     if (strstr($_SERVER['HTTP_USER_AGENT']'MSIE'))
  2156.     {
  2157.         $textext str_replace(array ("[tex]""[/tex]")array ("<object classid=\"clsid:5AFAB315-AD87-11D3-98BB-002035EFB1A4\"><param name=\"autosize\" value=\"true\" /><param name=\"DataType\" value=\"0\" /><param name=\"Data\" value=\"""\" /></object>")$textext);
  2158.     }
  2159.     else
  2160.     {
  2161.         $textext str_replace(array ("[tex]""[/tex]")array ("<embed type=\"application/x-techexplorer\" texdata=\"""\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">")$textext);
  2162.     }
  2163.     return $textext;
  2164. }
  2165.  
  2166.  
  2167. /**
  2168.  * Transform a number of seconds in hh:mm:ss format
  2169.  * @author Julian Prud'homme
  2170.  * @param integer the number of seconds
  2171.  * @return string the formated time
  2172.  */
  2173. function api_time_to_hms($seconds)
  2174. {
  2175.  
  2176.   //How many hours ?
  2177.   $hours floor($seconds 3600);
  2178.  
  2179.   //How many minutes ?
  2180.   $min floor(($seconds ($hours 3600)) 60);
  2181.  
  2182.   //How many seconds
  2183.   $sec floor($seconds ($hours 3600($min 60));
  2184.  
  2185.   if ($sec 10)
  2186.     $sec "0".$sec;
  2187.  
  2188.   if ($min 10)
  2189.     $min "0".$min;
  2190.  
  2191.   return $hours.":".$min.":".$sec;
  2192.  
  2193. }
  2194.  
  2195.  
  2196. /**
  2197.  * function adapted from a php.net comment
  2198.  * copy recursively a folder
  2199.  * @param the source folder
  2200.  * @param the dest folder
  2201.  * @param an array of excluded file_name (without extension)
  2202.  * @param copied_files the returned array of copied files
  2203.  */
  2204.  
  2205. function copyr($source$dest$exclude=array()$copied_files=array())
  2206. {
  2207.     // Simple copy for a file
  2208.     if (is_file($source)) {
  2209.         $path_infos pathinfo($source);
  2210.         if(!in_array($path_infos['filename']$exclude))
  2211.                copy($source$dest);
  2212.            return;
  2213.     }
  2214.  
  2215.  
  2216.     // Make destination directory
  2217.     if (!is_dir($dest)) {
  2218.         mkdir($dest);
  2219.     }
  2220.  
  2221.     // Loop through the folder
  2222.     $dir dir($source);
  2223.     while (false !== $entry $dir->read()) {
  2224.         // Skip pointers
  2225.         if ($entry == '.' || $entry == '..'{
  2226.             continue;
  2227.         }
  2228.  
  2229.         // Deep copy directories
  2230.         if ($dest !== "$source/$entry"{
  2231.             $zip_files copyr("$source/$entry""$dest/$entry"$exclude$copied_files);
  2232.         }
  2233.     }
  2234.     // Clean up
  2235.     $dir->close();
  2236.     return $zip_files;
  2237. }
  2238.  
  2239.  
  2240. function api_chmod_R($path$filemode
  2241.     if (!is_dir($path))
  2242.        return chmod($path$filemode);
  2243.  
  2244.     $dh opendir($path);
  2245.     while ($file readdir($dh)) {
  2246.         if($file != '.' && $file != '..'{
  2247.             $fullpath $path.'/'.$file;
  2248.             if(!is_dir($fullpath)) {
  2249.               if (!chmod($fullpath$filemode))
  2250.                  return FALSE;
  2251.             else {
  2252.               if (!api_chmod_R($fullpath$filemode))
  2253.                  return FALSE;
  2254.             }
  2255.         }
  2256.     }
  2257.  
  2258.     closedir($dh);
  2259.     
  2260.     if(chmod($path$filemode))
  2261.       return TRUE;
  2262.     else 
  2263.       return FALSE;
  2264. }
  2265.  
  2266. /**
  2267.  * Get Dokeos version from the configuration files
  2268.  * @return    string    A string of type "1.8.4", or an empty string if the version could not be found
  2269.  */
  2270. function api_get_version()
  2271. {
  2272.     global $_configuration;
  2273.     if(!empty($_configuration['dokeos_version']))
  2274.     {
  2275.         return $_configuration['dokeos_version'];
  2276.     }
  2277.     else
  2278.     {
  2279.         return '';
  2280.     }
  2281. }
  2282.  
  2283.  
  2284. /**
  2285.  * Check if status given in parameter exists in the platform
  2286.  * @param mixed the status (can be either int either string)
  2287.  * @return true if the status exists, else returns false
  2288.  */
  2289. function api_status_exists($status_asked)
  2290. {
  2291.     global $_status_list;
  2292.     if(in_array($status_asked$_status_list))
  2293.     {
  2294.         return true;
  2295.     }
  2296.     else 
  2297.     {
  2298.         return isset($_status_list[$status_asked]);
  2299.     }
  2300. }
  2301.  
  2302. /**
  2303.  * Check if status given in parameter exists in the platform
  2304.  * @param mixed the status (can be either int either string)
  2305.  * @return true if the status exists, else returns false
  2306.  */
  2307. function api_status_key($status)
  2308. {
  2309.     global $_status_list;
  2310.     if(isset($_status_list[$status]))
  2311.     {
  2312.         return $status;
  2313.     }
  2314.     else
  2315.     {
  2316.         return array_search($status,$_status_list);
  2317.     }
  2318. }
  2319.  
  2320. /**
  2321.  * get the status langvars list
  2322.  * @return array the list of status with their translations
  2323.  */
  2324. {
  2325.     return array(
  2326.                 COURSEMANAGER=>get_lang('Teacher'),
  2327.                 SESSIONADMIN=>get_lang('SessionsAdmin'),
  2328.                 DRH=>get_lang('Drh'),
  2329.                 STUDENT=>get_lang('Student'),
  2330.                 ANONYMOUS=>get_lang('Anonymous')
  2331.                 );
  2332. }
  2333. /**
  2334.  * Sets a platform configuration setting to a given value
  2335.  * @param    string    The variable we want to update
  2336.  * @param    string    The value we want to record
  2337.  * @param    string    The sub-variable if any (in most cases, this will remain null)
  2338.  * @param    string    The category if any (in most cases, this will remain null)
  2339.  * @param    int        The access_url for which this parameter is valid
  2340.  */
  2341. function api_set_setting($var,$value,$subvar=null,$cat=null,$access_url=1)
  2342. {
  2343.     if(empty($var)) return false}
  2344.     $var Database::escape_string($var);
  2345.     $value Database::escape_string($value);
  2346.     $access_url = (int) $access_url;
  2347.     if(empty($access_url)){$access_url=1;}
  2348.     $select "SELECT * FROM $t_settings WHERE variable = '$var";
  2349.     if(!empty($subvar))
  2350.     {
  2351.         $subvar Database::escape_string($subvar);
  2352.         $select .= " AND subkey = '$subvar'";
  2353.     }
  2354.     if(!empty($cat))
  2355.     {
  2356.         $cat Database::escape_string($cat);
  2357.         $select .= " AND category = '$cat'";
  2358.     }
  2359.     if($access_url 1)
  2360.     {
  2361.         $select .= " AND access_url = $access_url";
  2362.     }
  2363.     else
  2364.     {
  2365.         $select .= " AND access_url = 1 ";
  2366.     }
  2367.     $res api_sql_query($select,__FILE__,__LINE__);
  2368.     if(Database::num_rows($res)>0)
  2369.     //found item for this access_url
  2370.         $row Database::fetch_array($res);
  2371.         $update "UPDATE $t_settings SET selected_value = '$value' WHERE id = ".$row['id'];
  2372.         $res api_sql_query($update,__FILE__,__LINE__);     
  2373.     }
  2374.     else
  2375.     //item not found for this access_url, we have to check if the whole thing is missing 
  2376.       //(in which case we ignore the insert) or if there *is* a record but just for access_url=1
  2377.         $select "SELECT * FROM $t_settings WHERE variable = '$var' AND access_url = 1 ";
  2378.         if(!empty($subvar))
  2379.         {
  2380.             $select .= " AND subkey = '$subvar'";
  2381.         }
  2382.         if(!empty($cat))
  2383.         {
  2384.             $select .= " AND category = '$cat'";
  2385.         }
  2386.         $res api_sql_query($select,__FILE__,__LINE__);
  2387.         if(Database::num_rows($select)>0)
  2388.         //we have a setting for access_url 1, but none for the current one, so create one
  2389.             $row Database::fetch_array($res);
  2390.             $insert "INSERT INTO $t_settings .
  2391.                     "(variable,subkey," .
  2392.                     "type,category," .
  2393.                     "selected_value,title," .
  2394.                     "comment,scope," .
  2395.                     "subkeytext,access_url)" .
  2396.                     " VALUES " .
  2397.                     "('".$row['variable']."',".(!empty($row['subkey'])?"'".$row['subkey']."'":"NULL")."," .
  2398.                     "'".$row['type']."','".$row['category']."'," .
  2399.                     "'$value','".$row['title']."'," .
  2400.                     "".(!empty($row['comment'])?"'".$row['comment']."'":"NULL").",'".(!empty($row['scope'])?"'".$row['scope']."'":"NULL")."'," .
  2401.                     "'".(!empty($row['subkeytext'])?"'".$row['subkeytext']."'":"NULL")."',$access_url)";
  2402.             $res api_sql_query($insert,__FILE__,__LINE__);
  2403.         }
  2404.         else
  2405.         // this setting does not exist
  2406.             error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all',0);
  2407.         }
  2408.     }
  2409. }
  2410. /**
  2411.  * Sets a whole category of settings to one specific value
  2412.  * @param    string    Category
  2413.  * @param    string     Value
  2414.  * @param    int        Access URL. Optional. Defaults to 1
  2415.  */
  2416. function api_set_settings_category($category,$value=null,$access_url=1)
  2417. {
  2418.     if(empty($category)){return false;}
  2419.     $category Database::escape_string($category);
  2420.     $access_url = (int) $access_url;
  2421.     if(empty($access_url)){$access_url=1;}
  2422.     if(isset($value))
  2423.     {
  2424.         $value Database::escape_string($value);
  2425.         $sql "UPDATE $t_s SET selected_value = '$value' WHERE category = '$category' AND access_url = $access_url";
  2426.         $res api_sql_query($sql,__FILE__,__LINE__)
  2427.         if($res === false)return false}
  2428.         return true;
  2429.     }
  2430.     else
  2431.     {
  2432.         $sql "UPDATE $t_s SET selected_value = NULL WHERE category = '$category' AND access_url = $access_url";
  2433.         $res api_sql_query($sql,__FILE__,__LINE__)
  2434.         if($res === false)return false}
  2435.         return true;        
  2436.     }
  2437. }
  2438. /**
  2439.  * Get all available access urls in an array (as in the database)
  2440.  * @return    array    Array of database records
  2441.  */
  2442. function api_get_access_urls($from=0,$to=1000000,$order='url',$direction='ASC')
  2443. {
  2444.     $result array();
  2445.     $from = (int) $from;
  2446.     $to = (int) $to;
  2447.     $order Database::escape_string($order);
  2448.     $direction Database::escape_string($direction);
  2449.     $sql "SELECT id, url, description, active, created_by, tms FROM $t_au ORDER BY $order $direction LIMIT $to OFFSET $from";
  2450.     $res api_sql_query($sql,__FILE__,__LINE__);
  2451.     if($res !==false)
  2452.     {
  2453.         $result api_store_result($res);
  2454.     }
  2455.     return $result;
  2456. }
  2457. /**
  2458.  * Adds an access URL into the database
  2459.  * @param    string    URL
  2460.  * @param    string    Description
  2461.  * @param    int        Active (1= active, 0=disabled)
  2462.  * @return    int        The new database id, or the existing database id if this url already exists
  2463.  */
  2464. function api_add_access_url($u,$d='',$a=1)
  2465. {
  2466.     $u Database::escape_string($u);
  2467.     $d Database::escape_string($d);
  2468.     $a = (int) $a;
  2469.     $sql "SELECT * FROM $t_au WHERE url LIKE '$u'";
  2470.     $res api_sql_query($sql,__FILE__,__LINE__);
  2471.     if($res === false)
  2472.     {
  2473.         //problem querying the database - return false
  2474.         return false;
  2475.     }
  2476.     else
  2477.     {
  2478.         if(Database::num_rows($res)>0)
  2479.         {
  2480.             return Database::result($res,0,'id');
  2481.         }
  2482.         else
  2483.         {
  2484.             $ui api_get_user_id();
  2485.             $time 
  2486.             $sql "INSERT INTO $t_au (url,description,active,created_by,tms)"
  2487.                     ." VALUES ('$u','$d',$a,$ui,'')";
  2488.             $res api_sql_query($sql,__FILE__,__LINE__);
  2489.             if($res === false){return false;}
  2490.             return Database::insert_id();
  2491.         }
  2492.     }
  2493. }
  2494. /**
  2495.  * Gets all the current settings for a specific access url
  2496.  * @param    string    The category, if any, that we want to get
  2497.  * @param    string    Whether we want a simple list (display a catgeory) or a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
  2498.  * @param    int        Access URL's ID. Optional. Uses 1 by default, which is the unique URL
  2499.  * @return    array    Array of database results for the current settings of the current access URL
  2500.  */
  2501. function api_get_settings($cat=null,$ordering='list',$access_url=1)
  2502. {
  2503.     $results array();
  2504.     $access_url = (int) $access_url;
  2505.     if(empty($access_url)){$access_url=1;}
  2506.     $sql "SELECT id, variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable " .
  2507.             " FROM $t_cs WHERE access_url = $access_url ";
  2508.     if(!empty($cat))
  2509.     {
  2510.         $cat Database::escape_string($cat);
  2511.         $sql .= " AND category='$cat";
  2512.     }
  2513.     if($ordering=='group')
  2514.     {
  2515.         $sql .= " GROUP BY variable ORDER BY id ASC";
  2516.     }
  2517.     else
  2518.     {
  2519.         $sql .= " ORDER BY 1,2 ASC";
  2520.     }
  2521.     $res api_sql_query($sql,__FILE__,__LINE__);
  2522.     if($res === false){return $results;}
  2523.     $results api_store_result($res);
  2524.     return $results;
  2525. }
  2526. /**
  2527.  * Gets the distinct settings categories
  2528.  * @param    array    Array of strings giving the categories we want to exclude
  2529.  * @param    int        Access URL. Optional. Defaults to 1
  2530.  * @return    array    A list of categories
  2531.  */
  2532. function api_get_settings_categories($exceptions=array(),$access_url=1)
  2533. {
  2534.     $result array();
  2535.     $access_url = (int) $access_url;
  2536.     $list "'".implode("','",$exceptions)."'";
  2537.     $sql "SELECT DISTINCT category FROM $t_cs";
  2538.     if($list != "'',''" and $list != "''" and !empty($list))
  2539.     {
  2540.         $sql .= " WHERE category NOT IN ($list)"
  2541.     }
  2542.     $r api_sql_query($sql,__FILE__,__LINE__);
  2543.     if($r === false)
  2544.     {
  2545.         return $result;
  2546.     }
  2547.     $result api_store_result($r);
  2548.     return $result;
  2549. }
  2550. /**
  2551.  * Delete setting
  2552.  * @param    string    Variable
  2553.  * @param    string    Subkey
  2554.  * @param    int        Access URL
  2555.  * @return    boolean    False on failure, true on success
  2556.  */
  2557. function api_delete_setting($v,$s=NULL,$a=1)
  2558. {
  2559.     if(empty($v)){return false;}
  2560.     $v Database::escape_string($v);
  2561.     $a = (int) $a;
  2562.     if(empty($a)){$a=1;}
  2563.     if(!empty($s))
  2564.     {
  2565.         $s Database::escape_string($s);
  2566.         $sql "DELETE FROM $t_cs WHERE variable = '$v' AND subkey = '$s' AND access_url = $a";
  2567.         $r api_sql_query($sql);
  2568.         return $r;
  2569.     }
  2570.     else
  2571.     {
  2572.         $sql "DELETE FROM $t_cs WHERE variable = '$v' AND access_url = $a";
  2573.         $r api_sql_query($sql);
  2574.         return $r;
  2575.     }
  2576. }
  2577. /**
  2578.  * Delete all the settings from one category
  2579.  * @param    string    Category
  2580.  * @param    int        Access URL
  2581.  * @return    boolean    False on failure, true on success
  2582.  */
  2583. function api_delete_category_settings($c,$a=1)
  2584. {
  2585.     if(empty($c)){return false;}
  2586.     $c Database::escape_string($c);
  2587.     $a = (int) $a;
  2588.     if(empty($a)){$a=1;}
  2589.     $sql "DELETE FROM $t_cs WHERE category = '$c' AND access_url = $a";
  2590.     $r api_sql_query($sql);
  2591.     return $r;
  2592. }
  2593. /**
  2594.  * Sets a platform configuration setting to a given value
  2595.  * @param    string    The value we want to record
  2596.  * @param    string    The variable name we want to insert
  2597.  * @param    string    The subkey for the variable we want to insert
  2598.  * @param    string    The type for the variable we want to insert
  2599.  * @param    string    The category for the variable we want to insert
  2600.  * @param    string    The title
  2601.  * @param    string    The comment
  2602.  * @param    string    The scope
  2603.  * @param    string    The subkey text
  2604.  * @param    int        The access_url for which this parameter is valid
  2605.  * @param    int        The changeability of this setting for non-master urls
  2606.  * @return    boolean    true on success, false on failure
  2607.  */
  2608. function api_add_setting($val,$var,$sk=null,$type='textfield',$c=null,$title='',$com='',$sc=null,$skt=null,$a=1,$v=0)
  2609. {
  2610.     if(empty($varor !isset($val)) return false}
  2611.     $var Database::escape_string($var);
  2612.     $val Database::escape_string($val);
  2613.     $a = (int) $a;
  2614.     if(empty($a)){$a=1;}
  2615.     //check if this variable doesn't exist already
  2616.     $select "SELECT * FROM $t_settings WHERE variable = '$var";
  2617.     if(!empty($sk))
  2618.     {
  2619.         $sk Database::escape_string($sk);
  2620.         $select .= " AND subkey = '$sk'";
  2621.     }
  2622.     if($a 1)
  2623.     {
  2624.         $select .= " AND access_url = $a";
  2625.     }
  2626.     else
  2627.     {
  2628.         $select .= " AND access_url = 1 ";
  2629.     }
  2630.     $res api_sql_query($select,__FILE__,__LINE__);
  2631.     if(Database::num_rows($res)>0)
  2632.     //found item for this access_url
  2633.         $row Database::fetch_array($res);
  2634.         return $row['id'];     
  2635.     }
  2636.     else
  2637.     //item not found for this access_url, we have to check if the whole thing is missing 
  2638.       //(in which case we ignore the insert) or if there *is* a record but just for access_url=1        
  2639.         $insert "INSERT INTO $t_settings .
  2640.                 "(variable,selected_value," .
  2641.                 "type,category," .
  2642.                 "subkey,title," .
  2643.                 "comment,scope," .
  2644.                 "subkeytext,access_url,access_url_changeable)" .
  2645.                 " VALUES ('$var','$val',";
  2646.         if(isset($type))
  2647.         {
  2648.             $type Database::escape_string($type);
  2649.             $insert .= "'$type',";
  2650.         }
  2651.         else
  2652.         {
  2653.             $insert .= "NULL,";
  2654.         }
  2655.         if(isset($c)) //category
  2656.         {
  2657.             $c Database::escape_string($c);
  2658.             $insert .= "'$c',";
  2659.         }
  2660.         else
  2661.         {
  2662.             $insert .= "NULL,";
  2663.         }
  2664.         if(isset($sk)) //subkey
  2665.         {
  2666.             $sk Database::escape_string($sk);
  2667.             $insert .= "'$sk',";
  2668.         }
  2669.         else
  2670.         {
  2671.             $insert .= "NULL,";
  2672.         }
  2673.         if(isset($title)) //title
  2674.         {
  2675.             $title Database::escape_string($title);
  2676.             $insert .= "'$title',";
  2677.         }
  2678.         else
  2679.         {
  2680.             $insert .= "NULL,";
  2681.         }
  2682.         if(isset($com)) //comment
  2683.         {
  2684.             $com Database::escape_string($com);
  2685.             $insert .= "'$com',";
  2686.         }
  2687.         else
  2688.         {
  2689.             $insert .= "NULL,";
  2690.         }
  2691.         if(isset($sc)) //scope
  2692.         {
  2693.             $sc Database::escape_string($sc);
  2694.             $insert .= "'$sc',";
  2695.         }
  2696.         else
  2697.         {
  2698.             $insert .= "NULL,";
  2699.         }
  2700.         if(isset($skt)) //subkey text
  2701.         {
  2702.             $skt Database::escape_string($skt);
  2703.             $insert .= "'$skt',";
  2704.         }
  2705.         else
  2706.         {
  2707.             $insert .= "NULL,";
  2708.         }
  2709.         $insert .= "$a,$v)";
  2710.         $res api_sql_query($insert,__FILE__,__LINE__);
  2711.         return $res;
  2712.     }
  2713. }
  2714. ?>

Documentation generated on Thu, 12 Jun 2008 14:04:38 -0500 by phpDocumentor 1.4.1