api.lib.php 278 KB

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