main_api.lib.php 120 KB

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