main_api.lib.php 229 KB

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