api.lib.php 275 KB

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