main_api.lib.php 95 KB

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