api.lib.php 277 KB

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