main_api.lib.php 213 KB

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