api.lib.php 259 KB

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