api.lib.php 268 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\CourseBundle\Entity\CItemProperty;
  5. /**
  6. * This is a code library for Chamilo.
  7. * It is included by default in every Chamilo file (through including the global.inc.php)
  8. * This library is in process of being transferred to src/Chamilo/CoreBundle/Component/Utils/ChamiloApi.
  9. * Whenever a function is transferred to the ChamiloApi class, the places where it is used should include
  10. * the "use Chamilo\CoreBundle\Component\Utils\ChamiloApi;" statement.
  11. * @package chamilo.library
  12. */
  13. /**
  14. * Constants declaration
  15. */
  16. // PHP version requirement.
  17. define('REQUIRED_PHP_VERSION', '5.4');
  18. define('REQUIRED_MIN_MEMORY_LIMIT', '128');
  19. define('REQUIRED_MIN_UPLOAD_MAX_FILESIZE', '10');
  20. define('REQUIRED_MIN_POST_MAX_SIZE', '10');
  21. // USER STATUS CONSTANTS
  22. /** global status of a user: student */
  23. define('STUDENT', 5);
  24. /** global status of a user: course manager */
  25. define('COURSEMANAGER', 1);
  26. /** global status of a user: session admin */
  27. define('SESSIONADMIN', 3);
  28. /** global status of a user: human ressource manager */
  29. define('DRH', 4);
  30. /** global status of a user: human ressource manager */
  31. define('ANONYMOUS', 6);
  32. /** global status of a user: low security, necessary for inserting data from
  33. * the teacher through HTMLPurifier */
  34. define('COURSEMANAGERLOWSECURITY', 10);
  35. // Soft user status
  36. define('PLATFORM_ADMIN', 11);
  37. define('SESSION_COURSE_COACH', 12);
  38. define('SESSION_GENERAL_COACH', 13);
  39. define('COURSE_STUDENT', 14); //student subscribed in a course
  40. define('SESSION_STUDENT', 15); //student subscribed in a session course
  41. define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
  42. define('STUDENT_BOSS', 17); // student is boss
  43. define('INVITEE', 20);
  44. // Table of status
  45. $_status_list[COURSEMANAGER] = 'teacher'; // 1
  46. $_status_list[SESSIONADMIN] = 'session_admin'; // 3
  47. $_status_list[DRH] = 'drh'; // 4
  48. $_status_list[STUDENT] = 'user'; // 5
  49. $_status_list[ANONYMOUS] = 'anonymous'; // 6
  50. $_status_list[INVITEE] = 'invited'; // 20
  51. // COURSE VISIBILITY CONSTANTS
  52. /** only visible for course admin */
  53. define('COURSE_VISIBILITY_CLOSED', 0);
  54. /** only visible for users registered in the course */
  55. define('COURSE_VISIBILITY_REGISTERED', 1);
  56. /** Open for all registered users on the platform */
  57. define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
  58. /** Open for the whole world */
  59. define('COURSE_VISIBILITY_OPEN_WORLD', 3);
  60. /** Invisible to all except admin */
  61. define('COURSE_VISIBILITY_HIDDEN', 4);
  62. define('COURSE_REQUEST_PENDING', 0);
  63. define('COURSE_REQUEST_ACCEPTED', 1);
  64. define('COURSE_REQUEST_REJECTED', 2);
  65. define('DELETE_ACTION_ENABLED', false);
  66. // EMAIL SENDING RECIPIENT CONSTANTS
  67. define('SEND_EMAIL_EVERYONE', 1);
  68. define('SEND_EMAIL_STUDENTS', 2);
  69. define('SEND_EMAIL_TEACHERS', 3);
  70. // SESSION VISIBILITY CONSTANTS
  71. define('SESSION_VISIBLE_READ_ONLY', 1);
  72. define('SESSION_VISIBLE', 2);
  73. define('SESSION_INVISIBLE', 3); // not available
  74. define('SESSION_AVAILABLE', 4);
  75. define('SESSION_LINK_TARGET', '_self');
  76. define('SUBSCRIBE_ALLOWED', 1);
  77. define('SUBSCRIBE_NOT_ALLOWED', 0);
  78. define('UNSUBSCRIBE_ALLOWED', 1);
  79. define('UNSUBSCRIBE_NOT_ALLOWED', 0);
  80. // SURVEY VISIBILITY CONSTANTS
  81. define('SURVEY_VISIBLE_TUTOR', 0);
  82. define('SURVEY_VISIBLE_TUTOR_STUDENT', 1);
  83. define('SURVEY_VISIBLE_PUBLIC', 2);
  84. // CONSTANTS defining all tools, using the english version
  85. /* When you add a new tool you must add it into function api_get_tools_lists() too */
  86. define('TOOL_DOCUMENT', 'document');
  87. define('TOOL_LP_FINAL_ITEM', 'final_item');
  88. define('TOOL_THUMBNAIL', 'thumbnail');
  89. define('TOOL_HOTPOTATOES', 'hotpotatoes');
  90. define('TOOL_CALENDAR_EVENT', 'calendar_event');
  91. define('TOOL_LINK', 'link');
  92. define('TOOL_LINK_CATEGORY', 'link_category');
  93. define('TOOL_COURSE_DESCRIPTION', 'course_description');
  94. define('TOOL_SEARCH', 'search');
  95. define('TOOL_LEARNPATH', 'learnpath');
  96. define('TOOL_AGENDA', 'agenda');
  97. define('TOOL_ANNOUNCEMENT', 'announcement');
  98. define('TOOL_FORUM', 'forum');
  99. define('TOOL_FORUM_CATEGORY', 'forum_category');
  100. define('TOOL_FORUM_THREAD', 'forum_thread');
  101. define('TOOL_FORUM_POST', 'forum_post');
  102. define('TOOL_FORUM_ATTACH', 'forum_attachment');
  103. define('TOOL_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
  104. define('TOOL_THREAD', 'thread');
  105. define('TOOL_POST', 'post');
  106. define('TOOL_DROPBOX', 'dropbox');
  107. define('TOOL_QUIZ', 'quiz');
  108. define('TOOL_TEST_CATEGORY', 'test_category');
  109. define('TOOL_USER', 'user');
  110. define('TOOL_GROUP', 'group');
  111. define('TOOL_BLOGS', 'blog_management');
  112. define('TOOL_CHAT', 'chat');
  113. define('TOOL_STUDENTPUBLICATION', 'student_publication');
  114. define('TOOL_TRACKING', 'tracking');
  115. define('TOOL_HOMEPAGE_LINK', 'homepage_link');
  116. define('TOOL_COURSE_SETTING', 'course_setting');
  117. define('TOOL_BACKUP', 'backup');
  118. define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
  119. define('TOOL_RECYCLE_COURSE', 'recycle_course');
  120. define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
  121. define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
  122. define('TOOL_UPLOAD', 'file_upload');
  123. define('TOOL_COURSE_MAINTENANCE', 'course_maintenance');
  124. define('TOOL_SURVEY', 'survey');
  125. define('TOOL_WIKI', 'wiki');
  126. define('TOOL_GLOSSARY', 'glossary');
  127. define('TOOL_GRADEBOOK', 'gradebook');
  128. define('TOOL_NOTEBOOK', 'notebook');
  129. define('TOOL_ATTENDANCE', 'attendance');
  130. define('TOOL_COURSE_PROGRESS', 'course_progress');
  131. // CONSTANTS defining Chamilo interface sections
  132. define('SECTION_CAMPUS', 'mycampus');
  133. define('SECTION_COURSES', 'mycourses');
  134. define('SECTION_CATALOG', 'catalog');
  135. define('SECTION_MYPROFILE', 'myprofile');
  136. define('SECTION_MYAGENDA', 'myagenda');
  137. define('SECTION_COURSE_ADMIN', 'course_admin');
  138. define('SECTION_PLATFORM_ADMIN', 'platform_admin');
  139. define('SECTION_MYGRADEBOOK', 'mygradebook');
  140. define('SECTION_TRACKING', 'session_my_space');
  141. define('SECTION_SOCIAL', 'social-network');
  142. define('SECTION_DASHBOARD', 'dashboard');
  143. define('SECTION_REPORTS', 'reports');
  144. define('SECTION_GLOBAL', 'global');
  145. // CONSTANT name for local authentication source
  146. define('PLATFORM_AUTH_SOURCE', 'platform');
  147. define('CAS_AUTH_SOURCE', 'cas');
  148. define('LDAP_AUTH_SOURCE', 'extldap');
  149. // CONSTANT defining the default HotPotatoes files directory
  150. define('DIR_HOTPOTATOES', '/HotPotatoes_files');
  151. // event logs types
  152. define('LOG_COURSE_DELETE', 'course_deleted');
  153. define('LOG_COURSE_CREATE', 'course_created');
  154. // @todo replace 'soc_gr' with social_group
  155. define('LOG_GROUP_PORTAL_CREATED', 'soc_gr_created');
  156. define('LOG_GROUP_PORTAL_UPDATED', 'soc_gr_updated');
  157. define('LOG_GROUP_PORTAL_DELETED', 'soc_gr_deleted');
  158. define('LOG_GROUP_PORTAL_USER_DELETE_ALL', 'soc_gr_delete_users');
  159. define('LOG_GROUP_PORTAL_ID', 'soc_gr_portal_id');
  160. define('LOG_GROUP_PORTAL_REL_USER_ARRAY', 'soc_gr_user_array');
  161. define('LOG_GROUP_PORTAL_USER_SUBSCRIBED', 'soc_gr_u_subs');
  162. define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED', 'soc_gr_u_unsubs');
  163. define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE', 'soc_gr_update_role');
  164. define('LOG_USER_DELETE', 'user_deleted');
  165. define('LOG_USER_CREATE', 'user_created');
  166. define('LOG_USER_ENABLE', 'user_enable');
  167. define('LOG_USER_DISABLE', 'user_disable');
  168. define('LOG_USER_FIELD_CREATE', 'user_field_created');
  169. define('LOG_USER_FIELD_DELETE', 'user_field_deleted');
  170. define('LOG_SESSION_CREATE', 'session_created');
  171. define('LOG_SESSION_DELETE', 'session_deleted');
  172. define('LOG_SESSION_ADD_USER_COURSE', 'session_add_user_course');
  173. define('LOG_SESSION_DELETE_USER_COURSE', 'session_delete_user_course');
  174. define('LOG_SESSION_DELETE_USER', 'session_delete_user');
  175. define('LOG_SESSION_ADD_COURSE', 'session_add_course');
  176. define('LOG_SESSION_DELETE_COURSE', 'session_delete_course');
  177. define('LOG_SESSION_CATEGORY_CREATE', 'session_cat_created'); //changed in 1.9.8
  178. define('LOG_SESSION_CATEGORY_DELETE', 'session_cat_deleted'); //changed in 1.9.8
  179. define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
  180. define('LOG_PLATFORM_LANGUAGE_CHANGE', 'platform_lng_changed'); //changed in 1.9.8
  181. define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
  182. define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
  183. define('LOG_ATTEMPTED_FORCED_LOGIN', 'attempted_forced_login');
  184. define('LOG_HOMEPAGE_CHANGED', 'homepage_changed');
  185. define('LOG_PROMOTION_CREATE', 'promotion_created');
  186. define('LOG_PROMOTION_DELETE', 'promotion_deleted');
  187. define('LOG_CAREER_CREATE', 'career_created');
  188. define('LOG_CAREER_DELETE', 'career_deleted');
  189. define('LOG_USER_PERSONAL_DOC_DELETED', 'user_doc_deleted');
  190. define('LOG_WIKI_ACCESS', 'wiki_page_view');
  191. define('LOG_EXERCISE_RESULT_DELETE', 'exe_result_deleted');
  192. define('LOG_LP_ATTEMPT_DELETE', 'lp_attempt_deleted');
  193. define('LOG_QUESTION_RESULT_DELETE', 'qst_attempt_deleted');
  194. define('LOG_MY_FOLDER_CREATE', 'my_folder_created');
  195. define('LOG_MY_FOLDER_CHANGE', 'my_folder_changed');
  196. define('LOG_MY_FOLDER_DELETE', 'my_folder_deleted');
  197. define('LOG_MY_FOLDER_COPY', 'my_folder_copied');
  198. define('LOG_MY_FOLDER_CUT', 'my_folder_cut');
  199. define('LOG_MY_FOLDER_PASTE', 'my_folder_pasted');
  200. define('LOG_MY_FOLDER_UPLOAD', 'my_folder_uploaded');
  201. // Event logs data types (max 20 chars)
  202. define('LOG_COURSE_CODE', 'course_code');
  203. define('LOG_COURSE_ID', 'course_id');
  204. define('LOG_USER_ID', 'user_id');
  205. define('LOG_USER_OBJECT', 'user_object');
  206. define('LOG_USER_FIELD_VARIABLE', 'user_field_variable');
  207. define('LOG_SESSION_ID', 'session_id');
  208. define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
  209. define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
  210. define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
  211. define('LOG_PLATFORM_LANGUAGE', 'default_platform_language');
  212. define('LOG_CAREER_ID', 'career_id');
  213. define('LOG_PROMOTION_ID', 'promotion_id');
  214. define('LOG_GRADEBOOK_LOCKED', 'gradebook_locked');
  215. define('LOG_GRADEBOOK_UNLOCKED', 'gradebook_unlocked');
  216. define('LOG_GRADEBOOK_ID', 'gradebook_id');
  217. define('LOG_WIKI_PAGE_ID', 'wiki_page_id');
  218. define('LOG_EXERCISE_ID', 'exercise_id');
  219. define('LOG_EXERCISE_AND_USER_ID', 'exercise_and_user_id');
  220. define('LOG_LP_ID', 'lp_id');
  221. define('LOG_EXERCISE_ATTEMPT_QUESTION_ID', 'exercise_a_q_id');
  222. define('LOG_WORK_DIR_DELETE', 'work_dir_delete');
  223. define('LOG_WORK_FILE_DELETE', 'work_file_delete');
  224. define('LOG_WORK_DATA', 'work_data_array');
  225. define('LOG_MY_FOLDER_PATH', 'path');
  226. define('LOG_MY_FOLDER_NEW_PATH', 'new_path');
  227. define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
  228. //used when login_is_email setting is true
  229. define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
  230. define('USERNAME_PURIFIER_SHALLOW', '/\s/');
  231. // This constant is a result of Windows OS detection, it has a boolean value:
  232. // true whether the server runs on Windows OS, false otherwise.
  233. define('IS_WINDOWS_OS', api_is_windows_os());
  234. // Checks for installed optional php-extensions.
  235. define('INTL_INSTALLED', function_exists('intl_get_error_code')); // intl extension (from PECL), it is installed by default as of PHP 5.3.0
  236. define('ICONV_INSTALLED', function_exists('iconv')); // iconv extension, for PHP5 on Windows it is installed by default.
  237. define('MBSTRING_INSTALLED', function_exists('mb_strlen')); // mbstring extension.
  238. // Patterns for processing paths. // Examples:
  239. define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  240. define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
  241. define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i'); // $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
  242. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  243. // basic (leaf elements)
  244. define('REL_CODE_PATH', 'REL_CODE_PATH');
  245. define('REL_COURSE_PATH', 'REL_COURSE_PATH');
  246. define('REL_HOME_PATH', 'REL_HOME_PATH');
  247. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  248. define('WEB_PATH', 'WEB_PATH');
  249. define('WEB_APP_PATH', 'WEB_APP_PATH');
  250. define('SYS_PATH', 'SYS_PATH');
  251. define('SYS_APP_PATH', 'SYS_APP_PATH');
  252. define('SYS_UPLOAD_PATH', 'SYS_UPLOAD_PATH');
  253. define('WEB_UPLOAD_PATH', 'WEB_UPLOAD_PATH');
  254. define('REL_PATH', 'REL_PATH');
  255. define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
  256. define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
  257. define('WEB_CODE_PATH', 'WEB_CODE_PATH');
  258. define('SYS_CODE_PATH', 'SYS_CODE_PATH');
  259. define('SYS_LANG_PATH', 'SYS_LANG_PATH');
  260. define('WEB_IMG_PATH', 'WEB_IMG_PATH');
  261. define('WEB_CSS_PATH', 'WEB_CSS_PATH');
  262. define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
  263. define('SYS_CSS_PATH', 'SYS_CSS_PATH');
  264. define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
  265. define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
  266. define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
  267. define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
  268. define('SYS_INC_PATH', 'SYS_INC_PATH');
  269. define('LIBRARY_PATH', 'LIBRARY_PATH');
  270. define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
  271. define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
  272. define('WEB_LIBRARY_JS_PATH', 'WEB_LIBRARY_JS_PATH');
  273. define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
  274. define('SYS_TEST_PATH', 'SYS_TEST_PATH');
  275. define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
  276. define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
  277. define('SYS_PUBLIC_PATH', 'SYS_PUBLIC_PATH');
  278. define('SYS_HOME_PATH', 'SYS_HOME_PATH');
  279. define('WEB_HOME_PATH', 'WEB_HOME_PATH');
  280. define('WEB_FONTS_PATH', 'WEB_FONTS_PATH');
  281. define('SYS_FONTS_PATH', 'SYS_FONTS_PATH');
  282. define('SYS_DEFAULT_COURSE_DOCUMENT_PATH', 'SYS_DEFAULT_COURSE_DOCUMENT_PATH');
  283. define('REL_DEFAULT_COURSE_DOCUMENT_PATH', 'REL_DEFAULT_COURSE_DOCUMENT_PATH');
  284. define('WEB_DEFAULT_COURSE_DOCUMENT_PATH', 'WEB_DEFAULT_COURSE_DOCUMENT_PATH');
  285. // Relations type with Course manager
  286. define('COURSE_RELATION_TYPE_COURSE_MANAGER', 1);
  287. define('SESSION_RELATION_TYPE_COURSE_MANAGER', 1);
  288. // Relations type with Human resources manager
  289. define('COURSE_RELATION_TYPE_RRHH', 1);
  290. define('SESSION_RELATION_TYPE_RRHH', 1);
  291. //User image sizes
  292. define('USER_IMAGE_SIZE_ORIGINAL', 1);
  293. define('USER_IMAGE_SIZE_BIG', 2);
  294. define('USER_IMAGE_SIZE_MEDIUM', 3);
  295. define('USER_IMAGE_SIZE_SMALL', 4);
  296. // Relation type between users
  297. define('USER_UNKNOW', 0);
  298. define('USER_RELATION_TYPE_UNKNOW', 1);
  299. define('USER_RELATION_TYPE_PARENT', 2); // should be deprecated is useless
  300. define('USER_RELATION_TYPE_FRIEND', 3);
  301. define('USER_RELATION_TYPE_GOODFRIEND', 4); // should be deprecated is useless
  302. define('USER_RELATION_TYPE_ENEMY', 5); // should be deprecated is useless
  303. define('USER_RELATION_TYPE_DELETED', 6);
  304. define('USER_RELATION_TYPE_RRHH', 7);
  305. define('USER_RELATION_TYPE_BOSS', 8);
  306. // Gradebook link constants
  307. // Please do not change existing values, they are used in the database !
  308. define('GRADEBOOK_ITEM_LIMIT', 1000);
  309. define('LINK_EXERCISE', 1);
  310. define('LINK_DROPBOX', 2);
  311. define('LINK_STUDENTPUBLICATION', 3);
  312. define('LINK_LEARNPATH', 4);
  313. define('LINK_FORUM_THREAD', 5);
  314. //define('LINK_WORK',6);
  315. define('LINK_ATTENDANCE', 7);
  316. define('LINK_SURVEY', 8);
  317. define('LINK_HOTPOTATOES', 9);
  318. // Score display types constants
  319. define('SCORE_DIV', 1); // X / Y
  320. define('SCORE_PERCENT', 2); // XX %
  321. define('SCORE_DIV_PERCENT', 3); // X / Y (XX %)
  322. define('SCORE_AVERAGE', 4); // XX %
  323. define('SCORE_DECIMAL', 5); // 0.50 (X/Y)
  324. define('SCORE_BAR', 6); // Uses the Display::bar_progress function
  325. define('SCORE_SIMPLE', 7); // X
  326. define('SCORE_IGNORE_SPLIT', 8); // ??
  327. define('SCORE_DIV_PERCENT_WITH_CUSTOM', 9); // X / Y (XX %) - Good!
  328. define('SCORE_CUSTOM', 10); // Good!
  329. define('SCORE_DIV_SIMPLE_WITH_CUSTOM', 11); // X - Good!
  330. define('SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS', 12); // X - Good!
  331. define('SCORE_ONLY_SCORE', 13); // X - Good!
  332. define('SCORE_BOTH', 1);
  333. define('SCORE_ONLY_DEFAULT', 2);
  334. define('SCORE_ONLY_CUSTOM', 3);
  335. // From display.lib.php
  336. define('MAX_LENGTH_BREADCRUMB', 100);
  337. define('ICON_SIZE_ATOM', 8);
  338. define('ICON_SIZE_TINY', 16);
  339. define('ICON_SIZE_SMALL', 22);
  340. define('ICON_SIZE_MEDIUM', 32);
  341. define('ICON_SIZE_LARGE', 48);
  342. define('ICON_SIZE_BIG', 64);
  343. define('ICON_SIZE_HUGE', 128);
  344. define('SHOW_TEXT_NEAR_ICONS', false);
  345. // Session catalog
  346. define('CATALOG_COURSES', 0);
  347. define('CATALOG_SESSIONS', 1);
  348. define('CATALOG_COURSES_SESSIONS', 2);
  349. // Hook type events, pre-process and post-process.
  350. // All means to be executed for both hook event types
  351. define('HOOK_EVENT_TYPE_PRE', 0);
  352. define('HOOK_EVENT_TYPE_POST', 1);
  353. define('HOOK_EVENT_TYPE_ALL', 10);
  354. define('CAREER_STATUS_ACTIVE', 1);
  355. define('CAREER_STATUS_INACTIVE', 0);
  356. define('PROMOTION_STATUS_ACTIVE', 1);
  357. define('PROMOTION_STATUS_INACTIVE', 0);
  358. // Group permissions
  359. define('GROUP_PERMISSION_OPEN', '1');
  360. define('GROUP_PERMISSION_CLOSED', '2');
  361. // Group user permissions
  362. define('GROUP_USER_PERMISSION_ADMIN', '1'); // the admin of a group
  363. define('GROUP_USER_PERMISSION_READER', '2'); // a normal user
  364. define('GROUP_USER_PERMISSION_PENDING_INVITATION', '3'); // When an admin/moderator invites a user
  365. define('GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER', '4'); // an user joins a group
  366. define('GROUP_USER_PERMISSION_MODERATOR', '5'); // a moderator
  367. define('GROUP_USER_PERMISSION_ANONYMOUS', '6'); // an anonymous user
  368. define('GROUP_USER_PERMISSION_HRM', '7'); // a human resources manager
  369. define('GROUP_IMAGE_SIZE_ORIGINAL', 1);
  370. define('GROUP_IMAGE_SIZE_BIG', 2);
  371. define('GROUP_IMAGE_SIZE_MEDIUM', 3);
  372. define('GROUP_IMAGE_SIZE_SMALL', 4);
  373. define('GROUP_TITLE_LENGTH', 50);
  374. // Exercise
  375. // @todo move into a class
  376. define('ALL_ON_ONE_PAGE', 1);
  377. define('ONE_PER_PAGE', 2);
  378. define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback - show score and expected answers
  379. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
  380. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); //NoFeedback - Show score only
  381. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
  382. define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
  383. define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
  384. define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
  385. define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4); //Show final score only with categories
  386. define('EXERCISE_MAX_NAME_SIZE', 80);
  387. // Question types (edit next array as well when adding values)
  388. // @todo move into a class
  389. define('UNIQUE_ANSWER', 1);
  390. define('MULTIPLE_ANSWER', 2);
  391. define('FILL_IN_BLANKS', 3);
  392. define('MATCHING', 4);
  393. define('FREE_ANSWER', 5);
  394. define('HOT_SPOT', 6);
  395. define('HOT_SPOT_ORDER', 7);
  396. define('HOT_SPOT_DELINEATION', 8);
  397. define('MULTIPLE_ANSWER_COMBINATION', 9);
  398. define('UNIQUE_ANSWER_NO_OPTION', 10);
  399. define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
  400. define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
  401. define('ORAL_EXPRESSION', 13);
  402. define('GLOBAL_MULTIPLE_ANSWER', 14);
  403. define('MEDIA_QUESTION', 15);
  404. define('CALCULATED_ANSWER', 16);
  405. define('UNIQUE_ANSWER_IMAGE', 17);
  406. define('DRAGGABLE', 18);
  407. define('MATCHING_DRAGGABLE', 19);
  408. define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
  409. define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
  410. define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
  411. // Question selection type
  412. define('EX_Q_SELECTION_ORDERED', 1);
  413. define('EX_Q_SELECTION_RANDOM', 2);
  414. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
  415. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
  416. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
  417. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
  418. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
  419. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
  420. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
  421. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
  422. // one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
  423. define('QUESTION_TYPES',
  424. UNIQUE_ANSWER.':'.
  425. MULTIPLE_ANSWER.':'.
  426. FILL_IN_BLANKS.':'.
  427. MATCHING.':'.
  428. FREE_ANSWER.':'.
  429. HOT_SPOT.':'.
  430. HOT_SPOT_ORDER.':'.
  431. HOT_SPOT_DELINEATION.':'.
  432. MULTIPLE_ANSWER_COMBINATION.':'.
  433. UNIQUE_ANSWER_NO_OPTION.':'.
  434. MULTIPLE_ANSWER_TRUE_FALSE.':'.
  435. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
  436. ORAL_EXPRESSION.':'.
  437. GLOBAL_MULTIPLE_ANSWER.':'.
  438. MEDIA_QUESTION.':'.
  439. CALCULATED_ANSWER.':'.
  440. UNIQUE_ANSWER_IMAGE.':'.
  441. DRAGGABLE.':'.
  442. MATCHING_DRAGGABLE
  443. );
  444. //Some alias used in the QTI exports
  445. define('MCUA', 1);
  446. define('TF', 1);
  447. define('MCMA', 2);
  448. define('FIB', 3);
  449. // Skills
  450. define('SKILL_TYPE_REQUIREMENT', 'required');
  451. define('SKILL_TYPE_ACQUIRED', 'acquired');
  452. define('SKILL_TYPE_BOTH', 'both');
  453. // Message
  454. define('MESSAGE_STATUS_NEW', '0');
  455. define('MESSAGE_STATUS_UNREAD', '1');
  456. //2 ??
  457. define('MESSAGE_STATUS_DELETED', '3');
  458. define('MESSAGE_STATUS_OUTBOX', '4');
  459. define('MESSAGE_STATUS_INVITATION_PENDING', '5');
  460. define('MESSAGE_STATUS_INVITATION_ACCEPTED', '6');
  461. define('MESSAGE_STATUS_INVITATION_DENIED', '7');
  462. define('MESSAGE_STATUS_WALL', '8');
  463. define('MESSAGE_STATUS_WALL_DELETE', '9');
  464. define('MESSAGE_STATUS_WALL_POST', '10');
  465. // Images
  466. define('IMAGE_WALL_SMALL_SIZE', 200);
  467. define('IMAGE_WALL_MEDIUM_SIZE', 500);
  468. define('IMAGE_WALL_BIG_SIZE', 2000);
  469. define('IMAGE_WALL_SMALL', 'small');
  470. define('IMAGE_WALL_MEDIUM', 'medium');
  471. define('IMAGE_WALL_BIG', 'big');
  472. // Social PLUGIN PLACES
  473. define('SOCIAL_LEFT_PLUGIN', 1);
  474. define('SOCIAL_CENTER_PLUGIN', 2);
  475. define('SOCIAL_RIGHT_PLUGIN', 3);
  476. define('CUT_GROUP_NAME', 50);
  477. /**
  478. * FormValidator Filter
  479. */
  480. define('NO_HTML', 1);
  481. define('STUDENT_HTML', 2);
  482. define('TEACHER_HTML', 3);
  483. define('STUDENT_HTML_FULLPAGE', 4);
  484. define('TEACHER_HTML_FULLPAGE', 5);
  485. // Timeline
  486. define('TIMELINE_STATUS_ACTIVE', '1');
  487. define('TIMELINE_STATUS_INACTIVE', '2');
  488. // Event email template class
  489. define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
  490. define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
  491. // Course home
  492. define('SHORTCUTS_HORIZONTAL', 0);
  493. define('SHORTCUTS_VERTICAL', 1);
  494. // Image class
  495. define('IMAGE_PROCESSOR', 'gd'); // 'imagick' or 'gd' strings
  496. // Course copy
  497. define('FILE_SKIP', 1);
  498. define('FILE_RENAME', 2);
  499. define('FILE_OVERWRITE', 3);
  500. define('UTF8_CONVERT', false); //false by default
  501. define('DOCUMENT','file');
  502. define('FOLDER','folder');
  503. define('RESOURCE_DOCUMENT', 'document');
  504. define('RESOURCE_GLOSSARY', 'glossary');
  505. define('RESOURCE_EVENT', 'calendar_event');
  506. define('RESOURCE_LINK', 'link');
  507. define('RESOURCE_COURSEDESCRIPTION', 'course_description');
  508. define('RESOURCE_LEARNPATH', 'learnpath');
  509. define('RESOURCE_ANNOUNCEMENT', 'announcement');
  510. define('RESOURCE_FORUM', 'forum');
  511. define('RESOURCE_FORUMTOPIC', 'thread');
  512. define('RESOURCE_FORUMPOST', 'post');
  513. define('RESOURCE_QUIZ', 'quiz');
  514. define('RESOURCE_TEST_CATEGORY', 'test_category');
  515. define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
  516. define('RESOURCE_TOOL_INTRO', 'Tool introduction');
  517. define('RESOURCE_LINKCATEGORY', 'Link_Category');
  518. define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
  519. define('RESOURCE_SCORM', 'Scorm');
  520. define('RESOURCE_SURVEY', 'survey');
  521. define('RESOURCE_SURVEYQUESTION', 'survey_question');
  522. define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
  523. define('RESOURCE_WIKI', 'wiki');
  524. define('RESOURCE_THEMATIC', 'thematic');
  525. define('RESOURCE_ATTENDANCE', 'attendance');
  526. define('RESOURCE_WORK', 'work');
  527. define('RESOURCE_SESSION_COURSE', 'session_course');
  528. define('RESOURCE_GRADEBOOK', 'gradebook');
  529. define('ADD_THEMATIC_PLAN', 6);
  530. // Max online users to show per page (whoisonline)
  531. define('MAX_ONLINE_USERS', 12);
  532. // Make sure the CHAMILO_LOAD_WYSIWYG constant is defined
  533. // To remove CKeditor libs from HTML, set this constant to true before loading
  534. if (!defined('CHAMILO_LOAD_WYSIWYG')) {
  535. define('CHAMILO_LOAD_WYSIWYG', true);
  536. }
  537. /**
  538. * Inclusion of internationalization libraries
  539. */
  540. require_once __DIR__.'/internationalization.lib.php';
  541. /**
  542. * Returns a path to a certain resource within the Chamilo area, specifyed through a parameter.
  543. * Also, this function provides conversion between path types, in this case the input path points inside the Chamilo area too.
  544. *
  545. * See $_configuration['course_folder'] in the configuration.php to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  546. * @param string $path (optional) A path which type is to be converted. Also, it may be a defined constant for a path.
  547. * This parameter has meaning when $type parameter has one of the following values: TO_WEB, TO_SYS, TO_REL. Otherwise it is ignored.
  548. * @return string The requested path or the converted path.
  549. *
  550. *
  551. * Notes about the current behaviour model:
  552. * 1. Windows back-slashes are converted to slashes in the result.
  553. * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
  554. * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
  555. * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
  556. * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
  557. * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
  558. * It has not been identified as needed yet.
  559. * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
  560. *
  561. * For examples go to: *
  562. * See main/admin/system_status.php?section=paths
  563. *
  564. * Vchamilo changes : allow using an alternate configuration
  565. * to get vchamilo instance paths
  566. */
  567. function api_get_path($path = '', $configuration = [])
  568. {
  569. global $paths;
  570. // get proper configuration data if exists
  571. global $_configuration;
  572. if (empty($configuration)) {
  573. $configuration = (array) $_configuration;
  574. }
  575. $course_folder = 'courses/';
  576. $root_sys = $_configuration['root_sys'];
  577. // Resolve master hostname.
  578. if (!empty($configuration) && array_key_exists('root_web', $configuration)) {
  579. $root_web = $configuration['root_web'];
  580. } else {
  581. $root_web = '';
  582. // Try guess it from server.
  583. if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) {
  584. if (($pos = strpos(($requested_page_rel = api_get_self()), 'main/install')) !== false) {
  585. $root_rel = substr($requested_page_rel, 0, $pos);
  586. // See http://www.mediawiki.org/wiki/Manual:$wgServer
  587. $server_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
  588. $server_name =
  589. isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME']
  590. : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
  591. : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
  592. : (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR']
  593. : 'localhost')));
  594. if (isset($_SERVER['SERVER_PORT']) && !strpos($server_name, ':')
  595. && (($server_protocol == 'http'
  596. && $_SERVER['SERVER_PORT'] != 80 ) || ($server_protocol == 'https' && $_SERVER['SERVER_PORT'] != 443 ))) {
  597. $server_name .= ":" . $_SERVER['SERVER_PORT'];
  598. }
  599. $root_web = $server_protocol.'://'.$server_name.$root_rel;
  600. $root_sys = str_replace('\\', '/', realpath(__DIR__.'/../../../')).'/';
  601. }
  602. // Here we give up, so we don't touch anything.
  603. }
  604. }
  605. if (isset($configuration['multiple_access_urls']) && $configuration['multiple_access_urls']) {
  606. // To avoid that the api_get_access_url() function fails since global.inc.php also calls the main_api.lib.php
  607. if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
  608. // We look into the DB the function api_get_access_url
  609. $url_info = api_get_access_url($configuration['access_url']);
  610. // Avoid default value
  611. $defaulValues = ['http://localhost/', 'https://localhost/'];
  612. if (!empty($url_info['url']) && !in_array($url_info['url'], $defaulValues)) {
  613. $root_web = $url_info['active'] == 1 ? $url_info['url'] : $configuration['root_web'];
  614. }
  615. }
  616. }
  617. if (empty($paths)) {
  618. $paths = [];
  619. }
  620. $paths = [];
  621. // Initialise cache with default values.
  622. if (!array_key_exists($root_web, $paths)) {
  623. $paths[$root_web] = array(
  624. WEB_PATH => '',
  625. SYS_PATH => '',
  626. REL_PATH => '',
  627. WEB_COURSE_PATH => '',
  628. SYS_COURSE_PATH => '',
  629. REL_COURSE_PATH => '',
  630. WEB_CODE_PATH => 'main/',
  631. SYS_CODE_PATH => 'main/',
  632. REL_CODE_PATH => '/main/',
  633. SYS_LANG_PATH => 'lang/',
  634. WEB_IMG_PATH => 'img/',
  635. WEB_CSS_PATH => 'web/css/',
  636. SYS_CSS_PATH => 'app/Resources/public/css/',
  637. SYS_PLUGIN_PATH => 'plugin/',
  638. WEB_PLUGIN_PATH => 'plugin/',
  639. SYS_ARCHIVE_PATH => 'app/cache/',
  640. WEB_ARCHIVE_PATH => 'app/cache/',
  641. SYS_HOME_PATH => 'app/home/',
  642. WEB_HOME_PATH => 'app/home/',
  643. REL_HOME_PATH => 'app/home/',
  644. SYS_APP_PATH => 'app/',
  645. WEB_APP_PATH => 'app/',
  646. SYS_UPLOAD_PATH => 'app/upload/',
  647. SYS_INC_PATH => 'inc/',
  648. CONFIGURATION_PATH => 'app/config/',
  649. LIBRARY_PATH => 'inc/lib/',
  650. WEB_LIBRARY_PATH => 'inc/lib/',
  651. WEB_LIBRARY_JS_PATH => 'inc/lib/javascript/',
  652. WEB_AJAX_PATH => 'inc/ajax/',
  653. SYS_TEST_PATH => 'tests/',
  654. WEB_TEMPLATE_PATH => 'template/',
  655. SYS_TEMPLATE_PATH => 'template/',
  656. WEB_UPLOAD_PATH => 'app/upload/',
  657. WEB_PUBLIC_PATH => 'web/',
  658. SYS_PUBLIC_PATH => 'web/',
  659. WEB_FONTS_PATH => 'fonts/',
  660. SYS_FONTS_PATH => 'fonts/',
  661. );
  662. }
  663. $isInitialized = [];
  664. $course_folder = isset($configuration['course_folder']) ? $configuration['course_folder'] : $course_folder;
  665. $root_rel = isset($configuration['url_append']) ? $configuration['url_append'] : '';
  666. // Web server base and system server base.
  667. if (!array_key_exists($root_web, $isInitialized)) {
  668. // process absolute global roots
  669. if (!empty($configuration)) {
  670. $code_folder = 'main';
  671. } else {
  672. $code_folder = $paths[$root_web][REL_CODE_PATH];
  673. }
  674. // Support for the installation process.
  675. // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
  676. // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
  677. // Dealing with trailing slashes.
  678. $slashed_root_web = api_add_trailing_slash($root_web);
  679. $root_sys = api_add_trailing_slash($root_sys);
  680. $root_rel = api_add_trailing_slash($root_rel);
  681. $code_folder = api_add_trailing_slash($code_folder);
  682. $course_folder = api_add_trailing_slash($course_folder);
  683. // Initialization of a table that contains common-purpose paths.
  684. $paths[$root_web][REL_PATH] = $root_rel;
  685. $paths[$root_web][REL_COURSE_PATH] = $root_rel.$course_folder;
  686. $paths[$root_web][REL_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][REL_PATH].'main/default_course_document/';
  687. $paths[$root_web][WEB_PATH] = $slashed_root_web;
  688. $paths[$root_web][WEB_CODE_PATH] = $paths[$root_web][WEB_PATH].$code_folder;
  689. $paths[$root_web][WEB_COURSE_PATH] = $paths[$root_web][WEB_PATH].$course_folder;
  690. $paths[$root_web][WEB_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][WEB_CODE_PATH].'default_course_document/';
  691. $paths[$root_web][WEB_APP_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_APP_PATH];
  692. $paths[$root_web][WEB_PLUGIN_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_PATH];
  693. $paths[$root_web][WEB_ARCHIVE_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_ARCHIVE_PATH];
  694. $paths[$root_web][WEB_CSS_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_CSS_PATH];
  695. $paths[$root_web][WEB_IMG_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_IMG_PATH];
  696. $paths[$root_web][WEB_LIBRARY_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_PATH];
  697. $paths[$root_web][WEB_LIBRARY_JS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_JS_PATH];
  698. $paths[$root_web][WEB_AJAX_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_AJAX_PATH];
  699. $paths[$root_web][WEB_FONTS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_FONTS_PATH];
  700. $paths[$root_web][WEB_TEMPLATE_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_TEMPLATE_PATH];
  701. $paths[$root_web][WEB_UPLOAD_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_UPLOAD_PATH];
  702. $paths[$root_web][WEB_PUBLIC_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PUBLIC_PATH];
  703. $paths[$root_web][WEB_HOME_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][REL_HOME_PATH];
  704. $paths[$root_web][SYS_PATH] = $root_sys;
  705. $paths[$root_web][SYS_CODE_PATH] = $root_sys.$code_folder;
  706. $paths[$root_web][SYS_TEST_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_TEST_PATH];
  707. $paths[$root_web][SYS_TEMPLATE_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_TEMPLATE_PATH];
  708. $paths[$root_web][SYS_PUBLIC_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PUBLIC_PATH];
  709. $paths[$root_web][SYS_CSS_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_CSS_PATH];
  710. $paths[$root_web][SYS_FONTS_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_FONTS_PATH];
  711. $paths[$root_web][SYS_ARCHIVE_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_ARCHIVE_PATH];
  712. $paths[$root_web][SYS_APP_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_APP_PATH];
  713. $paths[$root_web][SYS_COURSE_PATH] = $paths[$root_web][SYS_APP_PATH].$course_folder;
  714. $paths[$root_web][SYS_UPLOAD_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_UPLOAD_PATH];
  715. $paths[$root_web][SYS_LANG_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_LANG_PATH];
  716. $paths[$root_web][SYS_HOME_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_HOME_PATH];
  717. $paths[$root_web][SYS_PLUGIN_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PLUGIN_PATH];
  718. $paths[$root_web][SYS_INC_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_INC_PATH];
  719. $paths[$root_web][LIBRARY_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][LIBRARY_PATH];
  720. $paths[$root_web][CONFIGURATION_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][CONFIGURATION_PATH];
  721. global $virtualChamilo;
  722. if (!empty($virtualChamilo)) {
  723. $paths[$root_web][SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
  724. $paths[$root_web][SYS_HOME_PATH] = api_add_trailing_slash($virtualChamilo[SYS_HOME_PATH]);
  725. $paths[$root_web][WEB_HOME_PATH] = api_add_trailing_slash($virtualChamilo[WEB_HOME_PATH]);
  726. $paths[$root_web][SYS_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_COURSE_PATH]);
  727. $paths[$root_web][SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
  728. $paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
  729. //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
  730. //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
  731. }
  732. $isInitialized[$root_web] = true;
  733. }
  734. $path = trim($path);
  735. // Retrieving a common-purpose path.
  736. if (isset($paths[$root_web][$path])) {
  737. return $paths[$root_web][$path];
  738. }
  739. // Second purification.
  740. // Replacing Windows back slashes.
  741. $path = str_replace('\\', '/', $path);
  742. // Query strings sometimes mighth wrongly appear in non-URLs.
  743. // Let us check remove them from all types of paths.
  744. if (($pos = strpos($path, '?')) !== false) {
  745. $path = substr($path, 0, $pos);
  746. }
  747. // Detection of the input path type. Conversion to semi-absolute type ( /chamilo/main/inc/.... ).
  748. if (preg_match(VALID_WEB_PATH, $path)) {
  749. // A special case: When a URL points to the document download script directly, without
  750. // mod-rewrite translation, we have to translate it into an "ordinary" web path.
  751. // For example:
  752. // http://localhost/chamilo/main/document/download.php?doc_url=/image.png&cDir=/
  753. // becomes
  754. // http://localhost/chamilo/courses/TEST/document/image.png
  755. // TEST is a course directory name, so called "system course code".
  756. if (strpos($path, 'download.php') !== false) { // Fast detection first.
  757. $path = urldecode($path);
  758. if (preg_match('/(.*)main\/document\/download.php\?doc_url=\/(.*)&cDir=\/(.*)?/', $path, $matches)) {
  759. $sys_course_code =
  760. isset($_SESSION['_course']['sysCode']) // User is inside a course?
  761. ? $_SESSION['_course']['sysCode'] // Yes, then use course's directory name.
  762. : '{SYS_COURSE_CODE}'; // No, then use a fake code, it may be processed later.
  763. $path = $matches[1].'courses/'.$sys_course_code.'/document/'.str_replace('//', '/', $matches[3].'/'.$matches[2]);
  764. }
  765. }
  766. // Replacement of the present web server base with a slash '/'.
  767. $path = preg_replace(VALID_WEB_SERVER_BASE, '/', $path);
  768. }
  769. // Path now is semi-absolute. It is convenient at this moment repeated slashes to be removed.
  770. $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  771. return $path;
  772. }
  773. /**
  774. * Gets a modified version of the path for the CDN, if defined in
  775. * configuration.php
  776. * @param string $web_path The path of the resource without CDN
  777. * @return string The path of the resource converted to CDN
  778. * @author Yannick Warnier <ywarnier@beeznst.org>
  779. */
  780. function api_get_cdn_path($web_path)
  781. {
  782. global $_configuration;
  783. $web_root = api_get_path(WEB_PATH);
  784. $ext = substr($web_path,strrpos($web_path,'.'));
  785. if (isset($ext[2])) { // faster version of strlen to check if len>2
  786. // Check for CDN definitions
  787. if (!empty($_configuration['cdn_enable']) && !empty($ext)) {
  788. foreach ($_configuration['cdn'] as $host => $exts) {
  789. if (in_array($ext,$exts)) {
  790. //Use host as defined in $_configuration['cdn'], without
  791. // trailing slash
  792. return str_replace($web_root,$host.'/',$web_path);
  793. }
  794. }
  795. }
  796. }
  797. return $web_path;
  798. }
  799. /**
  800. * @return bool Return true if CAS authentification is activated
  801. *
  802. */
  803. function api_is_cas_activated() {
  804. return api_get_setting('cas_activate') == "true";
  805. }
  806. /**
  807. * @return bool Return true if LDAP authentification is activated
  808. *
  809. */
  810. function api_is_ldap_activated() {
  811. global $extAuthSource;
  812. return is_array($extAuthSource[LDAP_AUTH_SOURCE]);
  813. }
  814. /**
  815. * @return bool Return true if Facebook authentification is activated
  816. *
  817. */
  818. function api_is_facebook_auth_activated() {
  819. global $_configuration;
  820. return (isset($_configuration['facebook_auth']) && $_configuration['facebook_auth'] == 1);
  821. }
  822. /**
  823. * This function checks whether a given path points inside the system.
  824. * @param string $path The path to be tested.
  825. * It should be full path, web-absolute (WEB), semi-absolute (REL) or system-absolyte (SYS).
  826. * @return bool Returns true when the given path is inside the system, false otherwise.
  827. */
  828. function api_is_internal_path($path) {
  829. $path = str_replace('\\', '/', trim($path));
  830. if (empty($path)) {
  831. return false;
  832. }
  833. if (strpos($path, api_remove_trailing_slash(api_get_path(WEB_PATH))) === 0) {
  834. return true;
  835. }
  836. if (strpos($path, api_remove_trailing_slash(api_get_path(SYS_PATH))) === 0) {
  837. return true;
  838. }
  839. $server_base_web = api_remove_trailing_slash(api_get_path(REL_PATH));
  840. $server_base_web = empty($server_base_web) ? '/' : $server_base_web;
  841. if (strpos($path, $server_base_web) === 0) {
  842. return true;
  843. }
  844. return false;
  845. }
  846. /**
  847. * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
  848. * @param string $path The input path.
  849. * @return string Returns the modified path.
  850. */
  851. function api_add_trailing_slash($path) {
  852. return substr($path, -1) == '/' ? $path : $path.'/';
  853. }
  854. /**
  855. * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
  856. * @param string $path The input path.
  857. * @return string Returns the modified path.
  858. */
  859. function api_remove_trailing_slash($path) {
  860. return substr($path, -1) == '/' ? substr($path, 0, -1) : $path;
  861. }
  862. /**
  863. * Checks the RFC 3986 syntax of a given URL.
  864. * @param string $url The URL to be checked.
  865. * @param bool $absolute Whether the URL is absolute (beginning with a scheme such as "http:").
  866. * @return string|false Returns the URL if it is valid, FALSE otherwise.
  867. * This function is an adaptation from the function valid_url(), Drupal CMS.
  868. * @link http://drupal.org
  869. * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
  870. * @link http://bugs.php.net/51192
  871. */
  872. function api_valid_url($url, $absolute = false) {
  873. if ($absolute) {
  874. if (preg_match("
  875. /^ # Start at the beginning of the text
  876. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  877. (?: # Userinfo (optional) which is typically
  878. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  879. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  880. )?
  881. (?:
  882. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  883. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  884. )
  885. (?::[0-9]+)? # Server port number (optional)
  886. (?:[\/|\?]
  887. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  888. *)?
  889. $/xi", $url)) {
  890. return $url;
  891. }
  892. return false;
  893. } else {
  894. return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
  895. }
  896. }
  897. /**
  898. * Checks whether a given string looks roughly like an email address.
  899. *
  900. * @param string $address The e-mail address to be checked.
  901. * @return mixed Returns the e-mail if it is valid, FALSE otherwise.
  902. */
  903. function api_valid_email($address)
  904. {
  905. return filter_var($address, FILTER_VALIDATE_EMAIL);
  906. }
  907. /* PROTECTION FUNCTIONS
  908. Use these functions to protect your scripts. */
  909. /**
  910. * Function used to protect a course script.
  911. * The function blocks access when
  912. * - there is no $_SESSION["_course"] defined; or
  913. * - $is_allowed_in_course is set to false (this depends on the course
  914. * visibility and user status).
  915. *
  916. * This is only the first proposal, test and improve!
  917. * @param boolean Option to print headers when displaying error message. Default: false
  918. * @param boolean Whether session admins should be allowed or not.
  919. * @return boolean True if the user has access to the current course or is out of a course context, false otherwise
  920. * @todo replace global variable
  921. * @author Roan Embrechts
  922. */
  923. function api_protect_course_script($print_headers = false, $allow_session_admins = false, $allow_drh = false)
  924. {
  925. $is_allowed_in_course = api_is_allowed_in_course();
  926. $is_visible = false;
  927. $course_info = api_get_course_info();
  928. if (empty($course_info)) {
  929. api_not_allowed($print_headers);
  930. return false;
  931. }
  932. if (api_is_drh()) {
  933. return true;
  934. }
  935. if (api_is_platform_admin($allow_session_admins)) {
  936. return true;
  937. }
  938. if (isset($course_info) && isset($course_info['visibility'])) {
  939. switch ($course_info['visibility']) {
  940. default:
  941. case COURSE_VISIBILITY_CLOSED:
  942. // Completely closed: the course is only accessible to the teachers. - 0
  943. if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
  944. $is_visible = true;
  945. }
  946. break;
  947. case COURSE_VISIBILITY_REGISTERED:
  948. // Private - access authorized to course members only - 1
  949. if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
  950. $is_visible = true;
  951. }
  952. break;
  953. case COURSE_VISIBILITY_OPEN_PLATFORM:
  954. // Open - access allowed for users registered on the platform - 2
  955. if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
  956. $is_visible = true;
  957. }
  958. break;
  959. case COURSE_VISIBILITY_OPEN_WORLD:
  960. //Open - access allowed for the whole world - 3
  961. $is_visible = true;
  962. break;
  963. case COURSE_VISIBILITY_HIDDEN:
  964. //Completely closed: the course is only accessible to the teachers. - 0
  965. if (api_is_platform_admin()) {
  966. $is_visible = true;
  967. }
  968. break;
  969. }
  970. //If password is set and user is not registered to the course then the course is not visible
  971. if ($is_allowed_in_course == false &
  972. isset($course_info['registration_code']) &&
  973. !empty($course_info['registration_code'])
  974. ) {
  975. $is_visible = false;
  976. }
  977. }
  978. // Check session visibility
  979. $session_id = api_get_session_id();
  980. if (!empty($session_id)) {
  981. //$is_allowed_in_course was set in local.inc.php
  982. if (!$is_allowed_in_course) {
  983. $is_visible = false;
  984. }
  985. }
  986. if (!$is_visible) {
  987. api_not_allowed($print_headers);
  988. return false;
  989. }
  990. return true;
  991. }
  992. /**
  993. * Function used to protect an admin script.
  994. *
  995. * The function blocks access when the user has no platform admin rights
  996. * with an error message printed on default output
  997. * @param bool Whether to allow session admins as well
  998. * @param bool Whether to allow HR directors as well
  999. * @param string An optional message (already passed through get_lang)
  1000. * @return bool True if user is allowed, false otherwise.
  1001. * The function also outputs an error message in case not allowed
  1002. * @author Roan Embrechts (original author)
  1003. */
  1004. function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
  1005. {
  1006. if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
  1007. api_not_allowed(true, $message);
  1008. return false;
  1009. }
  1010. return true;
  1011. }
  1012. /**
  1013. * Function used to protect a teacher script.
  1014. * The function blocks access when the user has no teacher rights.
  1015. *
  1016. * @author Yoselyn Castillo
  1017. */
  1018. function api_protect_teacher_script($allow_sessions_admins = false)
  1019. {
  1020. if (!api_is_allowed_to_edit()) {
  1021. api_not_allowed(true);
  1022. return false;
  1023. }
  1024. return true;
  1025. }
  1026. /**
  1027. * Function used to prevent anonymous users from accessing a script.
  1028. * @param bool|true $printHeaders
  1029. * @author Roan Embrechts
  1030. *
  1031. * @return bool
  1032. */
  1033. function api_block_anonymous_users($printHeaders = true)
  1034. {
  1035. $user = api_get_user_info();
  1036. if (!(isset($user['user_id']) && $user['user_id']) || api_is_anonymous($user['user_id'], true)) {
  1037. api_not_allowed($printHeaders);
  1038. return false;
  1039. }
  1040. return true;
  1041. }
  1042. /**
  1043. * @return array with the navigator name and version
  1044. */
  1045. function api_get_navigator() {
  1046. $navigator = 'Unknown';
  1047. $version = 0;
  1048. if (!isset($_SERVER['HTTP_USER_AGENT'])) {
  1049. return array('name' => 'Unknown', 'version' => '0.0.0');
  1050. }
  1051. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
  1052. $navigator = 'Opera';
  1053. list (, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
  1054. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  1055. $navigator = 'Internet Explorer';
  1056. list (, $version) = explode('MSIE', $_SERVER['HTTP_USER_AGENT']);
  1057. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
  1058. $navigator = 'Chrome';
  1059. list (, $version) = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
  1060. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) {
  1061. $navigator = 'Safari';
  1062. list (, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  1063. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
  1064. $navigator = 'Mozilla';
  1065. list (, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
  1066. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') !== false) {
  1067. $navigator = 'Netscape';
  1068. list (, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
  1069. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false) {
  1070. $navigator = 'Konqueror';
  1071. list (, $version) = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
  1072. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit') !== false) {
  1073. $navigator = 'AppleWebKit';
  1074. list (, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  1075. }
  1076. $version = str_replace('/', '', $version);
  1077. if (strpos($version, '.') === false) {
  1078. $version = number_format(doubleval($version), 1);
  1079. }
  1080. $return = array('name' => $navigator, 'version' => $version);
  1081. return $return;
  1082. }
  1083. /**
  1084. * @return True if user self registration is allowed, false otherwise.
  1085. */
  1086. function api_is_self_registration_allowed()
  1087. {
  1088. return isset($GLOBALS['allowSelfReg']) ? $GLOBALS['allowSelfReg'] : false;
  1089. }
  1090. /**
  1091. * This function returns the id of the user which is stored in the $_user array.
  1092. *
  1093. * example: The function can be used to check if a user is logged in
  1094. * if (api_get_user_id())
  1095. * @return integer the id of the current user, 0 if is empty
  1096. */
  1097. function api_get_user_id()
  1098. {
  1099. $userInfo = Session::read('_user');
  1100. if ($userInfo && isset($userInfo['user_id'])) {
  1101. return $userInfo['user_id'];
  1102. }
  1103. return 0;
  1104. }
  1105. /**
  1106. * Gets the list of courses a specific user is subscribed to
  1107. * @param int User ID
  1108. * @param boolean $fetch_session Whether to get session courses or not - NOT YET IMPLEMENTED
  1109. * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
  1110. */
  1111. function api_get_user_courses($userid, $fetch_session = true)
  1112. {
  1113. // Get out if not integer
  1114. if ($userid != strval(intval($userid))) {
  1115. return array();
  1116. }
  1117. $t_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1118. $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1119. $sql = "SELECT cc.id as real_id, cc.code code, cc.directory dir, cu.status status
  1120. FROM $t_course cc,
  1121. $t_course_user cu
  1122. WHERE
  1123. cc.id = cu.c_id AND
  1124. cu.user_id = '".$userid."' AND
  1125. cu.relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
  1126. $result = Database::query($sql);
  1127. if ($result === false) {
  1128. return array();
  1129. }
  1130. $courses = array();
  1131. while ($row = Database::fetch_array($result)) {
  1132. // we only need the database name of the course
  1133. $courses[] = $row;
  1134. }
  1135. return $courses;
  1136. }
  1137. /**
  1138. * Formats user information into a standard array
  1139. * This function should be only used inside api_get_user_info()
  1140. *
  1141. * @param array Non-standard user array
  1142. * @param bool $add_password
  1143. *
  1144. * @return array Standard user array
  1145. */
  1146. function _api_format_user($user, $add_password = false)
  1147. {
  1148. $result = array();
  1149. $firstname = null;
  1150. $lastname = null;
  1151. if (isset($user['firstname']) && isset($user['lastname'])) {
  1152. $firstname = $user['firstname'];
  1153. $lastname = $user['lastname'];
  1154. } elseif (isset($user['firstName']) && isset($user['lastName'])) {
  1155. $firstname = isset($user['firstName']) ? $user['firstName'] : null;
  1156. $lastname = isset($user['lastName']) ? $user['lastName'] : null;
  1157. }
  1158. $result['complete_name'] = api_get_person_name($firstname, $lastname);
  1159. $result['complete_name_with_username'] = $result['complete_name'];
  1160. if (!empty($user['username'])) {
  1161. $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
  1162. }
  1163. $result['firstname'] = $firstname;
  1164. $result['lastname'] = $lastname;
  1165. // Kept for historical reasons
  1166. $result['firstName'] = $firstname;
  1167. $result['lastName'] = $lastname;
  1168. $attributes = array(
  1169. 'phone',
  1170. 'address',
  1171. 'picture_uri',
  1172. 'official_code',
  1173. 'status',
  1174. 'active',
  1175. 'auth_source',
  1176. 'username',
  1177. 'theme',
  1178. 'language',
  1179. 'creator_id',
  1180. 'registration_date',
  1181. 'hr_dept_id',
  1182. 'expiration_date',
  1183. 'last_login'
  1184. );
  1185. if (api_get_setting('extended_profile') === 'true') {
  1186. $attributes[] = 'competences';
  1187. $attributes[] = 'diplomas';
  1188. $attributes[] = 'teach';
  1189. $attributes[] = 'openarea';
  1190. }
  1191. foreach ($attributes as $attribute) {
  1192. $result[$attribute] = isset($user[$attribute]) ? $user[$attribute] : null;
  1193. }
  1194. if (isset($user['email'])) {
  1195. $result['mail'] = isset($user['email']) ? $user['email'] : null;
  1196. $result['email'] = isset($user['email'])? $user['email'] : null;
  1197. } else {
  1198. $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
  1199. $result['email'] = isset($user['mail'])? $user['mail'] : null;
  1200. }
  1201. $user_id = intval($user['user_id']);
  1202. // Maintain the user_id index for backwards compatibility
  1203. $result['user_id'] = $result['id'] = $user_id;
  1204. // Getting user avatar.
  1205. $originalFile = UserManager::getUserPicture($user_id, USER_IMAGE_SIZE_ORIGINAL, null, $result);
  1206. $smallFile = UserManager::getUserPicture($user_id, USER_IMAGE_SIZE_SMALL, null, $result);
  1207. $mediumFile = UserManager::getUserPicture($user_id, USER_IMAGE_SIZE_MEDIUM, null, $result);
  1208. $result['avatar'] = $originalFile;
  1209. $avatarString = explode('?', $originalFile);
  1210. $result['avatar_no_query'] = reset($avatarString);
  1211. $result['avatar_small'] = $smallFile;
  1212. $result['avatar_medium'] = $mediumFile;
  1213. if (isset($user['user_is_online'])) {
  1214. $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
  1215. }
  1216. if (isset($user['user_is_online_in_chat'])) {
  1217. $result['user_is_online_in_chat'] = intval($user['user_is_online_in_chat']);
  1218. }
  1219. if ($add_password) {
  1220. $result['password'] = $user['password'];
  1221. }
  1222. if (isset($result['profile_completed'])) {
  1223. $result['profile_completed'] = $user['profile_completed'];
  1224. }
  1225. $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
  1226. if (isset($user['extra'])) {
  1227. $result['extra'] = $user['extra'];
  1228. }
  1229. return $result;
  1230. }
  1231. /**
  1232. * Finds all the information about a user.
  1233. * If no parameter is passed you find all the information about the current user.
  1234. * @param int $user_id
  1235. * @param bool $checkIfUserOnline
  1236. * @param bool $showPassword
  1237. * @param bool $loadExtraData
  1238. * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
  1239. * @return array $user_info user_id, lastname, firstname, username, email, etc
  1240. * @author Patrick Cool <patrick.cool@UGent.be>
  1241. * @author Julio Montoya
  1242. * @version 21 September 2004
  1243. */
  1244. function api_get_user_info(
  1245. $user_id = 0,
  1246. $checkIfUserOnline = false,
  1247. $showPassword = false,
  1248. $loadExtraData = false,
  1249. $loadOnlyVisibleExtraData = false
  1250. ) {
  1251. if (empty($user_id)) {
  1252. $userFromSession = Session::read('_user');
  1253. if (isset($userFromSession)) {
  1254. return _api_format_user($userFromSession);
  1255. }
  1256. return false;
  1257. }
  1258. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)."
  1259. WHERE id='".intval($user_id)."'";
  1260. $result = Database::query($sql);
  1261. if (Database::num_rows($result) > 0) {
  1262. $result_array = Database::fetch_array($result);
  1263. if ($checkIfUserOnline) {
  1264. $use_status_in_platform = user_is_online($user_id);
  1265. $result_array['user_is_online'] = $use_status_in_platform;
  1266. $user_online_in_chat = 0;
  1267. if ($use_status_in_platform) {
  1268. $user_status = UserManager::get_extra_user_data_by_field(
  1269. $user_id,
  1270. 'user_chat_status',
  1271. false,
  1272. true
  1273. );
  1274. if (intval($user_status['user_chat_status']) == 1) {
  1275. $user_online_in_chat = 1;
  1276. }
  1277. }
  1278. $result_array['user_is_online_in_chat'] = $user_online_in_chat;
  1279. }
  1280. if ($loadExtraData) {
  1281. $fieldValue = new ExtraFieldValue('user');
  1282. $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
  1283. $user_id,
  1284. $loadOnlyVisibleExtraData
  1285. );
  1286. }
  1287. $user = _api_format_user($result_array, $showPassword);
  1288. return $user;
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * @param int $userId
  1294. * @return User
  1295. */
  1296. function api_get_user_entity($userId)
  1297. {
  1298. /** @var \Chamilo\UserBundle\Repository\UserRepository $repo */
  1299. $repo = Database::getManager()->getRepository('ChamiloUserBundle:User');
  1300. return $repo->find($userId);
  1301. }
  1302. /**
  1303. * Finds all the information about a user from username instead of user id
  1304. * @param string $username
  1305. * @return array $user_info array user_id, lastname, firstname, username, email
  1306. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  1307. */
  1308. function api_get_user_info_from_username($username = '')
  1309. {
  1310. if (empty($username)) {
  1311. return false;
  1312. }
  1313. $username = trim($username);
  1314. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)."
  1315. WHERE username='".Database::escape_string($username)."'";
  1316. $result = Database::query($sql);
  1317. if (Database::num_rows($result) > 0) {
  1318. $result_array = Database::fetch_array($result);
  1319. return _api_format_user($result_array);
  1320. }
  1321. return false;
  1322. }
  1323. /**
  1324. * Get first user with an email
  1325. * @param string $email
  1326. * @return array|bool
  1327. */
  1328. function api_get_user_info_from_email($email = '')
  1329. {
  1330. if (empty($email)) {
  1331. return false;
  1332. }
  1333. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)."
  1334. WHERE email ='".Database::escape_string($email)."' LIMIT 1";
  1335. $result = Database::query($sql);
  1336. if (Database::num_rows($result) > 0) {
  1337. $result_array = Database::fetch_array($result);
  1338. return _api_format_user($result_array);
  1339. }
  1340. return false;
  1341. }
  1342. /**
  1343. * @return string
  1344. */
  1345. function api_get_course_id()
  1346. {
  1347. return Session::read('_cid', null);
  1348. }
  1349. /**
  1350. * Returns the current course id (integer)
  1351. * @param string $code Optional course code
  1352. * @return int
  1353. */
  1354. function api_get_course_int_id($code = null)
  1355. {
  1356. if (!empty($code)) {
  1357. $code = Database::escape_string($code);
  1358. $row = Database::select(
  1359. 'id',
  1360. Database::get_main_table(TABLE_MAIN_COURSE),
  1361. array('where'=> array('code = ?' => array($code))),
  1362. 'first'
  1363. );
  1364. if (is_array($row) && isset($row['id'])) {
  1365. return $row['id'];
  1366. } else {
  1367. return false;
  1368. }
  1369. }
  1370. return Session::read('_real_cid', 0);
  1371. }
  1372. /**
  1373. * Returns the current course directory
  1374. *
  1375. * This function relies on api_get_course_info()
  1376. * @param string The course code - optional (takes it from session if not given)
  1377. * @return string The directory where the course is located inside the Chamilo "courses" directory
  1378. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  1379. */
  1380. function api_get_course_path($course_code = null)
  1381. {
  1382. $info = !empty($course_code) ? api_get_course_info($course_code) : api_get_course_info();
  1383. return $info['path'];
  1384. }
  1385. /**
  1386. * Gets a course setting from the current course_setting table. Try always using integer values.
  1387. * @param string The name of the setting we want from the table
  1388. * @param string Optional: course code
  1389. * @param string $setting_name
  1390. * @return mixed The value of that setting in that table. Return -1 if not found.
  1391. */
  1392. function api_get_course_setting($setting_name, $course_code = null)
  1393. {
  1394. $course_info = api_get_course_info($course_code);
  1395. $table = Database::get_course_table(TABLE_COURSE_SETTING);
  1396. $setting_name = Database::escape_string($setting_name);
  1397. if (!empty($course_info['real_id']) && !empty($setting_name)) {
  1398. $sql = "SELECT value FROM $table
  1399. WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
  1400. $res = Database::query($sql);
  1401. if (Database::num_rows($res) > 0) {
  1402. $row = Database::fetch_array($res);
  1403. return $row['value'];
  1404. }
  1405. }
  1406. return -1;
  1407. }
  1408. /**
  1409. * Gets an anonymous user ID
  1410. *
  1411. * For some tools that need tracking, like the learnpath tool, it is necessary
  1412. * to have a usable user-id to enable some kind of tracking, even if not
  1413. * perfect. An anonymous ID is taken from the users table by looking for a
  1414. * status of "6" (anonymous).
  1415. * @return int User ID of the anonymous user, or O if no anonymous user found
  1416. */
  1417. function api_get_anonymous_id()
  1418. {
  1419. $table = Database::get_main_table(TABLE_MAIN_USER);
  1420. $sql = "SELECT user_id FROM $table WHERE status = ".ANONYMOUS;
  1421. $res = Database::query($sql);
  1422. if (Database::num_rows($res) > 0) {
  1423. $row = Database::fetch_array($res);
  1424. return $row['user_id'];
  1425. }
  1426. // No anonymous user was found.
  1427. return 0;
  1428. }
  1429. /**
  1430. * @param string $courseCode
  1431. * @param int $sessionId
  1432. * @param int $groupId
  1433. * @return string
  1434. */
  1435. function api_get_cidreq_params($courseCode, $sessionId = 0, $groupId = 0)
  1436. {
  1437. $courseCode = !empty($courseCode) ? htmlspecialchars($courseCode) : '';
  1438. $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
  1439. $groupId = !empty($groupId) ? (int) $groupId : 0;
  1440. $url = 'cidReq='.$courseCode;
  1441. $url .= '&id_session='.$sessionId;
  1442. $url .= '&gidReq='.$groupId;
  1443. return $url;
  1444. }
  1445. /**
  1446. * Returns the current course url part including session, group, and gradebook params
  1447. *
  1448. * @param bool $addSessionId
  1449. * @param bool $addGroupId
  1450. * @param string $origin
  1451. *
  1452. * @return string Course & session references to add to a URL
  1453. *
  1454. */
  1455. function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
  1456. {
  1457. $courseCode = api_get_course_id();
  1458. $url = empty($courseCode) ? '' : 'cidReq='.htmlspecialchars($courseCode);
  1459. $origin = empty($origin) ? api_get_origin() : Security::remove_XSS($origin);
  1460. if ($addSessionId) {
  1461. if (!empty($url)) {
  1462. $url .= api_get_session_id() == 0 ? '&id_session=0' : '&id_session='.api_get_session_id();
  1463. }
  1464. }
  1465. if ($addGroupId) {
  1466. if (!empty($url)) {
  1467. $url .= api_get_group_id() == 0 ? '&gidReq=0' : '&gidReq='.api_get_group_id();
  1468. }
  1469. }
  1470. if (!empty($url)) {
  1471. $url .= '&gradebook='.intval(api_is_in_gradebook());
  1472. $url .= '&origin='.$origin;
  1473. }
  1474. return $url;
  1475. }
  1476. /**
  1477. * get gradebook in session
  1478. */
  1479. function api_is_in_gradebook()
  1480. {
  1481. return Session::read('in_gradebook', false);
  1482. }
  1483. /**
  1484. * set gradebook session
  1485. */
  1486. function api_set_in_gradebook()
  1487. {
  1488. Session::write('in_gradebook', true);
  1489. }
  1490. /**
  1491. * remove gradebook session
  1492. */
  1493. function api_remove_in_gradebook()
  1494. {
  1495. Session::erase('in_gradebook');
  1496. }
  1497. /**
  1498. * Returns the current course info array see api_format_course_array()
  1499. * If the course_code is given, the returned array gives info about that
  1500. * particular course, if none given it gets the course info from the session.
  1501. *
  1502. * @param string $course_code
  1503. * @param bool $strict
  1504. *
  1505. * @return array
  1506. */
  1507. function api_get_course_info($course_code = null, $strict = false)
  1508. {
  1509. if (!empty($course_code)) {
  1510. $course_code = Database::escape_string($course_code);
  1511. $courseId = api_get_course_int_id($course_code);
  1512. if (empty($courseId)) {
  1513. return array();
  1514. }
  1515. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1516. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1517. $sql = "SELECT
  1518. course.*,
  1519. course_category.code faCode,
  1520. course_category.name faName
  1521. FROM $course_table
  1522. LEFT JOIN $course_cat_table
  1523. ON course.category_code = course_category.code
  1524. WHERE course.id = $courseId";
  1525. $result = Database::query($sql);
  1526. $courseInfo = array();
  1527. if (Database::num_rows($result) > 0) {
  1528. $data = Database::fetch_array($result);
  1529. $courseInfo = api_format_course_array($data);
  1530. }
  1531. return $courseInfo;
  1532. }
  1533. global $_course;
  1534. if ($_course == '-1') {
  1535. $_course = array();
  1536. }
  1537. return $_course;
  1538. }
  1539. /**
  1540. * Returns the current course info array.
  1541. * Now if the course_code is given, the returned array gives info about that
  1542. * particular course, not specially the current one.
  1543. * @param int $id Numeric ID of the course
  1544. * @return array The course info as an array formatted by api_format_course_array, including category.name
  1545. */
  1546. function api_get_course_info_by_id($id = null)
  1547. {
  1548. if (!empty($id)) {
  1549. $id = intval($id);
  1550. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1551. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1552. $sql = "SELECT
  1553. course.*,
  1554. course_category.code faCode,
  1555. course_category.name faName
  1556. FROM $course_table
  1557. LEFT JOIN $course_cat_table
  1558. ON course.category_code = course_category.code
  1559. WHERE course.id = $id";
  1560. $result = Database::query($sql);
  1561. $_course = array();
  1562. if (Database::num_rows($result) > 0) {
  1563. $course_data = Database::fetch_array($result);
  1564. $_course = api_format_course_array($course_data);
  1565. }
  1566. return $_course;
  1567. }
  1568. global $_course;
  1569. if ($_course == '-1') $_course = array();
  1570. return $_course;
  1571. }
  1572. /**
  1573. * Reformat the course array (output by api_get_course_info()) in order, mostly,
  1574. * to switch from 'code' to 'id' in the array. This is a legacy feature and is
  1575. * now possibly causing massive confusion as a new "id" field has been added to
  1576. * the course table in 1.9.0.
  1577. * @param $course_data
  1578. * @return array
  1579. * @todo eradicate the false "id"=code field of the $_course array and use the int id
  1580. */
  1581. function api_format_course_array($course_data)
  1582. {
  1583. if (empty($course_data)) {
  1584. return array();
  1585. }
  1586. $_course = array();
  1587. $_course['id'] = $course_data['code'];
  1588. $_course['real_id'] = $course_data['id'];
  1589. // Added
  1590. $_course['code'] = $course_data['code'];
  1591. $_course['name'] = $course_data['title'];
  1592. $_course['title'] = $course_data['title'];
  1593. $_course['official_code'] = $course_data['visual_code'];
  1594. $_course['visual_code'] = $course_data['visual_code'];
  1595. $_course['sysCode'] = $course_data['code'];
  1596. $_course['path'] = $course_data['directory']; // Use as key in path.
  1597. $_course['directory'] = $course_data['directory'];
  1598. $_course['creation_date'] = $course_data['creation_date'];
  1599. $_course['titular'] = $course_data['tutor_name'];
  1600. $_course['language'] = $course_data['course_language'];
  1601. $_course['extLink']['url'] = $course_data['department_url'];
  1602. $_course['extLink']['name'] = $course_data['department_name'];
  1603. $_course['categoryCode'] = $course_data['faCode'];
  1604. $_course['categoryName'] = $course_data['faName'];
  1605. $_course['visibility'] = $course_data['visibility'];
  1606. $_course['subscribe_allowed'] = $course_data['subscribe'];
  1607. $_course['subscribe'] = $course_data['subscribe'];
  1608. $_course['unsubscribe'] = $course_data['unsubscribe'];
  1609. $_course['course_language'] = $course_data['course_language'];
  1610. $_course['activate_legal'] = isset($course_data['activate_legal']) ? $course_data['activate_legal'] : false;
  1611. $_course['legal'] = $course_data['legal'];
  1612. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  1613. $_course['department_name'] = $course_data['department_name'];
  1614. $_course['department_url'] = $course_data['department_url'];
  1615. // Course password
  1616. $_course['registration_code'] = !empty($course_data['registration_code']) ? sha1($course_data['registration_code']) : null;
  1617. $_course['disk_quota'] = $course_data['disk_quota'];
  1618. $_course['course_public_url'] = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/index.php';
  1619. if (array_key_exists('add_teachers_to_sessions_courses', $course_data)) {
  1620. $_course['add_teachers_to_sessions_courses'] = $course_data['add_teachers_to_sessions_courses'];
  1621. }
  1622. if (file_exists(api_get_path(SYS_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png')) {
  1623. $url_image = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png';
  1624. } else {
  1625. $url_image = Display::return_icon('course.png', null, null, ICON_SIZE_BIG, null, true, false);
  1626. }
  1627. $_course['course_image'] = $url_image;
  1628. if (file_exists(api_get_path(SYS_COURSE_PATH).$course_data['directory'].'/course-pic.png')) {
  1629. $url_image = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/course-pic.png';
  1630. } else {
  1631. $url_image = Display::returnIconPath('session_default.png');
  1632. }
  1633. $_course['course_image_large'] = $url_image;
  1634. return $_course;
  1635. }
  1636. /**
  1637. * Add a parameter to the existing URL. If this parameter already exists,
  1638. * just replace it with the new value
  1639. * @param string The URL
  1640. * @param string param=value string
  1641. * @param boolean Whether to filter XSS or not
  1642. * @return string The URL with the added parameter
  1643. */
  1644. function api_add_url_param($url, $param, $filter_xss = true) {
  1645. if (empty($param)) {
  1646. return $url;
  1647. }
  1648. if (strpos($url, '?') !== false) {
  1649. if ($param[0] != '&') {
  1650. $param = '&'.$param;
  1651. }
  1652. list (, $query_string) = explode('?', $url);
  1653. $param_list1 = explode('&', $param);
  1654. $param_list2 = explode('&', $query_string);
  1655. $param_list1_keys = $param_list1_vals = array();
  1656. foreach ($param_list1 as $key => $enreg) {
  1657. list ($param_list1_keys[$key], $param_list1_vals[$key]) = explode('=', $enreg);
  1658. }
  1659. $param_list1 = array ('keys' => $param_list1_keys, 'vals' => $param_list1_vals);
  1660. foreach ($param_list2 as $enreg) {
  1661. $enreg = explode('=', $enreg);
  1662. $key = array_search($enreg[0], $param_list1['keys']);
  1663. if (!is_null($key) && !is_bool($key)) {
  1664. $url = str_replace($enreg[0].'='.$enreg[1], $enreg[0].'='.$param_list1['vals'][$key], $url);
  1665. $param = str_replace('&'.$enreg[0].'='.$param_list1['vals'][$key], '', $param);
  1666. }
  1667. }
  1668. $url .= $param;
  1669. } else {
  1670. $url = $url.'?'.$param;
  1671. }
  1672. if ($filter_xss === true) {
  1673. $url = Security::remove_XSS(urldecode($url));
  1674. }
  1675. return $url;
  1676. }
  1677. /**
  1678. * Returns a difficult to guess password.
  1679. * @param int $length the length of the password
  1680. * @return string the generated password
  1681. */
  1682. function api_generate_password($length = 8)
  1683. {
  1684. $characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  1685. $numbers = '23456789';
  1686. if ($length < 2) {
  1687. $length = 2;
  1688. }
  1689. $password = '';
  1690. for ($i = 0; $i < $length; $i ++) {
  1691. $password .= $characters[rand() % strlen($characters)];
  1692. }
  1693. // At least 2 digits
  1694. for ($i = 0; $i < 2; $i ++) {
  1695. $password .= $numbers[rand() % strlen($numbers)];
  1696. }
  1697. return $password;
  1698. }
  1699. /**
  1700. * Checks a password to see wether it is OK to use.
  1701. * @param string $password
  1702. * @return boolean if the password is acceptable, false otherwise
  1703. * Notes about what a password "OK to use" is:
  1704. * 1. The password should be at least 5 characters long.
  1705. * 2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
  1706. * 3. The password should contain at least 3 letters.
  1707. * 4. It should contain at least 2 digits.
  1708. * 5. It should not contain 3 or more consequent (according to ASCII table) characters.
  1709. */
  1710. function api_check_password($password) {
  1711. $password_length = api_strlen($password);
  1712. if ($password_length < 5) {
  1713. return false;
  1714. }
  1715. $password = api_strtolower($password);
  1716. $letters = 0;
  1717. $digits = 0;
  1718. $consequent_characters = 0;
  1719. $previous_character_code = 0;
  1720. for ($i = 0; $i < $password_length; $i ++) {
  1721. $current_character_code = api_ord(api_substr($password, $i, 1));
  1722. if ($i && abs($current_character_code - $previous_character_code) <= 1) {
  1723. $consequent_characters ++;
  1724. if ($consequent_characters == 3) {
  1725. return false;
  1726. }
  1727. } else {
  1728. $consequent_characters = 1;
  1729. }
  1730. if ($current_character_code >= 97 && $current_character_code <= 122) {
  1731. $letters ++;
  1732. } elseif ($current_character_code >= 48 && $current_character_code <= 57) {
  1733. $digits ++;
  1734. } else {
  1735. return false;
  1736. }
  1737. $previous_character_code = $current_character_code;
  1738. }
  1739. return ($letters >= 3 && $digits >= 2);
  1740. }
  1741. /**
  1742. * Clears the user ID from the session if it was the anonymous user. Generally
  1743. * used on out-of-tools pages to remove a user ID that could otherwise be used
  1744. * in the wrong context.
  1745. * This function is to be used in conjunction with the api_set_anonymous()
  1746. * function to simulate the user existence in case of an anonymous visit.
  1747. * @param bool database check switch - passed to api_is_anonymous()
  1748. * @return bool true if succesfully unregistered, false if not anonymous.
  1749. */
  1750. function api_clear_anonymous($db_check = false)
  1751. {
  1752. global $_user;
  1753. if (api_is_anonymous($_user['user_id'], $db_check)) {
  1754. unset($_user['user_id']);
  1755. Session::erase('_uid');
  1756. return true;
  1757. }
  1758. return false;
  1759. }
  1760. /**
  1761. * Returns the status string corresponding to the status code
  1762. * @author Noel Dieschburg
  1763. * @param the int status code
  1764. */
  1765. function get_status_from_code($status_code) {
  1766. switch ($status_code) {
  1767. case STUDENT:
  1768. return get_lang('Student', '');
  1769. case TEACHER:
  1770. return get_lang('Teacher', '');
  1771. case COURSEMANAGER:
  1772. return get_lang('Manager', '');
  1773. case SESSIONADMIN:
  1774. return get_lang('SessionsAdmin', '');
  1775. case DRH:
  1776. return get_lang('Drh', '');
  1777. }
  1778. }
  1779. /**
  1780. * Sets the current user as anonymous if it hasn't been identified yet. This
  1781. * function should be used inside a tool only. The function api_clear_anonymous()
  1782. * acts in the opposite direction by clearing the anonymous user's data every
  1783. * time we get on a course homepage or on a neutral page (index, admin, my space)
  1784. * @return bool true if set user as anonymous, false if user was already logged in or anonymous id could not be found
  1785. */
  1786. function api_set_anonymous() {
  1787. global $_user;
  1788. if (!empty($_user['user_id'])) {
  1789. return false;
  1790. }
  1791. $user_id = api_get_anonymous_id();
  1792. if ($user_id == 0) {
  1793. return false;
  1794. }
  1795. Session::erase('_user');
  1796. $_user['user_id'] = $user_id;
  1797. $_user['is_anonymous'] = true;
  1798. $GLOBALS['_user'] = $_user;
  1799. Session::write('_user', $_user);
  1800. return true;
  1801. }
  1802. /* CONFIGURATION SETTINGS */
  1803. /**
  1804. * Gets the current Chamilo (not PHP/cookie) session ID
  1805. * @return int O if no active session, the session ID otherwise
  1806. */
  1807. function api_get_session_id()
  1808. {
  1809. return Session::read('id_session', 0);
  1810. }
  1811. /**
  1812. * Gets the current Chamilo (not social network) group ID
  1813. * @return int O if no active session, the session ID otherwise
  1814. */
  1815. function api_get_group_id()
  1816. {
  1817. return Session::read('_gid', 0);
  1818. }
  1819. /**
  1820. * Gets the current or given session name
  1821. * @param int Session ID (optional)
  1822. * @return string The session name, or null if unfound
  1823. */
  1824. function api_get_session_name($session_id = 0) {
  1825. if (empty($session_id)) {
  1826. $session_id = api_get_session_id();
  1827. if (empty($session_id)) { return null; }
  1828. }
  1829. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1830. $s = "SELECT name FROM $t WHERE id = ".(int)$session_id;
  1831. $r = Database::query($s);
  1832. $c = Database::num_rows($r);
  1833. if ($c > 0) {
  1834. //technically, there can be only one, but anyway we take the first
  1835. $rec = Database::fetch_array($r);
  1836. return $rec['name'];
  1837. }
  1838. return null;
  1839. }
  1840. /**
  1841. * Gets the session info by id
  1842. * @param int Session ID
  1843. * @return array information of the session
  1844. */
  1845. function api_get_session_info($session_id)
  1846. {
  1847. return SessionManager::fetch($session_id);
  1848. }
  1849. /**
  1850. * Gets the session visibility by session id
  1851. * @param int $session_id
  1852. * @param int $courseId
  1853. * @param bool $ignore_visibility_for_admins
  1854. * @return int
  1855. * 0 = session still available,
  1856. * SESSION_VISIBLE_READ_ONLY = 1,
  1857. * SESSION_VISIBLE = 2,
  1858. * SESSION_INVISIBLE = 3
  1859. */
  1860. function api_get_session_visibility(
  1861. $session_id,
  1862. $courseId = null,
  1863. $ignore_visibility_for_admins = true
  1864. ) {
  1865. // Means that the session is still available.
  1866. $visibility = 0;
  1867. if (api_is_platform_admin()) {
  1868. if ($ignore_visibility_for_admins) {
  1869. return SESSION_AVAILABLE;
  1870. }
  1871. }
  1872. $now = time();
  1873. if (!empty($session_id)) {
  1874. $session_id = intval($session_id);
  1875. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1876. $sql = "SELECT * FROM $tbl_session
  1877. WHERE id = $session_id ";
  1878. $result = Database::query($sql);
  1879. if (Database::num_rows($result) > 0) {
  1880. $row = Database::fetch_array($result, 'ASSOC');
  1881. $visibility = $original_visibility = $row['visibility'];
  1882. // I don't care the session visibility.
  1883. if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
  1884. // Session duration per student.
  1885. if (isset($row['duration']) && !empty($row['duration'])) {
  1886. $duration = $row['duration'] * 24 * 60 * 60;
  1887. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  1888. $session_id,
  1889. api_get_user_id()
  1890. );
  1891. // If there is a session duration but there is no previous
  1892. // access by the user, then the session is still available
  1893. if (count($courseAccess) == 0) {
  1894. return SESSION_AVAILABLE;
  1895. }
  1896. $currentTime = time();
  1897. $firstAccess = 0;
  1898. if (isset($courseAccess['login_course_date'])) {
  1899. $firstAccess = api_strtotime(
  1900. $courseAccess['login_course_date'],
  1901. 'UTC'
  1902. );
  1903. }
  1904. $userDurationData = SessionManager::getUserSession(
  1905. api_get_user_id(),
  1906. $session_id
  1907. );
  1908. $userDuration = 0;
  1909. if (isset($userDurationData['duration'])) {
  1910. $userDuration = intval($userDurationData['duration']) * 24 * 60 * 60;
  1911. }
  1912. $totalDuration = $firstAccess + $duration + $userDuration;
  1913. if ($totalDuration > $currentTime) {
  1914. return SESSION_AVAILABLE;
  1915. } else {
  1916. return SESSION_INVISIBLE;
  1917. }
  1918. }
  1919. return SESSION_AVAILABLE;
  1920. } else {
  1921. // If start date was set.
  1922. if (!empty($row['access_start_date'])) {
  1923. if ($now > api_strtotime($row['access_start_date'], 'UTC')) {
  1924. $visibility = SESSION_AVAILABLE;
  1925. } else {
  1926. $visibility = SESSION_INVISIBLE;
  1927. }
  1928. }
  1929. // If the end date was set.
  1930. if (!empty($row['access_end_date'])) {
  1931. // Only if date_start said that it was ok
  1932. if ($visibility === SESSION_AVAILABLE) {
  1933. if ($now < api_strtotime($row['access_end_date'], 'UTC')) {
  1934. // Date still available
  1935. $visibility = SESSION_AVAILABLE;
  1936. } else {
  1937. // Session ends
  1938. $visibility = $row['visibility'];
  1939. }
  1940. }
  1941. }
  1942. }
  1943. /* If I'm a coach the visibility can change in my favor depending in
  1944. the coach dates */
  1945. $isCoach = api_is_coach($session_id, $courseId);
  1946. if ($isCoach) {
  1947. // Test end date.
  1948. if (!empty($row['coach_access_end_date'])) {
  1949. $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
  1950. if ($endDateCoach >= $now) {
  1951. $visibility = SESSION_AVAILABLE;
  1952. } else {
  1953. $visibility = SESSION_INVISIBLE;
  1954. }
  1955. }
  1956. // Test start date.
  1957. if (!empty($row['coach_access_start_date'])) {
  1958. $start = api_strtotime($row['coach_access_start_date'], 'UTC');
  1959. if ($start < $now) {
  1960. $visibility = SESSION_AVAILABLE;
  1961. } else {
  1962. $visibility = SESSION_INVISIBLE;
  1963. }
  1964. }
  1965. }
  1966. } else {
  1967. $visibility = SESSION_INVISIBLE;
  1968. }
  1969. }
  1970. return $visibility;
  1971. }
  1972. /**
  1973. * This function returns a (star) session icon if the session is not null and
  1974. * the user is not a student
  1975. * @param int $session_id
  1976. * @param int $status_id User status id - if 5 (student), will return empty
  1977. * @return string Session icon
  1978. */
  1979. function api_get_session_image($session_id, $status_id)
  1980. {
  1981. $session_id = (int)$session_id;
  1982. $session_img = '';
  1983. if ((int)$status_id != 5) { //check whether is not a student
  1984. if ($session_id > 0) {
  1985. $session_img = "&nbsp;&nbsp;".Display::return_icon(
  1986. 'star.png',
  1987. get_lang('SessionSpecificResource'),
  1988. array('align' => 'absmiddle'),
  1989. ICON_SIZE_SMALL
  1990. );
  1991. }
  1992. }
  1993. return $session_img;
  1994. }
  1995. /**
  1996. * This function add an additional condition according to the session of the course
  1997. * @param int $session_id session id
  1998. * @param bool $and optional, true if more than one condition false if the only condition in the query
  1999. * @param bool $with_base_content optional, true to accept content with session=0 as well, false for strict session condition
  2000. * @return string condition of the session
  2001. */
  2002. function api_get_session_condition(
  2003. $session_id,
  2004. $and = true,
  2005. $with_base_content = false,
  2006. $session_field = "session_id"
  2007. ) {
  2008. $session_id = intval($session_id);
  2009. if (empty($session_field)) {
  2010. $session_field = "session_id";
  2011. }
  2012. // Condition to show resources by session
  2013. $condition_add = $and ? " AND " : " WHERE ";
  2014. if ($with_base_content) {
  2015. $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
  2016. } else {
  2017. if (empty($session_id)) {
  2018. $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
  2019. } else {
  2020. $condition_session = $condition_add." $session_field = $session_id ";
  2021. }
  2022. }
  2023. return $condition_session;
  2024. }
  2025. /**
  2026. * Returns the value of a setting from the web-adjustable admin config settings.
  2027. *
  2028. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  2029. * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
  2030. * instead of
  2031. * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
  2032. * @param string $variable The variable name
  2033. * @param string $key The subkey (sub-variable) if any. Defaults to NULL
  2034. * @return string
  2035. * @author René Haentjens
  2036. * @author Bart Mollet
  2037. */
  2038. function api_get_setting($variable, $key = null)
  2039. {
  2040. global $_setting;
  2041. if ($variable == 'header_extra_content') {
  2042. $filename = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt';
  2043. if (file_exists($filename)) {
  2044. $value = file_get_contents($filename);
  2045. return $value;
  2046. } else {
  2047. return '';
  2048. }
  2049. }
  2050. if ($variable == 'footer_extra_content') {
  2051. $filename = api_get_path(SYS_PATH).api_get_home_path().'footer_extra_content.txt';
  2052. if (file_exists($filename)) {
  2053. $value = file_get_contents($filename);
  2054. return $value;
  2055. } else {
  2056. return '';
  2057. }
  2058. }
  2059. $value = null;
  2060. if (is_null($key)) {
  2061. $value = ((isset($_setting[$variable]) && $_setting[$variable] != '') ? $_setting[$variable] : null);
  2062. } else {
  2063. if (isset($_setting[$variable][$key])) {
  2064. $value = $_setting[$variable][$key];
  2065. }
  2066. }
  2067. return $value;
  2068. }
  2069. /**
  2070. * @param string $plugin
  2071. * @param string $variable
  2072. * @return string
  2073. */
  2074. function api_get_plugin_setting($plugin, $variable)
  2075. {
  2076. $variableName = $plugin.'_'.$variable;
  2077. $result = api_get_setting($variableName);
  2078. if (isset($result[$plugin])) {
  2079. return $result[$plugin];
  2080. }
  2081. return null;
  2082. }
  2083. /**
  2084. * Returns the value of a setting from the web-adjustable admin config settings.
  2085. **/
  2086. function api_get_settings_params($params) {
  2087. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2088. $result = Database::select('*', $table, array('where' => $params));
  2089. return $result;
  2090. }
  2091. function api_get_settings_params_simple($params) {
  2092. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2093. $result = Database::select('*', $table, array('where' => $params), 'one');
  2094. return $result;
  2095. }
  2096. /**
  2097. * Returns the value of a setting from the web-adjustable admin config settings.
  2098. **/
  2099. function api_delete_settings_params($params) {
  2100. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2101. $result = Database::delete($table, $params);
  2102. return $result;
  2103. }
  2104. /**
  2105. * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection
  2106. * @return string Escaped version of $_SERVER['PHP_SELF']
  2107. */
  2108. function api_get_self() {
  2109. return htmlentities($_SERVER['PHP_SELF']);
  2110. }
  2111. /* USER PERMISSIONS */
  2112. /**
  2113. * Checks whether current user is a platform administrator
  2114. * @param boolean $allowSessionAdmins Whether session admins should be considered admins or not
  2115. * @param boolean $allowDrh Whether HR directors should be considered admins or not
  2116. * @return boolean True if the user has platform admin rights,
  2117. * false otherwise.
  2118. * @see usermanager::is_admin(user_id) for a user-id specific function
  2119. */
  2120. function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
  2121. {
  2122. $isAdmin = Session::read('is_platformAdmin');
  2123. if ($isAdmin) {
  2124. return true;
  2125. }
  2126. $user = api_get_user_info();
  2127. return
  2128. isset($user['status']) &&
  2129. (
  2130. ($allowSessionAdmins && $user['status'] == SESSIONADMIN) ||
  2131. ($allowDrh && $user['status'] == DRH)
  2132. );
  2133. }
  2134. /**
  2135. * Checks whether the user given as user id is in the admin table.
  2136. * @param int $user_id If none provided, will use current user
  2137. * @param int $url URL ID. If provided, also check if the user is active on given URL
  2138. * @return bool True if the user is admin, false otherwise
  2139. */
  2140. function api_is_platform_admin_by_id($user_id = null, $url = null)
  2141. {
  2142. $user_id = intval($user_id);
  2143. if (empty($user_id)) {
  2144. $user_id = api_get_user_id();
  2145. }
  2146. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  2147. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  2148. $res = Database::query($sql);
  2149. $is_admin = Database::num_rows($res) === 1;
  2150. if (!$is_admin || !isset($url)) {
  2151. return $is_admin;
  2152. }
  2153. // We get here only if $url is set
  2154. $url = intval($url);
  2155. $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2156. $sql = "SELECT * FROM $url_user_table
  2157. WHERE access_url_id = $url AND user_id = $user_id";
  2158. $res = Database::query($sql);
  2159. $is_on_url = Database::num_rows($res) === 1;
  2160. return $is_on_url;
  2161. }
  2162. /**
  2163. * Returns the user's numeric status ID from the users table
  2164. * @param int $user_id If none provided, will use current user
  2165. * @return int User's status (1 for teacher, 5 for student, etc)
  2166. */
  2167. function api_get_user_status($user_id = null)
  2168. {
  2169. $user_id = intval($user_id);
  2170. if (empty($user_id)) {
  2171. $user_id = api_get_user_id();
  2172. }
  2173. $table = Database::get_main_table(TABLE_MAIN_USER);
  2174. $sql = "SELECT status FROM $table WHERE user_id = $user_id ";
  2175. $result = Database::query($sql);
  2176. $status = null;
  2177. if (Database::num_rows($result)) {
  2178. $row = Database::fetch_array($result);
  2179. $status = $row['status'];
  2180. }
  2181. return $status;
  2182. }
  2183. /**
  2184. * Checks whether current user is allowed to create courses
  2185. * @return boolean True if the user has course creation rights,
  2186. * false otherwise.
  2187. */
  2188. function api_is_allowed_to_create_course()
  2189. {
  2190. if (api_is_platform_admin()) {
  2191. return true;
  2192. }
  2193. // Teachers can only create courses
  2194. if (api_is_teacher()) {
  2195. if (api_get_setting('allow_users_to_create_courses') === 'true') {
  2196. return true;
  2197. } else {
  2198. return false;
  2199. }
  2200. }
  2201. return Session::read('is_allowedCreateCourse');
  2202. }
  2203. /**
  2204. * Checks whether the current user is a course administrator
  2205. * @return boolean True if current user is a course administrator
  2206. */
  2207. function api_is_course_admin() {
  2208. if (api_is_platform_admin()) {
  2209. return true;
  2210. }
  2211. return Session::read('is_courseAdmin');
  2212. }
  2213. /**
  2214. * Checks whether the current user is a course coach
  2215. * @return bool True if current user is a course coach
  2216. */
  2217. function api_is_course_coach() {
  2218. return Session::read('is_courseCoach');
  2219. }
  2220. /**
  2221. * Checks whether the current user is a course tutor
  2222. * @return bool True if current user is a course tutor
  2223. */
  2224. function api_is_course_tutor() {
  2225. return Session::read('is_courseTutor');
  2226. }
  2227. /**
  2228. * @param int $user_id
  2229. * @param int $courseId
  2230. * @param int $session_id
  2231. * @return bool
  2232. */
  2233. function api_is_course_session_coach($user_id, $courseId, $session_id)
  2234. {
  2235. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2236. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2237. $user_id = intval($user_id);
  2238. $session_id = intval($session_id);
  2239. $courseId = intval($courseId);
  2240. $sql = "SELECT DISTINCT session.id
  2241. FROM $session_table
  2242. INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  2243. ON session.id = session_rc_ru.session_id
  2244. WHERE
  2245. session_rc_ru.user_id = '".$user_id."' AND
  2246. session_rc_ru.c_id = '$courseId' AND
  2247. session_rc_ru.status = 2 AND
  2248. session_rc_ru.session_id = '$session_id'";
  2249. $result = Database::query($sql);
  2250. return Database::num_rows($result) > 0;
  2251. }
  2252. /**
  2253. * Checks whether the current user is a course or session coach
  2254. * @param int $session_id
  2255. * @param int $courseId
  2256. * @param bool Check whether we are in student view and, if we are, return false
  2257. * @return boolean True if current user is a course or session coach
  2258. */
  2259. function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true)
  2260. {
  2261. $userId = api_get_user_id();
  2262. if (!empty($session_id)) {
  2263. $session_id = intval($session_id);
  2264. } else {
  2265. $session_id = api_get_session_id();
  2266. }
  2267. // The student preview was on
  2268. if ($check_student_view &&
  2269. isset($_SESSION['studentview']) && $_SESSION['studentview'] == "studentview"
  2270. ) {
  2271. return false;
  2272. }
  2273. if (!empty($courseId)) {
  2274. $courseId = intval($courseId);
  2275. } else {
  2276. $courseId = api_get_course_int_id();
  2277. }
  2278. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2279. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2280. $sessionIsCoach = null;
  2281. if (!empty($courseId)) {
  2282. $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
  2283. FROM $session_table s
  2284. INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  2285. ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
  2286. WHERE
  2287. session_rc_ru.c_id = '$courseId' AND
  2288. session_rc_ru.status = 2 AND
  2289. session_rc_ru.session_id = '$session_id'";
  2290. $result = Database::query($sql);
  2291. $sessionIsCoach = Database::store_result($result);
  2292. }
  2293. if (!empty($session_id)) {
  2294. $sql = "SELECT DISTINCT id, name, access_start_date, access_end_date
  2295. FROM $session_table
  2296. WHERE session.id_coach = $userId AND id = $session_id
  2297. ORDER BY access_start_date, access_end_date, name";
  2298. $result = Database::query($sql);
  2299. if (!empty($sessionIsCoach)) {
  2300. $sessionIsCoach = array_merge($sessionIsCoach , Database::store_result($result));
  2301. } else {
  2302. $sessionIsCoach = Database::store_result($result);
  2303. }
  2304. }
  2305. return (count($sessionIsCoach) > 0);
  2306. }
  2307. /**
  2308. * Checks whether the current user is a session administrator
  2309. * @return boolean True if current user is a course administrator
  2310. */
  2311. function api_is_session_admin()
  2312. {
  2313. $user = api_get_user_info();
  2314. return isset($user['status']) && $user['status'] == SESSIONADMIN;
  2315. }
  2316. /**
  2317. * Checks whether the current user is a human resources manager
  2318. * @return boolean True if current user is a human resources manager
  2319. */
  2320. function api_is_drh()
  2321. {
  2322. $user = api_get_user_info();
  2323. return isset($user['status']) && $user['status'] == DRH;
  2324. }
  2325. /**
  2326. * Checks whether the current user is a student
  2327. * @return boolean True if current user is a human resources manager
  2328. */
  2329. function api_is_student()
  2330. {
  2331. $user = api_get_user_info();
  2332. return isset($user['status']) && $user['status'] == STUDENT;
  2333. }
  2334. /**
  2335. * Checks whether the current user has the status 'teacher'
  2336. * @return boolean True if current user is a human resources manager
  2337. */
  2338. function api_is_teacher()
  2339. {
  2340. $user = api_get_user_info();
  2341. return isset($user['status']) && $user['status'] == COURSEMANAGER;
  2342. }
  2343. /**
  2344. * Checks whether the current user is a invited user
  2345. * @return boolean
  2346. */
  2347. function api_is_invitee()
  2348. {
  2349. $user = api_get_user_info();
  2350. return isset($user['status']) && $user['status'] == INVITEE;
  2351. }
  2352. /**
  2353. * This function checks whether a session is assigned into a category
  2354. * @param int - session id
  2355. * @param string - category name
  2356. * @return bool - true if is found, otherwise false
  2357. */
  2358. function api_is_session_in_category($session_id, $category_name)
  2359. {
  2360. $session_id = intval($session_id);
  2361. $category_name = Database::escape_string($category_name);
  2362. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2363. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2364. $sql = "SELECT 1
  2365. FROM $tbl_session
  2366. WHERE $session_id IN (
  2367. SELECT s.id FROM $tbl_session s, $tbl_session_category sc
  2368. WHERE
  2369. s.session_category_id = sc.id AND
  2370. sc.name LIKE '%$category_name'
  2371. )";
  2372. $rs = Database::query($sql);
  2373. if (Database::num_rows($rs) > 0) {
  2374. return true;
  2375. } else {
  2376. return false;
  2377. }
  2378. }
  2379. /**
  2380. * Displays the title of a tool.
  2381. * Normal use: parameter is a string:
  2382. * api_display_tool_title("My Tool")
  2383. *
  2384. * Optionally, there can be a subtitle below
  2385. * the normal title, and / or a supra title above the normal title.
  2386. *
  2387. * e.g. supra title:
  2388. * group
  2389. * GROUP PROPERTIES
  2390. *
  2391. * e.g. subtitle:
  2392. * AGENDA
  2393. * calender & events tool
  2394. *
  2395. * @author Hugues Peeters <hugues.peeters@claroline.net>
  2396. * @param mixed $title_element - it could either be a string or an array
  2397. * containing 'supraTitle', 'mainTitle',
  2398. * 'subTitle'
  2399. * @return void
  2400. */
  2401. function api_display_tool_title($title_element) {
  2402. if (is_string($title_element)) {
  2403. $tit = $title_element;
  2404. unset ($title_element);
  2405. $title_element['mainTitle'] = $tit;
  2406. }
  2407. echo '<h3>';
  2408. if (!empty($title_element['supraTitle'])) {
  2409. echo '<small>'.$title_element['supraTitle'].'</small><br />';
  2410. }
  2411. if (!empty($title_element['mainTitle'])) {
  2412. echo $title_element['mainTitle'];
  2413. }
  2414. if (!empty($title_element['subTitle'])) {
  2415. echo '<br /><small>'.$title_element['subTitle'].'</small>';
  2416. }
  2417. echo '</h3>';
  2418. }
  2419. /**
  2420. * Displays options for switching between student view and course manager view
  2421. *
  2422. * Changes in version 1.2 (Patrick Cool)
  2423. * Student view switch now behaves as a real switch. It maintains its current state until the state
  2424. * is changed explicitly
  2425. *
  2426. * Changes in version 1.1 (Patrick Cool)
  2427. * student view now works correctly in subfolders of the document tool
  2428. * student view works correctly in the new links tool
  2429. *
  2430. * Example code for using this in your tools:
  2431. * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
  2432. * // display_tool_view_option($isStudentView);
  2433. * //}
  2434. * //and in later sections, use api_is_allowed_to_edit()
  2435. *
  2436. * @author Roan Embrechts
  2437. * @author Patrick Cool
  2438. * @author Julio Montoya, changes added in Chamilo
  2439. * @version 1.2
  2440. * @todo rewrite code so it is easier to understand
  2441. */
  2442. function api_display_tool_view_option() {
  2443. if (api_get_setting('student_view_enabled') != 'true') {
  2444. return '';
  2445. }
  2446. $sourceurl = '';
  2447. $is_framed = false;
  2448. // Exceptions apply for all multi-frames pages
  2449. if (strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php') !== false) {
  2450. // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
  2451. return '';
  2452. }
  2453. // Uncomment to remove student view link from document view page
  2454. if (strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php') !== false) {
  2455. if (empty($_GET['lp_id'])) {
  2456. return '';
  2457. }
  2458. $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
  2459. $sourceurl = str_replace('lp/lp_header.php', 'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview']=='studentview' ? 'false' : 'true'), $sourceurl);
  2460. //showinframes doesn't handle student view anyway...
  2461. //return '';
  2462. $is_framed = true;
  2463. }
  2464. // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  2465. if (!$is_framed) {
  2466. if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
  2467. $sourceurl = api_get_self().'?'.api_get_cidreq();
  2468. } else {
  2469. $sourceurl = $_SERVER['REQUEST_URI'];
  2470. }
  2471. }
  2472. $output_string = '';
  2473. if (!empty($_SESSION['studentview'])) {
  2474. if ($_SESSION['studentview'] == 'studentview') {
  2475. // We have to remove the isStudentView=true from the $sourceurl
  2476. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2477. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2478. $output_string .= '<a class="btn btn-primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToTeacherView').'</a>';
  2479. } elseif ($_SESSION['studentview'] == 'teacherview') {
  2480. // Switching to teacherview
  2481. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2482. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2483. $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
  2484. }
  2485. } else {
  2486. $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
  2487. }
  2488. $html = Display::tag('div', $output_string, array('class'=>'view-options'));
  2489. return $html;
  2490. }
  2491. // TODO: This is for the permission section.
  2492. /**
  2493. * Function that removes the need to directly use is_courseAdmin global in
  2494. * tool scripts. It returns true or false depending on the user's rights in
  2495. * this particular course.
  2496. * Optionally checking for tutor and coach roles here allows us to use the
  2497. * student_view feature altogether with these roles as well.
  2498. * @param bool Whether to check if the user has the tutor role
  2499. * @param bool Whether to check if the user has the coach role
  2500. * @param bool Whether to check if the user has the session coach role
  2501. * @param bool check the student view or not
  2502. *
  2503. * @author Roan Embrechts
  2504. * @author Patrick Cool
  2505. * @author Julio Montoya
  2506. * @version 1.1, February 2004
  2507. * @return boolean true: the user has the rights to edit, false: he does not
  2508. */
  2509. function api_is_allowed_to_edit(
  2510. $tutor = false,
  2511. $coach = false,
  2512. $session_coach = false,
  2513. $check_student_view = true
  2514. ) {
  2515. $my_session_id = api_get_session_id();
  2516. $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
  2517. $session_visibility = api_get_session_visibility($my_session_id);
  2518. // Admins can edit anything.
  2519. if (api_is_platform_admin(false)) {
  2520. //The student preview was on
  2521. if ($check_student_view &&
  2522. isset($_SESSION['studentview']) &&
  2523. $_SESSION['studentview'] == "studentview"
  2524. ) {
  2525. return false;
  2526. } else {
  2527. return true;
  2528. }
  2529. }
  2530. $is_courseAdmin = api_is_course_admin();
  2531. if (!$is_courseAdmin && $tutor) {
  2532. // If we also want to check if the user is a tutor...
  2533. $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
  2534. }
  2535. if (!$is_courseAdmin && $coach) {
  2536. // If we also want to check if the user is a coach...';
  2537. // Check if session visibility is read only for coaches.
  2538. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  2539. $is_allowed_coach_to_edit = false;
  2540. }
  2541. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
  2542. // Check if coach is allowed to edit a course.
  2543. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  2544. }
  2545. }
  2546. if (!$is_courseAdmin && $session_coach) {
  2547. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  2548. }
  2549. // Check if the student_view is enabled, and if so, if it is activated.
  2550. if (api_get_setting('student_view_enabled') == 'true') {
  2551. if (!empty($my_session_id)) {
  2552. // Check if session visibility is read only for coaches.
  2553. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  2554. $is_allowed_coach_to_edit = false;
  2555. }
  2556. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
  2557. // Check if coach is allowed to edit a course.
  2558. $is_allowed = $is_allowed_coach_to_edit;
  2559. } else {
  2560. $is_allowed = false;
  2561. }
  2562. if ($check_student_view) {
  2563. $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
  2564. }
  2565. } else {
  2566. if ($check_student_view) {
  2567. $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
  2568. } else {
  2569. $is_allowed = $is_courseAdmin;
  2570. }
  2571. }
  2572. return $is_allowed;
  2573. } else {
  2574. return $is_courseAdmin;
  2575. }
  2576. }
  2577. /**
  2578. * Returns true if user is a course coach of at least one course in session
  2579. * @param int $sessionId
  2580. * @return bool
  2581. */
  2582. function api_is_coach_of_course_in_session($sessionId)
  2583. {
  2584. if (api_is_platform_admin()) {
  2585. return true;
  2586. }
  2587. $userId = api_get_user_id();
  2588. $courseList = UserManager::get_courses_list_by_session(
  2589. $userId,
  2590. $sessionId
  2591. );
  2592. // Session visibility.
  2593. $visibility = api_get_session_visibility(
  2594. $sessionId,
  2595. null,
  2596. false
  2597. );
  2598. if ($visibility != SESSION_VISIBLE && !empty($courseList)) {
  2599. // Course Coach session visibility.
  2600. $blockedCourseCount = 0;
  2601. $closedVisibilityList = array(
  2602. COURSE_VISIBILITY_CLOSED,
  2603. COURSE_VISIBILITY_HIDDEN
  2604. );
  2605. foreach ($courseList as $course) {
  2606. // Checking session visibility
  2607. $sessionCourseVisibility = api_get_session_visibility(
  2608. $sessionId,
  2609. $course['real_id'],
  2610. $ignore_visibility_for_admins
  2611. );
  2612. $courseIsVisible = !in_array(
  2613. $course['visibility'],
  2614. $closedVisibilityList
  2615. );
  2616. if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
  2617. $blockedCourseCount++;
  2618. }
  2619. }
  2620. // If all courses are blocked then no show in the list.
  2621. if ($blockedCourseCount === count($courseList)) {
  2622. $visibility = SESSION_INVISIBLE;
  2623. } else {
  2624. $visibility = SESSION_VISIBLE;
  2625. }
  2626. }
  2627. switch ($visibility) {
  2628. case SESSION_VISIBLE_READ_ONLY:
  2629. case SESSION_VISIBLE:
  2630. case SESSION_AVAILABLE:
  2631. return true;
  2632. break;
  2633. case SESSION_INVISIBLE:
  2634. return false;
  2635. }
  2636. return false;
  2637. }
  2638. /**
  2639. * Checks if a student can edit contents in a session depending
  2640. * on the session visibility
  2641. * @param bool $tutor Whether to check if the user has the tutor role
  2642. * @param bool $coach Whether to check if the user has the coach role
  2643. * @return boolean true: the user has the rights to edit, false: he does not
  2644. */
  2645. function api_is_allowed_to_session_edit($tutor = false, $coach = false)
  2646. {
  2647. if (api_is_allowed_to_edit($tutor, $coach)) {
  2648. // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
  2649. return true;
  2650. } else {
  2651. if (api_get_session_id() == 0) {
  2652. // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
  2653. return true;
  2654. } else {
  2655. // I'm in a session and I'm a student
  2656. $session_id = api_get_session_id();
  2657. // Get the session visibility
  2658. $session_visibility = api_get_session_visibility($session_id);
  2659. // if 5 the session is still available
  2660. //@todo We could load the session_rel_course_rel_user permission to increase the level of detail.
  2661. //echo api_get_user_id();
  2662. //echo api_get_course_id();
  2663. switch ($session_visibility) {
  2664. case SESSION_VISIBLE_READ_ONLY: // 1
  2665. return false;
  2666. case SESSION_VISIBLE: // 2
  2667. return true;
  2668. case SESSION_INVISIBLE: // 3
  2669. return false;
  2670. case SESSION_AVAILABLE: //5
  2671. return true;
  2672. }
  2673. }
  2674. }
  2675. }
  2676. /**
  2677. * Checks whether the user is allowed in a specific tool for a specific action
  2678. * @param string $tool the tool we are checking if the user has a certain permission
  2679. * @param string $action the action we are checking (add, edit, delete, move, visibility)
  2680. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2681. * @author Julio Montoya
  2682. * @version 1.0
  2683. */
  2684. function api_is_allowed($tool, $action, $task_id = 0)
  2685. {
  2686. $_user = api_get_user_info();
  2687. $_course = api_get_course_info();
  2688. if (api_is_course_admin()) {
  2689. return true;
  2690. }
  2691. //if (!$_SESSION['total_permissions'][$_course['code']] and $_course)
  2692. if (is_array($_course) and count($_course) > 0) {
  2693. require_once api_get_path(SYS_CODE_PATH).'permissions/permissions_functions.inc.php';
  2694. // Getting the permissions of this user.
  2695. if ($task_id == 0) {
  2696. $user_permissions = get_permissions('user', $_user['user_id']);
  2697. $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
  2698. }
  2699. // Getting the permissions of the task.
  2700. if ($task_id != 0) {
  2701. $task_permissions = get_permissions('task', $task_id);
  2702. /* !!! */$_SESSION['total_permissions'][$_course['code']] = $task_permissions;
  2703. }
  2704. //print_r($_SESSION['total_permissions']);
  2705. // Getting the permissions of the groups of the user
  2706. //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  2707. //foreach($groups_of_user as $group)
  2708. // $this_group_permissions = get_permissions('group', $group);
  2709. // Getting the permissions of the courseroles of the user
  2710. $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
  2711. // Getting the permissions of the platformroles of the user
  2712. //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  2713. // Getting the permissions of the roles of the groups of the user
  2714. //foreach($groups_of_user as $group)
  2715. // $this_group_courserole_permissions = get_roles_permissions('group', $group);
  2716. // Getting the permissions of the platformroles of the groups of the user
  2717. //foreach($groups_of_user as $group)
  2718. // $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  2719. }
  2720. // If the permissions are limited, we have to map the extended ones to the limited ones.
  2721. if (api_get_setting('permissions') == 'limited') {
  2722. if ($action == 'Visibility') {
  2723. $action = 'Edit';
  2724. }
  2725. if ($action == 'Move') {
  2726. $action = 'Edit';
  2727. }
  2728. }
  2729. // The session that contains all the permissions already exists for this course
  2730. // so there is no need to requery everything.
  2731. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  2732. if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) {
  2733. if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) {
  2734. return true;
  2735. } else {
  2736. return false;
  2737. }
  2738. }
  2739. }
  2740. /**
  2741. * Tells whether this user is an anonymous user
  2742. * @param int $user_id User ID (optional, will take session ID if not provided)
  2743. * @param bool $db_check Whether to check in the database (true) or simply in
  2744. * the session (false) to see if the current user is the anonymous user
  2745. * @return bool true if this user is anonymous, false otherwise
  2746. */
  2747. function api_is_anonymous($user_id = null, $db_check = false)
  2748. {
  2749. if (!isset($user_id)) {
  2750. $user_id = api_get_user_id();
  2751. }
  2752. if ($db_check) {
  2753. $info = api_get_user_info($user_id);
  2754. if ($info['status'] == ANONYMOUS) {
  2755. return true;
  2756. }
  2757. }
  2758. $_user = api_get_user_info();
  2759. if (isset($_user['status']) && $_user['status'] == ANONYMOUS) {
  2760. //if ($_user['user_id'] == 0) {
  2761. // In some cases, api_set_anonymous doesn't seem to be triggered in local.inc.php. Make sure it is.
  2762. // Occurs in agenda for admin links - YW
  2763. global $use_anonymous;
  2764. if (isset($use_anonymous) && $use_anonymous) {
  2765. api_set_anonymous();
  2766. }
  2767. return true;
  2768. }
  2769. return (isset($_user['is_anonymous']) && $_user['is_anonymous'] === true) || $_user === false;
  2770. }
  2771. /**
  2772. * Displays message "You are not allowed here..." and exits the entire script.
  2773. * @param bool $print_headers Whether or not to print headers (default = false -> does not print them)
  2774. * @param string $message
  2775. */
  2776. function api_not_allowed($print_headers = false, $message = null)
  2777. {
  2778. if (api_get_setting('sso_authentication') === 'true') {
  2779. global $osso;
  2780. if ($osso) {
  2781. $osso->logout();
  2782. }
  2783. }
  2784. $home_url = api_get_path(WEB_PATH);
  2785. $user_id = api_get_user_id();
  2786. $course = api_get_course_id();
  2787. global $this_section;
  2788. if (CustomPages::enabled() && !isset($user_id)) {
  2789. if (empty($user_id)) {
  2790. // Why the CustomPages::enabled() need to be to set the request_uri
  2791. $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
  2792. }
  2793. CustomPages::display(CustomPages::INDEX_UNLOGGED);
  2794. }
  2795. $origin = isset($_GET['origin']) ? $_GET['origin'] : '';
  2796. $msg = null;
  2797. if (isset($message)) {
  2798. $msg = $message;
  2799. } else {
  2800. $msg = Display::return_message(
  2801. get_lang('NotAllowedClickBack').'<br/><br/><a href="'.$home_url.'">'.get_lang('ReturnToCourseHomepage').'</a>',
  2802. 'error',
  2803. false
  2804. );
  2805. }
  2806. $msg = Display::div($msg, array('align'=>'center'));
  2807. $show_headers = 0;
  2808. if ($print_headers && $origin != 'learnpath') {
  2809. $show_headers = 1;
  2810. }
  2811. $tpl = new Template(null, $show_headers, $show_headers);
  2812. $tpl->assign('hide_login_link', 1);
  2813. $tpl->assign('content', $msg);
  2814. if (($user_id != 0 && !api_is_anonymous()) &&
  2815. (!isset($course) || $course == -1) &&
  2816. empty($_GET['cidReq'])
  2817. ) {
  2818. // if the access is not authorized and there is some login information
  2819. // but the cidReq is not found, assume we are missing course data and send the user
  2820. // to the user_portal
  2821. $tpl->display_one_col_template();
  2822. exit;
  2823. }
  2824. if (!empty($_SERVER['REQUEST_URI']) &&
  2825. (!empty($_GET['cidReq']) ||
  2826. $this_section == SECTION_MYPROFILE ||
  2827. $this_section == SECTION_PLATFORM_ADMIN
  2828. )
  2829. ) {
  2830. $courseCode = api_get_course_id();
  2831. // Only display form and return to the previous URL if there was a course ID included
  2832. if ($user_id != 0 && !api_is_anonymous()) {
  2833. //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
  2834. $tpl->assign('content', $msg);
  2835. $tpl->display_one_col_template();
  2836. exit;
  2837. }
  2838. if (!is_null($courseCode)) {
  2839. api_set_firstpage_parameter($courseCode);
  2840. }
  2841. // If the user has no user ID, then his session has expired
  2842. $action = api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
  2843. $action = str_replace('&amp;', '&', $action);
  2844. $form = new FormValidator(
  2845. 'formLogin',
  2846. 'post',
  2847. $action,
  2848. null,
  2849. array(),
  2850. FormValidator::LAYOUT_BOX_NO_LABEL
  2851. );
  2852. $form->addElement(
  2853. 'text',
  2854. 'login',
  2855. null,
  2856. array('placeholder' => get_lang('UserName'), 'autocapitalize' => 'none')
  2857. );
  2858. $form->addElement(
  2859. 'password',
  2860. 'password',
  2861. null,
  2862. array('placeholder' => get_lang('Password'), 'autocapitalize' => 'none')
  2863. );
  2864. $form->addButton('submitAuth', get_lang('LoginEnter'), '', 'primary');
  2865. // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (above)
  2866. $content = Display::return_message(get_lang('NotAllowed'), 'error', false);
  2867. if (!empty($courseCode)) {
  2868. $content .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
  2869. }
  2870. if (api_is_cas_activated()) {
  2871. $content .= Display::return_message(sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")), '', false);
  2872. $content .= Display::div("<br/><a href='".get_cas_direct_URL(api_get_course_id())."'>".sprintf(get_lang('LoginWithYourAccount'), api_get_setting("Institution"))."</a><br/><br/>", array('align'=>'center'));
  2873. $content .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
  2874. $content .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
  2875. $content .= "<div style='display:none;'>";
  2876. }
  2877. $content .= '<div class="well">';
  2878. $content .= $form->returnForm();
  2879. $content .='</div>';
  2880. if (api_is_cas_activated()) {
  2881. $content .= "</div>";
  2882. }
  2883. if (!empty($courseCode)) {
  2884. $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
  2885. get_lang('ReturnToCourseHomepage').'</a></p>';
  2886. } else {
  2887. $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
  2888. get_lang('BackHome').'</a></p>';
  2889. }
  2890. $tpl->setLoginBodyClass();
  2891. $tpl->assign('content', $content);
  2892. $tpl->display_one_col_template();
  2893. exit;
  2894. }
  2895. if ($user_id != 0 && !api_is_anonymous()) {
  2896. $tpl->display_one_col_template();
  2897. exit;
  2898. }
  2899. $msg = null;
  2900. // The session is over and we were not in a course,
  2901. // or we try to get directly to a private course without being logged
  2902. $courseId = api_get_course_int_id();
  2903. if (!empty($courseId)) {
  2904. api_set_firstpage_parameter(api_get_course_id());
  2905. $tpl->setLoginBodyClass();
  2906. $action = api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
  2907. $action = str_replace('&amp;', '&', $action);
  2908. $form = new FormValidator('formLogin', 'post', $action, null, array('class'=>'form-stacked'));
  2909. $form->addElement('text', 'login', null, array('autocapitalize' => 'none', 'placeholder' => get_lang('UserName'), 'class' => 'col-md-3'));
  2910. $form->addElement('password', 'password', null, array('placeholder' => get_lang('Password'), 'class' => 'col-md-3')); //new
  2911. $form->addButtonNext(get_lang('LoginEnter'), 'submitAuth');
  2912. // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (bellow)
  2913. $msg = Display::return_message(get_lang('NotAllowed'), 'error', false);
  2914. $msg .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
  2915. $casEnabled = api_is_cas_activated();
  2916. if ($casEnabled) {
  2917. $msg .= Display::return_message(sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")), '', false);
  2918. $msg .= Display::div("<br/><a href='".get_cas_direct_URL(api_get_course_int_id())."'>".getCASLogoHTML()." ".sprintf(get_lang('LoginWithYourAccount'), api_get_setting("Institution"))."</a><br/><br/>", array('align'=>'center'));
  2919. $msg .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
  2920. $msg .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
  2921. $msg .= "<div style='display:none;'>";
  2922. }
  2923. $msg .= '<div class="well">';
  2924. $msg .= $form->returnForm();
  2925. $msg .='</div>';
  2926. if ($casEnabled) {
  2927. $msg .= "</div>";
  2928. }
  2929. } else {
  2930. // we were not in a course, return to home page
  2931. $msg = Display::return_message(
  2932. get_lang('NotAllowed').'<br/><br/><a href="'.$home_url.'">'.get_lang('BackHome').'</a><br />',
  2933. 'error',
  2934. false
  2935. );
  2936. }
  2937. $tpl->assign('content', $msg);
  2938. $tpl->display_one_col_template();
  2939. exit;
  2940. }
  2941. /**
  2942. * Gets a UNIX timestamp from a database (MySQL) datetime format string
  2943. * @param $last_post_datetime standard output date in a sql query
  2944. * @return integer timestamp
  2945. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  2946. * @version October 2003
  2947. * @desc convert sql date to unix timestamp
  2948. */
  2949. function convert_sql_date($last_post_datetime) {
  2950. list ($last_post_date, $last_post_time) = explode(' ', $last_post_datetime);
  2951. list ($year, $month, $day) = explode('-', $last_post_date);
  2952. list ($hour, $min, $sec) = explode(':', $last_post_time);
  2953. return mktime((int)$hour, (int)$min, (int)$sec, (int)$month, (int)$day, (int)$year);
  2954. }
  2955. /**
  2956. * Gets item visibility from the item_property table
  2957. *
  2958. * Getting the visibility is done by getting the last updated visibility entry,
  2959. * using the largest session ID found if session 0 and another was found (meaning
  2960. * the only one that is actually from the session, in case there are results from
  2961. * session 0 *AND* session n).
  2962. * @param array Course properties array (result of api_get_course_info())
  2963. * @param string Tool (learnpath, document, etc)
  2964. * @param int The item ID in the given tool
  2965. * @param int The session ID (optional)
  2966. * @param string $tool
  2967. * @param integer $user_id
  2968. * @param string $type
  2969. * @return int -1 on error, 0 if invisible, 1 if visible
  2970. */
  2971. function api_get_item_visibility(
  2972. $_course,
  2973. $tool,
  2974. $id,
  2975. $session = 0,
  2976. $user_id = null,
  2977. $type = null,
  2978. $group_id = null
  2979. ) {
  2980. if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) {
  2981. return -1;
  2982. }
  2983. $tool = Database::escape_string($tool);
  2984. $id = intval($id);
  2985. $session = (int) $session;
  2986. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2987. $course_id = intval($_course['real_id']);
  2988. $userCondition = '';
  2989. if (!empty($user_id)) {
  2990. $user_id = intval($user_id);
  2991. $userCondition = " AND to_user_id = $user_id ";
  2992. }
  2993. $typeCondition = '';
  2994. if (!empty($type)) {
  2995. $type = Database::escape_string($type);
  2996. $typeCondition = " AND lastedit_type = '$type' ";
  2997. }
  2998. $groupCondition = '';
  2999. if (!empty($group_id)) {
  3000. $group_id = intval($group_id);
  3001. $groupCondition = " AND to_group_id = '$group_id' ";
  3002. }
  3003. $sql = "SELECT visibility
  3004. FROM $TABLE_ITEMPROPERTY
  3005. WHERE
  3006. c_id = $course_id AND
  3007. tool = '$tool' AND
  3008. ref = $id AND
  3009. (session_id = $session OR session_id = 0 OR session_id IS NULL)
  3010. $userCondition $typeCondition $groupCondition
  3011. ORDER BY session_id DESC, lastedit_date DESC
  3012. LIMIT 1";
  3013. $res = Database::query($sql);
  3014. if ($res === false || Database::num_rows($res) == 0) {
  3015. return -1;
  3016. }
  3017. $row = Database::fetch_array($res);
  3018. return $row['visibility'];
  3019. }
  3020. /**
  3021. * Delete a row in the c_item_property table
  3022. *
  3023. * @param array $courseInfo
  3024. * @param string $tool
  3025. * @param int $itemId
  3026. * @param int $userId
  3027. * @param int $groupId
  3028. * @param int $sessionId
  3029. * @return false|null
  3030. */
  3031. function api_item_property_delete(
  3032. $courseInfo,
  3033. $tool,
  3034. $itemId,
  3035. $userId,
  3036. $groupId = 0,
  3037. $sessionId = 0
  3038. ) {
  3039. if (empty($courseInfo)) {
  3040. return false;
  3041. }
  3042. $courseId = intval($courseInfo['real_id']);
  3043. if (empty($courseId) || empty($tool) || empty($itemId)) {
  3044. return false;
  3045. }
  3046. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3047. $tool = Database::escape_string($tool);
  3048. $itemId = intval($itemId);
  3049. $userId = intval($userId);
  3050. $groupId = intval($groupId);
  3051. $sessionId = intval($sessionId);
  3052. $groupCondition = " AND to_group_id = $groupId ";
  3053. if (empty($groupId)) {
  3054. $groupCondition = " AND (to_group_id is NULL OR to_group_id = 0) ";
  3055. }
  3056. $userCondition = " AND to_user_id = $userId ";
  3057. if (empty($userId)) {
  3058. $userCondition = " AND (to_user_id is NULL OR to_user_id = 0) ";
  3059. }
  3060. $sessionCondition = api_get_session_condition($sessionId, true, false, 'session_id');
  3061. $sql = "DELETE FROM $table
  3062. WHERE
  3063. c_id = $courseId AND
  3064. tool = '$tool' AND
  3065. ref = $itemId
  3066. $sessionCondition
  3067. $userCondition
  3068. $groupCondition
  3069. ";
  3070. Database::query($sql);
  3071. }
  3072. /**
  3073. * Updates or adds item properties to the Item_propetry table
  3074. * Tool and lastedit_type are language independant strings (langvars->get_lang!)
  3075. *
  3076. * @param array $_course array with course properties
  3077. * @param string $tool tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3078. * @param int $item_id id of the item itself, linked to key of every tool ('id', ...)
  3079. * @param string $last_edit_type add or update action
  3080. * (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  3081. * (2) "delete"
  3082. * (3) "visible"
  3083. * (4) "invisible"
  3084. * @param int $user_id id of the editing/adding user
  3085. * @param int $to_group_id group.iid
  3086. * @param int $to_user_id id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  3087. * @param string $start_visible 0000-00-00 00:00:00 format
  3088. * @param string $end_visible 0000-00-00 00:00:00 format
  3089. * @param int $session_id The session ID, if any, otherwise will default to 0
  3090. * @return boolean False if update fails.
  3091. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  3092. * @version January 2005
  3093. * @desc update the item_properties table (if entry not exists, insert) of the course
  3094. */
  3095. function api_item_property_update(
  3096. $_course,
  3097. $tool,
  3098. $item_id,
  3099. $last_edit_type,
  3100. $user_id,
  3101. $to_group_id = 0,
  3102. $to_user_id = null,
  3103. $start_visible = '',
  3104. $end_visible = '',
  3105. $session_id = 0
  3106. ) {
  3107. if (empty($_course)) {
  3108. return false;
  3109. }
  3110. $course_id = $_course['real_id'];
  3111. if (empty($course_id)) {
  3112. return false;
  3113. }
  3114. $em = Database::getManager();
  3115. // Definition of variables.
  3116. $tool = Database::escape_string($tool);
  3117. $item_id = intval($item_id);
  3118. $lastEditTypeNoFilter = $last_edit_type;
  3119. $last_edit_type = Database::escape_string($last_edit_type);
  3120. $user_id = intval($user_id);
  3121. $startVisible = "NULL";
  3122. if (!empty($start_visible)) {
  3123. $start_visible = Database::escape_string($start_visible);
  3124. $startVisible = "'$start_visible'";
  3125. }
  3126. $endVisible = "NULL";
  3127. if (!empty($end_visible)) {
  3128. $end_visible = Database::escape_string($end_visible);
  3129. $endVisible = "'$end_visible'";
  3130. }
  3131. $to_filter = '';
  3132. $time = api_get_utc_datetime();
  3133. if (!empty($session_id)) {
  3134. $session_id = intval($session_id);
  3135. } else {
  3136. $session_id = api_get_session_id();
  3137. }
  3138. // Definition of tables.
  3139. $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3140. if ($to_user_id <= 0) {
  3141. $to_user_id = null; // No to_user_id set
  3142. }
  3143. if (!is_null($to_user_id)) {
  3144. // $to_user_id has more priority than $to_group_id
  3145. $to_user_id = intval($to_user_id);
  3146. $to_field = 'to_user_id';
  3147. $to_value = $to_user_id;
  3148. } else {
  3149. // $to_user_id is not set.
  3150. $to_field = 'to_group_id';
  3151. $to_value = $to_group_id;
  3152. }
  3153. $toValueCondition = empty($to_value) ? "NULL" : "'$to_value'";
  3154. // Set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  3155. $condition_session = " AND session_id = $session_id ";
  3156. if (empty($session_id)) {
  3157. $condition_session = " AND (session_id = 0 OR session_id IS NULL) ";
  3158. }
  3159. $filter = " c_id = $course_id AND tool = '$tool' AND ref = $item_id $condition_session ";
  3160. // Check whether $to_user_id and $to_group_id are passed in the function call.
  3161. // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  3162. if (is_null($to_user_id) && is_null($to_group_id)) {
  3163. $to_group_id = 0;
  3164. }
  3165. if (!is_null($to_user_id)) {
  3166. // Set filter to intended user.
  3167. $to_filter = " AND to_user_id = $to_user_id $condition_session";
  3168. } else {
  3169. // Set filter to intended group.
  3170. if (($to_group_id != 0) && $to_group_id == strval(intval($to_group_id))) {
  3171. $to_filter = " AND to_group_id = $to_group_id $condition_session";
  3172. }
  3173. }
  3174. // Adding filter if set.
  3175. $filter .= $to_filter;
  3176. // Update if possible
  3177. $set_type = '';
  3178. switch ($lastEditTypeNoFilter) {
  3179. case 'delete':
  3180. // delete = make item only visible for the platform admin.
  3181. $visibility = '2';
  3182. if (!empty($session_id)) {
  3183. // Check whether session id already exist into item_properties for updating visibility or add it.
  3184. $sql = "SELECT session_id FROM $tableItemProperty
  3185. WHERE
  3186. c_id = $course_id AND
  3187. tool = '$tool' AND
  3188. ref = $item_id AND
  3189. session_id = $session_id";
  3190. $rs = Database::query($sql);
  3191. if (Database::num_rows($rs) > 0) {
  3192. $sql = "UPDATE $tableItemProperty
  3193. SET lastedit_type = '".str_replace('_', '', ucwords($tool))."Deleted',
  3194. lastedit_date = '$time',
  3195. lastedit_user_id = $user_id,
  3196. visibility = $visibility,
  3197. session_id = $session_id $set_type
  3198. WHERE $filter";
  3199. $result = Database::query($sql);
  3200. } else {
  3201. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
  3202. VALUES ($course_id, '$tool',$item_id, '$time', $user_id, '$time', '$last_edit_type',$user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3203. $result = Database::query($sql);
  3204. $id = Database::insert_id();
  3205. if ($id) {
  3206. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3207. Database::query($sql);
  3208. }
  3209. }
  3210. } else {
  3211. $sql = "UPDATE $tableItemProperty
  3212. SET
  3213. lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted',
  3214. lastedit_date='$time',
  3215. lastedit_user_id = $user_id,
  3216. visibility = $visibility $set_type
  3217. WHERE $filter";
  3218. $result = Database::query($sql);
  3219. }
  3220. break;
  3221. case 'visible' : // Change item to visible.
  3222. $visibility = '1';
  3223. if (!empty($session_id)) {
  3224. // Check whether session id already exist into item_properties for updating visibility or add it.
  3225. $sql = "SELECT session_id FROM $tableItemProperty
  3226. WHERE
  3227. c_id = $course_id AND
  3228. tool = '$tool' AND
  3229. ref = $item_id AND
  3230. session_id = $session_id";
  3231. $rs = Database::query($sql);
  3232. if (Database::num_rows($rs) > 0) {
  3233. $sql = "UPDATE $tableItemProperty
  3234. SET
  3235. lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
  3236. lastedit_date='$time',
  3237. lastedit_user_id = $user_id,
  3238. visibility = $visibility,
  3239. session_id = $session_id $set_type
  3240. WHERE $filter";
  3241. $result = Database::query($sql);
  3242. } else {
  3243. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
  3244. VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3245. $result = Database::query($sql);
  3246. $id = Database::insert_id();
  3247. if ($id) {
  3248. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3249. Database::query($sql);
  3250. }
  3251. }
  3252. } else {
  3253. $sql = "UPDATE $tableItemProperty
  3254. SET
  3255. lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
  3256. lastedit_date='$time',
  3257. lastedit_user_id = $user_id,
  3258. visibility = $visibility $set_type
  3259. WHERE $filter";
  3260. $result = Database::query($sql);
  3261. }
  3262. break;
  3263. case 'invisible' : // Change item to invisible.
  3264. $visibility = '0';
  3265. if (!empty($session_id)) {
  3266. // Check whether session id already exist into item_properties for updating visibility or add it
  3267. $sql = "SELECT session_id FROM $tableItemProperty
  3268. WHERE
  3269. c_id = $course_id AND
  3270. tool = '$tool' AND
  3271. ref = $item_id AND
  3272. session_id = $session_id";
  3273. $rs = Database::query($sql);
  3274. if (Database::num_rows($rs) > 0) {
  3275. $sql = "UPDATE $tableItemProperty
  3276. SET
  3277. lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
  3278. lastedit_date = '$time',
  3279. lastedit_user_id = $user_id,
  3280. visibility = $visibility,
  3281. session_id = $session_id $set_type
  3282. WHERE $filter";
  3283. $result = Database::query($sql);
  3284. } else {
  3285. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id)
  3286. VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3287. $result = Database::query($sql);
  3288. $id = Database::insert_id();
  3289. if ($id) {
  3290. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3291. Database::query($sql);
  3292. }
  3293. }
  3294. } else {
  3295. $sql = "UPDATE $tableItemProperty
  3296. SET
  3297. lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
  3298. lastedit_date = '$time',
  3299. lastedit_user_id = $user_id,
  3300. visibility = $visibility $set_type
  3301. WHERE $filter";
  3302. $result = Database::query($sql);
  3303. }
  3304. break;
  3305. default: // The item will be added or updated.
  3306. $set_type = ", lastedit_type = '$last_edit_type' ";
  3307. $visibility = '1';
  3308. //$filter .= $to_filter; already added
  3309. $sql = "UPDATE $tableItemProperty
  3310. SET
  3311. lastedit_date = '$time',
  3312. lastedit_user_id = $user_id $set_type
  3313. WHERE $filter";
  3314. $result = Database::query($sql);
  3315. }
  3316. // Insert if no entries are found (can only happen in case of $last_edit_type switch is 'default').
  3317. if ($result == false || Database::affected_rows($result) == 0) {
  3318. $objCourse = $em->find('ChamiloCoreBundle:Course', intval($course_id));
  3319. $objTime = new DateTime('now', new DateTimeZone('UTC'));
  3320. $objUser = $em->find('ChamiloUserBundle:User', intval($user_id));
  3321. $objGroup = $em->find('ChamiloCourseBundle:CGroupInfo', intval($to_group_id));
  3322. $objToUser = $em->find('ChamiloUserBundle:User', intval($to_user_id));
  3323. $objSession = $em->find('ChamiloCoreBundle:Session', intval($session_id));
  3324. $startVisibleDate = !empty($start_visible) ? new DateTime($start_visible, new DateTimeZone('UTC')) : null;
  3325. $endVisibleDate = !empty($endVisibleDate) ? new DateTime($endVisibleDate, new DateTimeZone('UTC')) : null;
  3326. $cItemProperty = new CItemProperty($objCourse);
  3327. $cItemProperty
  3328. ->setTool($tool)
  3329. ->setRef($item_id)
  3330. ->setInsertDate($objTime)
  3331. ->setInsertUser($objUser)
  3332. ->setLasteditDate($objTime)
  3333. ->setLasteditType($last_edit_type)
  3334. ->setGroup($objGroup)
  3335. ->setToUser($objToUser)
  3336. ->setVisibility($visibility)
  3337. ->setStartVisible($startVisibleDate)
  3338. ->setEndVisible($endVisibleDate)
  3339. ->setSession($objSession);
  3340. $em->persist($cItemProperty);
  3341. $em->flush();
  3342. $id = $cItemProperty->getIid();
  3343. if ($id) {
  3344. $cItemProperty->setId($id);
  3345. $em->merge($cItemProperty);
  3346. $em->flush();
  3347. return false;
  3348. }
  3349. }
  3350. return true;
  3351. }
  3352. /**
  3353. * Gets item property by tool
  3354. * @param string course code
  3355. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3356. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  3357. * @param int $session_id
  3358. * @param string $tool
  3359. * @param string $course_code
  3360. * @return array All fields from c_item_property (all rows found) or empty array
  3361. */
  3362. function api_get_item_property_by_tool($tool, $course_code, $session_id = null)
  3363. {
  3364. $course_info = api_get_course_info($course_code);
  3365. $tool = Database::escape_string($tool);
  3366. // Definition of tables.
  3367. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3368. $session_id = intval($session_id);
  3369. $session_condition = ' AND session_id = '.$session_id;
  3370. if (empty($session_id)) {
  3371. $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
  3372. }
  3373. $course_id = $course_info['real_id'];
  3374. $sql = "SELECT * FROM $item_property_table
  3375. WHERE
  3376. c_id = $course_id AND
  3377. tool = '$tool'
  3378. $session_condition ";
  3379. $rs = Database::query($sql);
  3380. $list = array();
  3381. if (Database::num_rows($rs) > 0) {
  3382. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3383. $list[] = $row;
  3384. }
  3385. }
  3386. return $list;
  3387. }
  3388. /**
  3389. * Gets item property by tool and user
  3390. * @param int $userId
  3391. * @param int $tool
  3392. * @param int $courseId
  3393. * @param int $session_id
  3394. * @return array
  3395. */
  3396. function api_get_item_property_list_by_tool_by_user(
  3397. $userId,
  3398. $tool,
  3399. $courseId,
  3400. $session_id = 0
  3401. ) {
  3402. $userId = intval($userId);
  3403. $tool = Database::escape_string($tool);
  3404. $session_id = intval($session_id);
  3405. $courseId = intval($courseId);
  3406. // Definition of tables.
  3407. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3408. $session_condition = ' AND session_id = '.$session_id;
  3409. if (empty($session_id)) {
  3410. $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
  3411. }
  3412. $sql = "SELECT * FROM $item_property_table
  3413. WHERE
  3414. insert_user_id = $userId AND
  3415. c_id = $courseId AND
  3416. tool = '$tool'
  3417. $session_condition ";
  3418. $rs = Database::query($sql);
  3419. $list = array();
  3420. if (Database::num_rows($rs) > 0) {
  3421. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3422. $list[] = $row;
  3423. }
  3424. }
  3425. return $list;
  3426. }
  3427. /**
  3428. * Gets item property id from tool of a course
  3429. * @param string $course_code course code
  3430. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3431. * @param int $ref id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  3432. * @param int $sessionId Session ID (optional)
  3433. * @return int
  3434. */
  3435. function api_get_item_property_id($course_code, $tool, $ref, $sessionId = 0)
  3436. {
  3437. $course_info = api_get_course_info($course_code);
  3438. $tool = Database::escape_string($tool);
  3439. $ref = intval($ref);
  3440. // Definition of tables.
  3441. $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3442. $course_id = $course_info['real_id'];
  3443. $sessionId = (int) $sessionId;
  3444. $sessionCondition = " AND session_id = $sessionId ";
  3445. if (empty($sessionId)) {
  3446. $sessionCondition = " AND (session_id = 0 OR session_id IS NULL) ";
  3447. }
  3448. $sql = "SELECT id FROM $tableItemProperty
  3449. WHERE
  3450. c_id = $course_id AND
  3451. tool = '$tool' AND
  3452. ref = $ref
  3453. $sessionCondition";
  3454. $rs = Database::query($sql);
  3455. $item_property_id = '';
  3456. if (Database::num_rows($rs) > 0) {
  3457. $row = Database::fetch_array($rs);
  3458. $item_property_id = $row['id'];
  3459. }
  3460. return $item_property_id;
  3461. }
  3462. /**
  3463. * Inserts a record in the track_e_item_property table (No update)
  3464. * @param string $tool
  3465. * @param int $ref
  3466. * @param string $title
  3467. * @param string $content
  3468. * @param int $progress
  3469. * @return bool|int
  3470. */
  3471. function api_track_item_property_update($tool, $ref, $title, $content, $progress)
  3472. {
  3473. $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  3474. $course_id = api_get_course_int_id(); //numeric
  3475. $course_code = api_get_course_id(); //alphanumeric
  3476. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  3477. if (!empty($item_property_id)) {
  3478. $sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
  3479. course_id = '$course_id',
  3480. item_property_id = '$item_property_id',
  3481. title = '".Database::escape_string($title)."',
  3482. content = '".Database::escape_string($content)."',
  3483. progress = '".intval($progress)."',
  3484. lastedit_date = '".api_get_utc_datetime()."',
  3485. lastedit_user_id = '".api_get_user_id()."',
  3486. session_id = '".api_get_session_id()."'";
  3487. $result = Database::query($sql);
  3488. $affected_rows = Database::affected_rows($result);
  3489. return $affected_rows;
  3490. }
  3491. return false;
  3492. }
  3493. /**
  3494. * @param string $tool
  3495. * @param int $ref
  3496. * @return array|resource
  3497. */
  3498. function api_get_track_item_property_history($tool, $ref)
  3499. {
  3500. $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  3501. $course_id = api_get_course_int_id(); //numeric
  3502. $course_code = api_get_course_id(); //alphanumeric
  3503. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  3504. $sql = "SELECT * FROM $tbl_stats_item_property
  3505. WHERE item_property_id = $item_property_id AND course_id = $course_id
  3506. ORDER BY lastedit_date DESC";
  3507. $result = Database::query($sql);
  3508. if ($result == false) {
  3509. $result = array();
  3510. } else {
  3511. $result = Database::store_result($result,'ASSOC');
  3512. }
  3513. return $result;
  3514. }
  3515. /**
  3516. * Gets item property data from tool of a course id
  3517. * @param int $course_id
  3518. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3519. * @param int $ref id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  3520. * @param int $session_id
  3521. * @param int $groupId
  3522. *
  3523. * @return array Array with all fields from c_item_property, empty array if not found or false if course could not be found
  3524. */
  3525. function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0, $groupId = 0)
  3526. {
  3527. $courseInfo = api_get_course_info_by_id($course_id);
  3528. if (empty($courseInfo)) {
  3529. return false;
  3530. }
  3531. $tool = Database::escape_string($tool);
  3532. $ref = intval($ref);
  3533. $course_id = $courseInfo['real_id'];
  3534. $session_id = intval($session_id);
  3535. $sessionCondition = " session_id = $session_id";
  3536. if (empty($session_id)) {
  3537. $sessionCondition = " (session_id = 0 OR session_id IS NULL) ";
  3538. }
  3539. // Definition of tables.
  3540. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3541. $sql = "SELECT * FROM $table
  3542. WHERE
  3543. c_id = $course_id AND
  3544. tool = '$tool' AND
  3545. ref = $ref AND
  3546. $sessionCondition ";
  3547. if (!empty($groupId)) {
  3548. $groupId = intval($groupId);
  3549. $sql .= " AND to_group_id = $groupId ";
  3550. }
  3551. $rs = Database::query($sql);
  3552. $row = array();
  3553. if (Database::num_rows($rs) > 0) {
  3554. $row = Database::fetch_array($rs,'ASSOC');
  3555. }
  3556. return $row;
  3557. }
  3558. /**
  3559. * Displays a combo box so the user can select his/her preferred language.
  3560. * @param string The desired name= value for the select
  3561. * @param bool Whether we use the JQuery Chozen library or not
  3562. * (in some cases, like the indexing language picker, it can alter the presentation)
  3563. * @return string
  3564. */
  3565. function api_get_languages_combo($name = 'language')
  3566. {
  3567. $ret = '';
  3568. $platformLanguage = api_get_setting('platformLanguage');
  3569. // Retrieve a complete list of all the languages.
  3570. $language_list = api_get_languages();
  3571. if (count($language_list['name']) < 2) {
  3572. return $ret;
  3573. }
  3574. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  3575. if (isset($_SESSION['user_language_choice'])) {
  3576. $default = $_SESSION['user_language_choice'];
  3577. } else {
  3578. $default = $platformLanguage;
  3579. }
  3580. $languages = $language_list['name'];
  3581. $folder = $language_list['folder'];
  3582. $ret .= '<select name="' . $name . '" id="language_chosen" class="selectpicker show-tick form-control">';
  3583. foreach ($languages as $key => $value) {
  3584. if ($folder[$key] == $default) {
  3585. $selected = ' selected="selected"';
  3586. } else {
  3587. $selected = '';
  3588. }
  3589. $ret .= sprintf('<option value=%s" %s>%s</option>', $folder[$key], $selected, $value);
  3590. }
  3591. $ret .= '</select>';
  3592. return $ret;
  3593. }
  3594. /**
  3595. * Displays a form (drop down menu) so the user can select his/her preferred language.
  3596. * The form works with or without javascript
  3597. * @param boolean Hide form if only one language available (defaults to false = show the box anyway)
  3598. * @return null|string Display the box directly
  3599. */
  3600. function api_display_language_form($hide_if_no_choice = false)
  3601. {
  3602. // Retrieve a complete list of all the languages.
  3603. $language_list = api_get_languages();
  3604. if (count($language_list['name']) <= 1 && $hide_if_no_choice) {
  3605. return; //don't show any form
  3606. }
  3607. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  3608. if (isset($_SESSION['user_language_choice'])) {
  3609. $user_selected_language = $_SESSION['user_language_choice'];
  3610. }
  3611. if (empty($user_selected_language)) {
  3612. $user_selected_language = api_get_setting('platformLanguage');
  3613. }
  3614. $original_languages = $language_list['name'];
  3615. $folder = $language_list['folder']; // This line is probably no longer needed.
  3616. $html = '<script>
  3617. $(document).ready(function() {
  3618. $("#language_list").change(function() {
  3619. jumpMenu("parent",this,0);
  3620. });
  3621. });
  3622. function jumpMenu(targ,selObj,restore){ // v3.0
  3623. eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
  3624. if (restore) selObj.selectedIndex=0;
  3625. }
  3626. </script>';
  3627. $html .= '<form id="lang_form" name="lang_form" method="post" action="'.api_get_self().'">';
  3628. $html .= '<label style="display: none;" for="language_list">' . get_lang('Language') . '</label>';
  3629. $html .= '<select id="language_list" class="selectpicker show-tick form-control" name="language_list" >';
  3630. foreach ($original_languages as $key => $value) {
  3631. if ($folder[$key] == $user_selected_language) {
  3632. $option_end = ' selected="selected" >';
  3633. } else {
  3634. $option_end = '>';
  3635. }
  3636. $html .= '<option value="'.api_get_self().'?language='.$folder[$key].'"'.$option_end;
  3637. //echo substr($value, 0, 16); // Cut string to keep 800x600 aspect.
  3638. $html .= $value.'</option>';
  3639. }
  3640. $html .= '</select>';
  3641. $html .= '<noscript><input type="submit" name="user_select_language" value="'.get_lang('Ok').'" /></noscript>';
  3642. $html .= '</form>';
  3643. return $html;
  3644. }
  3645. /**
  3646. * Returns a list of all the languages that are made available by the admin.
  3647. * @return array An array with all languages. Structure of the array is
  3648. * array['name'] = An array with the name of every language
  3649. * array['folder'] = An array with the corresponding names of the language-folders in the filesystem
  3650. */
  3651. function api_get_languages() {
  3652. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  3653. $sql = "SELECT * FROM $tbl_language WHERE available='1'
  3654. ORDER BY original_name ASC";
  3655. $result = Database::query($sql);
  3656. $language_list = array();
  3657. while ($row = Database::fetch_array($result)) {
  3658. $language_list['name'][] = $row['original_name'];
  3659. $language_list['folder'][] = $row['dokeos_folder'];
  3660. }
  3661. return $language_list;
  3662. }
  3663. /**
  3664. * Returns a list of all the languages that are made available by the admin.
  3665. * @return array
  3666. */
  3667. function api_get_languages_to_array() {
  3668. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  3669. $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  3670. $result = Database::query($sql);
  3671. $languages = array();
  3672. while ($row = Database::fetch_array($result)) {
  3673. $languages[$row['dokeos_folder']] = $row['original_name'];
  3674. }
  3675. return $languages;
  3676. }
  3677. /**
  3678. * Returns the id (the database id) of a language
  3679. * @param string language name (the corresponding name of the language-folder in the filesystem)
  3680. * @return int id of the language
  3681. */
  3682. function api_get_language_id($language)
  3683. {
  3684. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  3685. if (empty($language)) {
  3686. return null;
  3687. }
  3688. $language = Database::escape_string($language);
  3689. $sql = "SELECT id FROM $tbl_language
  3690. WHERE dokeos_folder = '$language' LIMIT 1";
  3691. $result = Database::query($sql);
  3692. $row = Database::fetch_array($result);
  3693. return $row['id'];
  3694. }
  3695. /**
  3696. * Gets language of the requested type for the current user. Types are :
  3697. * user_profil_lang : profile language of current user
  3698. * user_select_lang : language selected by user at login
  3699. * course_lang : language of the current course
  3700. * platform_lang : default platform language
  3701. * @param string $lang_type
  3702. * @return string
  3703. **/
  3704. function api_get_language_from_type($lang_type)
  3705. {
  3706. $return = false;
  3707. switch ($lang_type) {
  3708. case 'platform_lang':
  3709. $temp_lang = api_get_setting('platformLanguage');
  3710. if (!empty($temp_lang))
  3711. $return = $temp_lang;
  3712. break;
  3713. case 'user_profil_lang':
  3714. $_user = api_get_user_info();
  3715. if (isset($_user['language']) && !empty($_user['language']))
  3716. $return = $_user['language'];
  3717. break;
  3718. case 'user_selected_lang':
  3719. if (isset($_SESSION['user_language_choice']) && !empty($_SESSION['user_language_choice']))
  3720. $return = $_SESSION['user_language_choice'];
  3721. break;
  3722. case 'course_lang':
  3723. global $_course;
  3724. $cidReq = null;
  3725. if (empty($_course)) {
  3726. // Code modified because the local.inc.php file it's declarated after this work
  3727. // causing the function api_get_course_info() returns a null value
  3728. $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : null;
  3729. $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
  3730. if (empty($cidReq) && !empty($cDir)) {
  3731. $c = CourseManager::get_course_id_from_path($cDir);
  3732. if ($c) {
  3733. $cidReq = $c;
  3734. }
  3735. }
  3736. }
  3737. $_course = api_get_course_info($cidReq);
  3738. if (isset($_course['language']) && !empty($_course['language'])) {
  3739. $return = $_course['language'];
  3740. $showCourseInUserLanguage = api_get_course_setting('show_course_in_user_language');
  3741. if ($showCourseInUserLanguage == 1) {
  3742. $userInfo = api_get_user_info();
  3743. if (isset($userInfo['language'])) {
  3744. $return = $userInfo['language'];
  3745. }
  3746. }
  3747. }
  3748. break;
  3749. default:
  3750. $return = false;
  3751. break;
  3752. }
  3753. return $return;
  3754. }
  3755. /**
  3756. * Get the language information by its id
  3757. * @param int $languageId
  3758. * @return array
  3759. */
  3760. function api_get_language_info($languageId) {
  3761. $language = Database::getManager()
  3762. ->find('ChamiloCoreBundle:Language', intval($languageId));
  3763. if (!$language) {
  3764. return [];
  3765. }
  3766. return [
  3767. 'id' => $language->getId(),
  3768. 'original_name' => $language->getOriginalName(),
  3769. 'english_name' => $language->getEnglishName(),
  3770. 'isocode' => $language->getIsocode(),
  3771. 'dokeos_folder' => $language->getDokeosFolder(),
  3772. 'available' => $language->getAvailable(),
  3773. 'parent_id' => $language->getParent() ? $language->getParent()->getId() : null
  3774. ];
  3775. }
  3776. /**
  3777. * Returns the name of the visual (CSS) theme to be applied on the current page.
  3778. * The returned name depends on the platform, course or user -wide settings.
  3779. * @return string The visual theme's name, it is the name of a folder inside .../chamilo/main/css/
  3780. */
  3781. function api_get_visual_theme()
  3782. {
  3783. static $visual_theme;
  3784. if (!isset($visual_theme)) {
  3785. $platform_theme = api_get_setting('stylesheets');
  3786. // Platform's theme.
  3787. $visual_theme = $platform_theme;
  3788. if (api_get_setting('user_selected_theme') == 'true') {
  3789. $user_info = api_get_user_info();
  3790. if (isset($user_info['theme'])) {
  3791. $user_theme = $user_info['theme'];
  3792. if (!empty($user_theme)) {
  3793. $visual_theme = $user_theme;
  3794. // User's theme.
  3795. }
  3796. }
  3797. }
  3798. $course_id = api_get_course_id();
  3799. if (!empty($course_id) && $course_id != -1) {
  3800. if (api_get_setting('allow_course_theme') == 'true') {
  3801. $course_theme = api_get_course_setting('course_theme');
  3802. if (!empty($course_theme) && $course_theme != -1) {
  3803. if (!empty($course_theme)) {
  3804. // Course's theme.
  3805. $visual_theme = $course_theme;
  3806. }
  3807. }
  3808. $allow_lp_theme = api_get_course_setting('allow_learning_path_theme');
  3809. if ($allow_lp_theme == 1) {
  3810. global $lp_theme_css, $lp_theme_config;
  3811. // These variables come from the file lp_controller.php.
  3812. if (!$lp_theme_config) {
  3813. if (!empty($lp_theme_css)) {
  3814. // LP's theme.
  3815. $visual_theme = $lp_theme_css;
  3816. }
  3817. }
  3818. }
  3819. }
  3820. }
  3821. if (empty($visual_theme)) {
  3822. $visual_theme = 'chamilo';
  3823. }
  3824. global $lp_theme_log;
  3825. if ($lp_theme_log) {
  3826. $visual_theme = $platform_theme;
  3827. }
  3828. }
  3829. return $visual_theme;
  3830. }
  3831. /**
  3832. * Returns a list of CSS themes currently available in the CSS folder
  3833. * @return array List of themes directories from the css folder
  3834. * Note: Directory names (names of themes) in the file system should contain ASCII-characters only.
  3835. */
  3836. function api_get_themes() {
  3837. $cssdir = api_get_path(SYS_CSS_PATH) . 'themes/';
  3838. $list_dir = array();
  3839. $list_name = array();
  3840. if (is_dir($cssdir)) {
  3841. $themes = @scandir($cssdir);
  3842. if (is_array($themes)) {
  3843. if ($themes !== false) {
  3844. sort($themes);
  3845. foreach ($themes as & $theme) {
  3846. if (substr($theme, 0, 1) == '.') {
  3847. continue;
  3848. } else {
  3849. if (is_dir($cssdir.$theme)) {
  3850. $list_dir[] = $theme;
  3851. $list_name[] = ucwords(str_replace('_', ' ', $theme));
  3852. }
  3853. }
  3854. }
  3855. }
  3856. }
  3857. }
  3858. return array($list_dir, $list_name);
  3859. }
  3860. /**
  3861. * Find the largest sort value in a given user_course_category
  3862. * This function is used when we are moving a course to a different category
  3863. * and also when a user subscribes to courses (the new course is added at the end of the main category
  3864. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3865. * @param int $user_course_category the id of the user_course_category
  3866. * @param integer $user_id
  3867. * @return int the value of the highest sort of the user_course_category
  3868. */
  3869. function api_max_sort_value($user_course_category, $user_id)
  3870. {
  3871. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3872. $sql = "SELECT max(sort) as max_sort FROM $tbl_course_user
  3873. WHERE
  3874. user_id='".intval($user_id)."' AND
  3875. relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  3876. user_course_cat='".intval($user_course_category)."'";
  3877. $result_max = Database::query($sql);
  3878. if (Database::num_rows($result_max) == 1) {
  3879. $row_max = Database::fetch_array($result_max);
  3880. return $row_max['max_sort'];
  3881. }
  3882. return 0;
  3883. }
  3884. /**
  3885. * Determines the number of plugins installed for a given location
  3886. */
  3887. function api_number_of_plugins($location) {
  3888. global $_plugins;
  3889. return isset($_plugins[$location]) && is_array($_plugins[$location]) ? count($_plugins[$location]) : 0;
  3890. }
  3891. /**
  3892. * Transforms a number of seconds in hh:mm:ss format
  3893. * @author Julian Prud'homme
  3894. * @param integer the number of seconds
  3895. * @return string the formated time
  3896. */
  3897. function api_time_to_hms($seconds)
  3898. {
  3899. // $seconds = -1 means that we have wrong data in the db.
  3900. if ($seconds == -1) {
  3901. return
  3902. get_lang('Unknown').
  3903. Display::return_icon(
  3904. 'info2.gif',
  3905. get_lang('WrongDatasForTimeSpentOnThePlatform'),
  3906. array('align' => 'absmiddle', 'hspace' => '3px')
  3907. );
  3908. }
  3909. // How many hours ?
  3910. $hours = floor($seconds / 3600);
  3911. // How many minutes ?
  3912. $min = floor(($seconds - ($hours * 3600)) / 60);
  3913. // How many seconds
  3914. $sec = floor($seconds - ($hours * 3600) - ($min * 60));
  3915. if ($sec < 10) {
  3916. $sec = "0$sec";
  3917. }
  3918. if ($min < 10) {
  3919. $min = "0$min";
  3920. }
  3921. return "$hours:$min:$sec";
  3922. }
  3923. /* FILE SYSTEM RELATED FUNCTIONS */
  3924. /**
  3925. * Returns the permissions to be assigned to every newly created directory by the web-server.
  3926. * The return value is based on the platform administrator's setting
  3927. * "Administration > Configuration settings > Security > Permissions for new directories".
  3928. * @return int Returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value.
  3929. */
  3930. function api_get_permissions_for_new_directories() {
  3931. static $permissions;
  3932. if (!isset($permissions)) {
  3933. $permissions = trim(api_get_setting('permissions_for_new_directories'));
  3934. // The default value 0777 is according to that in the platform administration panel after fresh system installation.
  3935. $permissions = octdec(!empty($permissions) ? $permissions : '0777');
  3936. }
  3937. return $permissions;
  3938. }
  3939. /**
  3940. * Returns the permissions to be assigned to every newly created directory by the web-server.
  3941. * The return value is based on the platform administrator's setting
  3942. * "Administration > Configuration settings > Security > Permissions for new files".
  3943. * @return int Returns the permissions in the format
  3944. * "Owner-Group-Others, Read-Write-Execute", as an integer value.
  3945. */
  3946. function api_get_permissions_for_new_files() {
  3947. static $permissions;
  3948. if (!isset($permissions)) {
  3949. $permissions = trim(api_get_setting('permissions_for_new_files'));
  3950. // The default value 0666 is according to that in the platform
  3951. // administration panel after fresh system installation.
  3952. $permissions = octdec(!empty($permissions) ? $permissions : '0666');
  3953. }
  3954. return $permissions;
  3955. }
  3956. /**
  3957. * Deletes a file, or a folder and its contents
  3958. *
  3959. * @author Aidan Lister <aidan@php.net>
  3960. * @version 1.0.3
  3961. * @param string $dirname Directory to delete
  3962. * @param bool Deletes only the content or not
  3963. * @param bool $strict if one folder/file fails stop the loop
  3964. * @return bool Returns TRUE on success, FALSE on failure
  3965. * @link http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
  3966. * @author Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
  3967. * @author Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
  3968. */
  3969. function rmdirr($dirname, $delete_only_content_in_folder = false, $strict = false) {
  3970. $res = true;
  3971. // A sanity check.
  3972. if (!file_exists($dirname)) {
  3973. return false;
  3974. }
  3975. $php_errormsg = '';
  3976. // Simple delete for a file.
  3977. if (is_file($dirname) || is_link($dirname)) {
  3978. $res = unlink($dirname);
  3979. if ($res === false) {
  3980. 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);
  3981. }
  3982. return $res;
  3983. }
  3984. // Loop through the folder.
  3985. $dir = dir($dirname);
  3986. // A sanity check.
  3987. $is_object_dir = is_object($dir);
  3988. if ($is_object_dir) {
  3989. while (false !== $entry = $dir->read()) {
  3990. // Skip pointers.
  3991. if ($entry == '.' || $entry == '..') {
  3992. continue;
  3993. }
  3994. // Recurse.
  3995. if ($strict) {
  3996. $result = rmdirr("$dirname/$entry");
  3997. if ($result == false) {
  3998. $res = false;
  3999. break;
  4000. }
  4001. } else {
  4002. rmdirr("$dirname/$entry");
  4003. }
  4004. }
  4005. }
  4006. // Clean up.
  4007. if ($is_object_dir) {
  4008. $dir->close();
  4009. }
  4010. if ($delete_only_content_in_folder == false) {
  4011. $res = rmdir($dirname);
  4012. if ($res === false) {
  4013. 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);
  4014. }
  4015. }
  4016. return $res;
  4017. }
  4018. // TODO: This function is to be simplified. File access modes to be implemented.
  4019. /**
  4020. * function adapted from a php.net comment
  4021. * copy recursively a folder
  4022. * @param the source folder
  4023. * @param the dest folder
  4024. * @param an array of excluded file_name (without extension)
  4025. * @param copied_files the returned array of copied files
  4026. * @param string $source
  4027. * @param string $dest
  4028. */
  4029. function copyr($source, $dest, $exclude = array(), $copied_files = array()) {
  4030. if (empty($dest)) { return false; }
  4031. // Simple copy for a file
  4032. if (is_file($source)) {
  4033. $path_info = pathinfo($source);
  4034. if (!in_array($path_info['filename'], $exclude)) {
  4035. copy($source, $dest);
  4036. }
  4037. return true;
  4038. } elseif (!is_dir($source)) {
  4039. //then source is not a dir nor a file, return
  4040. return false;
  4041. }
  4042. // Make destination directory.
  4043. if (!is_dir($dest)) {
  4044. mkdir($dest, api_get_permissions_for_new_directories());
  4045. }
  4046. // Loop through the folder.
  4047. $dir = dir($source);
  4048. while (false !== $entry = $dir->read()) {
  4049. // Skip pointers
  4050. if ($entry == '.' || $entry == '..') {
  4051. continue;
  4052. }
  4053. // Deep copy directories.
  4054. if ($dest !== "$source/$entry") {
  4055. $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
  4056. }
  4057. }
  4058. // Clean up.
  4059. $dir->close();
  4060. return true;
  4061. }
  4062. // TODO: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach. Documentation header to be added here.
  4063. /**
  4064. * @param string $pathname
  4065. * @param string $base_path_document
  4066. * @param integer $session_id
  4067. */
  4068. function copy_folder_course_session(
  4069. $pathname,
  4070. $base_path_document,
  4071. $session_id,
  4072. $course_info,
  4073. $document,
  4074. $source_course_id
  4075. ) {
  4076. $table = Database :: get_course_table(TABLE_DOCUMENT);
  4077. $session_id = intval($session_id);
  4078. $source_course_id = intval($source_course_id);
  4079. // Check whether directory already exists.
  4080. if (is_dir($pathname) || empty($pathname)) {
  4081. return true;
  4082. }
  4083. // Ensure that a file with the same name does not already exist.
  4084. if (is_file($pathname)) {
  4085. trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
  4086. return false;
  4087. }
  4088. $course_id = $course_info['real_id'];
  4089. $folders = explode(DIRECTORY_SEPARATOR,str_replace($base_path_document.DIRECTORY_SEPARATOR,'',$pathname));
  4090. $new_pathname = $base_path_document;
  4091. $path = '';
  4092. foreach ($folders as $folder) {
  4093. $new_pathname .= DIRECTORY_SEPARATOR.$folder;
  4094. $path .= DIRECTORY_SEPARATOR.$folder;
  4095. if (!file_exists($new_pathname)) {
  4096. $path = Database::escape_string($path);
  4097. $sql = "SELECT * FROM $table
  4098. WHERE
  4099. c_id = $source_course_id AND
  4100. path = '$path' AND
  4101. filetype = 'folder' AND
  4102. session_id = '$session_id'";
  4103. $rs1 = Database::query($sql);
  4104. $num_rows = Database::num_rows($rs1);
  4105. if ($num_rows == 0) {
  4106. mkdir($new_pathname, api_get_permissions_for_new_directories());
  4107. // Insert new folder with destination session_id.
  4108. $params = [
  4109. 'c_id' => $course_id,
  4110. 'path' => $path,
  4111. 'comment' => $document->comment,
  4112. 'title' => basename($new_pathname),
  4113. 'filetype' => 'folder',
  4114. 'size' => '0',
  4115. 'session_id' => $session_id
  4116. ];
  4117. $document_id = Database::insert($table, $params);
  4118. if ($document_id) {
  4119. $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
  4120. Database::query($sql);
  4121. api_item_property_update(
  4122. $course_info,
  4123. TOOL_DOCUMENT,
  4124. $document_id,
  4125. 'FolderCreated',
  4126. api_get_user_id(),
  4127. 0,
  4128. 0,
  4129. null,
  4130. null,
  4131. $session_id
  4132. );
  4133. }
  4134. }
  4135. }
  4136. } // en foreach
  4137. }
  4138. // TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
  4139. /**
  4140. * @param string $path
  4141. */
  4142. function api_chmod_R($path, $filemode) {
  4143. if (!is_dir($path)) {
  4144. return chmod($path, $filemode);
  4145. }
  4146. $handler = opendir($path);
  4147. while ($file = readdir($handler)) {
  4148. if ($file != '.' && $file != '..') {
  4149. $fullpath = "$path/$file";
  4150. if (!is_dir($fullpath)) {
  4151. if (!chmod($fullpath, $filemode)) {
  4152. return false;
  4153. }
  4154. } else {
  4155. if (!api_chmod_R($fullpath, $filemode)) {
  4156. return false;
  4157. }
  4158. }
  4159. }
  4160. }
  4161. closedir($handler);
  4162. return chmod($path, $filemode);
  4163. }
  4164. // TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
  4165. /**
  4166. * Parse info file format. (e.g: file.info)
  4167. *
  4168. * Files should use an ini-like format to specify values.
  4169. * White-space generally doesn't matter, except inside values.
  4170. * e.g.
  4171. *
  4172. * @verbatim
  4173. * key = value
  4174. * key = "value"
  4175. * key = 'value'
  4176. * key = "multi-line
  4177. *
  4178. * value"
  4179. * key = 'multi-line
  4180. *
  4181. * value'
  4182. * key
  4183. * =
  4184. * 'value'
  4185. * @endverbatim
  4186. *
  4187. * Arrays are created using a GET-like syntax:
  4188. *
  4189. * @verbatim
  4190. * key[] = "numeric array"
  4191. * key[index] = "associative array"
  4192. * key[index][] = "nested numeric array"
  4193. * key[index][index] = "nested associative array"
  4194. * @endverbatim
  4195. *
  4196. * PHP constants are substituted in, but only when used as the entire value:
  4197. *
  4198. * Comments should start with a semi-colon at the beginning of a line.
  4199. *
  4200. * This function is NOT for placing arbitrary module-specific settings. Use
  4201. * variable_get() and variable_set() for that.
  4202. *
  4203. * Information stored in the module.info file:
  4204. * - name: The real name of the module for display purposes.
  4205. * - description: A brief description of the module.
  4206. * - dependencies: An array of shortnames of other modules this module depends on.
  4207. * - package: The name of the package of modules this module belongs to.
  4208. *
  4209. * Example of .info file:
  4210. * <code>
  4211. * @verbatim
  4212. * name = Forum
  4213. * description = Enables threaded discussions about general topics.
  4214. * dependencies[] = taxonomy
  4215. * dependencies[] = comment
  4216. * package = Core - optional
  4217. * version = VERSION
  4218. * @endverbatim
  4219. * </code>
  4220. * @param string $filename
  4221. * The file we are parsing. Accepts file with relative or absolute path.
  4222. * @return
  4223. * The info array.
  4224. */
  4225. function api_parse_info_file($filename) {
  4226. $info = array();
  4227. if (!file_exists($filename)) {
  4228. return $info;
  4229. }
  4230. $data = file_get_contents($filename);
  4231. if (preg_match_all('
  4232. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  4233. ((?:
  4234. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  4235. \[[^\[\]]*\] # unless they are balanced and not nested
  4236. )+?)
  4237. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  4238. (?:
  4239. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  4240. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  4241. ([^\r\n]*?) # Non-quoted string
  4242. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  4243. @msx', $data, $matches, PREG_SET_ORDER)) {
  4244. $key = $value1 = $value2 = $value3 = '';
  4245. foreach ($matches as $match) {
  4246. // Fetch the key and value string.
  4247. $i = 0;
  4248. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  4249. $$var = isset($match[++$i]) ? $match[$i] : '';
  4250. }
  4251. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  4252. // Parse array syntax.
  4253. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  4254. $last = array_pop($keys);
  4255. $parent = &$info;
  4256. // Create nested arrays.
  4257. foreach ($keys as $key) {
  4258. if ($key == '') {
  4259. $key = count($parent);
  4260. }
  4261. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  4262. $parent[$key] = array();
  4263. }
  4264. $parent = &$parent[$key];
  4265. }
  4266. // Handle PHP constants.
  4267. if (defined($value)) {
  4268. $value = constant($value);
  4269. }
  4270. // Insert actual value.
  4271. if ($last == '') {
  4272. $last = count($parent);
  4273. }
  4274. $parent[$last] = $value;
  4275. }
  4276. }
  4277. return $info;
  4278. }
  4279. /**
  4280. * Gets Chamilo version from the configuration files
  4281. * @return string A string of type "1.8.4", or an empty string if the version could not be found
  4282. */
  4283. function api_get_version()
  4284. {
  4285. return (string) api_get_configuration_value('system_version');
  4286. }
  4287. /**
  4288. * Gets the software name (the name/brand of the Chamilo-based customized system)
  4289. * @return string
  4290. */
  4291. function api_get_software_name() {
  4292. $name = api_get_configuration_value('software_name');
  4293. if (!empty($name)) {
  4294. return $name;
  4295. } else {
  4296. return 'Chamilo';
  4297. }
  4298. }
  4299. /**
  4300. * Checks whether status given in parameter exists in the platform
  4301. * @param mixed the status (can be either int either string)
  4302. * @return boolean if the status exists, else returns false
  4303. */
  4304. function api_status_exists($status_asked) {
  4305. global $_status_list;
  4306. return in_array($status_asked, $_status_list) ? true : isset($_status_list[$status_asked]);
  4307. }
  4308. /**
  4309. * Checks whether status given in parameter exists in the platform. The function
  4310. * returns the status ID or false if it does not exist, but given the fact there
  4311. * is no "0" status, the return value can be checked against
  4312. * if(api_status_key()) to know if it exists.
  4313. * @param mixed The status (can be either int or string)
  4314. * @return mixed Status ID if exists, false otherwise
  4315. */
  4316. function api_status_key($status) {
  4317. global $_status_list;
  4318. return isset($_status_list[$status]) ? $status : array_search($status, $_status_list);
  4319. }
  4320. /**
  4321. * Gets the status langvars list
  4322. * @return string[] the list of status with their translations
  4323. */
  4324. function api_get_status_langvars() {
  4325. return array(
  4326. COURSEMANAGER => get_lang('Teacher', ''),
  4327. SESSIONADMIN => get_lang('SessionsAdmin', ''),
  4328. DRH => get_lang('Drh', ''),
  4329. STUDENT => get_lang('Student', ''),
  4330. ANONYMOUS => get_lang('Anonymous', ''),
  4331. STUDENT_BOSS => get_lang('RoleStudentBoss', ''),
  4332. INVITEE => get_lang('Invited'),
  4333. );
  4334. }
  4335. /**
  4336. * The function that retrieves all the possible settings for a certain config setting
  4337. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  4338. */
  4339. function api_get_settings_options($var) {
  4340. $table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  4341. $var = Database::escape_string($var);
  4342. $sql = "SELECT * FROM $table_settings_options
  4343. WHERE variable = '$var'
  4344. ORDER BY id";
  4345. $result = Database::query($sql);
  4346. $settings_options_array = array();
  4347. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4348. $settings_options_array[] = $row;
  4349. }
  4350. return $settings_options_array;
  4351. }
  4352. /**
  4353. * @param array $params
  4354. */
  4355. function api_set_setting_option($params) {
  4356. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  4357. if (empty($params['id'])) {
  4358. Database::insert($table, $params);
  4359. } else {
  4360. Database::update($table, $params, array('id = ? '=> $params['id']));
  4361. }
  4362. }
  4363. /**
  4364. * @param array $params
  4365. */
  4366. function api_set_setting_simple($params) {
  4367. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  4368. $url_id = api_get_current_access_url_id();
  4369. if (empty($params['id'])) {
  4370. $params['access_url'] = $url_id;
  4371. Database::insert($table, $params);
  4372. } else {
  4373. Database::update($table, $params, array('id = ? '=> array($params['id'])));
  4374. }
  4375. }
  4376. /**
  4377. * @param int $id
  4378. */
  4379. function api_delete_setting_option($id) {
  4380. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  4381. if (!empty($id)) {
  4382. Database::delete($table, array('id = ? '=> $id));
  4383. }
  4384. }
  4385. /**
  4386. * Sets a platform configuration setting to a given value
  4387. * @param string The variable we want to update
  4388. * @param string The value we want to record
  4389. * @param string The sub-variable if any (in most cases, this will remain null)
  4390. * @param string The category if any (in most cases, this will remain null)
  4391. * @param int The access_url for which this parameter is valid
  4392. * @param string $cat
  4393. */
  4394. function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1)
  4395. {
  4396. if (empty($var)) {
  4397. return false;
  4398. }
  4399. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  4400. $var = Database::escape_string($var);
  4401. $value = Database::escape_string($value);
  4402. $access_url = (int)$access_url;
  4403. if (empty($access_url)) { $access_url = 1; }
  4404. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  4405. if (!empty($subvar)) {
  4406. $subvar = Database::escape_string($subvar);
  4407. $select .= " AND subkey = '$subvar'";
  4408. }
  4409. if (!empty($cat)) {
  4410. $cat = Database::escape_string($cat);
  4411. $select .= " AND category = '$cat'";
  4412. }
  4413. if ($access_url > 1) {
  4414. $select .= " AND access_url = $access_url";
  4415. } else {
  4416. $select .= " AND access_url = 1 ";
  4417. }
  4418. $res = Database::query($select);
  4419. if (Database::num_rows($res) > 0) {
  4420. // Found item for this access_url.
  4421. $row = Database::fetch_array($res);
  4422. $sql = "UPDATE $t_settings SET selected_value = '$value'
  4423. WHERE id = ".$row['id'];
  4424. Database::query($sql);
  4425. } else {
  4426. // Item not found for this access_url, we have to check if it exist with access_url = 1
  4427. $select = "SELECT * FROM $t_settings
  4428. WHERE variable = '$var' AND access_url = 1 ";
  4429. // Just in case
  4430. if ($access_url == 1) {
  4431. if (!empty($subvar)) {
  4432. $select .= " AND subkey = '$subvar'";
  4433. }
  4434. if (!empty($cat)) {
  4435. $select .= " AND category = '$cat'";
  4436. }
  4437. $res = Database::query($select);
  4438. if (Database::num_rows($res) > 0) {
  4439. // We have a setting for access_url 1, but none for the current one, so create one.
  4440. $row = Database::fetch_array($res);
  4441. $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url)
  4442. VALUES
  4443. ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," .
  4444. "'".$row['type']."','".$row['category']."'," .
  4445. "'$value','".$row['title']."'," .
  4446. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," .
  4447. "".(!empty($row['subkeytext'])?"'".$row['subkeytext']."'":"NULL").",$access_url)";
  4448. Database::query($insert);
  4449. } else {
  4450. // Such a setting does not exist.
  4451. //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
  4452. }
  4453. } else {
  4454. // Other access url.
  4455. if (!empty($subvar)) {
  4456. $select .= " AND subkey = '$subvar'";
  4457. }
  4458. if (!empty($cat)) {
  4459. $select .= " AND category = '$cat'";
  4460. }
  4461. $res = Database::query($select);
  4462. if (Database::num_rows($res) > 0) {
  4463. // We have a setting for access_url 1, but none for the current one, so create one.
  4464. $row = Database::fetch_array($res);
  4465. if ($row['access_url_changeable'] == 1) {
  4466. $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES
  4467. ('".$row['variable']."',".
  4468. (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," .
  4469. "'".$row['type']."','".$row['category']."'," .
  4470. "'$value','".$row['title']."'," .
  4471. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
  4472. (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," .
  4473. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
  4474. Database::query($insert);
  4475. }
  4476. } else { // Such a setting does not exist.
  4477. //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
  4478. }
  4479. }
  4480. }
  4481. }
  4482. /**
  4483. * Sets a whole category of settings to one specific value
  4484. * @param string Category
  4485. * @param string Value
  4486. * @param int Access URL. Optional. Defaults to 1
  4487. * @param array Optional array of filters on field type
  4488. * @param string $category
  4489. * @param string $value
  4490. */
  4491. function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = array())
  4492. {
  4493. if (empty($category)) {
  4494. return false;
  4495. }
  4496. $category = Database::escape_string($category);
  4497. $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  4498. $access_url = (int) $access_url;
  4499. if (empty($access_url)) { $access_url = 1; }
  4500. if (isset($value)) {
  4501. $value = Database::escape_string($value);
  4502. $sql = "UPDATE $t_s SET selected_value = '$value'
  4503. WHERE category = '$category' AND access_url = $access_url";
  4504. if (is_array($fieldtype) && count($fieldtype)>0) {
  4505. $sql .= " AND ( ";
  4506. $i = 0;
  4507. foreach ($fieldtype as $type){
  4508. if ($i > 0) {
  4509. $sql .= ' OR ';
  4510. }
  4511. $type = Database::escape_string($type);
  4512. $sql .= " type='".$type."' ";
  4513. $i++;
  4514. }
  4515. $sql .= ")";
  4516. }
  4517. $res = Database::query($sql);
  4518. return $res !== false;
  4519. } else {
  4520. $sql = "UPDATE $t_s SET selected_value = NULL
  4521. WHERE category = '$category' AND access_url = $access_url";
  4522. if (is_array($fieldtype) && count($fieldtype)>0) {
  4523. $sql .= " AND ( ";
  4524. $i = 0;
  4525. foreach ($fieldtype as $type){
  4526. if ($i > 0) {
  4527. $sql .= ' OR ';
  4528. }
  4529. $type = Database::escape_string($type);
  4530. $sql .= " type='".$type."' ";
  4531. $i++;
  4532. }
  4533. $sql .= ")";
  4534. }
  4535. $res = Database::query($sql);
  4536. return $res !== false;
  4537. }
  4538. }
  4539. /**
  4540. * Gets all available access urls in an array (as in the database)
  4541. * @return array An array of database records
  4542. */
  4543. function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC')
  4544. {
  4545. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  4546. $from = (int) $from;
  4547. $to = (int) $to;
  4548. $order = Database::escape_string($order, null, false);
  4549. $direction = Database::escape_string($direction, null, false);
  4550. $sql = "SELECT id, url, description, active, created_by, tms
  4551. FROM $table
  4552. ORDER BY $order $direction
  4553. LIMIT $to OFFSET $from";
  4554. $res = Database::query($sql);
  4555. return Database::store_result($res);
  4556. }
  4557. /**
  4558. * Gets the access url info in an array
  4559. * @param int $id Id of the access url
  4560. * @param bool $returnDefault Set to false if you want the real URL if URL 1 is still 'http://localhost/'
  4561. * @return array All the info (url, description, active, created_by, tms)
  4562. * from the access_url table
  4563. * @author Julio Montoya
  4564. */
  4565. function api_get_access_url($id, $returnDefault = true)
  4566. {
  4567. $id = intval($id);
  4568. // Calling the Database:: library dont work this is handmade.
  4569. $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  4570. $sql = "SELECT url, description, active, created_by, tms
  4571. FROM $table_access_url WHERE id = '$id' ";
  4572. $res = Database::query($sql);
  4573. $result = @Database::fetch_array($res);
  4574. // If the result url is 'http://localhost/' (the default) and the root_web
  4575. // (=current url) is different, and the $id is = 1 (which might mean
  4576. // api_get_current_access_url_id() returned 1 by default), then return the
  4577. // root_web setting instead of the current URL
  4578. // This is provided as an option to avoid breaking the storage of URL-specific
  4579. // homepages in home/localhost/
  4580. if ($id === 1 && $returnDefault === false) {
  4581. $currentUrl = api_get_current_access_url_id();
  4582. // only do this if we are on the main URL (=1), otherwise we could get
  4583. // information on another URL instead of the one asked as parameter
  4584. if ($currentUrl === 1) {
  4585. $rootWeb = api_get_path(WEB_PATH);
  4586. $default = 'http://localhost/';
  4587. if ($result['url'] === $default && $rootWeb != $default) {
  4588. $result['url'] = $rootWeb;
  4589. }
  4590. }
  4591. }
  4592. return $result;
  4593. }
  4594. /**
  4595. * Gets all the current settings for a specific access url
  4596. * @param string The category, if any, that we want to get
  4597. * @param string Whether we want a simple list (display a category) or
  4598. * a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
  4599. * @param int Access URL's ID. Optional. Uses 1 by default, which is the unique URL
  4600. * @return array Array of database results for the current settings of the current access URL
  4601. */
  4602. function &api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0)
  4603. {
  4604. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  4605. $access_url = (int) $access_url;
  4606. $where_condition = '';
  4607. if ($url_changeable == 1) {
  4608. $where_condition = " AND access_url_changeable= '1' ";
  4609. }
  4610. if (empty($access_url) || $access_url == -1) {
  4611. $access_url = 1;
  4612. }
  4613. $sql = "SELECT * FROM $table
  4614. WHERE access_url = $access_url $where_condition ";
  4615. if (!empty($cat)) {
  4616. $cat = Database::escape_string($cat);
  4617. $sql .= " AND category='$cat' ";
  4618. }
  4619. if ($ordering == 'group') {
  4620. $sql .= " ORDER BY id ASC";
  4621. } else {
  4622. $sql .= " ORDER BY 1,2 ASC";
  4623. }
  4624. $result = Database::query($sql);
  4625. $result = Database::store_result($result,'ASSOC');
  4626. return $result;
  4627. }
  4628. /**
  4629. * Sets a platform configuration setting to a given value
  4630. * @param string The value we want to record
  4631. * @param string The variable name we want to insert
  4632. * @param string The subkey for the variable we want to insert
  4633. * @param string The type for the variable we want to insert
  4634. * @param string The category for the variable we want to insert
  4635. * @param string The title
  4636. * @param string The comment
  4637. * @param string The scope
  4638. * @param string The subkey text
  4639. * @param int The access_url for which this parameter is valid
  4640. * @param int The changeability of this setting for non-master urls
  4641. * @param string $val
  4642. * @param string $var
  4643. * @param string $sk
  4644. * @param string $c
  4645. * @return boolean true on success, false on failure
  4646. */
  4647. function api_add_setting(
  4648. $val,
  4649. $var,
  4650. $sk = null,
  4651. $type = 'textfield',
  4652. $c = null,
  4653. $title = '',
  4654. $com = '',
  4655. $sc = null,
  4656. $skt = null,
  4657. $a = 1,
  4658. $v = 0
  4659. ) {
  4660. if (empty($var) || !isset($val)) { return false; }
  4661. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  4662. $var = Database::escape_string($var);
  4663. $val = Database::escape_string($val);
  4664. $a = (int) $a;
  4665. if (empty($a)) { $a = 1; }
  4666. // Check if this variable doesn't exist already
  4667. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  4668. if (!empty($sk)) {
  4669. $sk = Database::escape_string($sk);
  4670. $select .= " AND subkey = '$sk'";
  4671. }
  4672. if ($a > 1) {
  4673. $select .= " AND access_url = $a";
  4674. } else {
  4675. $select .= " AND access_url = 1 ";
  4676. }
  4677. $res = Database::query($select);
  4678. if (Database::num_rows($res) > 0) { // Found item for this access_url.
  4679. $row = Database::fetch_array($res);
  4680. Database::update(
  4681. $t_settings,
  4682. array('selected_value' => $val),
  4683. array('id = ?' => array($row['id']))
  4684. );
  4685. return $row['id'];
  4686. }
  4687. // Item not found for this access_url, we have to check if the whole thing is missing
  4688. // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
  4689. $insert = "INSERT INTO $t_settings " .
  4690. "(variable,selected_value," .
  4691. "type,category," .
  4692. "subkey,title," .
  4693. "comment,scope," .
  4694. "subkeytext,access_url,access_url_changeable)" .
  4695. " VALUES ('$var','$val',";
  4696. if (isset($type)) {
  4697. $type = Database::escape_string($type);
  4698. $insert .= "'$type',";
  4699. } else {
  4700. $insert .= "NULL,";
  4701. }
  4702. if (isset($c)) { // Category
  4703. $c = Database::escape_string($c);
  4704. $insert .= "'$c',";
  4705. } else {
  4706. $insert .= "NULL,";
  4707. }
  4708. if (isset($sk)) { // Subkey
  4709. $sk = Database::escape_string($sk);
  4710. $insert .= "'$sk',";
  4711. } else {
  4712. $insert .= "NULL,";
  4713. }
  4714. if (isset($title)) { // Title
  4715. $title = Database::escape_string($title);
  4716. $insert .= "'$title',";
  4717. } else {
  4718. $insert .= "NULL,";
  4719. }
  4720. if (isset($com)) { // Comment
  4721. $com = Database::escape_string($com);
  4722. $insert .= "'$com',";
  4723. } else {
  4724. $insert .= "NULL,";
  4725. }
  4726. if (isset($sc)) { // Scope
  4727. $sc = Database::escape_string($sc);
  4728. $insert .= "'$sc',";
  4729. } else {
  4730. $insert .= "NULL,";
  4731. }
  4732. if (isset($skt)) { // Subkey text
  4733. $skt = Database::escape_string($skt);
  4734. $insert .= "'$skt',";
  4735. } else {
  4736. $insert .= "NULL,";
  4737. }
  4738. $insert .= "$a,$v)";
  4739. $res = Database::query($insert);
  4740. return $res;
  4741. }
  4742. /**
  4743. * Checks wether a user can or can't view the contents of a course.
  4744. *
  4745. * @param int $userid User id or NULL to get it from $_SESSION
  4746. * @param int $cid Course id to check whether the user is allowed.
  4747. * @return bool
  4748. */
  4749. function api_is_course_visible_for_user($userid = null, $cid = null) {
  4750. if ($userid === null) {
  4751. $userid = api_get_user_id();
  4752. }
  4753. if (empty($userid) || strval(intval($userid)) != $userid) {
  4754. if (api_is_anonymous()) {
  4755. $userid = api_get_anonymous_id();
  4756. } else {
  4757. return false;
  4758. }
  4759. }
  4760. $cid = Database::escape_string($cid);
  4761. $courseInfo = api_get_course_info($cid);
  4762. $courseId = $courseInfo['real_id'];
  4763. global $is_platformAdmin;
  4764. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  4765. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  4766. $sql = "SELECT
  4767. $course_table.category_code,
  4768. $course_table.visibility,
  4769. $course_table.code,
  4770. $course_cat_table.code
  4771. FROM $course_table
  4772. LEFT JOIN $course_cat_table
  4773. ON $course_table.category_code = $course_cat_table.code
  4774. WHERE
  4775. $course_table.code = '$cid'
  4776. LIMIT 1";
  4777. $result = Database::query($sql);
  4778. if (Database::num_rows($result) > 0) {
  4779. $visibility = Database::fetch_array($result);
  4780. $visibility = $visibility['visibility'];
  4781. } else {
  4782. $visibility = 0;
  4783. }
  4784. // Shortcut permissions in case the visibility is "open to the world".
  4785. if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
  4786. return true;
  4787. }
  4788. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  4789. $sql = "SELECT
  4790. is_tutor, status
  4791. FROM $tbl_course_user
  4792. WHERE
  4793. user_id = '$userid' AND
  4794. relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND
  4795. c_id = $courseId
  4796. LIMIT 1";
  4797. $result = Database::query($sql);
  4798. if (Database::num_rows($result) > 0) {
  4799. // This user has got a recorded state for this course.
  4800. $cuData = Database::fetch_array($result);
  4801. $is_courseMember = true;
  4802. $is_courseTutor = ($cuData['is_tutor'] == 1);
  4803. $is_courseAdmin = ($cuData['status'] == 1);
  4804. }
  4805. if (!$is_courseAdmin) {
  4806. // This user has no status related to this course.
  4807. // Is it the session coach or the session admin?
  4808. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4809. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4810. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4811. $sql = "SELECT
  4812. session.id_coach, session_admin_id, session.id
  4813. FROM
  4814. $tbl_session as session
  4815. INNER JOIN $tbl_session_course
  4816. ON session_rel_course.session_id = session.id
  4817. AND session_rel_course.c_id = '$courseId'
  4818. LIMIT 1";
  4819. $result = Database::query($sql);
  4820. $row = Database::store_result($result);
  4821. if ($row[0]['id_coach'] == $userid) {
  4822. $is_courseMember = true;
  4823. $is_courseTutor = true;
  4824. $is_courseAdmin = false;
  4825. $is_courseCoach = true;
  4826. $is_sessionAdmin = false;
  4827. }
  4828. elseif ($row[0]['session_admin_id'] == $userid) {
  4829. $is_courseMember = false;
  4830. $is_courseTutor = false;
  4831. $is_courseAdmin = false;
  4832. $is_courseCoach = false;
  4833. $is_sessionAdmin = true;
  4834. } else {
  4835. // Check if the current user is the course coach.
  4836. $sql = "SELECT 1
  4837. FROM $tbl_session_course
  4838. WHERE session_rel_course.c_id = '$courseId'
  4839. AND session_rel_course.id_coach = '$userid'
  4840. LIMIT 1";
  4841. $result = Database::query($sql);
  4842. //if ($row = Database::fetch_array($result)) {
  4843. if (Database::num_rows($result) > 0 ) {
  4844. $is_courseMember = true;
  4845. $is_courseTutor = true;
  4846. $is_courseCoach = true;
  4847. $is_sessionAdmin = false;
  4848. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  4849. $sql = "SELECT status FROM $tbl_user
  4850. WHERE user_id = $userid
  4851. LIMIT 1";
  4852. $result = Database::query($sql);
  4853. if (Database::result($result, 0, 0) == 1) {
  4854. $is_courseAdmin = true;
  4855. } else {
  4856. $is_courseAdmin = false;
  4857. }
  4858. } else {
  4859. // Check if the user is a student is this session.
  4860. $sql = "SELECT id
  4861. FROM $tbl_session_course_user
  4862. WHERE
  4863. user_id = '$userid' AND
  4864. c_id = '$courseId'
  4865. LIMIT 1";
  4866. if (Database::num_rows($result) > 0) {
  4867. // This user haa got a recorded state for this course.
  4868. while ($row = Database::fetch_array($result)) {
  4869. $is_courseMember = true;
  4870. $is_courseTutor = false;
  4871. $is_courseAdmin = false;
  4872. $is_sessionAdmin = false;
  4873. }
  4874. }
  4875. }
  4876. }
  4877. }
  4878. switch ($visibility) {
  4879. case COURSE_VISIBILITY_OPEN_WORLD:
  4880. return true;
  4881. case COURSE_VISIBILITY_OPEN_PLATFORM:
  4882. return isset($userid);
  4883. case COURSE_VISIBILITY_REGISTERED:
  4884. case COURSE_VISIBILITY_CLOSED:
  4885. return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
  4886. case COURSE_VISIBILITY_HIDDEN:
  4887. return $is_platformAdmin;
  4888. }
  4889. return false;
  4890. }
  4891. /**
  4892. * Returns whether an element (forum, message, survey ...) belongs to a session or not
  4893. * @param String the tool of the element
  4894. * @param int the element id in database
  4895. * @param int the session_id to compare with element session id
  4896. * @param string $tool
  4897. * @return boolean true if the element is in the session, false else
  4898. */
  4899. function api_is_element_in_the_session($tool, $element_id, $session_id = null) {
  4900. if (is_null($session_id)) {
  4901. $session_id = api_get_session_id();
  4902. }
  4903. // Get information to build query depending of the tool.
  4904. switch ($tool) {
  4905. case TOOL_SURVEY :
  4906. $table_tool = Database::get_course_table(TABLE_SURVEY);
  4907. $key_field = 'survey_id';
  4908. break;
  4909. case TOOL_ANNOUNCEMENT :
  4910. $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
  4911. $key_field = 'id';
  4912. break;
  4913. case TOOL_AGENDA :
  4914. $table_tool = Database::get_course_table(TABLE_AGENDA);
  4915. $key_field = 'id';
  4916. break;
  4917. case TOOL_GROUP :
  4918. $table_tool = Database::get_course_table(TABLE_GROUP);
  4919. $key_field = 'id';
  4920. break;
  4921. default:
  4922. return false;
  4923. }
  4924. $course_id = api_get_course_int_id();
  4925. $sql = "SELECT session_id FROM $table_tool
  4926. WHERE c_id = $course_id AND $key_field = ".intval($element_id);
  4927. $rs = Database::query($sql);
  4928. if ($element_session_id = Database::result($rs, 0, 0)) {
  4929. if ($element_session_id == intval($session_id)) {
  4930. // The element belongs to the session.
  4931. return true;
  4932. }
  4933. }
  4934. return false;
  4935. }
  4936. /**
  4937. * Replaces "forbidden" characters in a filename string.
  4938. *
  4939. * @param string $filename
  4940. * @param bool $treat_spaces_as_hyphens
  4941. *
  4942. * @return string
  4943. */
  4944. function api_replace_dangerous_char($filename, $treat_spaces_as_hyphens = true)
  4945. {
  4946. return URLify::filter($filename, 250, '', true, true, false, false, $treat_spaces_as_hyphens);
  4947. }
  4948. /**
  4949. * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
  4950. * @author Ivan Tcholakov, 28-JUN-2006.
  4951. */
  4952. function api_request_uri() {
  4953. if (!empty($_SERVER['REQUEST_URI'])) {
  4954. return $_SERVER['REQUEST_URI'];
  4955. }
  4956. $uri = $_SERVER['SCRIPT_NAME'];
  4957. if (!empty($_SERVER['QUERY_STRING'])) {
  4958. $uri .= '?'.$_SERVER['QUERY_STRING'];
  4959. }
  4960. $_SERVER['REQUEST_URI'] = $uri;
  4961. return $uri;
  4962. }
  4963. /** Gets the current access_url id of the Chamilo Platform
  4964. * @author Julio Montoya <gugli100@gmail.com>
  4965. * @return int access_url_id of the current Chamilo Installation
  4966. */
  4967. function api_get_current_access_url_id() {
  4968. $access_url_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
  4969. $path = Database::escape_string(api_get_path(WEB_PATH));
  4970. $sql = "SELECT id FROM $access_url_table WHERE url = '".$path."'";
  4971. $result = Database::query($sql);
  4972. if (Database::num_rows($result) > 0) {
  4973. $access_url_id = Database::result($result, 0, 0);
  4974. return $access_url_id;
  4975. }
  4976. //if the url in WEB_PATH was not found, it can only mean that there is
  4977. // either a configuration problem or the first URL has not been defined yet
  4978. // (by default it is http://localhost/). Thus the more sensible thing we can
  4979. // do is return 1 (the main URL) as the user cannot hack this value anyway
  4980. return 1;
  4981. }
  4982. /**
  4983. * Gets the registered urls from a given user id
  4984. * @author Julio Montoya <gugli100@gmail.com>
  4985. * @return int user id
  4986. */
  4987. function api_get_access_url_from_user($user_id) {
  4988. $user_id = intval($user_id);
  4989. $table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4990. $table_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
  4991. $sql = "SELECT access_url_id
  4992. FROM $table_url_rel_user url_rel_user
  4993. INNER JOIN $table_url u
  4994. ON (url_rel_user.access_url_id = u.id)
  4995. WHERE user_id = ".intval($user_id);
  4996. $result = Database::query($sql);
  4997. $url_list = array();
  4998. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4999. $url_list[] = $row['access_url_id'];
  5000. }
  5001. return $url_list;
  5002. }
  5003. /**
  5004. * Gets the status of a user in a course
  5005. * @param int $user_id
  5006. * @param int $courseId
  5007. * @return int user status
  5008. */
  5009. function api_get_status_of_user_in_course($user_id, $courseId)
  5010. {
  5011. $tbl_rel_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  5012. if (!empty($user_id) && !empty($courseId)) {
  5013. $user_id = intval($user_id);
  5014. $courseId = intval($courseId);
  5015. $sql = 'SELECT status
  5016. FROM '.$tbl_rel_course_user.'
  5017. WHERE user_id='.$user_id.' AND c_id = '.$courseId;
  5018. $result = Database::query($sql);
  5019. $row_status = Database::fetch_array($result, 'ASSOC');
  5020. return $row_status['status'];
  5021. } else {
  5022. return 0;
  5023. }
  5024. }
  5025. /**
  5026. * Checks whether the curent user is in a group or not.
  5027. *
  5028. * @param string The group id - optional (takes it from session if not given)
  5029. * @param string The course code - optional (no additional check by course if course code is not given)
  5030. * @return boolean
  5031. * @author Ivan Tcholakov
  5032. */
  5033. function api_is_in_group($groupIdParam = null, $courseCodeParam = null)
  5034. {
  5035. if (!empty($courseCodeParam)) {
  5036. $courseCode = api_get_course_id();
  5037. if (!empty($courseCode)) {
  5038. if ($courseCodeParam != $courseCode) {
  5039. return false;
  5040. }
  5041. } else {
  5042. return false;
  5043. }
  5044. }
  5045. $groupId = api_get_group_id();
  5046. if (isset($groupId) && $groupId != '') {
  5047. if (!empty($groupIdParam)) {
  5048. return $groupIdParam == $groupId;
  5049. } else {
  5050. return true;
  5051. }
  5052. }
  5053. return false;
  5054. }
  5055. /**
  5056. * Checks whether a secret key is valid
  5057. * @param string $original_key_secret - secret key from (webservice) client
  5058. * @param string $security_key - security key from Chamilo
  5059. * @return boolean - true if secret key is valid, false otherwise
  5060. */
  5061. function api_is_valid_secret_key($original_key_secret, $security_key) {
  5062. return $original_key_secret == sha1($security_key);
  5063. }
  5064. /**
  5065. * Checks whether a user is into course
  5066. * @param int $course_id - the course id
  5067. * @param int $user_id - the user id
  5068. */
  5069. function api_is_user_of_course($course_id, $user_id) {
  5070. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5071. $sql = 'SELECT user_id FROM '.$tbl_course_rel_user.'
  5072. WHERE
  5073. c_id ="'.intval($course_id).'" AND
  5074. user_id = "'.intval($user_id).'" AND
  5075. relation_type <> '.COURSE_RELATION_TYPE_RRHH.' ';
  5076. $result = Database::query($sql);
  5077. return Database::num_rows($result) == 1;
  5078. }
  5079. /**
  5080. * Checks whether the server's operating system is Windows (TM).
  5081. * @return boolean - true if the operating system is Windows, false otherwise
  5082. */
  5083. function api_is_windows_os() {
  5084. if (function_exists('php_uname')) {
  5085. // php_uname() exists as of PHP 4.0.2, according to the documentation.
  5086. // We expect that this function will always work for Chamilo 1.8.x.
  5087. $os = php_uname();
  5088. }
  5089. // The following methods are not needed, but let them stay, just in case.
  5090. elseif (isset($_ENV['OS'])) {
  5091. // Sometimes $_ENV['OS'] may not be present (bugs?)
  5092. $os = $_ENV['OS'];
  5093. }
  5094. elseif (defined('PHP_OS')) {
  5095. // PHP_OS means on which OS PHP was compiled, this is why
  5096. // using PHP_OS is the last choice for detection.
  5097. $os = PHP_OS;
  5098. } else {
  5099. return false;
  5100. }
  5101. return strtolower(substr((string)$os, 0, 3 )) == 'win';
  5102. }
  5103. /**
  5104. * This function informs whether the sent request is XMLHttpRequest
  5105. */
  5106. function api_is_xml_http_request() {
  5107. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  5108. }
  5109. /**
  5110. * This wrapper function has been implemented for avoiding some known problems about the function getimagesize().
  5111. * @link http://php.net/manual/en/function.getimagesize.php
  5112. * @link http://www.dokeos.com/forum/viewtopic.php?t=12345
  5113. * @link http://www.dokeos.com/forum/viewtopic.php?t=16355
  5114. * @return integer
  5115. */
  5116. function api_getimagesize($path) {
  5117. $image = new Image($path);
  5118. return $image->get_image_size();
  5119. }
  5120. /**
  5121. * This function resizes an image, with preserving its proportions (or aspect ratio).
  5122. * @author Ivan Tcholakov, MAY-2009.
  5123. * @param int $image System path or URL of the image
  5124. * @param int $target_width Targeted width
  5125. * @param int $target_height Targeted height
  5126. * @return array Calculated new width and height
  5127. */
  5128. function api_resize_image($image, $target_width, $target_height) {
  5129. $image_properties = api_getimagesize($image);
  5130. return api_calculate_image_size($image_properties['width'], $image_properties['height'], $target_width, $target_height);
  5131. }
  5132. /**
  5133. * This function calculates new image size, with preserving image's proportions (or aspect ratio).
  5134. * @author Ivan Tcholakov, MAY-2009.
  5135. * @author The initial idea has been taken from code by Patrick Cool, MAY-2004.
  5136. * @param int $image_width Initial width
  5137. * @param int $image_height Initial height
  5138. * @param int $target_width Targeted width
  5139. * @param int $target_height Targeted height
  5140. * @return array Calculated new width and height
  5141. */
  5142. function api_calculate_image_size($image_width, $image_height, $target_width, $target_height) {
  5143. // Only maths is here.
  5144. $result = array('width' => $image_width, 'height' => $image_height);
  5145. if ($image_width <= 0 || $image_height <= 0) {
  5146. return $result;
  5147. }
  5148. $resize_factor_width = $target_width / $image_width;
  5149. $resize_factor_height = $target_height / $image_height;
  5150. $delta_width = $target_width - $image_width * $resize_factor_height;
  5151. $delta_height = $target_height - $image_height * $resize_factor_width;
  5152. if ($delta_width > $delta_height) {
  5153. $result['width'] = ceil($image_width * $resize_factor_height);
  5154. $result['height'] = ceil($image_height * $resize_factor_height);
  5155. }
  5156. elseif ($delta_width < $delta_height) {
  5157. $result['width'] = ceil($image_width * $resize_factor_width);
  5158. $result['height'] = ceil($image_height * $resize_factor_width);
  5159. }
  5160. else {
  5161. $result['width'] = ceil($target_width);
  5162. $result['height'] = ceil($target_height);
  5163. }
  5164. return $result;
  5165. }
  5166. /**
  5167. * Returns a list of Chamilo's tools or
  5168. * checks whether a given identificator is a valid Chamilo's tool.
  5169. * @author Isaac flores paz
  5170. * @param string The tool name to filter
  5171. * @return mixed Filtered string or array
  5172. */
  5173. function api_get_tools_lists($my_tool = null) {
  5174. $tools_list = array(
  5175. TOOL_DOCUMENT,
  5176. TOOL_THUMBNAIL,
  5177. TOOL_HOTPOTATOES,
  5178. TOOL_CALENDAR_EVENT,
  5179. TOOL_LINK,
  5180. TOOL_COURSE_DESCRIPTION,
  5181. TOOL_SEARCH,
  5182. TOOL_LEARNPATH,
  5183. TOOL_ANNOUNCEMENT,
  5184. TOOL_FORUM,
  5185. TOOL_THREAD,
  5186. TOOL_POST,
  5187. TOOL_DROPBOX,
  5188. TOOL_QUIZ,
  5189. TOOL_USER,
  5190. TOOL_GROUP,
  5191. TOOL_BLOGS,
  5192. TOOL_CHAT,
  5193. TOOL_STUDENTPUBLICATION,
  5194. TOOL_TRACKING,
  5195. TOOL_HOMEPAGE_LINK,
  5196. TOOL_COURSE_SETTING,
  5197. TOOL_BACKUP,
  5198. TOOL_COPY_COURSE_CONTENT,
  5199. TOOL_RECYCLE_COURSE,
  5200. TOOL_COURSE_HOMEPAGE,
  5201. TOOL_COURSE_RIGHTS_OVERVIEW,
  5202. TOOL_UPLOAD,
  5203. TOOL_COURSE_MAINTENANCE,
  5204. TOOL_SURVEY,
  5205. TOOL_WIKI,
  5206. TOOL_GLOSSARY,
  5207. TOOL_GRADEBOOK,
  5208. TOOL_NOTEBOOK,
  5209. TOOL_ATTENDANCE,
  5210. TOOL_COURSE_PROGRESS,
  5211. );
  5212. if (empty($my_tool)) {
  5213. return $tools_list;
  5214. }
  5215. return in_array($my_tool, $tools_list) ? $my_tool : '';
  5216. }
  5217. /**
  5218. * Checks whether we already approved the last version term and condition
  5219. * @param int user id
  5220. * @return bool true if we pass false otherwise
  5221. */
  5222. function api_check_term_condition($user_id)
  5223. {
  5224. if (api_get_setting('allow_terms_conditions') == 'true') {
  5225. //check if exists terms and conditions
  5226. if (LegalManager::count() == 0) {
  5227. return true;
  5228. }
  5229. $extraFieldValue = new ExtraFieldValue('user');
  5230. $data = $extraFieldValue->get_values_by_handler_and_field_variable(
  5231. $user_id,
  5232. 'legal_accept'
  5233. );
  5234. if (!empty($data) && isset($data['value'])) {
  5235. $rowv = $data['value'];
  5236. $user_conditions = explode(':', $rowv);
  5237. $version = $user_conditions[0];
  5238. $lang_id = $user_conditions[1];
  5239. $real_version = LegalManager::get_last_version($lang_id);
  5240. return $version >= $real_version;
  5241. }
  5242. return false;
  5243. }
  5244. return false;
  5245. }
  5246. /**
  5247. * Gets all information of a tool into course
  5248. * @param int The tool id
  5249. * @return array
  5250. */
  5251. function api_get_tool_information($tool_id) {
  5252. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  5253. $course_id = api_get_course_int_id();
  5254. $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id AND id = ".intval($tool_id);
  5255. $rs = Database::query($sql);
  5256. return Database::fetch_array($rs);
  5257. }
  5258. /**
  5259. * Gets all information of a tool into course
  5260. * @param int The tool id
  5261. * @return array
  5262. */
  5263. function api_get_tool_information_by_name($name) {
  5264. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  5265. $course_id = api_get_course_int_id();
  5266. $sql = "SELECT * FROM $t_tool
  5267. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  5268. $rs = Database::query($sql);
  5269. return Database::fetch_array($rs, 'ASSOC');
  5270. }
  5271. /**
  5272. * Function used to protect a "global" admin script.
  5273. * The function blocks access when the user has no global platform admin rights.
  5274. * Global admins are the admins that are registered in the main.admin table
  5275. * AND the users who have access to the "principal" portal.
  5276. * That means that there is a record in the main.access_url_rel_user table
  5277. * with his user id and the access_url_id=1
  5278. *
  5279. * @author Julio Montoya
  5280. * @param integer $user_id
  5281. */
  5282. function api_is_global_platform_admin($user_id = null)
  5283. {
  5284. $user_id = intval($user_id);
  5285. if (empty($user_id)) {
  5286. $user_id = api_get_user_id();
  5287. }
  5288. if (api_is_platform_admin_by_id($user_id)) {
  5289. $urlList = api_get_access_url_from_user($user_id);
  5290. // The admin is registered in the first "main" site with access_url_id = 1
  5291. if (in_array(1, $urlList)) {
  5292. return true;
  5293. } else {
  5294. return false;
  5295. }
  5296. }
  5297. return false;
  5298. }
  5299. /**
  5300. * @param int $admin_id_to_check
  5301. * @param int $my_user_id
  5302. * @param bool $allow_session_admin
  5303. * @return bool
  5304. */
  5305. function api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id = null, $allow_session_admin = false)
  5306. {
  5307. if (empty($my_user_id)) {
  5308. $my_user_id = api_get_user_id();
  5309. }
  5310. $iam_a_global_admin = api_is_global_platform_admin($my_user_id);
  5311. $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
  5312. if ($iam_a_global_admin) {
  5313. // Global admin can edit everything
  5314. return true;
  5315. } else {
  5316. // If i'm a simple admin
  5317. $is_platform_admin = api_is_platform_admin_by_id($my_user_id);
  5318. if ($allow_session_admin) {
  5319. $is_platform_admin = api_is_platform_admin_by_id($my_user_id) || (api_get_user_status($my_user_id) == SESSIONADMIN);
  5320. }
  5321. if ($is_platform_admin) {
  5322. if ($user_is_global_admin) {
  5323. return false;
  5324. } else {
  5325. return true;
  5326. }
  5327. } else {
  5328. return false;
  5329. }
  5330. }
  5331. }
  5332. /**
  5333. * @param int $admin_id_to_check
  5334. * @param int $my_user_id
  5335. * @param bool $allow_session_admin
  5336. * @return boolean|null
  5337. */
  5338. function api_protect_super_admin($admin_id_to_check, $my_user_id = null, $allow_session_admin = false)
  5339. {
  5340. if (api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id, $allow_session_admin)) {
  5341. return true;
  5342. } else {
  5343. api_not_allowed();
  5344. }
  5345. }
  5346. /**
  5347. * Function used to protect a global admin script.
  5348. * The function blocks access when the user has no global platform admin rights.
  5349. * See also the api_is_global_platform_admin() function wich defines who's a "global" admin
  5350. *
  5351. * @author Julio Montoya
  5352. */
  5353. function api_protect_global_admin_script() {
  5354. if (!api_is_global_platform_admin()) {
  5355. api_not_allowed();
  5356. return false;
  5357. }
  5358. return true;
  5359. }
  5360. /**
  5361. * Get active template
  5362. * @param string theme type (optional: default)
  5363. * @param string path absolute(abs) or relative(rel) (optional:rel)
  5364. * @return string actived template path
  5365. */
  5366. function api_get_template($path_type = 'rel') {
  5367. $path_types = array('rel', 'abs');
  5368. $template_path = '';
  5369. if (in_array($path_type, $path_types)) {
  5370. if ($path_type == 'rel') {
  5371. $template_path = api_get_path(SYS_TEMPLATE_PATH);
  5372. } else {
  5373. $template_path = api_get_path(WEB_TEMPLATE_PATH);
  5374. }
  5375. }
  5376. $actived_theme = 'default';
  5377. if (api_get_setting('active_template')) {
  5378. $actived_theme = api_get_setting('active_template');
  5379. }
  5380. $actived_theme_path = $template_path.$actived_theme.DIRECTORY_SEPARATOR;
  5381. return $actived_theme_path;
  5382. }
  5383. /**
  5384. * Check browser support for type files
  5385. * This function check if the users browser support a file format or
  5386. * return the current browser and major ver when $format=check_browser
  5387. * @param string $format
  5388. *
  5389. * @return bool or return text array if $format=check_browser
  5390. * @author Juan Carlos Raña Trabado
  5391. */
  5392. function api_browser_support($format = '')
  5393. {
  5394. $browser = new Browser();
  5395. $current_browser = $browser->getBrowser();
  5396. $a_versiontemp = explode('.', $browser->getVersion());
  5397. $current_majorver = $a_versiontemp[0];
  5398. // Native svg support
  5399. if ($format == 'svg') {
  5400. if (($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  5401. ($current_browser == 'Firefox' && $current_majorver > 1) ||
  5402. ($current_browser == 'Safari' && $current_majorver >= 4) ||
  5403. ($current_browser == 'Chrome' && $current_majorver >= 1) ||
  5404. ($current_browser == 'Opera' && $current_majorver >= 9)
  5405. ) {
  5406. return true;
  5407. } else {
  5408. return false;
  5409. }
  5410. } elseif ($format == 'pdf') {
  5411. //native pdf support
  5412. if ($current_browser == 'Chrome' && $current_majorver >= 6) {
  5413. return true;
  5414. } else {
  5415. return false;
  5416. }
  5417. } elseif ($format == 'tif' || $format == 'tiff') {
  5418. //native tif support
  5419. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  5420. return true;
  5421. } else {
  5422. return false;
  5423. }
  5424. } elseif ($format == 'ogg' || $format == 'ogx' || $format == 'ogv' || $format == 'oga') {
  5425. //native ogg, ogv,oga support
  5426. if (($current_browser == 'Firefox' && $current_majorver >= 3) ||
  5427. ($current_browser == 'Chrome' && $current_majorver >= 3) ||
  5428. ($current_browser == 'Opera' && $current_majorver >= 9)) {
  5429. return true;
  5430. } else {
  5431. return false;
  5432. }
  5433. } elseif ($format == 'mpg' || $format == 'mpeg') {
  5434. //native mpg support
  5435. if (($current_browser == 'Safari' && $current_majorver >= 5)) {
  5436. return true;
  5437. } else {
  5438. return false;
  5439. }
  5440. } elseif ($format == 'mp4') {
  5441. //native mp4 support (TODO: Android, iPhone)
  5442. if ($current_browser == 'Android' || $current_browser == 'iPhone') {
  5443. return true;
  5444. } else {
  5445. return false;
  5446. }
  5447. } elseif ($format == 'mov') {
  5448. //native mov support( TODO:check iPhone)
  5449. if ($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone') {
  5450. return true;
  5451. } else {
  5452. return false;
  5453. }
  5454. } elseif ($format == 'avi') {
  5455. //native avi support
  5456. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  5457. return true;
  5458. } else {
  5459. return false;
  5460. }
  5461. } elseif ($format == 'wmv') {
  5462. //native wmv support
  5463. if ($current_browser == 'Firefox' && $current_majorver >= 4) {
  5464. return true;
  5465. } else {
  5466. return false;
  5467. }
  5468. } elseif ($format == 'webm') {
  5469. //native webm support (TODO:check IE9, Chrome9, Android)
  5470. if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
  5471. ($current_browser == 'Opera' && $current_majorver >= 9) ||
  5472. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  5473. ($current_browser == 'Chrome' && $current_majorver >= 9) ||
  5474. $current_browser == 'Android'
  5475. ) {
  5476. return true;
  5477. } else {
  5478. return false;
  5479. }
  5480. } elseif ($format == 'wav') {
  5481. //native wav support (only some codecs !)
  5482. if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
  5483. ($current_browser == 'Safari' && $current_majorver >= 5) ||
  5484. ($current_browser == 'Opera' && $current_majorver >= 9) ||
  5485. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  5486. ($current_browser == 'Chrome' && $current_majorver > 9) ||
  5487. $current_browser == 'Android' ||
  5488. $current_browser == 'iPhone'
  5489. ) {
  5490. return true;
  5491. } else {
  5492. return false;
  5493. }
  5494. } elseif ($format == 'mid' || $format == 'kar') {
  5495. //native midi support (TODO:check Android)
  5496. if ($current_browser == 'Opera' && $current_majorver >= 9 || $current_browser == 'Android') {
  5497. return true;
  5498. } else {
  5499. return false;
  5500. }
  5501. } elseif ($format == 'wma') {
  5502. //native wma support
  5503. if ($current_browser == 'Firefox' && $current_majorver >= 4) {
  5504. return true;
  5505. } else {
  5506. return false;
  5507. }
  5508. } elseif ($format == 'au') {
  5509. //native au support
  5510. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  5511. return true;
  5512. } else {
  5513. return false;
  5514. }
  5515. } elseif ($format == 'mp3') {
  5516. //native mp3 support (TODO:check Android, iPhone)
  5517. if (($current_browser == 'Safari' && $current_majorver >= 5) ||
  5518. ($current_browser == 'Chrome' && $current_majorver >= 6) ||
  5519. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  5520. $current_browser == 'Android' ||
  5521. $current_browser == 'iPhone' ||
  5522. $current_browser == 'Firefox'
  5523. ) {
  5524. return true;
  5525. } else {
  5526. return false;
  5527. }
  5528. } elseif ($format == "check_browser") {
  5529. $array_check_browser = array($current_browser, $current_majorver);
  5530. return $array_check_browser;
  5531. } else {
  5532. return false;
  5533. }
  5534. }
  5535. /**
  5536. * This function checks if exist path and file browscap.ini
  5537. * In order for this to work, your browscap configuration setting in php.ini
  5538. * must point to the correct location of the browscap.ini file on your system
  5539. * http://php.net/manual/en/function.get-browser.php
  5540. *
  5541. * @return bool
  5542. *
  5543. * @author Juan Carlos Raña Trabado
  5544. */
  5545. function api_check_browscap() {
  5546. $setting = ini_get('browscap');
  5547. if ($setting) {
  5548. $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
  5549. if (strpos($setting, 'browscap.ini') && !empty($browser)) {
  5550. return true;
  5551. }
  5552. }
  5553. return false;
  5554. }
  5555. /**
  5556. * Returns the <script> HTML tag
  5557. */
  5558. function api_get_js($file) {
  5559. return '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
  5560. }
  5561. /**
  5562. * Returns the <script> HTML tag
  5563. * @return string
  5564. */
  5565. function api_get_asset($file)
  5566. {
  5567. return '<script type="text/javascript" src="'.api_get_path(WEB_PATH).'web/assets/'.$file.'"></script>'."\n";
  5568. }
  5569. /**
  5570. * Returns the <script> HTML tag
  5571. * @return string
  5572. */
  5573. function api_get_css_asset($file, $media = 'screen')
  5574. {
  5575. return '<link href="'.api_get_path(WEB_PATH).'web/assets/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
  5576. }
  5577. /**
  5578. * Returns the <link> HTML tag
  5579. * @param string $file
  5580. */
  5581. function api_get_css($file, $media = 'screen') {
  5582. return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
  5583. }
  5584. /**
  5585. * Returns the js header to include the jquery library
  5586. */
  5587. function api_get_jquery_js()
  5588. {
  5589. return api_get_asset('jquery/dist/jquery.min.js');
  5590. }
  5591. /**
  5592. * Returns the jquery path
  5593. * @return string
  5594. */
  5595. function api_get_jquery_web_path()
  5596. {
  5597. return api_get_path(WEB_PATH).'web/assets/jquery/dist/jquery.min.js';
  5598. }
  5599. /**
  5600. * @return string
  5601. */
  5602. function api_get_jquery_ui_js_web_path()
  5603. {
  5604. return api_get_path(WEB_PATH).'web/assets/jquery-ui/jquery-ui.min.js';
  5605. }
  5606. /**
  5607. * @return string
  5608. */
  5609. function api_get_jquery_ui_css_web_path()
  5610. {
  5611. return api_get_path(WEB_PATH).'web/assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
  5612. }
  5613. /**
  5614. * Returns the jquery-ui library js headers
  5615. * @param bool add the jqgrid library
  5616. * @return string html tags
  5617. *
  5618. */
  5619. function api_get_jquery_ui_js($include_jqgrid = false) {
  5620. $libraries = array();
  5621. if ($include_jqgrid) {
  5622. $libraries[]='jqgrid';
  5623. }
  5624. return api_get_jquery_libraries_js($libraries);
  5625. }
  5626. function api_get_jqgrid_js() {
  5627. return api_get_jquery_libraries_js(array('jqgrid'));
  5628. }
  5629. /**
  5630. * Returns the jquery library js and css headers
  5631. *
  5632. * @param array list of jquery libraries supported jquery-ui, jqgrid
  5633. * @param bool add the jquery library
  5634. * @return string html tags
  5635. *
  5636. */
  5637. function api_get_jquery_libraries_js($libraries) {
  5638. $js = '';
  5639. $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
  5640. //jqgrid js and css
  5641. if (in_array('jqgrid', $libraries)) {
  5642. $languaje = 'en';
  5643. $platform_isocode = strtolower(api_get_language_isocode());
  5644. //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  5645. $jqgrid_langs = array(
  5646. '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'
  5647. );
  5648. if (in_array($platform_isocode, $jqgrid_langs)) {
  5649. $languaje = $platform_isocode;
  5650. }
  5651. //$js .= '<link rel="stylesheet" href="'.$js_path.'jqgrid/css/ui.jqgrid.css" type="text/css">';
  5652. $js .= api_get_css($js_path.'jqgrid/css/ui.jqgrid.css');
  5653. $js .= api_get_js('jqgrid/js/i18n/grid.locale-'.$languaje.'.js');
  5654. $js .= api_get_js('jqgrid/js/jquery.jqGrid.min.js');
  5655. }
  5656. //Document multiple upload funcionality
  5657. if (in_array('jquery-upload', $libraries)) {
  5658. $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
  5659. $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
  5660. $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
  5661. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
  5662. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
  5663. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
  5664. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
  5665. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
  5666. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
  5667. $js .= api_get_css(api_get_path(WEB_PATH).'web/assets/jquery-file-upload/css/jquery.fileupload.css');
  5668. $js .= api_get_css(api_get_path(WEB_PATH).'web/assets/jquery-file-upload/css/jquery.fileupload-ui.css');
  5669. }
  5670. // jquery datepicker
  5671. if (in_array('datepicker', $libraries)) {
  5672. $languaje = 'en-GB';
  5673. $platform_isocode = strtolower(api_get_language_isocode());
  5674. // languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  5675. $datapicker_langs = array(
  5676. 'af', 'ar', 'ar-DZ', 'az', 'bg', 'bs', 'ca', 'cs', 'cy-GB', 'da', 'de', 'el', 'en-AU', 'en-GB', 'en-NZ', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'fr-CH', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'lb', 'lt', 'lv', 'mk', 'ml', 'ms', 'nl', 'nl-BE', 'no', 'pl', 'pt', 'pt-BR', 'rm', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-SR', 'sv', 'ta', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-HK', 'zh-TW'
  5677. );
  5678. if (in_array($platform_isocode, $datapicker_langs)) {
  5679. $languaje = $platform_isocode;
  5680. }
  5681. $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
  5682. $script = '<script>
  5683. $(function(){
  5684. $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
  5685. $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
  5686. });
  5687. </script>
  5688. ';
  5689. $js .= $script;
  5690. }
  5691. return $js;
  5692. }
  5693. /**
  5694. * Returns the course's URL
  5695. *
  5696. * This function relies on api_get_course_info()
  5697. * @param string The course code - optional (takes it from session if not given)
  5698. * @param int The session id - optional (takes it from session if not given)
  5699. * @param integer $session_id
  5700. * @return string|null The URL of the course or null if something does not work
  5701. * @author Julio Montoya <gugli100@gmail.com>
  5702. */
  5703. function api_get_course_url($course_code = null, $session_id = null)
  5704. {
  5705. if (empty($course_code)) {
  5706. $course_info = api_get_course_info();
  5707. } else {
  5708. $course_info = api_get_course_info($course_code);
  5709. }
  5710. if (empty($session_id)) {
  5711. $session_url = '?id_session='.api_get_session_id();
  5712. } else {
  5713. $session_url = '?id_session='.intval($session_id);
  5714. }
  5715. /*
  5716. if (empty($group_id)) {
  5717. $group_url = '&gidReq='.api_get_group_id();
  5718. } else {
  5719. $group_url = '&gidReq='.intval($group_id);
  5720. }*/
  5721. if (!empty($course_info['path'])) {
  5722. return api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php'.$session_url;
  5723. }
  5724. return null;
  5725. }
  5726. /**
  5727. *
  5728. * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on
  5729. * @return bool true if multi site is enabled
  5730. *
  5731. **/
  5732. function api_get_multiple_access_url() {
  5733. global $_configuration;
  5734. if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
  5735. return true;
  5736. }
  5737. return false;
  5738. }
  5739. /**
  5740. * @return bool
  5741. */
  5742. function api_is_multiple_url_enabled() {
  5743. return api_get_multiple_access_url();
  5744. }
  5745. /**
  5746. * Returns a md5 unique id
  5747. * @todo add more parameters
  5748. */
  5749. function api_get_unique_id() {
  5750. $id = md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
  5751. return $id;
  5752. }
  5753. /**
  5754. * Get home path
  5755. * @return string
  5756. */
  5757. function api_get_home_path()
  5758. {
  5759. // FIX : Start the routing determination from central path definition
  5760. $home = api_get_path(SYS_HOME_PATH);
  5761. if (api_get_multiple_access_url()) {
  5762. $access_url_id = api_get_current_access_url_id();
  5763. $url_info = api_get_access_url($access_url_id);
  5764. $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
  5765. $clean_url = api_replace_dangerous_char($url);
  5766. $clean_url = str_replace('/', '-', $clean_url);
  5767. $clean_url .= '/';
  5768. if ($clean_url != 'localhost/') {
  5769. // means that the multiple URL was not well configured we don't rename the $home variable
  5770. return "{$home}{$clean_url}";
  5771. }
  5772. }
  5773. return $home;
  5774. }
  5775. /**
  5776. *
  5777. * @param int Course id
  5778. * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
  5779. * @param int the item id (tool id, exercise id, lp id)
  5780. *
  5781. */
  5782. function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null) {
  5783. if (api_is_platform_admin()) {
  5784. return false;
  5785. }
  5786. if (api_get_setting('gradebook_locking_enabled') == 'true') {
  5787. if (empty($course_code)) {
  5788. $course_code = api_get_course_id();
  5789. }
  5790. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
  5791. $item_id = intval($item_id);
  5792. $link_type = intval($link_type);
  5793. $course_code = Database::escape_string($course_code);
  5794. $sql = "SELECT locked FROM $table
  5795. WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
  5796. $result = Database::query($sql);
  5797. if (Database::num_rows($result)) {
  5798. return true;
  5799. }
  5800. }
  5801. return false;
  5802. }
  5803. /**
  5804. * Blocks a page if the item was added in a gradebook
  5805. *
  5806. * @param int exercise id, work id, thread id,
  5807. * @param int LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
  5808. * see gradebook/lib/be/linkfactory
  5809. * @param string course code
  5810. * @return false|null
  5811. */
  5812. function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null) {
  5813. if (api_is_platform_admin()) {
  5814. return false;
  5815. }
  5816. if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
  5817. $message = Display::return_message(get_lang('ResourceLockedByGradebook'), 'warning');
  5818. api_not_allowed(true, $message);
  5819. }
  5820. }
  5821. /**
  5822. * Checks the PHP version installed is enough to run Chamilo
  5823. * @param string Include path (used to load the error page)
  5824. * @return void
  5825. */
  5826. function api_check_php_version($my_inc_path = null) {
  5827. if (!function_exists('version_compare') || version_compare( phpversion(), REQUIRED_PHP_VERSION, '<')) {
  5828. $global_error_code = 1;
  5829. // Incorrect PHP version
  5830. $global_page = $my_inc_path.'global_error_message.inc.php';
  5831. if (file_exists($global_page)) {
  5832. require $global_page;
  5833. }
  5834. exit;
  5835. }
  5836. }
  5837. /**
  5838. * Checks whether the Archive directory is present and writeable. If not,
  5839. * prints a warning message.
  5840. */
  5841. function api_check_archive_dir() {
  5842. if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
  5843. $message = Display::return_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'),'warning');
  5844. api_not_allowed(true, $message);
  5845. }
  5846. }
  5847. /**
  5848. * Returns an array of global configuration settings which should be ignored
  5849. * when printing the configuration settings screens
  5850. * @return array Array of strings, each identifying one of the excluded settings
  5851. */
  5852. function api_get_locked_settings() {
  5853. return array(
  5854. 'server_type',
  5855. 'permanently_remove_deleted_files',
  5856. 'account_valid_duration',
  5857. 'service_ppt2lp',
  5858. 'wcag_anysurfer_public_pages',
  5859. 'upload_extensions_list_type',
  5860. 'upload_extensions_blacklist',
  5861. 'upload_extensions_whitelist',
  5862. 'upload_extensions_skip',
  5863. 'upload_extensions_replace_by',
  5864. 'hide_dltt_markup',
  5865. 'split_users_upload_directory',
  5866. 'permissions_for_new_directories',
  5867. 'permissions_for_new_files',
  5868. 'platform_charset',
  5869. 'ldap_description',
  5870. 'cas_activate',
  5871. 'cas_server',
  5872. 'cas_server_uri',
  5873. 'cas_port',
  5874. 'cas_protocol',
  5875. 'cas_add_user_activate',
  5876. 'update_user_info_cas_with_ldap',
  5877. 'languagePriority1',
  5878. 'languagePriority2',
  5879. 'languagePriority3',
  5880. 'languagePriority4',
  5881. 'login_is_email',
  5882. 'chamilo_database_version'
  5883. );
  5884. }
  5885. /**
  5886. * Checks if the user is corrently logged in. Returns the user ID if he is, or
  5887. * false if he isn't. If the user ID is given and is an integer, then the same
  5888. * ID is simply returned
  5889. * @param integer User ID
  5890. * @return boolean Integer User ID is logged in, or false otherwise
  5891. */
  5892. function api_user_is_login($user_id = null) {
  5893. $user_id = empty($user_id) ? api_get_user_id() : intval($user_id);
  5894. return $user_id && !api_is_anonymous();
  5895. }
  5896. /**
  5897. * Guess the real ip for register in the database, even in reverse proxy cases.
  5898. * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
  5899. * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
  5900. * @return string the user's real ip (unsafe - escape it before inserting to db)
  5901. * @author Jorge Frisancho Jibaja <jrfdeft@gmail.com>, USIL - Some changes to allow the use of real IP using reverse proxy
  5902. * @version CEV CHANGE 24APR2012
  5903. */
  5904. function api_get_real_ip(){
  5905. // Guess the IP if behind a reverse proxy
  5906. global $debug;
  5907. $ip = trim($_SERVER['REMOTE_ADDR']);
  5908. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  5909. if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  5910. @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  5911. } else {
  5912. $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
  5913. }
  5914. $ip = trim($ip1);
  5915. }
  5916. if (!empty($debug)) error_log('Real IP: '.$ip);
  5917. return $ip;
  5918. }
  5919. /**
  5920. * Checks whether an IP is included inside an IP range
  5921. * @param string IP address
  5922. * @param string IP range
  5923. * @param string $ip
  5924. * @return bool True if IP is in the range, false otherwise
  5925. * @author claudiu at cnixs dot com on http://www.php.net/manual/fr/ref.network.php#55230
  5926. * @author Yannick Warnier for improvements and managment of multiple ranges
  5927. * @todo check for IPv6 support
  5928. */
  5929. function api_check_ip_in_range($ip,$range)
  5930. {
  5931. if (empty($ip) or empty($range)) {
  5932. return false;
  5933. }
  5934. $ip_ip = ip2long ($ip);
  5935. // divide range param into array of elements
  5936. if (strpos($range,',')!==false) {
  5937. $ranges = explode(',',$range);
  5938. } else {
  5939. $ranges = array($range);
  5940. }
  5941. foreach ($ranges as $range) {
  5942. $range = trim($range);
  5943. if (empty($range)) { continue; }
  5944. if (strpos($range,'/')===false) {
  5945. if (strcmp($ip,$range)===0) {
  5946. return true; // there is a direct IP match, return OK
  5947. }
  5948. continue; //otherwise, get to the next range
  5949. }
  5950. // the range contains a "/", so analyse completely
  5951. list ($net, $mask) = explode("/", $range);
  5952. $ip_net = ip2long ($net);
  5953. // mask binary magic
  5954. $ip_mask = ~((1 << (32 - $mask)) - 1);
  5955. $ip_ip_net = $ip_ip & $ip_mask;
  5956. if ($ip_ip_net == $ip_net) {
  5957. return true;
  5958. }
  5959. }
  5960. return false;
  5961. }
  5962. function api_check_user_access_to_legal($course_visibility) {
  5963. $course_visibility_list = array(COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM);
  5964. return in_array($course_visibility, $course_visibility_list) || api_is_drh();
  5965. }
  5966. /**
  5967. * Checks if the global chat is enabled or not
  5968. *
  5969. * @return bool
  5970. */
  5971. function api_is_global_chat_enabled()
  5972. {
  5973. return
  5974. !api_is_anonymous() &&
  5975. api_get_setting('allow_global_chat') == 'true' &&
  5976. api_get_setting('allow_social_tool') == 'true';
  5977. }
  5978. /**
  5979. * @todo Fix tool_visible_by_default_at_creation labels
  5980. * @todo Add sessionId parameter to avoid using context
  5981. *
  5982. * @param int $item_id
  5983. * @param int $tool_id
  5984. * @param int $group_id iid
  5985. * @param array $courseInfo
  5986. */
  5987. function api_set_default_visibility(
  5988. $item_id,
  5989. $tool_id,
  5990. $group_id = 0,
  5991. $courseInfo = array(),
  5992. $sessionId = 0,
  5993. $userId = 0
  5994. ) {
  5995. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  5996. $courseId = $courseInfo['real_id'];
  5997. $courseCode = $courseInfo['code'];
  5998. $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
  5999. $userId = empty($userId) ? api_get_user_id() : $userId;
  6000. if (empty($group_id)) {
  6001. $group_id = api_get_group_id();
  6002. }
  6003. $groupInfo = GroupManager::get_group_properties($group_id);
  6004. $groupIid = 0;
  6005. if ($groupInfo) {
  6006. $groupIid = $groupInfo['iid'];
  6007. }
  6008. $original_tool_id = $tool_id;
  6009. switch ($tool_id) {
  6010. case TOOL_LINK:
  6011. case TOOL_LINK_CATEGORY:
  6012. $tool_id = 'links';
  6013. break;
  6014. case TOOL_DOCUMENT:
  6015. $tool_id = 'documents';
  6016. break;
  6017. case TOOL_LEARNPATH:
  6018. $tool_id = 'learning';
  6019. break;
  6020. case TOOL_ANNOUNCEMENT:
  6021. $tool_id = 'announcements';
  6022. break;
  6023. case TOOL_FORUM:
  6024. case TOOL_FORUM_CATEGORY:
  6025. case TOOL_FORUM_THREAD:
  6026. $tool_id = 'forums';
  6027. break;
  6028. case TOOL_QUIZ:
  6029. $tool_id = 'quiz';
  6030. break;
  6031. }
  6032. $setting = api_get_setting('tool_visible_by_default_at_creation');
  6033. if (isset($setting[$tool_id])) {
  6034. $visibility = 'invisible';
  6035. if ($setting[$tool_id] == 'true') {
  6036. $visibility = 'visible';
  6037. }
  6038. // Read the portal and course default visibility
  6039. if ($tool_id == 'documents') {
  6040. $visibility = DocumentManager::getDocumentDefaultVisibility($courseCode);
  6041. }
  6042. api_item_property_update(
  6043. $courseInfo,
  6044. $original_tool_id,
  6045. $item_id,
  6046. $visibility,
  6047. $userId,
  6048. $groupIid,
  6049. null,
  6050. null,
  6051. null,
  6052. api_get_session_id()
  6053. );
  6054. // Fixes default visibility for tests
  6055. switch ($original_tool_id) {
  6056. case TOOL_QUIZ:
  6057. if (empty($sessionId)) {
  6058. $objExerciseTmp = new Exercise($courseId);
  6059. $objExerciseTmp->read($item_id);
  6060. if ($visibility == 'visible') {
  6061. $objExerciseTmp->enable();
  6062. $objExerciseTmp->save();
  6063. } else {
  6064. $objExerciseTmp->disable();
  6065. $objExerciseTmp->save();
  6066. }
  6067. }
  6068. break;
  6069. }
  6070. }
  6071. }
  6072. /**
  6073. * @return string
  6074. */
  6075. function api_get_security_key() {
  6076. return api_get_configuration_value('security_key');
  6077. }
  6078. /**
  6079. * @param int $user_id
  6080. * @param int $courseId
  6081. * @param int $session_id
  6082. * @return array
  6083. */
  6084. function api_detect_user_roles($user_id, $courseId, $session_id = 0)
  6085. {
  6086. $user_roles = array();
  6087. /*$user_info = api_get_user_info($user_id);
  6088. $user_roles[] = $user_info['status'];*/
  6089. $courseInfo = api_get_course_info_by_id($courseId);
  6090. $course_code = $courseInfo['code'];
  6091. $url_id = api_get_current_access_url_id();
  6092. if (api_is_platform_admin_by_id($user_id, $url_id)) {
  6093. $user_roles[] = PLATFORM_ADMIN;
  6094. }
  6095. /*if (api_is_drh()) {
  6096. $user_roles[] = DRH;
  6097. }*/
  6098. if (!empty($session_id)) {
  6099. if (SessionManager::user_is_general_coach($user_id, $session_id)) {
  6100. $user_roles[] = SESSION_GENERAL_COACH;
  6101. }
  6102. }
  6103. if (!empty($course_code)) {
  6104. if (empty($session_id)) {
  6105. if (CourseManager::is_course_teacher($user_id, $course_code)) {
  6106. $user_roles[] = COURSEMANAGER;
  6107. }
  6108. if (CourseManager::get_tutor_in_course_status($user_id, $courseInfo['real_id'])) {
  6109. $user_roles[] = COURSE_TUTOR;
  6110. }
  6111. if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) {
  6112. $user_roles[] = COURSE_STUDENT;
  6113. }
  6114. } else {
  6115. $user_status_in_session = SessionManager::get_user_status_in_course_session(
  6116. $user_id,
  6117. $courseId,
  6118. $session_id
  6119. );
  6120. if (!empty($user_status_in_session)) {
  6121. if ($user_status_in_session == 0) {
  6122. $user_roles[] = SESSION_STUDENT;
  6123. }
  6124. if ($user_status_in_session == 2) {
  6125. $user_roles[] = SESSION_COURSE_COACH;
  6126. }
  6127. }
  6128. /*if (api_is_course_session_coach($user_id, $course_code, $session_id)) {
  6129. $user_roles[] = SESSION_COURSE_COACH;
  6130. }*/
  6131. }
  6132. }
  6133. return $user_roles;
  6134. }
  6135. /**
  6136. * @param int $courseId
  6137. * @param int $session_id
  6138. * @return bool
  6139. */
  6140. function api_coach_can_edit_view_results($courseId = null, $session_id = null)
  6141. {
  6142. $user_id = api_get_user_id();
  6143. if (empty($courseId)) {
  6144. $courseId = api_get_course_int_id();
  6145. }
  6146. if (empty($session_id)) {
  6147. $session_id = api_get_session_id();
  6148. }
  6149. if (api_is_platform_admin()) {
  6150. return true;
  6151. }
  6152. $roles = api_detect_user_roles($user_id, $courseId, $session_id);
  6153. if (in_array(SESSION_COURSE_COACH, $roles)) {
  6154. //return api_get_setting('session_tutor_reports_visibility') == 'true';
  6155. return true;
  6156. } else {
  6157. if (in_array(COURSEMANAGER, $roles)) {
  6158. return true;
  6159. }
  6160. return false;
  6161. }
  6162. }
  6163. function api_get_js_simple($file) {
  6164. return '<script type="text/javascript" src="'.$file.'"></script>'."\n";
  6165. }
  6166. function api_set_settings_and_plugins() {
  6167. global $_configuration;
  6168. $_setting = array();
  6169. $_plugins = array();
  6170. // access_url == 1 is the default chamilo location
  6171. $settings_by_access_list = array();
  6172. $access_url_id = api_get_current_access_url_id();
  6173. if ($access_url_id != 1) {
  6174. $url_info = api_get_access_url($_configuration['access_url']);
  6175. if ($url_info['active'] == 1) {
  6176. $settings_by_access = & api_get_settings(null, 'list', $_configuration['access_url'], 1);
  6177. foreach ($settings_by_access as & $row) {
  6178. if (empty($row['variable'])) {
  6179. $row['variable'] = 0;
  6180. }
  6181. if (empty($row['subkey'])) {
  6182. $row['subkey'] = 0;
  6183. }
  6184. if (empty($row['category'])) {
  6185. $row['category'] = 0;
  6186. }
  6187. $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
  6188. }
  6189. }
  6190. }
  6191. $result = api_get_settings(null, 'list', 1);
  6192. foreach ($result as & $row) {
  6193. if ($access_url_id != 1) {
  6194. if ($url_info['active'] == 1) {
  6195. $var = empty($row['variable']) ? 0 : $row['variable'];
  6196. $subkey = empty($row['subkey']) ? 0 : $row['subkey'];
  6197. $category = empty($row['category']) ? 0 : $row['category'];
  6198. }
  6199. if ($row['access_url_changeable'] == 1 && $url_info['active'] == 1) {
  6200. if (isset($settings_by_access_list[$var]) &&
  6201. $settings_by_access_list[$var][$subkey][$category]['selected_value'] != '') {
  6202. if ($row['subkey'] == null) {
  6203. $_setting[$row['variable']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
  6204. } else {
  6205. $_setting[$row['variable']][$row['subkey']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
  6206. }
  6207. } else {
  6208. if ($row['subkey'] == null) {
  6209. $_setting[$row['variable']] = $row['selected_value'];
  6210. } else {
  6211. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  6212. }
  6213. }
  6214. } else {
  6215. if ($row['subkey'] == null) {
  6216. $_setting[$row['variable']] = $row['selected_value'];
  6217. } else {
  6218. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  6219. }
  6220. }
  6221. } else {
  6222. if ($row['subkey'] == null) {
  6223. $_setting[$row['variable']] = $row['selected_value'];
  6224. } else {
  6225. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  6226. }
  6227. }
  6228. }
  6229. $result = api_get_settings('Plugins', 'list', $access_url_id);
  6230. $_plugins = array();
  6231. foreach ($result as & $row) {
  6232. $key = & $row['variable'];
  6233. if (is_string($_setting[$key])) {
  6234. $_setting[$key] = array();
  6235. }
  6236. $_setting[$key][] = $row['selected_value'];
  6237. $_plugins[$key][] = $row['selected_value'];
  6238. }
  6239. $_SESSION['_setting'] = $_setting;
  6240. $_SESSION['_plugins'] = $_plugins;
  6241. }
  6242. /**
  6243. * Tries to set memory limit, if authorized and new limit is higher than current
  6244. * @param string New memory limit
  6245. * @param string $mem
  6246. * @return bool True on success, false on failure or current is higher than suggested
  6247. * @assert (null) === false
  6248. * @assert (-1) === false
  6249. * @assert (0) === true
  6250. * @assert ('1G') === true
  6251. */
  6252. function api_set_memory_limit($mem){
  6253. //if ini_set() not available, this function is useless
  6254. if (!function_exists('ini_set') || is_null($mem) || $mem == -1) {
  6255. return false;
  6256. }
  6257. $memory_limit = ini_get('memory_limit');
  6258. if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)){
  6259. ini_set('memory_limit', $mem);
  6260. return true;
  6261. }
  6262. return false;
  6263. }
  6264. /**
  6265. * Gets memory limit in bytes
  6266. * @param string The memory size (128M, 1G, 1000K, etc)
  6267. * @return int
  6268. * @assert (null) === false
  6269. * @assert ('1t') === 1099511627776
  6270. * @assert ('1g') === 1073741824
  6271. * @assert ('1m') === 1048576
  6272. * @assert ('100k') === 102400
  6273. */
  6274. function api_get_bytes_memory_limit($mem){
  6275. $size = strtolower(substr($mem,-1));
  6276. switch ($size) {
  6277. case 't':
  6278. $mem = intval(substr($mem,-1))*1024*1024*1024*1024;
  6279. break;
  6280. case 'g':
  6281. $mem = intval(substr($mem,0,-1))*1024*1024*1024;
  6282. break;
  6283. case 'm':
  6284. $mem = intval(substr($mem,0,-1))*1024*1024;
  6285. break;
  6286. case 'k':
  6287. $mem = intval(substr($mem,0,-1))*1024;
  6288. break;
  6289. default:
  6290. // we assume it's integer only
  6291. $mem = intval($mem);
  6292. break;
  6293. }
  6294. return $mem;
  6295. }
  6296. /**
  6297. * Finds all the information about a user from username instead of user id
  6298. *
  6299. * @param string $officialCode
  6300. * @return array $user_info user_id, lastname, firstname, username, email, ...
  6301. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  6302. */
  6303. function api_get_user_info_from_official_code($officialCode)
  6304. {
  6305. if (empty($officialCode)) {
  6306. return false;
  6307. }
  6308. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)."
  6309. WHERE official_code ='".Database::escape_string($officialCode)."'";
  6310. $result = Database::query($sql);
  6311. if (Database::num_rows($result) > 0) {
  6312. $result_array = Database::fetch_array($result);
  6313. return _api_format_user($result_array);
  6314. }
  6315. return false;
  6316. }
  6317. /**
  6318. * @param string $usernameInputId
  6319. * @param string $passwordInputId
  6320. * @return null|string
  6321. */
  6322. function api_get_password_checker_js($usernameInputId, $passwordInputId)
  6323. {
  6324. $checkPass = api_get_setting('allow_strength_pass_checker');
  6325. $useStrengthPassChecker = $checkPass === 'true';
  6326. if ($useStrengthPassChecker === false) {
  6327. return null;
  6328. }
  6329. $translations = [
  6330. 'wordLength' => get_lang('PasswordIsTooShort'),
  6331. 'wordNotEmail' => get_lang('YourPasswordCannotBeTheSameAsYourEmail'),
  6332. 'wordSimilarToUsername' => get_lang('YourPasswordCannotContainYourUsername'),
  6333. 'wordTwoCharacterClasses' => get_lang('WordTwoCharacterClasses'),
  6334. 'wordRepetitions' => get_lang('TooManyRepetitions'),
  6335. 'wordSequences' => get_lang('YourPasswordContainsSequences'),
  6336. 'errorList' => get_lang('ErrorsFound'),
  6337. 'veryWeak' => get_lang('PasswordVeryWeak'),
  6338. 'weak' => get_lang('PasswordWeak'),
  6339. 'normal' => get_lang('PasswordNormal'),
  6340. 'medium' => get_lang('PasswordMedium'),
  6341. 'strong' => get_lang('PasswordStrong'),
  6342. 'veryStrong' => get_lang('PasswordVeryStrong')
  6343. ];
  6344. $js = api_get_asset('pwstrength-bootstrap/dist/pwstrength-bootstrap.min.js');
  6345. $js .= "<script>
  6346. var errorMessages = {
  6347. password_to_short : \"" . get_lang('PasswordIsTooShort')."\",
  6348. same_as_username : \"".get_lang('YourPasswordCannotBeTheSameAsYourUsername')."\"
  6349. };
  6350. $(document).ready(function() {
  6351. var lang = ".json_encode($translations).";
  6352. var options = {
  6353. onLoad : function () {
  6354. //$('#messages').text('Start typing password');
  6355. },
  6356. onKeyUp: function (evt) {
  6357. $(evt.target).pwstrength('outputErrorList');
  6358. },
  6359. errorMessages : errorMessages,
  6360. viewports: {
  6361. progress: '#password_progress',
  6362. verdict: '#password-verdict',
  6363. errors: '#password-errors'
  6364. },
  6365. usernameField: '$usernameInputId'
  6366. };
  6367. options.i18n = {
  6368. t: function (key) {
  6369. var result = lang[key];
  6370. return result === key ? '' : result; // This assumes you return the
  6371. }
  6372. };
  6373. $('".$passwordInputId."').pwstrength(options);
  6374. });
  6375. </script>";
  6376. return $js;
  6377. }
  6378. /**
  6379. * @param string $username
  6380. * create an user extra field called 'captcha_blocked_until_date'
  6381. */
  6382. function api_block_account_captcha($username)
  6383. {
  6384. $userInfo = api_get_user_info_from_username($username);
  6385. if (empty($userInfo)) {
  6386. return false;
  6387. }
  6388. $minutesToBlock = api_get_setting('captcha_time_to_block');
  6389. $time = time() + $minutesToBlock*60;
  6390. UserManager::update_extra_field_value(
  6391. $userInfo['user_id'],
  6392. 'captcha_blocked_until_date',
  6393. api_get_utc_datetime($time)
  6394. );
  6395. }
  6396. /**
  6397. * @param string $username
  6398. */
  6399. function api_clean_account_captcha($username)
  6400. {
  6401. $userInfo = api_get_user_info_from_username($username);
  6402. if (empty($userInfo)) {
  6403. return false;
  6404. }
  6405. Session::erase('loginFailedCount');
  6406. UserManager::update_extra_field_value(
  6407. $userInfo['user_id'],
  6408. 'captcha_blocked_until_date',
  6409. null
  6410. );
  6411. }
  6412. /**
  6413. * @param string $username
  6414. * @return bool
  6415. */
  6416. function api_get_user_blocked_by_captcha($username)
  6417. {
  6418. $userInfo = api_get_user_info_from_username($username);
  6419. if (empty($userInfo)) {
  6420. return false;
  6421. }
  6422. $data = UserManager::get_extra_user_data_by_field(
  6423. $userInfo['user_id'],
  6424. 'captcha_blocked_until_date'
  6425. );
  6426. if (isset($data) && isset($data['captcha_blocked_until_date'])) {
  6427. return $data['captcha_blocked_until_date'];
  6428. }
  6429. return false;
  6430. }
  6431. /**
  6432. * Remove tags from HTML anf return the $in_number_char first non-HTML char
  6433. * Postfix the text with "..." if it has been truncated.
  6434. * @param integer $in_number_char
  6435. * @return string
  6436. * @author hubert borderiou
  6437. */
  6438. function api_get_short_text_from_html($in_html, $in_number_char)
  6439. {
  6440. $out_res = api_remove_tags_with_space($in_html, false);
  6441. $postfix = "...";
  6442. if (strlen($out_res) > $in_number_char) {
  6443. $out_res = substr($out_res, 0, $in_number_char).$postfix;
  6444. }
  6445. return $out_res;
  6446. }
  6447. /**
  6448. * Replace tags with a space in a text.
  6449. * If $in_double_quote_replace, replace " with '' (for HTML attribute purpose, for exemple)
  6450. * @return string
  6451. * @author hubert borderiou
  6452. */
  6453. function api_remove_tags_with_space($in_html, $in_double_quote_replace = true) {
  6454. $out_res = $in_html;
  6455. if ($in_double_quote_replace) {
  6456. $out_res = str_replace('"', "''", $out_res);
  6457. }
  6458. // avoid text stuck together when tags are removed, adding a space after >
  6459. $out_res = str_replace (">", "> ", $out_res);
  6460. $out_res = strip_tags($out_res);
  6461. return $out_res;
  6462. }
  6463. /**
  6464. * If true, the drh can access all content (courses, users) inside a session
  6465. * @return bool
  6466. */
  6467. function api_drh_can_access_all_session_content()
  6468. {
  6469. $value = api_get_setting('drh_can_access_all_session_content');
  6470. return $value === 'true';
  6471. }
  6472. /**
  6473. * @param string $tool
  6474. * @param string $setting
  6475. * @param integer $defaultValue
  6476. * @return string
  6477. */
  6478. function api_get_default_tool_setting($tool, $setting, $defaultValue)
  6479. {
  6480. global $_configuration;
  6481. if (isset($_configuration[$tool]) &&
  6482. isset($_configuration[$tool]['default_settings']) &&
  6483. isset($_configuration[$tool]['default_settings'][$setting])
  6484. ) {
  6485. return $_configuration[$tool]['default_settings'][$setting];
  6486. }
  6487. return $defaultValue;
  6488. }
  6489. /**
  6490. * Checks if user can login as another user
  6491. *
  6492. * @param int $loginAsUserId the user id to log in
  6493. * @param int $userId my user id
  6494. * @return bool
  6495. */
  6496. function api_can_login_as($loginAsUserId, $userId = null)
  6497. {
  6498. if (empty($userId)) {
  6499. $userId = api_get_user_id();
  6500. }
  6501. if ($loginAsUserId == $userId) {
  6502. return false;
  6503. }
  6504. if (empty($loginAsUserId)) {
  6505. return false;
  6506. }
  6507. if ($loginAsUserId != strval(intval($loginAsUserId))) {
  6508. return false;
  6509. }
  6510. // Check if the user to login is an admin
  6511. if (api_is_platform_admin_by_id($loginAsUserId)) {
  6512. // Only super admins can login to admin accounts
  6513. if (!api_global_admin_can_edit_admin($loginAsUserId)) {
  6514. return false;
  6515. }
  6516. }
  6517. $userInfo = api_get_user_info($userId);
  6518. $isDrh = function() use($loginAsUserId) {
  6519. if (api_is_drh()) {
  6520. if (api_drh_can_access_all_session_content()) {
  6521. $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh_all', api_get_user_id());
  6522. $userList = array();
  6523. if (is_array($users)) {
  6524. foreach ($users as $user) {
  6525. $userList[] = $user['user_id'];
  6526. }
  6527. }
  6528. if (in_array($loginAsUserId, $userList)) {
  6529. return true;
  6530. }
  6531. } else {
  6532. if (api_is_drh() && UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())) {
  6533. return true;
  6534. }
  6535. }
  6536. }
  6537. return false;
  6538. };
  6539. return api_is_platform_admin() || (api_is_session_admin() && $userInfo['status'] == 5) || $isDrh();
  6540. }
  6541. /**
  6542. * @return bool
  6543. */
  6544. function api_is_allowed_in_course()
  6545. {
  6546. if (api_is_platform_admin()) {
  6547. return true;
  6548. }
  6549. return Session::read('is_allowed_in_course');
  6550. }
  6551. /**
  6552. * Set the cookie to go directly to the course code $in_firstpage
  6553. * after login
  6554. * @param string $in_firstpage is the course code of the course to go
  6555. */
  6556. function api_set_firstpage_parameter($in_firstpage)
  6557. {
  6558. setcookie('GotoCourse', $in_firstpage);
  6559. }
  6560. /**
  6561. * Delete the cookie to go directly to the course code $in_firstpage
  6562. * after login
  6563. */
  6564. function api_delete_firstpage_parameter()
  6565. {
  6566. setcookie('GotoCourse', '', time() - 3600);
  6567. }
  6568. /**
  6569. * @return boolean if course_code for direct course access after login is set
  6570. */
  6571. function exist_firstpage_parameter()
  6572. {
  6573. return (isset($_COOKIE['GotoCourse']) && $_COOKIE['GotoCourse'] != "");
  6574. }
  6575. /**
  6576. * @return return the course_code of the course where user login
  6577. */
  6578. function api_get_firstpage_parameter()
  6579. {
  6580. return $_COOKIE['GotoCourse'];
  6581. }
  6582. /**
  6583. * Return true on https install
  6584. * @return boolean
  6585. */
  6586. function api_is_https()
  6587. {
  6588. return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off');
  6589. }
  6590. /**
  6591. * Return protocol (http or https)
  6592. * @return string
  6593. */
  6594. function api_get_protocol()
  6595. {
  6596. return api_is_https() ? 'https' : 'http';
  6597. }
  6598. /**
  6599. * Return a string where " are replaced with 2 '
  6600. * It is useful when you pass a PHP variable in a Javascript browser dialog
  6601. * e.g. : alert("<?php get_lang('Message') ?>");
  6602. * and message contains character "
  6603. *
  6604. * @param string $in_text
  6605. * @return string
  6606. */
  6607. function convert_double_quote_to_single($in_text)
  6608. {
  6609. return api_preg_replace('/"/', "''", $in_text);
  6610. }
  6611. /**
  6612. * Get origin
  6613. *
  6614. * @param string
  6615. * @return string
  6616. **/
  6617. function api_get_origin()
  6618. {
  6619. if (isset($_REQUEST['origin'])) {
  6620. return $_REQUEST['origin'] === 'learnpath' ? 'learnpath' : '';
  6621. }
  6622. return '';
  6623. }
  6624. /**
  6625. * Warns an user that the portal reach certain limit.
  6626. * @param string $limitName
  6627. */
  6628. function api_warn_hosting_contact($limitName)
  6629. {
  6630. $hostingParams = api_get_configuration_value(1);
  6631. $email = null;
  6632. if (!empty($hostingParams)) {
  6633. if (isset($hostingParams['hosting_contact_mail'])) {
  6634. $email = $hostingParams['hosting_contact_mail'];
  6635. }
  6636. }
  6637. if (!empty($email)) {
  6638. $subject = get_lang('HostingWarningReached');
  6639. $body = get_lang('PortalName').': '.api_get_path(WEB_PATH)." \n ";
  6640. $body .= get_lang('PortalLimitType').': '.$limitName." \n ";
  6641. if (isset($hostingParams[$limitName])) {
  6642. $body .= get_lang('Value') . ': ' . $hostingParams[$limitName];
  6643. }
  6644. api_mail_html(null, $email, $subject, $body);
  6645. }
  6646. }
  6647. /**
  6648. * @param string $variable
  6649. * @return bool|mixed
  6650. */
  6651. function api_get_configuration_value($variable)
  6652. {
  6653. global $_configuration;
  6654. if (isset($_configuration[$variable])) {
  6655. return $_configuration[$variable];
  6656. }
  6657. return false;
  6658. }
  6659. /**
  6660. * Returns supported image extensions in the portal
  6661. * @param bool $supportVectors Whether vector images should also be accepted or not
  6662. * @return array Supported image extensions in the portal
  6663. */
  6664. function api_get_supported_image_extensions($supportVectors = true)
  6665. {
  6666. // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
  6667. $supportedImageExtensions = array('jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif');
  6668. if ($supportVectors) {
  6669. array_push($supportedImageExtensions, 'svg');
  6670. }
  6671. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  6672. array_push($supportedImageExtensions, 'webp');
  6673. }
  6674. return $supportedImageExtensions;
  6675. }
  6676. /**
  6677. * This setting changes the registration status for the campus
  6678. *
  6679. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  6680. * @version August 2006
  6681. * @param bool $listCampus Whether we authorize
  6682. * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
  6683. */
  6684. function api_register_campus($listCampus = true) {
  6685. $tbl_settings = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  6686. $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
  6687. Database::query($sql);
  6688. if (!$listCampus) {
  6689. $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
  6690. Database::query($sql);
  6691. }
  6692. }
  6693. /**
  6694. * Checks whether current user is a student boss
  6695. * @global array $_user
  6696. * @return boolean
  6697. */
  6698. function api_is_student_boss()
  6699. {
  6700. $_user = api_get_user_info();
  6701. return isset($_user['status']) && $_user['status'] == STUDENT_BOSS;
  6702. }
  6703. /**
  6704. * Check whether the user type should be exclude.
  6705. * Such as invited or anonymous users
  6706. * @param boolean $checkDB Optional. Whether check the user status
  6707. * @param int $userId Options. The user id
  6708. *
  6709. * @return boolean
  6710. */
  6711. function api_is_excluded_user_type($checkDB = false, $userId = 0)
  6712. {
  6713. if ($checkDB) {
  6714. $userId = empty($userId) ? api_get_user_id() : intval($userId);
  6715. if ($userId == 0) {
  6716. return true;
  6717. }
  6718. $userInfo = api_get_user_info($userId);
  6719. switch ($userInfo['status']) {
  6720. case INVITEE:
  6721. //no break;
  6722. case ANONYMOUS:
  6723. return true;
  6724. default:
  6725. return false;
  6726. }
  6727. }
  6728. $isInvited = api_is_invitee();
  6729. $isAnonymous = api_is_anonymous();
  6730. if ($isInvited || $isAnonymous) {
  6731. return true;
  6732. }
  6733. return false;
  6734. }
  6735. /**
  6736. * Get the user status to ignore in reports
  6737. * @param string $format Optional. The result type (array or string)
  6738. * @return array|string
  6739. */
  6740. function api_get_users_status_ignored_in_reports($format = 'array')
  6741. {
  6742. $excludedTypes = array(
  6743. INVITEE,
  6744. ANONYMOUS
  6745. );
  6746. if ($format == 'string') {
  6747. return implode(', ', $excludedTypes);
  6748. }
  6749. return $excludedTypes;
  6750. }
  6751. /**
  6752. * Set the Site Use Cookie Warning for 1 year
  6753. */
  6754. function api_set_site_use_cookie_warning_cookie()
  6755. {
  6756. setcookie('ChamiloUsesCookies', 'ok', time()+31556926);
  6757. }
  6758. /**
  6759. * Return true if the Site Use Cookie Warning Cookie warning exists
  6760. * @return bool
  6761. */
  6762. function api_site_use_cookie_warning_cookie_exist()
  6763. {
  6764. return isset($_COOKIE['ChamiloUsesCookies']);
  6765. }
  6766. /**
  6767. * Given a number of seconds, format the time to show hours, minutes and seconds
  6768. * @param int $time The time in seconds
  6769. * @param string $originFormat Optional. PHP o JS
  6770. * @return string (00h00'00")
  6771. */
  6772. function api_format_time($time, $originFormat = 'php')
  6773. {
  6774. $h = get_lang('h');
  6775. $hours = $time / 3600;
  6776. $mins = ($time % 3600) / 60;
  6777. $secs = ($time % 60);
  6778. if ($time < 0) {
  6779. $hours = 0;
  6780. $mins = 0;
  6781. $secs = 0;
  6782. }
  6783. if ($originFormat == 'js') {
  6784. $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
  6785. } else {
  6786. $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
  6787. }
  6788. return $formattedTime;
  6789. }
  6790. /**
  6791. * Create a new empty directory with index.html file
  6792. * @param string $name The new directory name
  6793. * @param string $parentDirectory Directory parent directory name
  6794. * @return boolean Return true if the directory was create. Otherwise return false
  6795. */
  6796. function api_create_protected_dir($name, $parentDirectory)
  6797. {
  6798. $isCreated = false;
  6799. if (!is_writable($parentDirectory)) {
  6800. return false;
  6801. }
  6802. $fullPath = $parentDirectory . api_replace_dangerous_char($name);
  6803. if (mkdir($fullPath, api_get_permissions_for_new_directories(), true)) {
  6804. $fp = fopen($fullPath . '/index.html', 'w');
  6805. if ($fp) {
  6806. if (fwrite($fp, '<html><head></head><body></body></html>')) {
  6807. $isCreated = true;
  6808. }
  6809. }
  6810. fclose($fp);
  6811. }
  6812. return $isCreated;
  6813. }
  6814. /**
  6815. * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
  6816. * Sender name and email can be specified, if not specified
  6817. * name and email of the platform admin are used
  6818. *
  6819. * @author Bert Vanderkimpen ICT&O UGent
  6820. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  6821. *
  6822. * @param string name of recipient
  6823. * @param string email of recipient
  6824. * @param string email subject
  6825. * @param string email body
  6826. * @param string sender name
  6827. * @param string sender e-mail
  6828. * @param array extra headers in form $headers = array($name => $value) to allow parsing
  6829. * @param array data file (path and filename)
  6830. * @param bool True for attaching a embedded file inside content html (optional)
  6831. * @param array Additional parameters
  6832. * @return integer true if mail was sent
  6833. * @see class.phpmailer.php
  6834. */
  6835. function api_mail_html(
  6836. $recipient_name,
  6837. $recipient_email,
  6838. $subject,
  6839. $message,
  6840. $senderName = '',
  6841. $senderEmail = '',
  6842. $extra_headers = array(),
  6843. $data_file = array(),
  6844. $embedded_image = false,
  6845. $additionalParameters = array()
  6846. ) {
  6847. global $platform_email;
  6848. $mail = new PHPMailer();
  6849. $mail->Mailer = $platform_email['SMTP_MAILER'];
  6850. $mail->Host = $platform_email['SMTP_HOST'];
  6851. $mail->Port = $platform_email['SMTP_PORT'];
  6852. $mail->CharSet = $platform_email['SMTP_CHARSET'];
  6853. // Stay far below SMTP protocol 980 chars limit.
  6854. $mail->WordWrap = 200;
  6855. if ($platform_email['SMTP_AUTH']) {
  6856. $mail->SMTPAuth = 1;
  6857. $mail->Username = $platform_email['SMTP_USER'];
  6858. $mail->Password = $platform_email['SMTP_PASS'];
  6859. if (isset($platform_email['SMTP_SECURE'])) {
  6860. $mail->SMTPSecure = $platform_email['SMTP_SECURE'];
  6861. }
  6862. }
  6863. $mail->SMTPDebug = isset($platform_email['SMTP_DEBUG'])?$platform_email['SMTP_DEBUG']:0;
  6864. // 5 = low, 1 = high
  6865. $mail->Priority = 3;
  6866. $mail->SMTPKeepAlive = true;
  6867. // Default values
  6868. $notification = new Notification();
  6869. $defaultEmail = $notification->getDefaultPlatformSenderEmail();
  6870. $defaultName = $notification->getDefaultPlatformSenderName();
  6871. // If the parameter is set don't use the admin.
  6872. $senderName = !empty($senderName) ? $senderName : $defaultName;
  6873. $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail;
  6874. // Reply to first
  6875. if (isset($extra_headers['reply_to'])) {
  6876. $mail->AddReplyTo(
  6877. $extra_headers['reply_to']['mail'],
  6878. $extra_headers['reply_to']['name']
  6879. );
  6880. // Errors to sender
  6881. $mail->AddCustomHeader('Errors-To: '.$extra_headers['reply_to']['mail']);
  6882. $mail->Sender = $extra_headers['reply_to']['mail'];
  6883. unset($extra_headers['reply_to']);
  6884. } else {
  6885. $mail->AddCustomHeader('Errors-To: '.$defaultEmail);
  6886. }
  6887. //If the SMTP configuration only accept one sender
  6888. if (isset($platform_email['SMTP_UNIQUE_SENDER']) && $platform_email['SMTP_UNIQUE_SENDER']) {
  6889. $senderName = $platform_email['SMTP_FROM_NAME'];
  6890. $senderEmail = $platform_email['SMTP_FROM_EMAIL'];
  6891. }
  6892. $mail->SetFrom($defaultEmail, $defaultName);
  6893. $mail->From = $defaultEmail;
  6894. $mail->Sender = $defaultEmail;
  6895. $mail->Subject = $subject;
  6896. $mail->AltBody = strip_tags(
  6897. str_replace('<br />', "\n", api_html_entity_decode($message))
  6898. );
  6899. // Send embedded image.
  6900. if ($embedded_image) {
  6901. // Get all images html inside content.
  6902. preg_match_all("/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i", $message, $m);
  6903. // Prepare new tag images.
  6904. $new_images_html = array();
  6905. $i = 1;
  6906. if (!empty($m[1])) {
  6907. foreach ($m[1] as $image_path) {
  6908. $real_path = realpath($image_path);
  6909. $filename = basename($image_path);
  6910. $image_cid = $filename.'_'.$i;
  6911. $encoding = 'base64';
  6912. $image_type = mime_content_type($real_path);
  6913. $mail->AddEmbeddedImage(
  6914. $real_path,
  6915. $image_cid,
  6916. $filename,
  6917. $encoding,
  6918. $image_type
  6919. );
  6920. $new_images_html[] = '<img src="cid:'.$image_cid.'" />';
  6921. $i++;
  6922. }
  6923. }
  6924. // Replace origin image for new embedded image html.
  6925. $x = 0;
  6926. if (!empty($m[0])) {
  6927. foreach ($m[0] as $orig_img) {
  6928. $message = str_replace($orig_img, $new_images_html[$x], $message);
  6929. $x++;
  6930. }
  6931. }
  6932. }
  6933. $mailView = new Template(null, false, false, false, false, false, false);
  6934. $mailView->assign('content', $message);
  6935. if (isset($additionalParameters['link'])) {
  6936. $mailView->assign('link', $additionalParameters['link']);
  6937. }
  6938. $layout = $mailView->get_template('mail/mail.tpl');
  6939. $mail->Body = $mailView->fetch($layout);
  6940. // Attachment ...
  6941. if (!empty($data_file)) {
  6942. $o = 0;
  6943. foreach ($data_file as $file_attach) {
  6944. if (!empty($file_attach['path']) && !empty($file_attach['filename'])) {
  6945. $mail->AddAttachment($file_attach['path'], $file_attach['filename']);
  6946. }
  6947. $o++;
  6948. }
  6949. }
  6950. // Only valid addresses are accepted.
  6951. if (is_array($recipient_email)) {
  6952. foreach ($recipient_email as $dest) {
  6953. if (api_valid_email($dest)) {
  6954. $mail->AddAddress($dest, $recipient_name);
  6955. }
  6956. }
  6957. } else {
  6958. if (api_valid_email($recipient_email)) {
  6959. $mail->AddAddress($recipient_email, $recipient_name);
  6960. } else {
  6961. return 0;
  6962. }
  6963. }
  6964. if (is_array($extra_headers) && count($extra_headers) > 0) {
  6965. foreach ($extra_headers as $key => $value) {
  6966. switch (strtolower($key)) {
  6967. case 'encoding':
  6968. case 'content-transfer-encoding':
  6969. $mail->Encoding = $value;
  6970. break;
  6971. case 'charset':
  6972. $mail->Charset = $value;
  6973. break;
  6974. case 'contenttype':
  6975. case 'content-type':
  6976. $mail->ContentType = $value;
  6977. break;
  6978. default:
  6979. $mail->AddCustomHeader($key.':'.$value);
  6980. break;
  6981. }
  6982. }
  6983. } else {
  6984. if (!empty($extra_headers)) {
  6985. $mail->AddCustomHeader($extra_headers);
  6986. }
  6987. }
  6988. // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
  6989. $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
  6990. // Send the mail message.
  6991. if (!$mail->Send()) {
  6992. error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'<br />');
  6993. if ($mail->SMTPDebug) {
  6994. error_log(
  6995. "Connection details :: " .
  6996. "Protocol: " . $mail->Mailer . ' :: ' .
  6997. "Host/Port: " . $mail->Host . ':' . $mail->Port . ' :: ' .
  6998. "Authent/Open: " . ($mail->SMTPAuth?'Authent':'Open') . ' :: ' .
  6999. ($mail->SMTPAuth?" User/Pass: " . $mail->Username . ':' . $mail->Password:'')
  7000. );
  7001. }
  7002. return 0;
  7003. }
  7004. if (!empty($additionalParameters)) {
  7005. $plugin = new AppPlugin();
  7006. $smsPlugin = $plugin->getSMSPluginLibrary();
  7007. if ($smsPlugin) {
  7008. $smsPlugin->send($additionalParameters);
  7009. }
  7010. }
  7011. // Clear all the addresses.
  7012. $mail->ClearAddresses();
  7013. // Clear all attachments
  7014. $mail->ClearAttachments();
  7015. return 1;
  7016. }
  7017. /**
  7018. * @param string $tool Possible values:
  7019. * GroupManager::GROUP_TOOL_*
  7020. *
  7021. */
  7022. function api_protect_course_group($tool, $showHeader = true)
  7023. {
  7024. $userId = api_get_user_id();
  7025. $groupId = api_get_group_id();
  7026. $groupInfo = GroupManager::get_group_properties($groupId);
  7027. if (!empty($groupInfo)) {
  7028. $allow = GroupManager::user_has_access(
  7029. $userId,
  7030. $groupInfo['iid'],
  7031. $tool
  7032. );
  7033. if (!$allow) {
  7034. api_not_allowed($showHeader);
  7035. }
  7036. }
  7037. }
  7038. /**
  7039. * Check if a date is in a date range
  7040. *
  7041. * @param datetime $startDate
  7042. * @param datetime $endDate
  7043. * @param datetime $currentDate
  7044. * @return bool true if date is in rage, false otherwise
  7045. */
  7046. function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
  7047. {
  7048. $startDate = strtotime(api_get_local_time($startDate));
  7049. $endDate = strtotime(api_get_local_time($endDate));
  7050. $currentDate = strtotime(api_get_local_time($currentDate));
  7051. if ($currentDate >= $startDate && $currentDate <= $endDate) {
  7052. return true;
  7053. }
  7054. return false;
  7055. }
  7056. /**
  7057. * Eliminate the duplicates of a multidimensional array by sending the key
  7058. *
  7059. * @param array $array multidimensional array
  7060. * @param int $key key to find to compare
  7061. * @return array
  7062. *
  7063. */
  7064. function api_unique_multidim_array($array, $key){
  7065. $temp_array = [];
  7066. $i = 0;
  7067. $key_array = [];
  7068. foreach($array as $val){
  7069. if(!in_array($val[$key],$key_array)){
  7070. $key_array[$i] = $val[$key];
  7071. $temp_array[$i] = $val;
  7072. }
  7073. $i++;
  7074. }
  7075. return $temp_array;
  7076. }
  7077. /**
  7078. * Limit the access to Session Admins wheen the limit_session_admin_role
  7079. * configuration variable is set to true
  7080. */
  7081. function api_protect_limit_for_session_admin()
  7082. {
  7083. $limitAdmin = api_get_setting('limit_session_admin_role');
  7084. if (api_is_session_admin() && $limitAdmin === 'true') {
  7085. api_not_allowed(true);
  7086. }
  7087. }
  7088. function api_is_student_view_active() {
  7089. $studentView = Session::read('studentview');
  7090. return $studentView == 'studentview';
  7091. }
  7092. /**
  7093. * Adds a file inside the upload/$type/id
  7094. *
  7095. * @param string $type
  7096. * @param array $file
  7097. * @param int $itemId
  7098. * @param string $cropParameters
  7099. * @return array|bool
  7100. */
  7101. function api_upload_file($type, $file, $itemId, $cropParameters = '')
  7102. {
  7103. $upload = process_uploaded_file($file);
  7104. if ($upload) {
  7105. $name = api_replace_dangerous_char($file['name']);
  7106. // No "dangerous" files
  7107. $name = disable_dangerous_file($name);
  7108. $pathId = '/'.substr((string)$itemId, 0, 1).'/'.$itemId.'/';
  7109. $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
  7110. if (!is_dir($path)) {
  7111. mkdir($path, api_get_permissions_for_new_directories(), true);
  7112. }
  7113. $pathToSave = $path.$name;
  7114. $result = move_uploaded_file($file['tmp_name'], $pathToSave);
  7115. if ($result) {
  7116. if (!empty($cropParameters)) {
  7117. $image = new Image($pathToSave);
  7118. $image->crop($cropParameters);
  7119. }
  7120. return ['path_to_save' => $pathId.$name];
  7121. }
  7122. return false;
  7123. }
  7124. }
  7125. /**
  7126. * @param string $type
  7127. * @param string $file
  7128. */
  7129. function api_remove_uploaded_file($type, $file)
  7130. {
  7131. $path = api_get_path(SYS_UPLOAD_PATH).$type.'/'.$file;
  7132. if (file_exists($path)) {
  7133. unlink($path);
  7134. }
  7135. }