main_api.lib.php 130 KB

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