main_api.lib.php 68 KB

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