main_api.lib.php 82 KB

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