api.lib.php 286 KB

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