main_api.lib.php 269 KB

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