main_api.lib.php 129 KB

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