main_api.lib.php 147 KB

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