main_api.lib.php 216 KB

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