api.lib.php 273 KB

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