main_api.lib.php 101 KB

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