main_api.lib.php 264 KB

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