main_api.lib.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. <?php
  2. /*
  3. ===============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2005 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, 44 rue des palais, 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. //COURSE VISIBILITY CONSTANTS
  46. /** only visible for course admin */
  47. define('COURSE_VISIBILITY_CLOSED', 0);
  48. /** only visible for users registered in the course*/
  49. define('COURSE_VISIBILITY_REGISTERED', 1);
  50. /** open for all registered users on the platform */
  51. define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
  52. /** open for the whole world */
  53. define('COURSE_VISIBILITY_OPEN_WORLD', 3);
  54. define('SUBSCRIBE_ALLOWED', 1);
  55. define('SUBSCRIBE_NOT_ALLOWED', 0);
  56. define('UNSUBSCRIBE_ALLOWED', 1);
  57. define('UNSUBSCRIBE_NOT_ALLOWED', 0);
  58. //CONSTANTS FOR api_get_path FUNCTION
  59. define('WEB_PATH', 'WEB_PATH');
  60. define('SYS_PATH', 'SYS_PATH');
  61. define('REL_PATH', 'REL_PATH');
  62. define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
  63. define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
  64. define('REL_COURSE_PATH', 'REL_COURSE_PATH');
  65. define('REL_CLARO_PATH', 'REL_CLARO_PATH');
  66. define('WEB_CODE_PATH', 'WEB_CODE_PATH');
  67. define('SYS_CODE_PATH', 'SYS_CODE_PATH');
  68. define('SYS_LANG_PATH', 'SYS_LANG_PATH');
  69. define('WEB_IMG_PATH', 'WEB_IMG_PATH');
  70. define('WEB_CSS_PATH', 'WEB_CSS_PATH');
  71. define('GARBAGE_PATH', 'GARBAGE_PATH');
  72. define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
  73. define('PLUGIN_PATH', 'PLUGIN_PATH');
  74. define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
  75. define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
  76. define('INCLUDE_PATH', 'INCLUDE_PATH');
  77. define('LIBRARY_PATH', 'LIBRARY_PATH');
  78. define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
  79. //CONSTANTS defining all tools, using the english version
  80. define('TOOL_DOCUMENT', 'document');
  81. define('TOOL_CALENDAR_EVENT', 'calendar_event');
  82. define('TOOL_LINK', 'link');
  83. define('TOOL_COURSE_DESCRIPTION', 'course_description');
  84. define('TOOL_LEARNPATH', 'learnpath');
  85. define('TOOL_ANNOUNCEMENT', 'announcement');
  86. define('TOOL_FORUM', 'forum');
  87. define('TOOL_THREAD', 'thread');
  88. define('TOOL_POST', 'post');
  89. define('TOOL_DROPBOX', 'dropbox');
  90. define('TOOL_QUIZ', 'quiz');
  91. define('TOOL_USER', 'user');
  92. define('TOOL_GROUP', 'group');
  93. define('TOOL_BLOGS', 'blog_management'); // Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be)
  94. define('TOOL_CHAT', 'chat');
  95. define('TOOL_CONFERENCE', 'conference');
  96. define('TOOL_STUDENTPUBLICATION', 'student_publication');
  97. define('TOOL_TRACKING', 'tracking');
  98. define('TOOL_HOMEPAGE_LINK', 'homepage_link');
  99. define('TOOL_COURSE_SETTING', 'course_setting');
  100. define('TOOL_BACKUP', 'backup');
  101. define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
  102. define('TOOL_RECYCLE_COURSE', 'recycle_course');
  103. define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
  104. define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
  105. define('TOOL_UPLOAD','file_upload');
  106. define('TOOL_COURSE_MAINTENANCE','course_maintenance');
  107. define('TOOL_VISIO','visio');
  108. // CONSTANTS defining dokeos sections
  109. define('SECTION_CAMPUS', 'mycampus');
  110. define('SECTION_COURSES', 'mycourses');
  111. define('SECTION_MYPROFILE', 'myprofile');
  112. define('SECTION_MYAGENDA', 'myagenda');
  113. define('SECTION_COURSE_ADMIN', 'course_admin');
  114. define('SECTION_PLATFORM_ADMIN', 'platform_admin');
  115. // CONSTANT name for local authentication source
  116. define('PLATFORM_AUTH_SOURCE', 'platform');
  117. /*
  118. ==============================================================================
  119. PROTECTION FUNCTIONS
  120. use these to protect your scripts
  121. ==============================================================================
  122. */
  123. /**
  124. * Function used to protect a course script.
  125. * The function blocks access when
  126. * - there is no $_SESSION["_course"] defined; or
  127. * - $is_allowed_in_course is set to false (this depends on the course
  128. * visibility and user status).
  129. *
  130. * This is only the first proposal, test and improve!
  131. *
  132. * @todo replace global variable
  133. * @author Roan Embrechts
  134. */
  135. function api_protect_course_script()
  136. {
  137. global $is_allowed_in_course;
  138. if (!isset ($_SESSION["_course"]) || !$is_allowed_in_course)
  139. {
  140. include (api_get_path(INCLUDE_PATH)."header.inc.php");
  141. api_not_allowed();
  142. }
  143. }
  144. /**
  145. * Function used to protect an admin script.
  146. * The function blocks access when the user has no platform admin rights.
  147. * This is only the first proposal, test and improve!
  148. *
  149. * @author Roan Embrechts
  150. */
  151. function api_protect_admin_script()
  152. {
  153. if (!api_is_platform_admin())
  154. {
  155. include (api_get_path(INCLUDE_PATH)."header.inc.php");
  156. api_not_allowed();
  157. }
  158. }
  159. /**
  160. * Function used to prevent anonymous users from accessing a script.
  161. *
  162. * @author Roan Embrechts
  163. */
  164. function api_block_anonymous_users()
  165. {
  166. global $_user;
  167. if (!(isset ($_user['user_id']) && $_user['user_id']))
  168. {
  169. include (api_get_path(INCLUDE_PATH)."header.inc.php");
  170. api_not_allowed();
  171. }
  172. }
  173. /*
  174. ==============================================================================
  175. ACCESSOR FUNCTIONS
  176. don't access kernel variables directly,
  177. use these functions instead
  178. ==============================================================================
  179. */
  180. /**
  181. * @return an array with the navigator name and version
  182. */
  183. function api_get_navigator()
  184. {
  185. $navigator = 'Unknown';
  186. $version = 0;
  187. if (strstr($_SERVER['HTTP_USER_AGENT'], 'Opera'))
  188. {
  189. $navigator = 'Opera';
  190. list (, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
  191. }
  192. elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  193. {
  194. $navigator = 'Internet Explorer';
  195. list (, $version) = explode('MSIE', $_SERVER['HTTP_USER_AGENT']);
  196. }
  197. elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'Gecko'))
  198. {
  199. $navigator = 'Mozilla';
  200. list (, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
  201. }
  202. elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'Netscape'))
  203. {
  204. $navigator = 'Netscape';
  205. list (, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
  206. }
  207. $version = doubleval($version);
  208. if (!strstr($version, '.'))
  209. {
  210. $version = number_format(doubleval($version), 1);
  211. }
  212. return array ('name' => $navigator, 'version' => $version);
  213. }
  214. /**
  215. * @return True if user selfregistration is allowed, false otherwise.
  216. */
  217. function api_is_self_registration_allowed()
  218. {
  219. return $GLOBALS["allowSelfReg"];
  220. }
  221. /**
  222. * Returns a full path to a certain Dokeos area, which you specify
  223. * through a parameter.
  224. *
  225. * See $_configuration['course_folder'] in the configuration.php
  226. * to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  227. *
  228. * @param one of the following constants:
  229. * WEB_PATH, SYS_PATH, REL_PATH, WEB_COURSE_PATH, SYS_COURSE_PATH,
  230. * REL_COURSE_PATH, REL_CLARO_PATH, WEB_CODE_PATH, SYS_CODE_PATH,
  231. * SYS_LANG_PATH, WEB_IMG_PATH, GARBAGE_PATH, PLUGIN_PATH, SYS_ARCHIVE_PATH,
  232. * INCLUDE_PATH, LIBRARY_PATH, CONFIGURATION_PATH
  233. *
  234. * @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
  235. * The other configuration paramaters have not been changed.
  236. * The different api_get_paths will give
  237. * WEB_PATH http://www.mydokeos.com
  238. * SYS_PATH /var/www/
  239. * REL_PATH dokeos/
  240. * WEB_COURSE_PATH http://www.mydokeos.com/courses/
  241. * SYS_COURSE_PATH /var/www/dokeos/courses/
  242. * REL_COURSE_PATH
  243. * REL_CLARO_PATH
  244. * WEB_CODE_PATH
  245. * SYS_CODE_PATH
  246. * SYS_LANG_PATH
  247. * WEB_IMG_PATH
  248. * GARBAGE_PATH
  249. * PLUGIN_PATH
  250. * SYS_ARCHIVE_PATH
  251. * INCLUDE_PATH
  252. * LIBRARY_PATH
  253. * CONFIGURATION_PATH
  254. */
  255. function api_get_path($path_type)
  256. {
  257. global $_configuration;
  258. switch ($path_type)
  259. {
  260. case WEB_PATH :
  261. // example: http://www.mydokeos.com
  262. return $_configuration['root_web'];
  263. break;
  264. case SYS_PATH :
  265. // example: /var/www/
  266. return $_configuration['root_sys'];
  267. break;
  268. case REL_PATH :
  269. // example: dokeos/
  270. if (substr($_configuration['url_append'], -1) === '/')
  271. {
  272. return $_configuration['url_append'];
  273. }
  274. else
  275. {
  276. return $_configuration['url_append'].'/';
  277. }
  278. break;
  279. case WEB_COURSE_PATH :
  280. // example: http://www.mydokeos.com/courses/
  281. return $_configuration['root_web'].$_configuration['course_folder'];
  282. break;
  283. case SYS_COURSE_PATH :
  284. // example: /var/www/dokeos/courses/
  285. return $_configuration['root_sys'].$_configuration['course_folder'];
  286. break;
  287. case REL_COURSE_PATH :
  288. return api_get_path(REL_PATH).$GLOBALS['coursesRepositoryAppend'];
  289. break;
  290. case REL_CLARO_PATH :
  291. return api_get_path(REL_PATH).$GLOBALS['clarolineRepositoryAppend'];
  292. break;
  293. case WEB_CODE_PATH :
  294. return $GLOBALS['clarolineRepositoryWeb'];
  295. break;
  296. case SYS_CODE_PATH :
  297. return $GLOBALS['clarolineRepositorySys'];
  298. break;
  299. case SYS_LANG_PATH :
  300. return api_get_path(SYS_CODE_PATH).'lang/';
  301. break;
  302. case WEB_IMG_PATH :
  303. return api_get_path(WEB_CODE_PATH).'img/';
  304. break;
  305. case GARBAGE_PATH :
  306. return $GLOBALS['garbageRepositorySys'];
  307. break;
  308. case SYS_PLUGIN_PATH :
  309. return api_get_path(SYS_PATH).'plugin/';
  310. break;
  311. case WEB_PLUGIN_PATH :
  312. return api_get_path(WEB_PATH).'plugin/';
  313. break;
  314. case SYS_ARCHIVE_PATH :
  315. return api_get_path(SYS_PATH).'archive/';
  316. break;
  317. case INCLUDE_PATH :
  318. return str_replace('\\', '/', $GLOBALS['includePath']).'/';
  319. break;
  320. case LIBRARY_PATH :
  321. return api_get_path(INCLUDE_PATH).'lib/';
  322. break;
  323. case WEB_LIBRARY_PATH :
  324. return api_get_path(WEB_CODE_PATH).'inc/lib/';
  325. break;
  326. case CONFIGURATION_PATH :
  327. return api_get_path(INCLUDE_PATH).'conf/';
  328. break;
  329. default :
  330. return;
  331. break;
  332. }
  333. }
  334. /**
  335. * This function returns the id of the user which is stored in the $_user array.
  336. *
  337. * @example The function can be used to check if a user is logged in
  338. * if (api_get_user_id())
  339. * @return integer the id of the current user
  340. */
  341. function api_get_user_id()
  342. {
  343. return $GLOBALS['_user']['user_id'];
  344. }
  345. /**
  346. * @param $user_id (integer): the id of the user
  347. * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  348. * @author Patrick Cool <patrick.cool@UGent.be>
  349. * @version 21 September 2004
  350. * @desc find all the information about a user. If no paramater is passed you find all the information about the current user.
  351. */
  352. function api_get_user_info($user_id = '')
  353. {
  354. global $tbl_user;
  355. if ($user_id == '')
  356. {
  357. return $GLOBALS["_user"];
  358. }
  359. else
  360. {
  361. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id=$user_id";
  362. $result = api_sql_query($sql, __FILE__, __LINE__);
  363. $result_array = mysql_fetch_array($result);
  364. // this is done so that it returns the same array-index-names
  365. // ideally the names of the fields of the user table are renamed so that they match $_user (or vice versa)
  366. // $_user should also contain every field of the user table (except password maybe). This would make the
  367. // following lines obsolete (and the code cleaner and slimmer !!!
  368. $user_info['firstName'] = $result_array['firstname'];
  369. $user_info['lastName'] = $result_array['lastname'];
  370. $user_info['mail'] = $result_array['email'];
  371. $user_info['picture_uri'] = $result_array['picture_uri'];
  372. $user_info['user_id'] = $result_array['user_id'];
  373. $user_info['official_code'] = $result_array['official_code'];
  374. $user_info['status'] = $result_array['status'];
  375. return $user_info;
  376. }
  377. }
  378. /**
  379. * Returns the current course id (integer)
  380. */
  381. function api_get_course_id()
  382. {
  383. return $GLOBALS["_cid"];
  384. }
  385. /**
  386. * Returns the current course directory
  387. *
  388. * This function relies on api_get_course_info()
  389. * @return string The directory where the course is located inside the Dokeos "courses" directory
  390. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  391. */
  392. function api_get_course_path()
  393. {
  394. $info = api_get_course_info();
  395. return $info['path'];
  396. }
  397. /**
  398. * Gets a course setting from the current course_setting table. Try always using integer values.
  399. * @param string The name of the setting we want from the table
  400. * @return mixed The value of that setting in that table. Return -1 if not found.
  401. */
  402. function api_get_course_setting($setting_name)
  403. {
  404. $table = Database::get_course_table(COURSE_SETTING_TABLE);
  405. $setting_name = mysql_real_escape_string($setting_name);
  406. $sql = "SELECT * FROM $table WHERE variable = '$setting_name'";
  407. $res = api_sql_query($sql,__FILE__,__LINE__);
  408. if(Database::num_rows($res)==1){
  409. $row = Database::fetch_array($res);
  410. return $row['value'];
  411. }
  412. return -1;
  413. }
  414. /**
  415. * Returns the cidreq parameter name + current course id
  416. */
  417. function api_get_cidreq()
  418. {
  419. if (!empty ($GLOBALS["_cid"]))
  420. {
  421. return 'cidReq='.$GLOBALS["_cid"];
  422. }
  423. return '';
  424. }
  425. /**
  426. * Returns the current course info array.
  427. * Note: this array is only defined if the user is inside a course.
  428. * Array elements:
  429. * ['name']
  430. * ['official_code']
  431. * ['sysCode']
  432. * ['path']
  433. * ['dbName']
  434. * ['dbNameGlu']
  435. * ['titular']
  436. * ['language']
  437. * ['extLink']['url' ]
  438. * ['extLink']['name']
  439. * ['categoryCode']
  440. * ['categoryName']
  441. *
  442. * @todo same behaviour as api_get_user_info so that api_get_course_id becomes absolete too
  443. */
  444. function api_get_course_info()
  445. {
  446. global $_course;
  447. return $_course;
  448. }
  449. /*
  450. ==============================================================================
  451. DATABASE QUERY MANAGEMENT
  452. ==============================================================================
  453. */
  454. /**
  455. * Executes an SQL query
  456. * You have to use addslashes() on each value that you want to record into the database
  457. *
  458. * @author Olivier Brouckaert
  459. * @param string $query - SQL query
  460. * @param string $file - optional, the file path and name of the error (__FILE__)
  461. * @param string $line - optional, the line of the error (__LINE__)
  462. * @return resource - the return value of the query
  463. */
  464. function api_sql_query($query, $file = '', $line = 0)
  465. {
  466. $result = mysql_query($query);
  467. if ($line && !$result)
  468. {
  469. if (api_get_setting('server_type') !== 'test')
  470. {
  471. @ mysql_close();
  472. die('SQL error in file <b>'.$file.'</b> at line <b>'.$line.'</b>');
  473. }
  474. else
  475. {
  476. $info = '<pre>';
  477. $info .= '<b>MYSQL ERROR :</b><br/> ';
  478. $info .= mysql_error();
  479. $info .= '<br/>';
  480. $info .= '<b>QUERY :</b><br/> ';
  481. $info .= $query;
  482. $info .= '<br/>';
  483. $info .= '<b>FILE :</b><br/> ';
  484. $info .= ($file == '' ? ' unknown ' : $file);
  485. $info .= '<br/>';
  486. $info .= '<b>LINE :</b><br/> ';
  487. $info .= ($line == 0 ? ' unknown ' : $line);
  488. $info .= '</pre>';
  489. @ mysql_close();
  490. die($info);
  491. }
  492. }
  493. return $result;
  494. }
  495. /**
  496. * Store the result of a query into an array
  497. *
  498. * @author Olivier Brouckaert
  499. * @param resource $result - the return value of the query
  500. * @return array - the value returned by the query
  501. */
  502. function api_store_result($result)
  503. {
  504. $tab = array ();
  505. while ($row = mysql_fetch_array($result))
  506. {
  507. $tab[] = $row;
  508. }
  509. return $tab;
  510. }
  511. /*
  512. ==============================================================================
  513. SESSION MANAGEMENT
  514. ==============================================================================
  515. */
  516. /**
  517. * start the dokeos session
  518. *
  519. * @author Olivier Brouckaert
  520. * @param string variable - the variable name to save into the session
  521. */
  522. function api_session_start($already_installed = true)
  523. {
  524. global $storeSessionInDb;
  525. if($already_installed){
  526. session_set_cookie_params(3600,api_get_path(REL_PATH));
  527. }
  528. if (is_null($storeSessionInDb))
  529. {
  530. $storeSessionInDb = false;
  531. }
  532. if ($storeSessionInDb && function_exists('session_set_save_handler'))
  533. {
  534. include_once (api_get_path(LIBRARY_PATH).'session_handler.class.php');
  535. $session_handler = new session_handler();
  536. @ 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'));
  537. }
  538. session_name('dk_sid');
  539. session_start();
  540. if ($already_installed)
  541. {
  542. if (empty ($_SESSION['checkDokeosURL']))
  543. {
  544. $_SESSION['checkDokeosURL'] = api_get_path(WEB_PATH);
  545. }
  546. elseif ($_SESSION['checkDokeosURL'] != api_get_path(WEB_PATH))
  547. {
  548. api_session_clear();
  549. }
  550. }
  551. }
  552. /**
  553. * save a variable into the session
  554. *
  555. * BUG: function works only with global variables
  556. *
  557. * @author Olivier Brouckaert
  558. * @param string variable - the variable name to save into the session
  559. */
  560. function api_session_register($variable)
  561. {
  562. global $$variable;
  563. session_register($variable);
  564. $_SESSION[$variable] = $$variable;
  565. }
  566. /**
  567. * Remove a variable from the session.
  568. *
  569. * @author Olivier Brouckaert
  570. * @param string variable - the variable name to remove from the session
  571. */
  572. function api_session_unregister($variable)
  573. {
  574. session_unregister($variable);
  575. $_SESSION[$variable] = null;
  576. unset ($GLOBALS[$variable]);
  577. }
  578. /**
  579. * Clear the session
  580. *
  581. * @author Olivier Brouckaert
  582. */
  583. function api_session_clear()
  584. {
  585. session_regenerate_id();
  586. session_unset();
  587. $_SESSION = array ();
  588. }
  589. /**
  590. * Destroy the session
  591. *
  592. * @author Olivier Brouckaert
  593. */
  594. function api_session_destroy()
  595. {
  596. session_unset();
  597. $_SESSION = array ();
  598. session_destroy();
  599. }
  600. /*
  601. ==============================================================================
  602. STRING MANAGEMENT
  603. ==============================================================================
  604. */
  605. function api_add_url_param($url, $param)
  606. {
  607. if (empty ($param))
  608. {
  609. return $url;
  610. }
  611. if (strstr($url, '?'))
  612. {
  613. if ($param[0] != '&')
  614. {
  615. $param = '&'.$param;
  616. }
  617. list (, $query_string) = explode('?', $url);
  618. $param_list1 = explode('&', $param);
  619. $param_list2 = explode('&', $query_string);
  620. $param_list1_keys = $param_list1_vals = array ();
  621. foreach ($param_list1 as $key => $enreg)
  622. {
  623. list ($param_list1_keys[$key], $param_list1_vals[$key]) = explode('=', $enreg);
  624. }
  625. $param_list1 = array ('keys' => $param_list1_keys, 'vals' => $param_list1_vals);
  626. foreach ($param_list2 as $enreg)
  627. {
  628. $enreg = explode('=', $enreg);
  629. $key = array_search($enreg[0], $param_list1['keys']);
  630. if (!is_null($key) && !is_bool($key))
  631. {
  632. $url = str_replace($enreg[0].'='.$enreg[1], $enreg[0].'='.$param_list1['vals'][$key], $url);
  633. $param = str_replace('&'.$enreg[0].'='.$param_list1['vals'][$key], '', $param);
  634. }
  635. }
  636. $url .= $param;
  637. }
  638. else
  639. {
  640. $url = $url.'?'.$param;
  641. }
  642. return $url;
  643. }
  644. /**
  645. * Returns a difficult to guess password.
  646. * @param int $length, the length of the password
  647. * @return string the generated password
  648. */
  649. function api_generate_password($length = 8)
  650. {
  651. $characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  652. if ($length < 2)
  653. {
  654. $length = 2;
  655. }
  656. $password = '';
  657. for ($i = 0; $i < $length; $i ++)
  658. {
  659. $password .= $characters[rand() % strlen($characters)];
  660. }
  661. return $password;
  662. }
  663. /**
  664. * Checks a password to see wether it is OK to use.
  665. * @param string $password
  666. * @return true if the password is acceptable, false otherwise
  667. */
  668. function api_check_password($password)
  669. {
  670. $lengthPass = strlen($password);
  671. if ($lengthPass < 5)
  672. {
  673. return false;
  674. }
  675. $passLower = strtolower($password);
  676. $cptLettres = $cptChiffres = 0;
  677. for ($i = 0; $i < $lengthPass; $i ++)
  678. {
  679. $codeCharCur = ord($passLower[$i]);
  680. if ($i && abs($codeCharCur - $codeCharPrev) <= 1)
  681. {
  682. $consecutif ++;
  683. if ($consecutif == 3)
  684. {
  685. return false;
  686. }
  687. }
  688. else
  689. {
  690. $consecutif = 1;
  691. }
  692. if ($codeCharCur >= 97 && $codeCharCur <= 122)
  693. {
  694. $cptLettres ++;
  695. }
  696. elseif ($codeCharCur >= 48 && $codeCharCur <= 57)
  697. {
  698. $cptChiffres ++;
  699. }
  700. else
  701. {
  702. return false;
  703. }
  704. $codeCharPrev = $codeCharCur;
  705. }
  706. return ($cptLettres >= 3 && $cptChiffres >= 2) ? true : false;
  707. }
  708. /**
  709. * truncates a string
  710. *
  711. * @author Brouckaert Olivier
  712. * @param string text - text to truncate
  713. * @param integer length - length of the truncated text
  714. * @param string endStr - suffix
  715. * @param boolean middle - if true, truncates on string middle
  716. */
  717. function api_trunc_str($text, $length = 30, $endStr = '...', $middle = false)
  718. {
  719. if (strlen($text) <= $length)
  720. {
  721. return $text;
  722. }
  723. if ($middle)
  724. {
  725. $text = rtrim(substr($text, 0, round($length / 2))).$endStr.ltrim(substr($text, -round($length / 2)));
  726. }
  727. else
  728. {
  729. $text = rtrim(substr($text, 0, $length)).$endStr;
  730. }
  731. return $text;
  732. }
  733. // deprecated, use api_trunc_str() instead
  734. function shorten($input, $length = 15)
  735. {
  736. $length = intval($length);
  737. if (!$length)
  738. {
  739. $length = 15;
  740. }
  741. return api_trunc_str($input, $length);
  742. }
  743. /**
  744. * handling simple and double apostrofe in order that strings be stored properly in database
  745. *
  746. * @author Denes Nagy
  747. * @param string variable - the variable to be revised
  748. */
  749. function domesticate($input)
  750. {
  751. $input = stripslashes($input);
  752. $input = str_replace("'", "''", $input);
  753. $input = str_replace('"', "''", $input);
  754. return ($input);
  755. }
  756. /*
  757. ==============================================================================
  758. FAILURE MANAGEMENT
  759. ==============================================================================
  760. */
  761. /*
  762. * The Failure Management module is here to compensate
  763. * the absence of an 'exception' device in PHP 4.
  764. */
  765. /**
  766. * $api_failureList - array containing all the failure recorded
  767. * in order of arrival.
  768. */
  769. $api_failureList = array ();
  770. /**
  771. * Fills a global array called $api_failureList
  772. * This array collects all the failure occuring during the script runs
  773. * The main purpose is allowing to manage the display messages externaly
  774. * from the functions or objects. This strengthens encupsalation principle
  775. *
  776. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  777. * @param string $failureType - the type of failure
  778. * @global array $api_failureList
  779. * @return bolean false to stay consistent with the main script
  780. */
  781. function api_set_failure($failureType)
  782. {
  783. global $api_failureList;
  784. $api_failureList[] = $failureType;
  785. return false;
  786. }
  787. /**
  788. * get the last failure stored in $api_failureList;
  789. *
  790. * @author Hugues Peeters <hugues.peeters@claroline.net>
  791. * @param void
  792. * @return string - the last failure stored
  793. */
  794. function api_get_last_failure()
  795. {
  796. global $api_failureList;
  797. return $api_failureList[count($api_failureList) - 1];
  798. }
  799. /**
  800. * collects and manage failures occuring during script execution
  801. * The main purpose is allowing to manage the display messages externaly
  802. * from functions or objects. This strengthens encupsalation principle
  803. *
  804. * @author Hugues Peeters <hugues.peeters@claroline.net>
  805. * @package dokeos.library
  806. */
  807. class api_failure
  808. {
  809. /*
  810. * IMPLEMENTATION NOTE : For now the $api_failureList list is set to the
  811. * global scope, as PHP 4 is unable to manage static variable in class. But
  812. * this feature is awaited in PHP 5. The class is already written to minize
  813. * the change when static class variable will be possible. And the API won't
  814. * change.
  815. */
  816. var $api_failureList = array ();
  817. /**
  818. * Pile the last failure in the failure list
  819. *
  820. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  821. * @param string $failureType - the type of failure
  822. * @global array $api_failureList
  823. * @return bolean false to stay consistent with the main script
  824. */
  825. function set_failure($failureType)
  826. {
  827. global $api_failureList;
  828. $api_failureList[] = $failureType;
  829. return false;
  830. }
  831. /**
  832. * get the last failure stored
  833. *
  834. * @author Hugues Peeters <hugues.peeters@claroline.net>
  835. * @param void
  836. * @return string - the last failure stored
  837. */
  838. function get_last_failure()
  839. {
  840. global $api_failureList;
  841. return $api_failureList[count($api_failureList) - 1];
  842. }
  843. }
  844. /*
  845. ==============================================================================
  846. CONFIGURATION SETTINGS
  847. ==============================================================================
  848. */
  849. /**
  850. * DEPRECATED, use api_get_setting instead
  851. */
  852. function get_setting($variable, $key = NULL)
  853. {
  854. global $_setting;
  855. return is_null($key) ? $_setting[$variable] : $_setting[$variable][$key];
  856. }
  857. /**
  858. * Returns the value of a setting from the web-adjustable admin config settings.
  859. *
  860. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  861. * if(api_get_setting("show_navigation_menu") == "true") //CORRECT
  862. * instead of
  863. * if(api_get_setting("show_navigation_menu") == true) //INCORRECT
  864. *
  865. * @author Rene Haentjens
  866. * @author Bart Mollet
  867. */
  868. function api_get_setting($variable, $key = NULL)
  869. {
  870. global $_setting;
  871. return is_null($key) ? $_setting[$variable] : $_setting[$variable][$key];
  872. }
  873. /*
  874. ==============================================================================
  875. LANGUAGE SUPPORT
  876. ==============================================================================
  877. */
  878. /**
  879. * Whenever the server type in the Dokeos Config settings is
  880. * set to test/development server you will get an indication that a language variable
  881. * is not translated and a link to a suggestions form of DLTT.
  882. *
  883. * @return language variable '$lang'.$variable or language variable $variable.
  884. *
  885. * @author Roan Embrechts
  886. * @author Patrick Cool
  887. */
  888. function get_lang($variable, $notrans = 'DLTT')
  889. {
  890. if (api_get_setting('server_type') != 'test')
  891. {
  892. $lvv = isset ($GLOBALS['lang'.$variable]) ? $GLOBALS['lang'.$variable] : (isset ($GLOBALS[$variable]) ? $GLOBALS[$variable] : '[='.$variable.'=]');
  893. if (!is_string($lvv))
  894. return $lvv;
  895. return str_replace("\\'", "'", $lvv);
  896. }
  897. if (!is_string($variable))
  898. return '[=get_lang(?)=]';
  899. global $language_interface, $langFile;
  900. //language file specified in tool
  901. if (isset ($langFile))
  902. {
  903. if (!is_array($langFile))
  904. {
  905. include (api_get_path(SYS_CODE_PATH)."lang/".$language_interface."/".$langFile.".inc.php");
  906. }
  907. else
  908. {
  909. foreach ($langFile as $index => $language_file)
  910. {
  911. include (api_get_path(SYS_CODE_PATH)."lang/".$language_interface."/".$language_file.".inc.php");
  912. }
  913. }
  914. }
  915. //general language variables
  916. include (api_get_path(SYS_CODE_PATH)."lang/".$language_interface."/trad4all.inc.php");
  917. //notification (what's new) language variables
  918. include (api_get_path(SYS_CODE_PATH)."lang/".$language_interface."/notification.inc.php");
  919. @ eval ('$langvar = $'.$variable.';'); // Note (RH): $$var doesn't work with arrays, see PHP doc
  920. if (isset ($langvar) && is_string($langvar) && strlen($langvar) > 0)
  921. {
  922. return str_replace("\\'", "'", $langvar);
  923. }
  924. @ eval ('$langvar = $lang'.$variable.';');
  925. if (isset ($langvar) && is_string($langvar) && strlen($langvar) > 0)
  926. {
  927. return str_replace("\\'", "'", $langvar);
  928. }
  929. if ($notrans != 'DLTT')
  930. return '[='.$variable.'=]';
  931. return '[='.$variable."=]<a href=\"http://www.dokeos.com/DLTT/suggestion.php?file=".$langFile.".inc.php&amp;variable=$".$variable."&amp;language=".$language_interface."\" style=\"color:#FF0000\"><strong>#</strong></a>";
  932. }
  933. /*
  934. ==============================================================================
  935. USER PERMISSIONS
  936. ==============================================================================
  937. */
  938. /**
  939. * Check if current user is a platform administrator
  940. * @return boolean True if the user has platform admin rights,
  941. * false otherwise.
  942. */
  943. function api_is_platform_admin()
  944. {
  945. return $_SESSION["is_platformAdmin"];
  946. }
  947. /**
  948. * Check if current user is allowed to create courses
  949. * @return boolean True if the user has course creation rights,
  950. * false otherwise.
  951. */
  952. function api_is_allowed_to_create_course()
  953. {
  954. return $_SESSION["is_allowedCreateCourse"];
  955. }
  956. /**
  957. * Check if the current user is a course administrator
  958. * @return boolean True if current user is a course administrator
  959. */
  960. function api_is_course_admin()
  961. {
  962. return $_SESSION["is_courseAdmin"];
  963. }
  964. /**
  965. * Check if the current user is a course or session coach
  966. * @return boolean True if current user is a course or session coach
  967. */
  968. function api_is_coach()
  969. {
  970. global $_user;
  971. global $sessionIsCoach;
  972. $sql = "SELECT DISTINCT id, name, date_start, date_end
  973. FROM session
  974. INNER JOIN session_rel_course
  975. ON session_rel_course.id_coach = '".mysql_real_escape_string($_user['user_id'])."'
  976. ORDER BY date_start, date_end, name";
  977. $result = api_sql_query($sql,__FILE__,__LINE__);
  978. $sessionIsCoach = api_store_result($result);
  979. $sql = "SELECT DISTINCT id, name, date_start, date_end
  980. FROM session
  981. WHERE session.id_coach = '".mysql_real_escape_string($_user['user_id'])."'
  982. ORDER BY date_start, date_end, name";
  983. $result = api_sql_query($sql,__FILE__,__LINE__);
  984. $sessionIsCoach = array_merge($sessionIsCoach , api_store_result($result));
  985. if(count($sessionIsCoach) > 0)
  986. {
  987. return true;
  988. }
  989. else
  990. {
  991. return false;
  992. }
  993. }
  994. /*
  995. ==============================================================================
  996. DISPLAY OPTIONS
  997. student view, title, message boxes,...
  998. ==============================================================================
  999. */
  1000. /**
  1001. * Displays the title of a tool.
  1002. * Normal use: parameter is a string:
  1003. * api_display_tool_title("My Tool")
  1004. *
  1005. * Optionally, there can be a subtitle below
  1006. * the normal title, and / or a supra title above the normal title.
  1007. *
  1008. * e.g. supra title:
  1009. * group
  1010. * GROUP PROPERTIES
  1011. *
  1012. * e.g. subtitle:
  1013. * AGENDA
  1014. * calender & events tool
  1015. *
  1016. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1017. * @param mixed $titleElement - it could either be a string or an array
  1018. * containing 'supraTitle', 'mainTitle',
  1019. * 'subTitle'
  1020. * @return void
  1021. */
  1022. function api_display_tool_title($titleElement)
  1023. {
  1024. if (is_string($titleElement))
  1025. {
  1026. $tit = $titleElement;
  1027. unset ($titleElement);
  1028. $titleElement['mainTitle'] = $tit;
  1029. }
  1030. echo '<h3>';
  1031. if ($titleElement['supraTitle'])
  1032. {
  1033. echo '<small>'.$titleElement['supraTitle'].'</small><br>';
  1034. }
  1035. if ($titleElement['mainTitle'])
  1036. {
  1037. echo $titleElement['mainTitle'];
  1038. }
  1039. if ($titleElement['subTitle'])
  1040. {
  1041. echo '<br><small>'.$titleElement['subTitle'].'</small>';
  1042. }
  1043. echo '</h3>';
  1044. }
  1045. /**
  1046. * Display options to switch between student view and course manager view
  1047. *
  1048. * Changes in version 1.2 (Patrick Cool)
  1049. * Student view switch now behaves as a real switch. It maintains its current state until the state
  1050. * is changed explicitly
  1051. *
  1052. * Changes in version 1.1 (Patrick Cool)
  1053. * student view now works correctly in subfolders of the document tool
  1054. * student view works correctly in the new links tool
  1055. *
  1056. * Example code for using this in your tools:
  1057. * //if ( $is_courseAdmin && is_student_view_enabled() )
  1058. * //{
  1059. * // display_tool_view_option($isStudentView);
  1060. * //}
  1061. * //and in later sections, use api_is_allowed_to_edit()
  1062. *
  1063. @author Roan Embrechts
  1064. * @author Patrick Cool
  1065. * @version 1.2
  1066. * @todo rewrite code so it is easier to understand
  1067. */
  1068. function api_display_tool_view_option()
  1069. {
  1070. $isStudentView = $_GET["isStudentView"];
  1071. // check if the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  1072. if (!strstr($_SERVER['REQUEST_URI'], "?"))
  1073. {
  1074. $sourceurl = $_SERVER['PHP_SELF']."?";
  1075. }
  1076. else
  1077. {
  1078. $sourceurl = $_SERVER['REQUEST_URI'];
  1079. }
  1080. if ($isStudentView == "true" and $_SESSION["studentview"])
  1081. {
  1082. // switching to studentview
  1083. // We are in studentview here
  1084. $_SESSION["studentview"] = "studentenview";
  1085. // we have to remove the isStudentView=true from the $sourceurl
  1086. $sourceurl = str_replace("&isStudentView=true", "", $sourceurl);
  1087. $sourceurl = str_replace("&isStudentView=false", "", $sourceurl);
  1088. $output_string .= "<a href='".$sourceurl."&amp;isStudentView=false'>".get_lang("CourseManagerview")."</a>";
  1089. }
  1090. elseif ($isStudentView == "false" and $_SESSION["studentview"])
  1091. {
  1092. //switching to teacherview
  1093. $sourceurl = str_replace("&isStudentView=true", "", $sourceurl);
  1094. $sourceurl = str_replace("&isStudentView=false", "", $sourceurl);
  1095. // We are in teacherview here
  1096. $_SESSION["studentview"] = "teacherview";
  1097. $output_string .= "<a href='".$sourceurl."&amp;isStudentView=true'>".get_lang("StudentView")."</a>";
  1098. }
  1099. elseif ($_SESSION["studentview"])
  1100. {
  1101. // no switching
  1102. if ($_SESSION["studentview"] == "teacherview")
  1103. {
  1104. $output_string .= "<a href='".$sourceurl."&amp;isStudentView=true'>".get_lang("StudentView")."</a>";
  1105. }
  1106. if ($_SESSION["studentview"] == "studentenview")
  1107. {
  1108. $sourceurl = str_replace("&isStudentView=true", "", $sourceurl);
  1109. $output_string .= " <a href='".$sourceurl."&amp;isStudentView=false'>".get_lang("CourseManagerview")."</a>";
  1110. }
  1111. }
  1112. elseif (!$_SESSION["studentview"])
  1113. {
  1114. // initialisation
  1115. // We are in teacherview here
  1116. $_SESSION["studentview"] = "teacherview";
  1117. $output_string .= "<a href='".$sourceurl."&amp;isStudentView=true'>".get_lang("StudentView")."</a>";
  1118. }
  1119. if (api_get_setting('show_student_view') == "true")
  1120. {
  1121. echo $output_string;
  1122. }
  1123. }
  1124. /**
  1125. * Displays the contents of an array in a messagebox.
  1126. * @param array $info_array An array with the messages to show
  1127. */
  1128. function api_display_array($info_array)
  1129. {
  1130. foreach ($info_array as $element)
  1131. {
  1132. $message .= $element."<br>";
  1133. }
  1134. Display :: display_normal_message($message);
  1135. }
  1136. /**
  1137. * Displays debug info
  1138. * @param string $debug_info The message to display
  1139. * @author Roan Embrechts
  1140. * @version 1.1, March 2004
  1141. */
  1142. function api_display_debug_info($debug_info)
  1143. {
  1144. $message = "<i>Debug info</i><br>";
  1145. $message .= $debug_info;
  1146. Display :: display_normal_message($message);
  1147. }
  1148. /**
  1149. * @deprecated, use api_is_allowed_to_edit() instead
  1150. */
  1151. function is_allowed_to_edit()
  1152. {
  1153. return api_is_allowed_to_edit();
  1154. }
  1155. /**
  1156. * Function that removes the need to directly use is_courseAdmin global in
  1157. * tool scripts. It returns true or false depending on the user's rights in
  1158. * this particular course.
  1159. *
  1160. * @author Roan Embrechts
  1161. * @author Patrick Cool
  1162. * @version 1.1, February 2004
  1163. * @return boolean, true: the user has the rights to edit, false: he does not
  1164. */
  1165. function api_is_allowed_to_edit()
  1166. {
  1167. $is_courseAdmin = api_is_course_admin();
  1168. if(is_student_view_enabled())
  1169. {
  1170. $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != "studentenview";
  1171. return $is_allowed;
  1172. }
  1173. else
  1174. return $is_courseAdmin;
  1175. }
  1176. /**
  1177. * this fun
  1178. * @param $tool the tool we are checking ifthe user has a certain permission
  1179. * @param $action the action we are checking (add, edit, delete, move, visibility)
  1180. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1181. * @version 1.0
  1182. */
  1183. function api_is_allowed($tool, $action, $task_id = 0)
  1184. {
  1185. global $_course;
  1186. global $_user;
  1187. if(api_is_course_admin())
  1188. return true;
  1189. //if(!$_SESSION['total_permissions'][$_course['code']] and $_course)
  1190. if($_course)
  1191. {
  1192. include_once(api_get_path(SYS_CODE_PATH) . 'permissions/permissions_functions.inc.php');
  1193. include_once(api_get_path(LIBRARY_PATH) . "/groupmanager.lib.php");
  1194. // getting the permissions of this user
  1195. if($task_id == 0)
  1196. {
  1197. $user_permissions = get_permissions('user', $_user['user_id']);
  1198. $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
  1199. }
  1200. // getting the permissions of the task
  1201. if($task_id != 0)
  1202. {
  1203. $task_permissions = get_permissions('task', $task_id);
  1204. /* !!! */$_SESSION['total_permissions'][$_course['code']] = $task_permissions;
  1205. }
  1206. //print_r($_SESSION['total_permissions']);
  1207. // getting the permissions of the groups of the user
  1208. $groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  1209. foreach($groups_of_user as $group)
  1210. $this_group_permissions = get_permissions('group', $group);
  1211. // getting the permissions of the courseroles of the user
  1212. $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
  1213. // getting the permissions of the platformroles of the user
  1214. //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  1215. // getting the permissions of the roles of the groups of the user
  1216. foreach($groups_of_user as $group)
  1217. $this_group_courserole_permissions = get_roles_permissions('group', $group);
  1218. // getting the permissions of the platformroles of the groups of the user
  1219. foreach($groups_of_user as $group)
  1220. $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  1221. }
  1222. // ifthe permissions are limited we have to map the extended ones to the limited ones
  1223. if(api_get_setting('permissions') == 'limited')
  1224. {
  1225. if($action == 'Visibility')
  1226. $action = 'Edit';
  1227. if($action == 'Move')
  1228. $action = 'Edit';
  1229. }
  1230. // the session that contains all the permissions already exists for this course
  1231. // so there is no need to requery everything.
  1232. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  1233. if(in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool]))
  1234. return true;
  1235. else
  1236. return false;
  1237. }
  1238. /**
  1239. * Displays message "You are not allowed here..." and exits the entire script.
  1240. *
  1241. * @author Roan Embrechts
  1242. * @author Yannick Warnier
  1243. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1244. *
  1245. * @version 1.0, February 2004
  1246. * @version dokeos 1.8, August 2006
  1247. */
  1248. function api_not_allowed()
  1249. {
  1250. $home_url = api_get_path(WEB_PATH);
  1251. include_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
  1252. $form = new FormValidator('formLogin');
  1253. $form->addElement('static',null,null,'Username');
  1254. $form->addElement('text','login','',array('size'=>15));
  1255. $form->addElement('static',null,null,'Password');
  1256. $form->addElement('password','password','',array('size'=>15));
  1257. $form->addElement('submit','submitAuth',get_lang('Ok'));
  1258. $test = $form->return_form();
  1259. Display :: display_error_message("<p>Either you are not allowed here or your session has expired.<br/><br/>Please try to login again using the following form: <br/>".$test);
  1260. echo '<div align="center">';
  1261. echo '</div>';
  1262. $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
  1263. Display::display_footer();
  1264. die();
  1265. }
  1266. /**
  1267. * Returns true if student view option is enabled, false otherwise. If it is
  1268. * true, tools can provide a student / course manager switch option. (see
  1269. * display_tool_view_option() )
  1270. * @return boolean True if student view option is enabled.
  1271. */
  1272. function is_student_view_enabled()
  1273. {
  1274. return api_get_setting('show_student_view') == 'true';
  1275. }
  1276. /*
  1277. ==============================================================================
  1278. WHAT'S NEW
  1279. functions for the what's new icons
  1280. in the user course list
  1281. ==============================================================================
  1282. */
  1283. /**
  1284. * @param $last_post_datetime standard output date in a sql query
  1285. * @return unix timestamp
  1286. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  1287. * @version October 2003
  1288. * @desc convert sql date to unix timestamp
  1289. */
  1290. function convert_mysql_date($last_post_datetime)
  1291. {
  1292. list ($last_post_date, $last_post_time) = split(" ", $last_post_datetime);
  1293. list ($year, $month, $day) = explode("-", $last_post_date);
  1294. list ($hour, $min, $sec) = explode(":", $last_post_time);
  1295. $announceDate = mktime($hour, $min, $sec, $month, $day, $year);
  1296. return $announceDate;
  1297. }
  1298. /**
  1299. * Updates or adds item properties to the Item_propetry table
  1300. * Tool and lastedit_type are language independant strings (langvars->get_lang!)
  1301. *
  1302. * @param $_course : array with course properties
  1303. * @param $tool : tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  1304. * @param $item_id : id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  1305. * @param $lastedit_type : add or update action (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  1306. * (2) "delete"; (3) "visible"; (4) "invisible";
  1307. * @param $user_id : id of the editing/adding user
  1308. * @param $to_group_id : id of the intended group ( 0 = for everybody), only relevant for $type (1)
  1309. * @param $to_user_id : id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  1310. * @param string $start_visible 0000-00-00 00:00:00 format
  1311. * @param unknown_type $end_visible 0000-00-00 00:00:00 format
  1312. * @return boolean False if update fails.
  1313. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  1314. * @version January 2005
  1315. * @desc update the item_properties table (if entry not exists, insert) of the course
  1316. */
  1317. 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)
  1318. {
  1319. $time = time();
  1320. $time = date("Y-m-d H:i:s", $time);
  1321. $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  1322. if ($to_user_id <= 0)
  1323. $to_user_id = NULL; //no to_user_id set
  1324. $start_visible = ($start_visible == 0) ? "0000-00-00 00:00:00" : $start_visible;
  1325. $end_visible = ($end_visible == 0) ? "0000-00-00 00:00:00" : $end_visible;
  1326. // set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  1327. $filter = "tool='$tool' AND ref='$item_id'";
  1328. if ($item_id == "*")
  1329. $filter = "tool='$tool' AND visibility<>'2'"; // for all (not deleted) items of the tool
  1330. // check if $to_user_id and $to_group_id are passed in the function call
  1331. // if both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  1332. if (is_null($to_user_id) && is_null($to_group_id))
  1333. $to_group_id = 0;
  1334. if (!is_null($to_user_id))
  1335. $to_filter = " AND to_user_id='$to_user_id'"; // set filter to intended user
  1336. else
  1337. if (!is_null($to_group_id))
  1338. $to_filter = " AND to_group_id='$to_group_id'"; // set filter to intended group
  1339. // update if possible
  1340. $set_type = "";
  1341. switch ($lastedit_type)
  1342. {
  1343. case "delete" : // delete = make item only visible for the platform admin
  1344. $visibility = '2';
  1345. $sql = "UPDATE $TABLE_ITEMPROPERTY
  1346. SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  1347. WHERE $filter";
  1348. break;
  1349. case "visible" : // change item to visible
  1350. $visibility = '1';
  1351. $sql = "UPDATE $TABLE_ITEMPROPERTY
  1352. SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  1353. WHERE $filter";
  1354. break;
  1355. case "invisible" : // change item to invisible
  1356. $visibility = '0';
  1357. $sql = "UPDATE $TABLE_ITEMPROPERTY
  1358. SET lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  1359. WHERE $filter";
  1360. break;
  1361. default : // item will be added or updated
  1362. $set_type = ", lastedit_type='$lastedit_type' ";
  1363. $visibility = '1';
  1364. $filter .= $to_filter;
  1365. $sql = "UPDATE $TABLE_ITEMPROPERTY
  1366. SET lastedit_date='$time', lastedit_user_id='$user_id' $set_type
  1367. WHERE $filter";
  1368. }
  1369. $res = mysql_query($sql);
  1370. // insert if no entries are found (can only happen in case of $lastedit_type switch is 'default')
  1371. if (mysql_affected_rows() == 0)
  1372. {
  1373. if (!is_null($to_user_id)) // $to_user_id has more priority than $to_group_id
  1374. {
  1375. $to_field = "to_user_id";
  1376. $to_value = $to_user_id;
  1377. }
  1378. else // $to_user_id is not set
  1379. {
  1380. $to_field = "to_group_id";
  1381. $to_value = $to_group_id;
  1382. }
  1383. $sql = "INSERT INTO $TABLE_ITEMPROPERTY
  1384. (tool, ref, insert_date,insert_user_id,lastedit_date,lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible)
  1385. VALUES ('$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value','$visibility','$start_visible','$end_visible')";
  1386. $res = mysql_query($sql);
  1387. if (!$res)
  1388. return FALSE;
  1389. }
  1390. return TRUE;
  1391. }
  1392. /*
  1393. ==============================================================================
  1394. Language Dropdown
  1395. ==============================================================================
  1396. */
  1397. /**
  1398. * Displays a form (drop down menu) so the user can select his/her preferred language.
  1399. * The form works with or without javascript
  1400. */
  1401. function api_display_language_form()
  1402. {
  1403. $platformLanguage = api_get_setting('platformLanguage');
  1404. $dirname = api_get_path(SYS_PATH)."main/lang/"; // this line is probably no longer needed
  1405. // retrieve a complete list of all the languages.
  1406. $language_list = api_get_languages();
  1407. // the the current language of the user so that his/her language occurs as selected in the dropdown menu
  1408. $user_selected_language = $_SESSION["user_language_choice"];
  1409. if (!isset ($user_selected_language))
  1410. $user_selected_language = $platformLanguage;
  1411. $original_languages = $language_list['name'];
  1412. $folder = $language_list['folder']; // this line is probably no longer needed
  1413. ?>
  1414. <script language="JavaScript" type="text/JavaScript">
  1415. <!--
  1416. function jumpMenu(targ,selObj,restore){ //v3.0
  1417. eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  1418. if (restore) selObj.selectedIndex=0;
  1419. }
  1420. //-->
  1421. </script>
  1422. <?php
  1423. echo "<form id=\"lang_form\" name=\"lang_form\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">", "<select name=\"language_list\" onchange=\"jumpMenu('parent',this,0)\">";
  1424. foreach ($original_languages as $key => $value)
  1425. {
  1426. if ($folder[$key] == $user_selected_language)
  1427. $option_end = " selected=\"selected\" >";
  1428. else
  1429. $option_end = ">";
  1430. echo "<option value=\"".$_SERVER['PHP_SELF']."?language=".$folder[$key]."\"$option_end";
  1431. #echo substr($value,0,16); #cut string to keep 800x600 aspect
  1432. echo $value;
  1433. echo "</option>\n";
  1434. }
  1435. echo "</select>";
  1436. echo "<noscript><input type=\"submit\" name=\"user_select_language\" value=\"".get_lang("Ok")."\" /></noscript>";
  1437. echo "</form>";
  1438. }
  1439. /**
  1440. * Return a list of all the languages that are made available by the admin.
  1441. * @return array An array with all languages. Structure of the array is
  1442. * array['name'] = An array with the name of every language
  1443. * array['folder'] = An array with the corresponding dokeos-folder
  1444. */
  1445. function api_get_languages()
  1446. {
  1447. $tbl_language = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
  1448. ;
  1449. $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  1450. $result = api_sql_query($sql, __FILE__, __LINE__);
  1451. while ($row = mysql_fetch_array($result))
  1452. {
  1453. $language_list['name'][] = $row['original_name'];
  1454. $language_list['folder'][] = $row['dokeos_folder'];
  1455. }
  1456. return $language_list;
  1457. }
  1458. /*
  1459. ==============================================================================
  1460. WYSIWYG HTML AREA
  1461. functions for the WYSIWYG html editor, TeX parsing...
  1462. ==============================================================================
  1463. */
  1464. /**
  1465. * Displays the FckEditor WYSIWYG editor for online editing of html
  1466. * @param string $name The name of the form-element
  1467. * @param string $content The default content of the html-editor
  1468. * @param int $height The height of the form element
  1469. * @param int $width The width of the form element
  1470. * @param string $optAttrib optional attributes for the form element
  1471. */
  1472. function api_disp_html_area($name, $content = '', $height = '', $width = '100%', $optAttrib = '')
  1473. {
  1474. global $_configuration, $_course, $fck_attribute;
  1475. require_once(dirname(__FILE__).'/formvalidator/Element/html_editor.php');
  1476. $editor = new HTML_QuickForm_html_editor($name);
  1477. $editor->setValue($content);
  1478. if( $height != '')
  1479. {
  1480. $fck_attribute['Height'] = $height;
  1481. }
  1482. if( $width != '')
  1483. {
  1484. $fck_attribute['Width'] = $width;
  1485. }
  1486. echo $editor->toHtml();
  1487. }
  1488. /**
  1489. * Send an email.
  1490. *
  1491. * Wrapper function for the standard php mail() function. Change this function
  1492. * to your needs. The parameters must follow the same rules as the standard php
  1493. * mail() function. Please look at the documentation on http: //www. php.
  1494. * net/manual/en/function. mail.php
  1495. * @param string $to
  1496. * @param string $subject
  1497. * @param string $message
  1498. * @param string $additional_headers
  1499. * @param string $additional_parameters
  1500. */
  1501. function api_send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
  1502. {
  1503. return mail($to, $subject, $message, $additional_headers, $additional_parameters);
  1504. }
  1505. /**
  1506. * Find the largest sort value in a given user_course_category
  1507. * This function is used when we are moving a course to a different category
  1508. * and also when a user subscribes to a courses (the new courses is added to the end
  1509. * of the main category
  1510. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1511. * @param int $user_course_category: the id of the user_course_category
  1512. * @return int the value of the highest sort of the user_course_category
  1513. */
  1514. function api_max_sort_value($user_course_category, $user_id)
  1515. {
  1516. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1517. $sql_max = "SELECT max(sort) as max_sort FROM $tbl_course_user WHERE user_id='".$user_id."' AND user_course_cat='".$user_course_category."'";
  1518. $result_max = mysql_query($sql_max) or die(mysql_error());
  1519. if (mysql_num_rows($result_max) == 1)
  1520. {
  1521. $row_max = mysql_fetch_array($result_max);
  1522. $max_sort = $row_max['max_sort'];
  1523. }
  1524. else
  1525. {
  1526. $max_sort = 0;
  1527. }
  1528. return $max_sort;
  1529. }
  1530. /**
  1531. * This function converts the string "true" or "false" to a boolean true or false.
  1532. * This function is in the first place written for the Dokeos Config Settings (also named AWACS)
  1533. * @param string "true" or "false"
  1534. * @return boolean true or false
  1535. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1536. */
  1537. function string_2_boolean($string)
  1538. {
  1539. if ($string == "true")
  1540. {
  1541. return true;
  1542. }
  1543. if ($string == "false")
  1544. {
  1545. return false;
  1546. }
  1547. }
  1548. /**
  1549. * including the necessary plugins
  1550. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1551. */
  1552. function api_plugin($location)
  1553. {
  1554. global $_plugins;
  1555. if (is_array($_plugins[$location]))
  1556. {
  1557. foreach ($_plugins[$location] as $this_plugin)
  1558. {
  1559. include (api_get_path(SYS_PLUGIN_PATH)."$this_plugin/index.php");
  1560. }
  1561. }
  1562. }
  1563. /**
  1564. * Checks to see wether a certain plugin is installed.
  1565. * @return boolean true if the plugin is installed, false otherwise.
  1566. */
  1567. function api_is_plugin_installed($plugin_list, $plugin_name)
  1568. {
  1569. foreach ($plugin_list as $plugin_location)
  1570. {
  1571. if ( array_search($plugin_name, $plugin_location) !== false ) return true;
  1572. }
  1573. return false;
  1574. }
  1575. /**
  1576. * Apply parsing to content to parse tex commandos that are seperated by [tex]
  1577. * [/tex] to make it readable for techexplorer plugin.
  1578. * @param string $text The text to parse
  1579. * @return string The text after parsing.
  1580. * @author Patrick Cool <patrick.cool@UGent.be>
  1581. * @version June 2004
  1582. */
  1583. function api_parse_tex($textext)
  1584. {
  1585. if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
  1586. {
  1587. $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);
  1588. }
  1589. else
  1590. {
  1591. $textext = str_replace(array ("[tex]", "[/tex]"), array ("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
  1592. }
  1593. return $textext;
  1594. }
  1595. ?>