main_api.lib.php 148 KB

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