api.lib.php 284 KB

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