api.lib.php 275 KB

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