api.lib.php 247 KB

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