main_api.lib.php 158 KB

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