main_api.lib.php 197 KB

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