api.lib.php 277 KB

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