main_api.lib.php 271 KB

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