main_api.lib.php 151 KB

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