main_api.lib.php 211 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is a code library for Chamilo.
  5. * It is included by default in every Chamilo file (through including the global.inc.php)
  6. *
  7. * @package chamilo.library
  8. */
  9. /**
  10. * Constants declaration
  11. */
  12. // USER STATUS CONSTANTS
  13. /** global status of a user: student */
  14. define('STUDENT', 5);
  15. /** global status of a user: course manager */
  16. define('COURSEMANAGER', 1);
  17. /** global status of a user: session admin */
  18. define('SESSIONADMIN', 3);
  19. /** global status of a user: human ressource manager */
  20. define('DRH', 4);
  21. /** global status of a user: human ressource manager */
  22. define('ANONYMOUS', 6);
  23. /** global status of a user: low security, necessary for inserting data from
  24. * the teacher through HTMLPurifier */
  25. define('COURSEMANAGERLOWSECURITY', 10);
  26. // Table of status
  27. $_status_list[COURSEMANAGER] = 'teacher'; // 1
  28. $_status_list[SESSIONADMIN] = 'session_admin'; // 3
  29. $_status_list[DRH] = 'drh'; // 4
  30. $_status_list[STUDENT] = 'user'; // 5
  31. $_status_list[ANONYMOUS] = 'anonymous'; // 6
  32. // COURSE VISIBILITY CONSTANTS
  33. /** only visible for course admin */
  34. define('COURSE_VISIBILITY_CLOSED', 0);
  35. /** only visible for users registered in the course*/
  36. define('COURSE_VISIBILITY_REGISTERED', 1);
  37. /** Open for all registered users on the platform */
  38. define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
  39. /** Open for the whole world */
  40. define('COURSE_VISIBILITY_OPEN_WORLD', 3);
  41. // SESSION VISIBILITY CONSTANTS
  42. define('SESSION_VISIBLE_READ_ONLY', 1);
  43. define('SESSION_VISIBLE', 2);
  44. define('SESSION_INVISIBLE', 3);
  45. define('SUBSCRIBE_ALLOWED', 1);
  46. define('SUBSCRIBE_NOT_ALLOWED', 0);
  47. define('UNSUBSCRIBE_ALLOWED', 1);
  48. define('UNSUBSCRIBE_NOT_ALLOWED', 0);
  49. // CONSTANTS defining all tools, using the english version
  50. /* When you add a new tool you must add it into function api_get_tools_lists() too */
  51. define('TOOL_DOCUMENT','document');
  52. define('TOOL_THUMBNAIL', 'thumbnail');
  53. define('TOOL_HOTPOTATOES', 'hotpotatoes');
  54. define('TOOL_CALENDAR_EVENT', 'calendar_event');
  55. define('TOOL_LINK', 'link');
  56. define('TOOL_COURSE_DESCRIPTION', 'course_description');
  57. define('TOOL_SEARCH', 'search');
  58. define('TOOL_LEARNPATH', 'learnpath');
  59. define('TOOL_ANNOUNCEMENT', 'announcement');
  60. define('TOOL_FORUM', 'forum');
  61. define('TOOL_THREAD', 'thread');
  62. define('TOOL_POST', 'post');
  63. define('TOOL_DROPBOX', 'dropbox');
  64. define('TOOL_QUIZ', 'quiz');
  65. define('TOOL_USER', 'user');
  66. define('TOOL_GROUP', 'group');
  67. define('TOOL_BLOGS', 'blog_management'); // Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be)
  68. define('TOOL_CHAT', 'chat');
  69. define('TOOL_CONFERENCE', 'conference');
  70. define('TOOL_STUDENTPUBLICATION', 'student_publication');
  71. define('TOOL_TRACKING', 'tracking');
  72. define('TOOL_HOMEPAGE_LINK', 'homepage_link');
  73. define('TOOL_COURSE_SETTING', 'course_setting');
  74. define('TOOL_BACKUP', 'backup');
  75. define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
  76. define('TOOL_RECYCLE_COURSE', 'recycle_course');
  77. define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
  78. define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
  79. define('TOOL_UPLOAD','file_upload');
  80. define('TOOL_COURSE_MAINTENANCE','course_maintenance');
  81. define('TOOL_VISIO','visio');
  82. define('TOOL_VISIO_CONFERENCE','visio_conference');
  83. define('TOOL_VISIO_CLASSROOM','visio_classroom');
  84. define('TOOL_SURVEY','survey');
  85. define('TOOL_WIKI','wiki');
  86. define('TOOL_GLOSSARY','glossary');
  87. define('TOOL_GRADEBOOK','gradebook');
  88. define('TOOL_NOTEBOOK','notebook');
  89. define('TOOL_ATTENDANCE','attendance');
  90. define('TOOL_COURSE_PROGRESS','course_progress');
  91. // CONSTANTS defining Chamilo interface sections
  92. define('SECTION_CAMPUS', 'mycampus');
  93. define('SECTION_COURSES', 'mycourses');
  94. define('SECTION_MYPROFILE', 'myprofile');
  95. define('SECTION_MYAGENDA', 'myagenda');
  96. define('SECTION_COURSE_ADMIN', 'course_admin');
  97. define('SECTION_PLATFORM_ADMIN', 'platform_admin');
  98. define('SECTION_MYGRADEBOOK', 'mygradebook');
  99. define('SECTION_TRACKING','session_my_space');
  100. define('SECTION_SOCIAL', 'social');
  101. define('SECTION_DASHBOARD', 'dashboard');
  102. define('SECTION_REPORTS', 'reports');
  103. define('SECTION_GLOBAL', 'global');
  104. // CONSTANT name for local authentication source
  105. define('PLATFORM_AUTH_SOURCE', 'platform');
  106. // CONSTANT defining the default HotPotatoes files directory
  107. define('DIR_HOTPOTATOES','/HotPotatoes_files');
  108. // event logs types
  109. define('LOG_COURSE_DELETE', 'course_deleted');
  110. define('LOG_COURSE_CREATE', 'course_created');
  111. define('LOG_USER_DELETE', 'user_deleted');
  112. define('LOG_USER_CREATE', 'user_created');
  113. define('LOG_SESSION_CREATE', 'session_created');
  114. define('LOG_SESSION_DELETE', 'session_deleted');
  115. define('LOG_SESSION_CATEGORY_CREATE', 'session_category_created');
  116. define('LOG_SESSION_CATEGORY_DELETE', 'session_category_deleted');
  117. define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
  118. define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
  119. define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
  120. define('LOG_PROMOTION_CREATE', 'promotion_created');
  121. define('LOG_PROMOTION_DELETE', 'promotion_deleted');
  122. define('LOG_CAREER_CREATE', 'career_created');
  123. define('LOG_CAREER_DELETE', 'career_deleted');
  124. // event logs data types
  125. define('LOG_COURSE_CODE', 'course_code');
  126. define('LOG_USER_ID', 'user_id');
  127. define('LOG_SESSION_ID', 'session_id');
  128. define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
  129. define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
  130. define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
  131. define('LOG_CAREER_ID', 'career_id');
  132. define('LOG_PROMOTION_ID', 'promotion_id');
  133. // Specification for usernames:
  134. // 1. ASCII-letters, digits, "." (dot), "_" (underscore) are acceptable, 40 characters maximum length.
  135. // 2. Empty username is formally valid, but it is reserved for the anonymous user.
  136. define('USERNAME_MAX_LENGTH', 40);
  137. define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
  138. define('USERNAME_PURIFIER_SHALLOW', '/\s/');
  139. // Constants for detection some important PHP5 subversions.
  140. $php_version = (float) PHP_VERSION;
  141. define('IS_PHP_52', !((float)$php_version < 5.2));
  142. define('IS_PHP_53', !((float)$php_version < 5.3));
  143. define('IS_PHP_SUP_OR_EQ_53', ($php_version >= 5.3));
  144. define('IS_PHP_SUP_OR_EQ_52', ($php_version >= 5.2 && !IS_PHP_53));
  145. define('IS_PHP_SUP_OR_EQ_51', ($php_version >= 5.1 && !IS_PHP_52 && !IS_PHP_53));
  146. // This constant is a result of Windows OS detection, it has a boolean value:
  147. // true whether the server runs on Windows OS, false otherwise.
  148. define('IS_WINDOWS_OS', api_is_windows_os());
  149. // Checks for installed optional php-extensions.
  150. define('INTL_INSTALLED', function_exists('intl_get_error_code')); // intl extension (from PECL), it is installed by default as of PHP 5.3.0
  151. define('ICONV_INSTALLED', function_exists('iconv')); // iconv extension, for PHP5 on Windows it is installed by default.
  152. define('MBSTRING_INSTALLED', function_exists('mb_strlen')); // mbstring extension.
  153. 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
  154. // Patterns for processing paths. // Examples:
  155. define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  156. define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
  157. define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i'); // $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
  158. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  159. define('WEB_PATH', 'WEB_PATH');
  160. define('SYS_PATH', 'SYS_PATH');
  161. define('REL_PATH', 'REL_PATH');
  162. define('WEB_SERVER_ROOT_PATH', 'WEB_SERVER_ROOT_PATH');
  163. define('SYS_SERVER_ROOT_PATH', 'SYS_SERVER_ROOT_PATH');
  164. define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
  165. define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
  166. define('REL_COURSE_PATH', 'REL_COURSE_PATH');
  167. define('REL_CODE_PATH', 'REL_CODE_PATH');
  168. define('WEB_CODE_PATH', 'WEB_CODE_PATH');
  169. define('SYS_CODE_PATH', 'SYS_CODE_PATH');
  170. define('SYS_LANG_PATH', 'SYS_LANG_PATH');
  171. define('WEB_IMG_PATH', 'WEB_IMG_PATH');
  172. define('WEB_CSS_PATH', 'WEB_CSS_PATH');
  173. define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
  174. define('PLUGIN_PATH', 'SYS_PLUGIN_PATH'); // deprecated ?
  175. define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
  176. define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
  177. define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
  178. define('INCLUDE_PATH', 'INCLUDE_PATH');
  179. define('LIBRARY_PATH', 'LIBRARY_PATH');
  180. define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
  181. define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
  182. define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
  183. define('SYS_TEST_PATH', 'SYS_TEST_PATH');
  184. define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
  185. define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
  186. // Constants for requesting path conversion.
  187. define('TO_WEB', 'TO_WEB');
  188. define('TO_SYS', 'TO_SYS');
  189. define('TO_REL', 'TO_REL');
  190. // Paths to regidtered specific resource files (scripts, players, etc.)
  191. define('FLASH_PLAYER_AUDIO', '{FLASH_PLAYER_AUDIO}');
  192. define('FLASH_PLAYER_VIDEO', '{FLASH_PLAYER_VIDEO}');
  193. define('SCRIPT_SWFOBJECT', '{SCRIPT_SWFOBJECT}');
  194. define('SCRIPT_ASCIIMATHML', '{SCRIPT_ASCIIMATHML}');
  195. define('DRAWING_ASCIISVG', '{DRAWING_ASCIISVG}');
  196. // Forcing PclZip library to use a custom temporary folder.
  197. define('PCLZIP_TEMPORARY_DIR', api_get_path(SYS_ARCHIVE_PATH));
  198. // Relations type with Human resources manager
  199. define('COURSE_RELATION_TYPE_RRHH', 1);
  200. define('SESSION_RELATION_TYPE_RRHH', 1);
  201. /**
  202. * Inclusion of internationalization libraries
  203. */
  204. require_once dirname(__FILE__).'/internationalization.lib.php';
  205. /* PATHS & FILES - ROUTINES */
  206. /**
  207. * Returns a path to a certain resource within the Chamilo area, specifyed through a parameter.
  208. * Also, this function provides conversion between path types, in this case the input path points inside the Chamilo area too.
  209. *
  210. * See $_configuration['course_folder'] in the configuration.php to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  211. * @param string $type The requested path type (a defined constant), see the examples.
  212. * @param string $path (optional) A path which type is to be converted. Also, it may be a defined constant for a path.
  213. * This parameter has meaning when $type parameter has one of the following values: TO_WEB, TO_SYS, TO_REL. Otherwise it is ignored.
  214. * @return string The requested path or the converted path.
  215. *
  216. * A terminology note:
  217. * The defined constants used by this function contain the abbreviations WEB, REL, SYS with the following meaning for types:
  218. * WEB - an absolute URL (we often call it web-path),
  219. * example: http://www.mychamilo.org/chamilo/courses/COURSE01/document/lesson01.html;
  220. *
  221. * REL - represents a semi-absolute URL - a web-path, which is relative to the root web-path of the server, without server's base,
  222. * example: /chamilo/courses/COURSE01/document/lesson01.html;
  223. *
  224. * SYS - represents an absolute path inside the scope of server's file system,
  225. * /var/www/chamilo/courses/COURSE01/document/lesson01.html or
  226. * C:/Inetpub/wwwroot/chamilo/courses/COURSE01/document/lesson01.html.
  227. *
  228. * In some abstract sense we can consider these three path types as absolute.
  229. *
  230. * Notes about the current behaviour model:
  231. * 1. Windows back-slashes are converted to slashes in the result.
  232. * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
  233. * a slash too, so an additional check about presense of leading system server base is implemented. For example, the function is
  234. * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
  235. * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
  236. * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
  237. * It has not been identified as needed yet.
  238. * 4. Also, resolving the meta-symbols "." and ".." withiin paths has not been implemented, it is to be identified as needed.
  239. *
  240. * Example:
  241. * 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
  242. * The other configuration paramaters have not been changed.
  243. *
  244. * This is how we can retireve mosth used paths, for common purpose:
  245. * api_get_path(REL_PATH) /chamilo/
  246. * api_get_path(REL_COURSE_PATH) /chamilo/courses/
  247. * api_get_path(REL_CODE_PATH) /chamilo/main/
  248. * 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'].
  249. * api_get_path(SYS_PATH) /var/www/chamilo/
  250. * api_get_path(SYS_ARCHIVE_PATH) /var/www/chamilo/archive/
  251. * api_get_path(SYS_COURSE_PATH) /var/www/chamilo/courses/
  252. * api_get_path(SYS_CODE_PATH) /var/www/chamilo/main/
  253. * api_get_path(INCLUDE_PATH) /var/www/chamilo/main/inc/
  254. * api_get_path(LIBRARY_PATH) /var/www/chamilo/main/inc/lib/
  255. * api_get_path(CONFIGURATION_PATH) /var/www/chamilo/main/inc/conf/
  256. * api_get_path(SYS_LANG_PATH) /var/www/chamilo/main/lang/
  257. * api_get_path(SYS_PLUGIN_PATH) /var/www/chamilo/plugin/
  258. * api_get_path(SYS_TEST_PATH) /var/www/chamilo/tests/
  259. * api_get_path(SYS_TEMPLATE_PATH) /var/www/chamilo/main/template/
  260. *
  261. * api_get_path(WEB_SERVER_ROOT_PATH) http://www.mychamilo.org/
  262. * api_get_path(WEB_PATH) http://www.mychamilo.org/chamilo/
  263. * api_get_path(WEB_COURSE_PATH) http://www.mychamilo.org/chamilo/courses/
  264. * api_get_path(WEB_CODE_PATH) http://www.mychamilo.org/chamilo/main/
  265. * api_get_path(WEB_PLUGIN_PATH) http://www.mychamilo.org/chamilo/plugin/
  266. * api_get_path(WEB_ARCHIVE_PATH) http://www.mychamilo.org/chamilo/archive/
  267. * api_get_path(WEB_IMG_PATH) http://www.mychamilo.org/chamilo/main/img/
  268. * api_get_path(WEB_CSS_PATH) http://www.mychamilo.org/chamilo/main/css/
  269. * api_get_path(WEB_LIBRARY_PATH) http://www.mychamilo.org/chamilo/main/inc/lib/
  270. * api_get_path(WEB_TEMPLATE_PATH) http://www.mychamilo.org/chamilo/main/template/
  271. *
  272. *
  273. * This is how we retrieve paths of "registerd" resource files (scripts, players, etc.):
  274. * api_get_path(TO_WEB, FLASH_PLAYER_AUDIO) http://www.mychamilo.org/chamilo/main/inc/lib/mediaplayer/player.swf
  275. * api_get_path(TO_WEB, FLASH_PLAYER_VIDEO) http://www.mychamilo.org/chamilo/main/inc/lib/mediaplayer/player.swf
  276. * api_get_path(TO_SYS, SCRIPT_SWFOBJECT) /var/www/chamilo/main/inc/lib/swfobject/swfobject.js
  277. * api_get_path(TO_REL, SCRIPT_ASCIIMATHML) /chamilo/main/inc/lib/asciimath/ASCIIMathML.js
  278. * ...
  279. *
  280. * We can convert arbitrary paths, that are not registered (no defined constant).
  281. * For guaranteed result, these paths should point inside the system Chamilo.
  282. * Some random examples:
  283. * api_get_path(TO_WEB, $_SERVER['REQUEST_URI'])
  284. * api_get_path(TO_SYS, $_SERVER['PHP_SELF'])
  285. * api_get_path(TO_REL, __FILE__)
  286. * ...
  287. */
  288. function api_get_path($path_type, $path = null) {
  289. static $paths = array(
  290. WEB_PATH => '',
  291. SYS_PATH => '',
  292. REL_PATH => '',
  293. WEB_SERVER_ROOT_PATH => '',
  294. SYS_SERVER_ROOT_PATH => '',
  295. WEB_COURSE_PATH => '',
  296. SYS_COURSE_PATH => '',
  297. REL_COURSE_PATH => '',
  298. REL_CODE_PATH => '',
  299. WEB_CODE_PATH => '',
  300. SYS_CODE_PATH => '',
  301. SYS_LANG_PATH => 'lang/',
  302. WEB_IMG_PATH => 'img/',
  303. WEB_CSS_PATH => 'css/',
  304. SYS_PLUGIN_PATH => 'plugin/',
  305. WEB_PLUGIN_PATH => 'plugin/',
  306. SYS_ARCHIVE_PATH => 'archive/',
  307. WEB_ARCHIVE_PATH => 'archive/',
  308. INCLUDE_PATH => 'inc/',
  309. LIBRARY_PATH => 'inc/lib/',
  310. CONFIGURATION_PATH => 'inc/conf/',
  311. WEB_LIBRARY_PATH => 'inc/lib/',
  312. WEB_AJAX_PATH => 'inc/ajax/',
  313. SYS_TEST_PATH => 'tests/',
  314. WEB_TEMPLATE_PATH => 'template/',
  315. SYS_TEMPLATE_PATH => 'template/'
  316. );
  317. static $resource_paths = array(
  318. FLASH_PLAYER_AUDIO => 'inc/lib/mediaplayer/player.swf',
  319. FLASH_PLAYER_VIDEO => 'inc/lib/mediaplayer/player.swf',
  320. SCRIPT_SWFOBJECT => 'inc/lib/swfobject/swfobject.js',
  321. SCRIPT_ASCIIMATHML => 'inc/lib/javascript/asciimath/ASCIIMathML.js',
  322. DRAWING_ASCIISVG => 'inc/lib/javascript/asciimath/d.svg'
  323. );
  324. static $is_this_function_initialized;
  325. static $server_base_web; // No trailing slash.
  326. static $server_base_sys; // No trailing slash.
  327. static $root_web;
  328. static $root_sys;
  329. static $root_rel;
  330. static $code_folder;
  331. static $course_folder;
  332. // Always load root_web modifications for multiple url features
  333. global $_configuration;
  334. //default $_configuration['root_web'] configuration
  335. $root_web = $_configuration['root_web'];
  336. // Configuration data for already installed system.
  337. $root_sys = $_configuration['root_sys'];
  338. $load_new_config = false;
  339. // To avoid that the api_get_access_url() function fails since global.inc.php also calls the main_api.lib.php
  340. if ($path_type == WEB_PATH) {
  341. if (isset($_configuration['access_url']) && $_configuration['access_url'] != 1) {
  342. //we look into the DB the function api_get_access_url
  343. $url_info = api_get_access_url($_configuration['access_url']);
  344. $root_web = $url_info['active'] == 1 ? $url_info['url'] : $_configuration['root_web'];
  345. $load_new_config = true;
  346. }
  347. }
  348. if (!$is_this_function_initialized) {
  349. global $_configuration;
  350. $root_rel = $_configuration['url_append'];
  351. $code_folder = $_configuration['code_append'];
  352. $course_folder = $_configuration['course_folder'];
  353. // Support for the installation process.
  354. // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
  355. // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
  356. if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) {
  357. if (($pos = strpos(($requested_page_rel = api_get_self()), 'main/install')) !== false) {
  358. $root_rel = substr($requested_page_rel, 0, $pos);
  359. // See http://www.mediawiki.org/wiki/Manual:$wgServer
  360. $server_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
  361. $server_name =
  362. isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME']
  363. : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
  364. : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
  365. : (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR']
  366. : 'localhost')));
  367. if (isset($_SERVER['SERVER_PORT']) && !strpos($server_name, ':')
  368. && (($server_protocol == 'http'
  369. && $_SERVER['SERVER_PORT'] != 80 ) || ($server_protocol == 'https' && $_SERVER['SERVER_PORT'] != 443 ))) {
  370. $server_name .= ":" . $_SERVER['SERVER_PORT'];
  371. }
  372. $root_web = $server_protocol.'://'.$server_name.$root_rel;
  373. $root_sys = str_replace('\\', '/', realpath(dirname(__FILE__).'/../../../')).'/';
  374. $code_folder = 'main/';
  375. $course_folder = 'courses/';
  376. }
  377. // Here we give up, so we don't touch anything.
  378. }
  379. // Dealing with trailing slashes.
  380. $root_web = api_add_trailing_slash($root_web);
  381. $root_sys = api_add_trailing_slash($root_sys);
  382. $root_rel = api_add_trailing_slash($root_rel);
  383. $code_folder = api_add_trailing_slash($code_folder);
  384. $course_folder = api_add_trailing_slash($course_folder);
  385. // Web server base and system server base.
  386. $server_base_web = preg_replace('@'.$root_rel.'$@', '', $root_web); // No trailing slash.
  387. $server_base_sys = preg_replace('@'.$root_rel.'$@', '', $root_sys); // No trailing slash.
  388. // Initialization of a table taht contains common-purpose paths.
  389. $paths[WEB_PATH] = $root_web;
  390. $paths[SYS_PATH] = $root_sys;
  391. $paths[REL_PATH] = $root_rel;
  392. $paths[WEB_SERVER_ROOT_PATH] = $server_base_web.'/';
  393. $paths[SYS_SERVER_ROOT_PATH] = $server_base_sys.'/';
  394. $paths[WEB_COURSE_PATH] = $root_web.$course_folder;
  395. $paths[SYS_COURSE_PATH] = $root_sys.$course_folder;
  396. $paths[REL_COURSE_PATH] = $root_rel.$course_folder;
  397. $paths[REL_CODE_PATH] = $root_rel.$code_folder;
  398. $paths[WEB_CODE_PATH] = $root_web.$code_folder;
  399. $paths[SYS_CODE_PATH] = $root_sys.$code_folder;
  400. // Now we can switch into api_get_path() "terminology".
  401. $paths[SYS_LANG_PATH] = $paths[SYS_CODE_PATH].$paths[SYS_LANG_PATH];
  402. $paths[SYS_PLUGIN_PATH] = $paths[SYS_PATH].$paths[SYS_PLUGIN_PATH];
  403. $paths[SYS_ARCHIVE_PATH] = $paths[SYS_PATH].$paths[SYS_ARCHIVE_PATH];
  404. $paths[SYS_TEST_PATH] = $paths[SYS_PATH].$paths[SYS_TEST_PATH];
  405. $paths[SYS_TEMPLATE_PATH] = $paths[SYS_CODE_PATH].$paths[SYS_TEMPLATE_PATH];
  406. $paths[WEB_CSS_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_CSS_PATH];
  407. $paths[WEB_IMG_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_IMG_PATH];
  408. $paths[WEB_LIBRARY_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_LIBRARY_PATH];
  409. $paths[WEB_AJAX_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_AJAX_PATH];
  410. $paths[WEB_PLUGIN_PATH] = $paths[WEB_PATH].$paths[WEB_PLUGIN_PATH];
  411. $paths[WEB_ARCHIVE_PATH] = $paths[WEB_PATH].$paths[WEB_ARCHIVE_PATH];
  412. $paths[WEB_TEMPLATE_PATH] = $paths[WEB_CODE_PATH].$paths[WEB_TEMPLATE_PATH];
  413. $paths[INCLUDE_PATH] = $paths[SYS_CODE_PATH].$paths[INCLUDE_PATH];
  414. $paths[LIBRARY_PATH] = $paths[SYS_CODE_PATH].$paths[LIBRARY_PATH];
  415. $paths[CONFIGURATION_PATH] = $paths[SYS_CODE_PATH].$paths[CONFIGURATION_PATH];
  416. $is_this_function_initialized = true;
  417. } else {
  418. if ($load_new_config) {
  419. // Redefining variables to work well with the "multiple url" feature
  420. // All web paths need to be here
  421. $web_paths = array(
  422. WEB_PATH => '',
  423. WEB_SERVER_ROOT_PATH => '',
  424. WEB_COURSE_PATH => '',
  425. WEB_CODE_PATH => '',
  426. WEB_IMG_PATH => 'img/',
  427. WEB_CSS_PATH => 'css/',
  428. WEB_PLUGIN_PATH => 'plugin/',
  429. WEB_ARCHIVE_PATH => 'archive/',
  430. WEB_LIBRARY_PATH => 'inc/lib/',
  431. WEB_AJAX_PATH => 'inc/ajax/',
  432. );
  433. $root_web = api_add_trailing_slash($root_web);
  434. // Web server base and system server base.
  435. $server_base_web = preg_replace('@'.$root_rel.'$@', '', $root_web); // No trailing slash.
  436. // Redefine root webs
  437. $paths[WEB_PATH] = $root_web;
  438. $paths[WEB_SERVER_ROOT_PATH] = $server_base_web.'/';
  439. $paths[WEB_COURSE_PATH] = $root_web.$course_folder;
  440. $paths[WEB_CODE_PATH] = $root_web.$code_folder;
  441. $paths[WEB_IMG_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_IMG_PATH];
  442. $paths[WEB_CSS_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_CSS_PATH];
  443. $paths[WEB_PLUGIN_PATH] = $paths[WEB_PATH].$web_paths[WEB_PLUGIN_PATH];
  444. $paths[WEB_ARCHIVE_PATH] = $paths[WEB_PATH].$web_paths[WEB_ARCHIVE_PATH];
  445. $paths[WEB_LIBRARY_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_LIBRARY_PATH];
  446. $paths[WEB_AJAX_PATH] = $paths[WEB_CODE_PATH].$web_paths[WEB_AJAX_PATH];
  447. }
  448. }
  449. // Shallow purification and validation of input parameters.
  450. $path_type = trim($path_type);
  451. $path = trim($path);
  452. if (empty($path_type)) {
  453. return null;
  454. }
  455. // Retrieving a common-purpose path.
  456. if (isset($paths[$path_type])) {
  457. return $paths[$path_type];
  458. }
  459. // Retrieving a specific resource path.
  460. if (isset($resource_paths[$path])) {
  461. switch ($path_type) {
  462. case TO_WEB:
  463. return $paths[WEB_CODE_PATH].$resource_paths[$path];
  464. case TO_SYS:
  465. return $paths[SYS_CODE_PATH].$resource_paths[$path];
  466. case TO_REL:
  467. return $paths[REL_CODE_PATH].$resource_paths[$path];
  468. default:
  469. return null;
  470. }
  471. }
  472. // Common-purpose paths as a second parameter - recognition.
  473. if (isset($paths[$path])) {
  474. $path = $paths[$path];
  475. }
  476. // Second purification.
  477. // Replacing Windows back slashes.
  478. $path = str_replace('\\', '/', $path);
  479. // Query strings sometimes mighth wrongly appear in non-URLs.
  480. // Let us check remove them from all types of paths.
  481. if (($pos = strpos($path, '?')) !== false) {
  482. $path = substr($path, 0, $pos);
  483. }
  484. // Detection of the input path type. Conversion to semi-absolute type ( /chamilo/main/inc/.... ).
  485. if (preg_match(VALID_WEB_PATH, $path)) {
  486. // A special case: When a URL points to the document download script directly, without
  487. // mod-rewrite translation, we have to translate it into an "ordinary" web path.
  488. // For example:
  489. // http://localhost/chamilo/main/document/download.php?doc_url=/image.png&cDir=/
  490. // becomes
  491. // http://localhost/chamilo/courses/TEST/document/image.png
  492. // TEST is a course directory name, so called "system course code".
  493. if (strpos($path, 'download.php') !== false) { // Fast detection first.
  494. $path = urldecode($path);
  495. if (preg_match('/(.*)main\/document\/download.php\?doc_url=\/(.*)&cDir=\/(.*)?/', $path, $matches)) {
  496. $sys_course_code =
  497. isset($_SESSION['_course']['sysCode']) // User is inside a course?
  498. ? $_SESSION['_course']['sysCode'] // Yes, then use course's directory name.
  499. : '{SYS_COURSE_CODE}'; // No, then use a fake code, it may be processed later.
  500. $path = $matches[1].'courses/'.$sys_course_code.'/document/'.str_replace('//', '/', $matches[3].'/'.$matches[2]);
  501. }
  502. }
  503. // Replacement of the present web server base with a slash '/'.
  504. $path = preg_replace(VALID_WEB_SERVER_BASE, '/', $path);
  505. } elseif (strpos($path, $server_base_sys) === 0) {
  506. $path = preg_replace('@^'.$server_base_sys.'@', '', $path);
  507. } elseif (strpos($path, '/') === 0) {
  508. // Leading slash - we assume that this path is semi-absolute (REL),
  509. // then path is left without furthes modifications.
  510. } else {
  511. return null; // Probably implementation of this case won't be needed.
  512. }
  513. // Path now is semi-absolute. It is convenient at this moment repeated slashes to be removed.
  514. $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  515. // Path conversion to the requested type.
  516. switch ($path_type) {
  517. case TO_WEB:
  518. return $server_base_web.$path;
  519. case TO_SYS:
  520. return $server_base_sys.$path;
  521. case TO_REL:
  522. return $path;
  523. }
  524. return null;
  525. }
  526. /**
  527. * This function checks whether a given path points inside the system.
  528. * @param string $path The path to be tesed. It should be full path, web-absolute (WEB), semi-absolute (REL) or system-absolyte (SYS).
  529. * @return bool Returns true when the given path is inside the system, false otherwise.
  530. */
  531. function api_is_internal_path($path) {
  532. $path = str_replace('\\', '/', trim($path));
  533. if (empty($path)) {
  534. return false;
  535. }
  536. if (strpos($path, api_remove_trailing_slash(api_get_path(WEB_PATH))) === 0) {
  537. return true;
  538. }
  539. if (strpos($path, api_remove_trailing_slash(api_get_path(SYS_PATH))) === 0) {
  540. return true;
  541. }
  542. $server_base_web = api_remove_trailing_slash(api_get_path(REL_PATH));
  543. $server_base_web = empty($server_base_web) ? '/' : $server_base_web;
  544. if (strpos($path, $server_base_web) === 0) {
  545. return true;
  546. }
  547. return false;
  548. }
  549. /**
  550. * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
  551. * @param string $path The input path.
  552. * @return string Returns the modified path.
  553. */
  554. function api_add_trailing_slash($path) {
  555. return substr($path, -1) == '/' ? $path : $path.'/';
  556. }
  557. /**
  558. * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
  559. * @param string $path The input path.
  560. * @return string Returns the modified path.
  561. */
  562. function api_remove_trailing_slash($path) {
  563. return substr($path, -1) == '/' ? substr($path, 0, -1) : $path;
  564. }
  565. /**
  566. * Checks the RFC 3986 syntax of a given URL.
  567. * @param string $url The URL to be checked.
  568. * @param bool $absolute Whether the URL is absolute (beginning with a scheme such as "http:").
  569. * @return bool Returns the URL if it is valid, FALSE otherwise.
  570. * This function is an adaptation from the function valid_url(), Drupal CMS.
  571. * @link http://drupal.org
  572. * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
  573. * @link http://bugs.php.net/51192
  574. */
  575. function api_valid_url($url, $absolute = false) {
  576. if ($absolute) {
  577. if (preg_match("
  578. /^ # Start at the beginning of the text
  579. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  580. (?: # Userinfo (optional) which is typically
  581. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  582. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  583. )?
  584. (?:
  585. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  586. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  587. )
  588. (?::[0-9]+)? # Server port number (optional)
  589. (?:[\/|\?]
  590. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  591. *)?
  592. $/xi", $url)) {
  593. return $url;
  594. }
  595. return false;
  596. } else {
  597. return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
  598. }
  599. }
  600. /**
  601. * Checks whether a given string looks roughly like an email address.
  602. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator.
  603. * Conforms approximately to RFC2822
  604. * @link http://www.hexillion.com/samples/#Regex Original pattern found here
  605. * This function is an adaptation from the method PHPMailer::ValidateAddress(), PHPMailer module.
  606. * @link http://phpmailer.worxware.com
  607. * @param string $address The e-mail address to be checked.
  608. * @return mixed Returns the e-mail if it is valid, FALSE otherwise.
  609. */
  610. function api_valid_email($address) {
  611. // disable for now because the results are incoherent - YW 20110926
  612. if (function_exists('filter_var')) { // Introduced in PHP 5.2.
  613. return filter_var($address, FILTER_VALIDATE_EMAIL);
  614. } else {
  615. 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;
  616. }
  617. }
  618. /* PROTECTION FUNCTIONS
  619. Use these functions to protect your scripts. */
  620. /**
  621. * Function used to protect a course script.
  622. * The function blocks access when
  623. * - there is no $_SESSION["_course"] defined; or
  624. * - $is_allowed_in_course is set to false (this depends on the course
  625. * visibility and user status).
  626. *
  627. * This is only the first proposal, test and improve!
  628. * @param boolean Option to print headers when displaying error message. Default: false
  629. * @return boolean True if the user has access to the current course or is out of a course context, false otherwise
  630. * @todo replace global variable
  631. * @author Roan Embrechts
  632. */
  633. function api_protect_course_script($print_headers = false) {
  634. global $is_allowed_in_course;
  635. $is_visible = false;
  636. if (api_is_platform_admin()) {
  637. return true;
  638. }
  639. $course_info = api_get_course_info();
  640. if (isset($course_info) && !empty($course_info['visibility'])) {
  641. switch($course_info['visibility']) {
  642. default:
  643. case 0: //Completely closed: the course is only accessible to the teachers.
  644. if (api_get_user_id() && !api_is_anonymous() && (api_is_allowed_to_edit())) {
  645. $is_visible = true;
  646. }
  647. break;
  648. case 1: //Private - access authorized to course members only
  649. if (api_get_user_id() && !api_is_anonymous() && $is_allowed_in_course) {
  650. $is_visible = true;
  651. }
  652. break;
  653. case 2: // Open - access allowed for users registered on the platform
  654. if (api_get_user_id() && !api_is_anonymous()) {
  655. $is_visible = true;
  656. }
  657. break;
  658. case 3: //Open - access allowed for the whole world
  659. $is_visible = true;
  660. break;
  661. }
  662. }
  663. if (!$is_visible) {
  664. api_not_allowed($print_headers);
  665. return false;
  666. }
  667. return true;
  668. }
  669. /**
  670. * Function used to protect an admin script.
  671. * The function blocks access when the user has no platform admin rights.
  672. * This is only the first proposal, test and improve!
  673. *
  674. * @author Roan Embrechts
  675. */
  676. function api_protect_admin_script($allow_sessions_admins = false) {
  677. if (!api_is_platform_admin($allow_sessions_admins)) {
  678. api_not_allowed(true);
  679. return false;
  680. }
  681. return true;
  682. }
  683. /**
  684. * Function used to prevent anonymous users from accessing a script.
  685. *
  686. * @author Roan Embrechts
  687. */
  688. function api_block_anonymous_users($print_headers = true) {
  689. global $_user;
  690. if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)) {
  691. api_not_allowed($print_headers);
  692. return false;
  693. }
  694. return true;
  695. }
  696. /* ACCESSOR FUNCTIONS
  697. Don't access kernel variables directly, use these functions instead. */
  698. /**
  699. * @return an array with the navigator name and version
  700. */
  701. function api_get_navigator() {
  702. $navigator = 'Unknown';
  703. $version = 0;
  704. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
  705. $navigator = 'Opera';
  706. list (, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
  707. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  708. $navigator = 'Internet Explorer';
  709. list (, $version) = explode('MSIE', $_SERVER['HTTP_USER_AGENT']);
  710. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
  711. $navigator = 'Chrome';
  712. list (, $version) = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
  713. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
  714. $navigator = 'Mozilla';
  715. list (, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
  716. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') !== false) {
  717. $navigator = 'Netscape';
  718. list (, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
  719. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false) {
  720. $navigator = 'Konqueror';
  721. list (, $version) = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
  722. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit') !== false) {
  723. $navigator = 'AppleWebKit';
  724. list (, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  725. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) {
  726. $navigator = 'Safari';
  727. list (, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  728. }
  729. $version = str_replace('/', '', $version);
  730. if (strpos($version, '.') === false) {
  731. $version = number_format(doubleval($version), 1);
  732. }
  733. $return_array = array ('name' => $navigator, 'version' => $version);
  734. return $return_array;
  735. }
  736. /**
  737. * @return True if user selfregistration is allowed, false otherwise.
  738. */
  739. function api_is_self_registration_allowed() {
  740. return isset($GLOBALS['allowSelfReg']) ? $GLOBALS['allowSelfReg'] : false;
  741. }
  742. /**
  743. * This function returns the id of the user which is stored in the $_user array.
  744. *
  745. * example: The function can be used to check if a user is logged in
  746. * if (api_get_user_id())
  747. * @return integer the id of the current user, 0 if is empty
  748. */
  749. function api_get_user_id() {
  750. return empty($GLOBALS['_user']['user_id']) ? 0 : intval($GLOBALS['_user']['user_id']);
  751. }
  752. /**
  753. * Gets the list of courses a specific user is subscribed to
  754. * @param int User ID
  755. * @param boolean Whether to get session courses or not - NOT YET IMPLEMENTED
  756. * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
  757. */
  758. function api_get_user_courses($userid, $fetch_session = true) {
  759. if ($userid != strval(intval($userid))) { return array(); } //get out if not integer
  760. $t_course = Database::get_main_table(TABLE_MAIN_COURSE);
  761. $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  762. $t_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  763. $t_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  764. $t_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  765. $sql_select_courses = "SELECT cc.code code, cc.db_name db, cc.directory dir, cu.status status
  766. FROM $t_course cc,
  767. $t_course_user cu
  768. WHERE cc.code = cu.course_code
  769. AND cu.user_id = '".$userid."' AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
  770. $result = Database::query($sql_select_courses);
  771. if ($result === false) { return array(); }
  772. while ($row = Database::fetch_array($result)) {
  773. // we only need the database name of the course
  774. $courses[] = $row;
  775. }
  776. return $courses;
  777. }
  778. /**
  779. * Formats user information into a standard array
  780. *
  781. * @param array Non-standard user array
  782. * @return array Standard user array
  783. */
  784. function _api_format_user($user) {
  785. $result = array();
  786. if (isset($user['firstname']) && isset($user['lastname'])) {
  787. $firstname = $user['firstname'];
  788. $lastname = $user['lastname'];
  789. } elseif (isset($user['firstName']) && isset($user['lastName'])) {
  790. $firstname = $user['firstName'];
  791. $lastname = $user['lastName'];
  792. }
  793. $result['complete_name'] = api_get_person_name($firstname, $lastname);
  794. $result['firstname'] = $firstname;
  795. $result['lastname'] = $lastname;
  796. // Kept for historical reasons
  797. $result['firstName'] = $firstname;
  798. $result['lastName'] = $lastname;
  799. if (isset($user['email'])) {
  800. $result['mail'] = $user['email'];
  801. } else {
  802. $result['mail'] = $user['mail'];
  803. }
  804. $user_id = intval($user['user_id']);
  805. $result['picture_uri'] = $user['picture_uri'];
  806. $result['user_id'] = $user_id;
  807. $result['official_code'] = $user['official_code'];
  808. $result['status'] = $user['status'];
  809. $result['auth_source'] = $user['auth_source'];
  810. if (isset($user['username'])) {
  811. $result['username'] = $user['username'];
  812. }
  813. $result['theme'] = $user['theme'];
  814. $result['language'] = $user['language'];
  815. if (!isset($user['lastLogin']) && !isset($user['last_login'])) {
  816. require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
  817. $timestamp = Tracking::get_last_connection_date($result['user_id'], false, true);
  818. // Convert the timestamp back into a datetime
  819. // NOTE: this timestamp has ALREADY been converted to the local timezone in the get_last_connection_date function
  820. $last_login = date('Y-m-d H:i:s', $timestamp);
  821. } else {
  822. if (isset($user['lastLogin'])) {
  823. $last_login = $user['lastLogin'];
  824. } else {
  825. $last_login = $user['last_login'];
  826. }
  827. }
  828. $result['last_login'] = $last_login;
  829. // Kept for historical reasons
  830. $result['lastLogin'] = $last_login;
  831. //Getting user avatar
  832. $picture_filename = trim($user['picture_uri']);
  833. $avatar = api_get_path(WEB_CODE_PATH).'img/unknown.jpg';
  834. $avatar_small = api_get_path(WEB_CODE_PATH).'img/unknown_22.jpg';
  835. $dir = 'upload/users/'.$user_id.'/';
  836. if (!empty($picture_filename) && api_is_anonymous() ) {
  837. if (api_get_setting('split_users_upload_directory') === 'true') {
  838. $dir = 'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
  839. }
  840. }
  841. $image_sys_path = api_get_path(SYS_CODE_PATH).$dir.$picture_filename;
  842. if (file_exists($image_sys_path) && !is_dir($image_sys_path)) {
  843. $avatar = api_get_path(WEB_CODE_PATH).$dir.$picture_filename;
  844. $avatar_small = api_get_path(WEB_CODE_PATH).$dir.'small_'.$picture_filename;
  845. }
  846. $result['avatar'] = $avatar;
  847. $result['avatar_small'] = $avatar_small;
  848. if (isset($user['user_is_online'])) {
  849. $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
  850. }
  851. return $result;
  852. }
  853. /**
  854. * Finds all the information about a user. If no paramater is passed you find all the information about the current user.
  855. * @param $user_id (integer): the id of the user
  856. * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  857. * @author Patrick Cool <patrick.cool@UGent.be>
  858. * @version 21 September 2004
  859. */
  860. function api_get_user_info($user_id = '', $check_if_user_is_online = false) {
  861. if ($user_id == '') {
  862. return _api_format_user($GLOBALS['_user']);
  863. }
  864. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE user_id='".Database::escape_string($user_id)."'";
  865. $result = Database::query($sql);
  866. if (Database::num_rows($result) > 0) {
  867. $result_array = Database::fetch_array($result);
  868. if ($check_if_user_is_online) {
  869. $result_array['user_is_online'] = user_is_online($user_id);
  870. }
  871. return _api_format_user($result_array);
  872. }
  873. return false;
  874. }
  875. /**
  876. * Finds all the information about a user from username instead of user id
  877. * @param $username (string): the username
  878. * @return $user_info (array): user_id, lastname, firstname, username, email, ...
  879. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  880. */
  881. function api_get_user_info_from_username($username = '') {
  882. if (empty($username)) { return false; }
  883. $sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE username='".Database::escape_string($username)."'";
  884. $result = Database::query($sql);
  885. if (Database::num_rows($result) > 0) {
  886. $result_array = Database::fetch_array($result);
  887. return _api_format_user($result_array);
  888. }
  889. return false;
  890. }
  891. /**
  892. * @TODO This function should be the real id (integer)
  893. * Returns the current course code (string)
  894. */
  895. function api_get_course_id() {
  896. return $GLOBALS['_cid'];
  897. }
  898. /**
  899. * Returns the current course id (integer)
  900. */
  901. function api_get_real_course_id() {
  902. return isset($_SESSION['_real_cid']) ? intval($_SESSION['_real_cid']) : 0;
  903. }
  904. /**
  905. * Returns the current course id (integer)
  906. */
  907. function api_get_course_int_id() {
  908. return isset($_SESSION['_real_cid']) ? intval($_SESSION['_real_cid']) : 0;
  909. }
  910. /**
  911. * Returns the current course directory
  912. *
  913. * This function relies on api_get_course_info()
  914. * @param string The course code - optional (takes it from session if not given)
  915. * @return string The directory where the course is located inside the Chamilo "courses" directory
  916. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  917. */
  918. function api_get_course_path($course_code = null) {
  919. $info = !empty($course_code) ? api_get_course_info($course_code) : api_get_course_info();
  920. return $info['path'];
  921. }
  922. /**
  923. * Gets a course setting from the current course_setting table. Try always using integer values.
  924. * @param string The name of the setting we want from the table
  925. * @param string Optional: course code
  926. * @return mixed The value of that setting in that table. Return -1 if not found.
  927. */
  928. function api_get_course_setting($setting_name, $course_code = null) {
  929. $course_info = api_get_course_info($course_code);
  930. $table = Database::get_course_table(TABLE_COURSE_SETTING);
  931. $setting_name = Database::escape_string($setting_name);
  932. if (!empty($course_info['real_id']) && !empty($setting_name)) {
  933. $sql = "SELECT value FROM $table WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
  934. $res = Database::query($sql);
  935. if (Database::num_rows($res) > 0) {
  936. $row = Database::fetch_array($res);
  937. return $row['value'];
  938. }
  939. }
  940. return -1;
  941. }
  942. /**
  943. * Gets an anonymous user ID
  944. *
  945. * For some tools that need tracking, like the learnpath tool, it is necessary
  946. * to have a usable user-id to enable some kind of tracking, even if not
  947. * perfect. An anonymous ID is taken from the users table by looking for a
  948. * status of "6" (anonymous).
  949. * @return int User ID of the anonymous user, or O if no anonymous user found
  950. */
  951. function api_get_anonymous_id() {
  952. $table = Database::get_main_table(TABLE_MAIN_USER);
  953. $sql = "SELECT user_id FROM $table WHERE status = 6";
  954. $res = Database::query($sql);
  955. if (Database::num_rows($res) > 0) {
  956. $row = Database::fetch_array($res);
  957. //error_log('api_get_anonymous_id() returns '.$row['user_id'], 0);
  958. return $row['user_id'];
  959. }
  960. // No anonymous user was found.
  961. return 0;
  962. }
  963. /**
  964. * Returns the cidreq parameter name + current course id taken from
  965. * $GLOBALS['_cid'] and returns a string like 'cidReq=ABC&id_session=123
  966. * @return string Course & session references to add to a URL
  967. */
  968. function api_get_cidreq() {
  969. return empty($GLOBALS['_cid']) ? '' : 'cidReq='.htmlspecialchars($GLOBALS['_cid']).(api_get_session_id() == 0 ? '&amp;id_session=0' : '&amp;id_session='.api_get_session_id());
  970. }
  971. /**
  972. * Returns the current course info array.
  973. * Note: this array is only defined if the user is inside a course.
  974. * Array elements:
  975. * ['name']
  976. * ['official_code']
  977. * ['sysCode']
  978. * ['path']
  979. * ['dbName']
  980. * ['dbNameGlu']
  981. * ['titular']
  982. * ['language']
  983. * ['extLink']['url' ]
  984. * ['extLink']['name']
  985. * ['categoryCode']
  986. * ['categoryName']
  987. *
  988. * Now if the course_code is given, the returned array gives info about that
  989. * particular course, not specially the current one.
  990. * @todo Same behaviour as api_get_user_info so that api_get_course_id becomes absolete too.
  991. */
  992. function api_get_course_info($course_code = null) {
  993. if (!empty($course_code)) {
  994. //global $_course;var_dump($_course);
  995. $course_code = Database::escape_string($course_code);
  996. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  997. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  998. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  999. FROM $course_table
  1000. LEFT JOIN $course_cat_table
  1001. ON course.category_code = course_category.code
  1002. WHERE course.code = '$course_code'";
  1003. $result = Database::query($sql);
  1004. $_course = array();
  1005. if (Database::num_rows($result) > 0) {
  1006. global $_configuration;
  1007. $course_data = Database::fetch_array($result);
  1008. $_course['id' ] = $course_data['code' ];
  1009. $_course['code' ] = $course_data['code' ];
  1010. $_course['name' ] = $course_data['title' ];
  1011. $_course['official_code'] = $course_data['visual_code' ]; // Use in echo statements.
  1012. $_course['sysCode' ] = $course_data['code' ]; // Use as key in db.
  1013. $_course['path' ] = $course_data['directory' ]; // Use as key in path.
  1014. $_course['directory' ] = $course_data['directory' ];
  1015. //@todo should be deprecated
  1016. $_course['dbName' ] = $course_data['db_name' ]; // Use as key in db list.
  1017. $_course['db_name' ] = $course_data['db_name']; //
  1018. $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; // Use in all queries.
  1019. $_course['titular' ] = $course_data['tutor_name' ];
  1020. $_course['language' ] = $course_data['course_language'];
  1021. $_course['extLink' ]['url' ] = $course_data['department_url' ];
  1022. $_course['extLink' ]['name'] = $course_data['department_name'];
  1023. $_course['categoryCode' ] = $course_data['faCode' ];
  1024. $_course['categoryName' ] = $course_data['faName' ];
  1025. $_course['visibility' ] = $course_data['visibility' ];
  1026. $_course['subscribe_allowed'] = $course_data['subscribe' ];
  1027. $_course['unubscribe_allowed'] = $course_data['unsubscribe' ];
  1028. $_course['department_name'] = $course_data['department_name'];
  1029. $_course['department_url'] = $course_data['department_url' ];
  1030. // The real_id is an integer. It is mandatory for future implementations.
  1031. $_course['real_id' ] = $course_data['id' ];
  1032. $_course['course_language'] = $course_data['course_language'];
  1033. //I know this is bad, but this reflects that it was a bad decistion to not add a flag in the DB if an image exists
  1034. if (file_exists(api_get_path(SYS_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png')) {
  1035. $url_image = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png';
  1036. } else {
  1037. $url_image = api_get_path(WEB_IMG_PATH).'without_picture.png';
  1038. }
  1039. $_course['course_image'] = $url_image;
  1040. }
  1041. return $_course;
  1042. }
  1043. global $_course;
  1044. if ($_course == '-1') $_course = array();
  1045. return $_course;
  1046. }
  1047. /**
  1048. * Returns the current course info array.
  1049. * Now if the course_code is given, the returned array gives info about that
  1050. * particular course, not specially the current one.
  1051. */
  1052. function api_get_course_info_by_id($id = null) {
  1053. if (!empty($id)) {
  1054. $id = intval($id);
  1055. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1056. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1057. $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
  1058. FROM $course_table
  1059. LEFT JOIN $course_cat_table
  1060. ON course.category_code = course_category.code
  1061. WHERE course.id = $id";
  1062. $result = Database::query($sql);
  1063. $_course = array();
  1064. if (Database::num_rows($result) > 0) {
  1065. global $_configuration;
  1066. $course_data = Database::fetch_array($result);
  1067. $_course['id' ] = $course_data['code' ];
  1068. // Added
  1069. $_course['code' ] = $course_data['code' ];
  1070. $_course['name' ] = $course_data['title' ];
  1071. $_course['official_code'] = $course_data['visual_code' ]; // Use in echo statements.
  1072. $_course['sysCode' ] = $course_data['code' ]; // Use as key in db.
  1073. $_course['path' ] = $course_data['directory' ]; // Use as key in path.
  1074. $_course['directory' ] = $course_data['directory' ];
  1075. //@todo should be deprecated
  1076. $_course['dbName' ] = $course_data['db_name' ]; // Use as key in db list.
  1077. $_course['db_name' ] = $course_data['db_name' ];
  1078. $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; // Use in all queries.
  1079. $_course['titular' ] = $course_data['tutor_name' ];
  1080. $_course['language' ] = $course_data['course_language'];
  1081. $_course['extLink' ]['url' ] = $course_data['department_url' ];
  1082. $_course['extLink' ]['name'] = $course_data['department_name'];
  1083. $_course['categoryCode' ] = $course_data['faCode' ];
  1084. $_course['categoryName' ] = $course_data['faName' ];
  1085. $_course['visibility' ] = $course_data['visibility' ];
  1086. $_course['subscribe_allowed'] = $course_data['subscribe' ];
  1087. $_course['unubscribe_allowed'] = $course_data['unsubscribe' ];
  1088. $_course['real_id' ] = $course_data['id' ];
  1089. $_course['title' ] = $course_data['title' ];
  1090. $_course['course_language'] = $course_data['course_language'];
  1091. if (file_exists(api_get_path(SYS_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png')) {
  1092. $url_image = api_get_path(WEB_COURSE_PATH).$course_data['directory'].'/course-pic85x85.png';
  1093. } else {
  1094. $url_image = api_get_path(WEB_IMG_PATH).'without_picture.png';
  1095. }
  1096. $_course['course_image'] = $url_image;
  1097. }
  1098. return $_course;
  1099. }
  1100. global $_course;
  1101. return $_course;
  1102. }
  1103. /* SESSION MANAGEMENT */
  1104. /**
  1105. * Starts the Chamilo session.
  1106. *
  1107. * The default lifetime for session is set here. It is not possible to have it
  1108. * as a database setting as it is used before the database connection has been made.
  1109. * It is taken from the configuration file, and if it doesn't exist there, it is set
  1110. * to 360000 seconds
  1111. *
  1112. * @author Olivier Brouckaert
  1113. * @param string variable - the variable name to save into the session
  1114. */
  1115. function api_session_start($already_installed = true) {
  1116. global $_configuration;
  1117. /* Causes too many problems and is not configurable dynamically.
  1118. if ($already_installed) {
  1119. $session_lifetime = 360000;
  1120. if (isset($_configuration['session_lifetime'])) {
  1121. $session_lifetime = $_configuration['session_lifetime'];
  1122. }
  1123. //session_set_cookie_params($session_lifetime,api_get_path(REL_PATH));
  1124. }
  1125. */
  1126. if (!isset($_configuration['session_stored_in_db'])) {
  1127. $_configuration['session_stored_in_db'] = false;
  1128. }
  1129. if ($_configuration['session_stored_in_db'] && function_exists('session_set_save_handler')) {
  1130. require_once api_get_path(LIBRARY_PATH).'session_handler.class.php';
  1131. $session_handler = new session_handler();
  1132. @session_set_save_handler(array(& $session_handler, 'open'), array(& $session_handler, 'close'), array(& $session_handler, 'read'), array(& $session_handler, 'write'), array(& $session_handler, 'destroy'), array(& $session_handler, 'garbage'));
  1133. }
  1134. /*
  1135. * Prevent Session fixation bug fixes
  1136. * See http://support.chamilo.org/issues/3600
  1137. * http://php.net/manual/en/session.configuration.php
  1138. * @todo use session_set_cookie_params with some custom admin parameters
  1139. */
  1140. //session.cookie_lifetime
  1141. //the session ID is only accepted from a cookie
  1142. ini_set('session.use_only_cookies', 1);
  1143. //HTTPS only if possible
  1144. //ini_set('session.cookie_secure', 1);
  1145. //session ID in the cookie is only readable by the server
  1146. ini_set('session.cookie_httponly', 1);
  1147. //Use entropy file
  1148. //session.entropy_file
  1149. //ini_set('session.entropy_length', 128);
  1150. //Do not include the identifier in the URL, and not to read the URL for identifiers.
  1151. ini_set('session.use_trans_sid', 0);
  1152. session_name('ch_sid');
  1153. session_start();
  1154. if (!isset($_SESSION['starttime'])) {
  1155. $_SESSION['starttime'] = time();
  1156. }
  1157. if ($already_installed) {
  1158. if (empty($_SESSION['checkDokeosURL'])) {
  1159. $_SESSION['checkDokeosURL'] = api_get_path(WEB_PATH);
  1160. //$_SESSION['session_expiry'] = time() + $session_lifetime; // It is useless at the moment.
  1161. } elseif ($_SESSION['checkDokeosURL'] != api_get_path(WEB_PATH)) {
  1162. api_session_clear();
  1163. //$_SESSION['session_expiry'] = time() + $session_lifetime;
  1164. }
  1165. }
  1166. if ( isset($_SESSION['starttime']) && $_SESSION['starttime'] < time() - $_configuration['session_lifetime'] ) {
  1167. $_SESSION['starttime'] = time();
  1168. }
  1169. }
  1170. /**
  1171. * Saves a variable into the session
  1172. *
  1173. * BUG: function works only with global variables
  1174. *
  1175. * @author Olivier Brouckaert
  1176. * @param string variable - the variable name to save into the session
  1177. */
  1178. function api_session_register($variable) {
  1179. global $$variable;
  1180. $_SESSION[$variable] = $$variable;
  1181. }
  1182. /**
  1183. * Removes a variable from the session.
  1184. *
  1185. * @author Olivier Brouckaert
  1186. * @param string variable - the variable name to remove from the session
  1187. */
  1188. function api_session_unregister($variable) {
  1189. $variable = strval($variable);
  1190. if (isset($GLOBALS[$variable])) {
  1191. unset ($GLOBALS[$variable]);
  1192. }
  1193. if (isset($_SESSION[$variable])) {
  1194. unset($_SESSION[$variable]);
  1195. }
  1196. }
  1197. /**
  1198. * Clears the session
  1199. *
  1200. * @author Olivier Brouckaert
  1201. */
  1202. function api_session_clear() {
  1203. session_regenerate_id();
  1204. session_unset();
  1205. $_SESSION = array();
  1206. }
  1207. /**
  1208. * Destroys the session
  1209. *
  1210. * @author Olivier Brouckaert
  1211. */
  1212. function api_session_destroy() {
  1213. session_unset();
  1214. $_SESSION = array();
  1215. session_destroy();
  1216. }
  1217. /* STRING MANAGEMENT */
  1218. /**
  1219. * Add a parameter to the existing URL. If this parameter already exists,
  1220. * just replace it with the new value
  1221. * @param string The URL
  1222. * @param string param=value string
  1223. * @param boolean Whether to filter XSS or not
  1224. * @return string The URL with the added parameter
  1225. */
  1226. function api_add_url_param($url, $param, $filter_xss = true) {
  1227. if (empty($param)) {
  1228. return $url;
  1229. }
  1230. if (strpos($url, '?') !== false) {
  1231. if ($param[0] != '&') {
  1232. $param = '&'.$param;
  1233. }
  1234. list (, $query_string) = explode('?', $url);
  1235. $param_list1 = explode('&', $param);
  1236. $param_list2 = explode('&', $query_string);
  1237. $param_list1_keys = $param_list1_vals = array();
  1238. foreach ($param_list1 as $key => $enreg) {
  1239. list ($param_list1_keys[$key], $param_list1_vals[$key]) = explode('=', $enreg);
  1240. }
  1241. $param_list1 = array ('keys' => $param_list1_keys, 'vals' => $param_list1_vals);
  1242. foreach ($param_list2 as $enreg) {
  1243. $enreg = explode('=', $enreg);
  1244. $key = array_search($enreg[0], $param_list1['keys']);
  1245. if (!is_null($key) && !is_bool($key)) {
  1246. $url = str_replace($enreg[0].'='.$enreg[1], $enreg[0].'='.$param_list1['vals'][$key], $url);
  1247. $param = str_replace('&'.$enreg[0].'='.$param_list1['vals'][$key], '', $param);
  1248. }
  1249. }
  1250. $url .= $param;
  1251. } else {
  1252. $url = $url.'?'.$param;
  1253. }
  1254. if ($filter_xss === true) {
  1255. $url = Security::remove_XSS(urldecode($url));
  1256. }
  1257. return $url;
  1258. }
  1259. /**
  1260. * Returns a difficult to guess password.
  1261. * @param int $length, the length of the password
  1262. * @return string the generated password
  1263. */
  1264. function api_generate_password($length = 8) {
  1265. $characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  1266. if ($length < 2) {
  1267. $length = 2;
  1268. }
  1269. $password = '';
  1270. for ($i = 0; $i < $length; $i ++) {
  1271. $password .= $characters[rand() % strlen($characters)];
  1272. }
  1273. return $password;
  1274. }
  1275. /**
  1276. * Checks a password to see wether it is OK to use.
  1277. * @param string $password
  1278. * @return true if the password is acceptable, false otherwise
  1279. * Notes about what a password "OK to use" is:
  1280. * 1. The password should be at least 5 characters long.
  1281. * 2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
  1282. * 3. The password should contain at least 3 letters.
  1283. * 4. It should contain at least 2 digits.
  1284. * 5. It should not contain 3 or more consequent (according to ASCII table) characters.
  1285. */
  1286. function api_check_password($password) {
  1287. $password_length = api_strlen($password);
  1288. if ($password_length < 5) {
  1289. return false;
  1290. }
  1291. $password = api_strtolower($password);
  1292. $letters = 0;
  1293. $digits = 0;
  1294. $consequent_characters = 0;
  1295. $previous_character_code = 0;
  1296. for ($i = 0; $i < $password_length; $i ++) {
  1297. $current_character_code = api_ord(api_substr($password, $i, 1));
  1298. if ($i && abs($current_character_code - $previous_character_code) <= 1) {
  1299. $consequent_characters ++;
  1300. if ($consequent_characters == 3) {
  1301. return false;
  1302. }
  1303. } else {
  1304. $consequent_characters = 1;
  1305. }
  1306. if ($current_character_code >= 97 && $current_character_code <= 122) {
  1307. $letters ++;
  1308. } elseif ($current_character_code >= 48 && $current_character_code <= 57) {
  1309. $digits ++;
  1310. } else {
  1311. return false;
  1312. }
  1313. $previous_character_code = $current_character_code;
  1314. }
  1315. return ($letters >= 3 && $digits >= 2);
  1316. }
  1317. /**
  1318. * Clears the user ID from the session if it was the anonymous user. Generally
  1319. * used on out-of-tools pages to remove a user ID that could otherwise be used
  1320. * in the wrong context.
  1321. * This function is to be used in conjunction with the api_set_anonymous()
  1322. * function to simulate the user existence in case of an anonymous visit.
  1323. * @param bool database check switch - passed to api_is_anonymous()
  1324. * @return bool true if succesfully unregistered, false if not anonymous.
  1325. */
  1326. function api_clear_anonymous($db_check = false) {
  1327. global $_user;
  1328. if (api_is_anonymous($_user['user_id'], $db_check)) {
  1329. unset($_user['user_id']);
  1330. api_session_unregister('_uid');
  1331. return true;
  1332. }
  1333. return false;
  1334. }
  1335. /**
  1336. * Returns the status string corresponding to the status code
  1337. * @author Noel Dieschburg
  1338. * @param the int status code
  1339. */
  1340. function get_status_from_code($status_code) {
  1341. switch ($status_code) {
  1342. case STUDENT:
  1343. return get_lang('Student', '');
  1344. case TEACHER:
  1345. return get_lang('Teacher', '');
  1346. case COURSEMANAGER:
  1347. return get_lang('Manager', '');
  1348. case SESSIONADMIN:
  1349. return get_lang('SessionsAdmin', '');
  1350. case DRH:
  1351. return get_lang('Drh', '');
  1352. }
  1353. }
  1354. /* FAILURE MANAGEMENT */
  1355. /**
  1356. * The Failure Management module is here to compensate
  1357. * the absence of an 'exception' device in PHP 4.
  1358. */
  1359. /**
  1360. * $api_failureList - array containing all the failure recorded in order of arrival.
  1361. */
  1362. $api_failureList = array();
  1363. /**
  1364. * Fills a global array called $api_failureList
  1365. * This array collects all the failure occuring during the script runs
  1366. * The main purpose is allowing to manage the display messages externaly
  1367. * from the functions or objects. This strengthens encupsalation principle
  1368. *
  1369. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  1370. * @param string $failure_type - the type of failure
  1371. * global: array $api_failureList
  1372. * @return bolean false to stay consistent with the main script
  1373. */
  1374. function api_set_failure($failure_type) {
  1375. global $api_failureList;
  1376. $api_failureList[] = $failure_type;
  1377. return false;
  1378. }
  1379. /**
  1380. * Sets the current user as anonymous if it hasn't been identified yet. This
  1381. * function should be used inside a tool only. The function api_clear_anonymous()
  1382. * acts in the opposite direction by clearing the anonymous user's data every
  1383. * time we get on a course homepage or on a neutral page (index, admin, my space)
  1384. * @return bool true if set user as anonymous, false if user was already logged in or anonymous id could not be found
  1385. */
  1386. function api_set_anonymous() {
  1387. global $_user;
  1388. if (!empty($_user['user_id'])) {
  1389. return false;
  1390. }
  1391. $user_id = api_get_anonymous_id();
  1392. if ($user_id == 0) {
  1393. return false;
  1394. }
  1395. api_session_unregister('_user');
  1396. $_user['user_id'] = $user_id;
  1397. $_user['is_anonymous'] = true;
  1398. api_session_register('_user');
  1399. $GLOBALS['_user'] = $_user;
  1400. return true;
  1401. }
  1402. /**
  1403. * Gets the last failure stored in $api_failureList;
  1404. *
  1405. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1406. * @param void
  1407. * @return string - the last failure stored
  1408. */
  1409. function api_get_last_failure() {
  1410. global $api_failureList;
  1411. return $api_failureList[count($api_failureList) - 1];
  1412. }
  1413. /**
  1414. * Collects and manages failures occuring during script execution
  1415. * The main purpose is allowing to manage the display messages externaly
  1416. * from functions or objects. This strengthens encupsalation principle
  1417. *
  1418. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1419. * @package chamilo.library
  1420. */
  1421. class api_failure {
  1422. // TODO: $api_failureList to be hidden from global scope and to be renamed according to our coding conventions.
  1423. /**
  1424. * IMPLEMENTATION NOTE : For now the $api_failureList list is set to the
  1425. * global scope, as PHP 4 is unable to manage static variable in class. But
  1426. * this feature is awaited in PHP 5. The class is already written to minize
  1427. * the change when static class variable will be possible. And the API won't
  1428. * change.
  1429. */
  1430. public $api_failureList = array();
  1431. /**
  1432. * Piles the last failure in the failure list
  1433. *
  1434. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  1435. * @param string $failure_type - the type of failure
  1436. * @global array $api_failureList
  1437. * @return bolean false to stay consistent with the main script
  1438. */
  1439. function set_failure($failure_type) {
  1440. global $api_failureList;
  1441. $api_failureList[] = $failure_type;
  1442. return false;
  1443. }
  1444. /**
  1445. * Gets the last failure stored
  1446. *
  1447. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1448. * @param void
  1449. * @return string - the last failure stored
  1450. */
  1451. function get_last_failure() {
  1452. global $api_failureList;
  1453. if (count($api_failureList) == 0) { return ''; }
  1454. return $api_failureList[count($api_failureList) - 1];
  1455. }
  1456. }
  1457. /* CONFIGURATION SETTINGS */
  1458. /**
  1459. * Gets the current Chamilo (not PHP/cookie) session ID
  1460. * @return int O if no active session, the session ID otherwise
  1461. */
  1462. function api_get_session_id() {
  1463. return empty($_SESSION['id_session']) ? 0 : intval($_SESSION['id_session']);
  1464. }
  1465. /**
  1466. * Gets the current Chamilo (not social network) group ID
  1467. * @return int O if no active session, the session ID otherwise
  1468. */
  1469. function api_get_group_id() {
  1470. return empty($_SESSION['_gid']) ? 0 : intval($_SESSION['_gid']);
  1471. }
  1472. /**
  1473. * Gets the current or given session name
  1474. * @param int Session ID (optional)
  1475. * @return string The session name, or null if unfound
  1476. */
  1477. function api_get_session_name($session_id) {
  1478. if (empty($session_id)) {
  1479. $session_id = api_get_session_id();
  1480. if (empty($session_id)) { return null; }
  1481. }
  1482. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1483. $s = "SELECT name FROM $t WHERE id = ".(int)$session_id;
  1484. $r = Database::query($s);
  1485. $c = Database::num_rows($r);
  1486. if ($c > 0) {
  1487. //technically, there can be only one, but anyway we take the first
  1488. $rec = Database::fetch_array($r);
  1489. return $rec['name'];
  1490. }
  1491. return null;
  1492. }
  1493. /**
  1494. * Gets the session info by id
  1495. * @param int Session ID
  1496. * @return array information of the session
  1497. */
  1498. function api_get_session_info($session_id) {
  1499. $data = array();
  1500. if (!empty($session_id)) {
  1501. $sesion_id = intval(Database::escape_string($session_id));
  1502. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1503. $sql = "SELECT * FROM $tbl_session WHERE id = $session_id";
  1504. $result = Database::query($sql);
  1505. if (Database::num_rows($result)>0) {
  1506. $data = Database::fetch_array($result, 'ASSOC');
  1507. }
  1508. }
  1509. return $data;
  1510. }
  1511. /**
  1512. * Gets the session visibility by session id
  1513. * @param int session id
  1514. * @return int 0 = session still available, SESSION_VISIBLE_READ_ONLY = 1, SESSION_VISIBLE = 2, SESSION_INVISIBLE = 3
  1515. */
  1516. function api_get_session_visibility($session_id) {
  1517. $visibility = 0; //means that the session is still available
  1518. if (!empty($session_id)) {
  1519. $sesion_id = intval(Database::escape_string($session_id));
  1520. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1521. $is_coach = api_is_coach();
  1522. $condition_date_end = "";
  1523. if ($is_coach) {
  1524. $condition_date_end = " AND (CURDATE() > (SELECT adddate(date_end,nb_days_access_after_end) FROM $tbl_session WHERE id = $session_id) AND date_end != '0000-00-00') ";
  1525. } else {
  1526. $condition_date_end = " AND (date_end < CURDATE() AND date_end != '0000-00-00') ";
  1527. }
  1528. $sql = "SELECT visibility FROM $tbl_session
  1529. WHERE id = $session_id $condition_date_end "; // session is old and is not unlimited
  1530. $result = Database::query($sql);
  1531. if (Database::num_rows($result)>0) {
  1532. $row = Database::fetch_array($result, 'ASSOC');
  1533. $visibility = $row['visibility'];
  1534. } else {
  1535. $visibility = 0;
  1536. }
  1537. }
  1538. return $visibility;
  1539. }
  1540. /**
  1541. * Gets the visibility of an session of a course that a student have
  1542. * @param int session id
  1543. * @param string Chamilo course code
  1544. * @param int user id
  1545. * @return int 0= Session available (in date), SESSION_VISIBLE_READ_ONLY = 1, SESSION_VISIBLE = 2, SESSION_INVISIBLE = 3
  1546. */
  1547. function api_get_session_visibility_by_user($session_id, $course_code, $user_id) {
  1548. $visibility = 0; // Means that the session is still available.
  1549. if (!empty($session_id) && !empty($user_id)){
  1550. $sesion_id = intval(Database::escape_string($session_id));
  1551. $user_id = intval(Database::escape_string($user_id));
  1552. $course_code = Database::escape_string($course_code);
  1553. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION_REL_COURSE_REL_USER);
  1554. $sql = "SELECT visibility FROM $tbl_session
  1555. WHERE id_session = $session_id AND id_user = $user_id AND course_code = '$course_code'"; // session old
  1556. $result = Database::query($sql);
  1557. if (Database::num_rows($result) > 0) {
  1558. $row = Database::fetch_array($result, 'ASSOC');
  1559. $visibility = $row['visibility'];
  1560. } else {
  1561. $visibility = 0;
  1562. }
  1563. }
  1564. return $visibility;
  1565. }
  1566. /**
  1567. * This function returns a (star) session icon if the session is not null and
  1568. * the user is not a student
  1569. * @param int Session id
  1570. * @param int User status id - if 5 (student), will return empty
  1571. * @return string Session icon
  1572. */
  1573. function api_get_session_image($session_id, $status_id) {
  1574. $session_id = (int)$session_id;
  1575. $session_img = '';
  1576. if ((int)$status_id != 5) { //check whether is not a student
  1577. if ($session_id > 0) {
  1578. $session_img = "&nbsp;&nbsp;".Display::return_icon('star.png', get_lang('SessionSpecificResource'), array('align' => 'absmiddle'), 22);
  1579. }
  1580. }
  1581. return $session_img;
  1582. }
  1583. /**
  1584. * This function add an additional condition according to the session of the course
  1585. * @param int session id
  1586. * @param bool optional, true if more than one condition false if the only condition in the query
  1587. * @param bool optional, true to accept content with session=0 as well, false for strict session condition
  1588. * @return string condition of the session
  1589. */
  1590. function api_get_session_condition($session_id, $and = true, $with_base_content = false) {
  1591. $session_id = intval($session_id);
  1592. //condition to show resources by session
  1593. $condition_session = '';
  1594. $condition_add = $and ? " AND " : " WHERE ";
  1595. if ($with_base_content) {
  1596. $condition_session = $condition_add." (session_id = $session_id OR session_id = 0) ";
  1597. } else {
  1598. $condition_session = $condition_add." session_id = $session_id ";
  1599. }
  1600. return $condition_session;
  1601. }
  1602. /**
  1603. * This function returns information about coachs from a course in session
  1604. * @param int - optional, session id
  1605. * @param string - optional, course code
  1606. * @return array - array containing user_id, lastname, firstname, username.
  1607. */
  1608. function api_get_coachs_from_course($session_id=0,$course_code='') {
  1609. if (!empty($session_id)) {
  1610. $session_id = intval($session_id);
  1611. } else {
  1612. $session_id = api_get_session_id();
  1613. }
  1614. if (!empty($course_code)) {
  1615. $course_code = Database::escape_string($course_code);
  1616. } else {
  1617. $course_code = api_get_course_id();
  1618. }
  1619. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  1620. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1621. $coaches = array();
  1622. $sql = "SELECT u.user_id,u.lastname,u.firstname,u.username FROM $tbl_user u,$tbl_session_course_user scu
  1623. WHERE u.user_id = scu.id_user AND scu.id_session = '$session_id' AND scu.course_code = '$course_code' AND scu.status = 2";
  1624. $rs = Database::query($sql);
  1625. if (Database::num_rows($rs) > 0) {
  1626. while ($row = Database::fetch_array($rs)) {
  1627. $coaches[] = $row;
  1628. }
  1629. return $coaches;
  1630. } else {
  1631. return false;
  1632. }
  1633. }
  1634. /**
  1635. * Returns the value of a setting from the web-adjustable admin config settings.
  1636. *
  1637. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  1638. * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
  1639. * instead of
  1640. * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
  1641. * @param string The variable name
  1642. * @param string The subkey (sub-variable) if any. Defaults to NULL
  1643. * @author René Haentjens
  1644. * @author Bart Mollet
  1645. */
  1646. function api_get_setting($variable, $key = null) {
  1647. global $_setting;
  1648. if ($variable == 'header_extra_content') {
  1649. $filename = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt';
  1650. if (file_exists($filename)) {
  1651. $value = file_get_contents($filename);
  1652. return $value ;
  1653. } else {
  1654. return '';
  1655. }
  1656. }
  1657. if ($variable == 'footer_extra_content') {
  1658. $filename = api_get_path(SYS_PATH).api_get_home_path().'footer_extra_content.txt';
  1659. if (file_exists($filename)) {
  1660. $value = file_get_contents($filename);
  1661. return $value ;
  1662. } else {
  1663. return '';
  1664. }
  1665. }
  1666. $value = null;
  1667. if (is_null($key)) {
  1668. $value = ((isset($_setting[$variable]) && $_setting[$variable] != '') ? $_setting[$variable] : null);
  1669. } else {
  1670. if (isset($_setting[$variable][$key])) {
  1671. $value = $_setting[$variable][$key];
  1672. }
  1673. }
  1674. return $value;
  1675. }
  1676. /**
  1677. * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection
  1678. * @return string Escaped version of $_SERVER['PHP_SELF']
  1679. */
  1680. function api_get_self() {
  1681. return htmlentities($_SERVER['PHP_SELF']);
  1682. }
  1683. /* USER PERMISSIONS */
  1684. /**
  1685. * Checks whether current user is a platform administrator
  1686. * @return boolean True if the user has platform admin rights,
  1687. * false otherwise.
  1688. * @see usermanager::is_admin(user_id) for a user-id specific function
  1689. */
  1690. function api_is_platform_admin($allow_sessions_admins = false) {
  1691. if ($_SESSION['is_platformAdmin']) {
  1692. return true;
  1693. }
  1694. global $_user;
  1695. return $allow_sessions_admins && $_user['status'] == SESSIONADMIN;
  1696. }
  1697. /**
  1698. * Checks whether current user is allowed to create courses
  1699. * @return boolean True if the user has course creation rights,
  1700. * false otherwise.
  1701. */
  1702. function api_is_allowed_to_create_course() {
  1703. return $_SESSION['is_allowedCreateCourse'];
  1704. }
  1705. /**
  1706. * Checks whether the current user is a course administrator
  1707. * @return boolean True if current user is a course administrator
  1708. */
  1709. function api_is_course_admin() {
  1710. return $_SESSION['is_courseAdmin'];
  1711. }
  1712. /**
  1713. * Checks whether the current user is a course coach
  1714. * @return bool True if current user is a course coach
  1715. */
  1716. function api_is_course_coach() {
  1717. return $_SESSION['is_courseCoach'];
  1718. }
  1719. /**
  1720. * Checks whether the current user is a course tutor
  1721. * @return bool True if current user is a course tutor
  1722. */
  1723. function api_is_course_tutor() {
  1724. return $_SESSION['is_courseTutor'];
  1725. }
  1726. function api_get_user_platform_status($user_id = false) {
  1727. $status = array();
  1728. $user_id = intval($user_id);
  1729. if (empty($user_id)) {
  1730. $user_id = api_get_user_id();
  1731. }
  1732. if (empty($user_id)) {
  1733. return false;
  1734. }
  1735. $group_id = api_get_group_id();
  1736. $course_id = api_get_course_int_id();
  1737. $course_code= api_get_course_id();
  1738. $session_id = api_get_session_id();
  1739. //Group (in course)
  1740. if ($group_id && $course_id) {
  1741. $group_status = array();
  1742. require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
  1743. $is_subscribed = GroupManager::is_subscribed($user_id, $group_id);
  1744. if ($is_subscribed) {
  1745. $group_status = array('id'=> $group_id , 'status' => 'student');
  1746. $is_tutor = GroupManager::is_tutor_of_group($user_id, $group_id);
  1747. if ($is_tutor) {
  1748. $group_status['status'] = 'tutor';
  1749. } else {
  1750. $group_status['status'] = 'student';
  1751. }
  1752. }
  1753. $status['group'] = $group_status;
  1754. }
  1755. //Session
  1756. if ($session_id && $course_id) {
  1757. $session_status = array();
  1758. $session_status = array('id' => $session_id, 'course_id' => $course_id);
  1759. $session_user_status = SessionManager::get_user_status_in_session($user_id, $course_code, $session_id);
  1760. switch ($session_user_status) {
  1761. case 0:
  1762. $session_status['status'] = 'student';
  1763. break;
  1764. case 2:
  1765. $session_status['status'] = 'coach';
  1766. break;
  1767. }
  1768. $is_general_coach = SessionManager::user_is_general_coach($user_id, $session_id);
  1769. if ($is_general_coach) {
  1770. $session_status['status'] = 'general_coach';
  1771. }
  1772. $status['session'] = $session_status;
  1773. } elseif($course_id) {
  1774. //Course
  1775. $course_status = array();
  1776. if ($course_id) {
  1777. $user_course_status = CourseManager::get_user_in_course_status($user_id, $course_code);
  1778. if ($user_course_status) {
  1779. $course_status = array('id'=> $course_id);
  1780. switch($user_course_status) {
  1781. case 1;
  1782. $course_status['status'] = 'teacher';
  1783. break;
  1784. case 5;
  1785. $course_status['status'] = 'student';
  1786. //check if tutor
  1787. $tutor_course_status = CourseManager::get_tutor_in_course_status($user_id, $course_code);
  1788. if ($tutor_course_status) {
  1789. $course_status['status'] = 'tutor';
  1790. }
  1791. break;
  1792. }
  1793. }
  1794. }
  1795. $status['course'] = $course_status;
  1796. }
  1797. return $status;
  1798. }
  1799. /**
  1800. * Checks whether the current user is a course or session coach
  1801. * @param int - optional, session id
  1802. * @param string - optional, course code
  1803. * @return boolean True if current user is a course or session coach
  1804. */
  1805. function api_is_coach($session_id = 0, $course_code = '') {
  1806. //@todo Not sure about this one
  1807. /*if (api_is_platform_admin()) {
  1808. return true;
  1809. }*/
  1810. if (!empty($session_id)) {
  1811. $session_id = intval($session_id);
  1812. } else {
  1813. $session_id = api_get_session_id();
  1814. }
  1815. if (!empty($course_code)) {
  1816. $course_code = Database::escape_string($course_code);
  1817. } else {
  1818. $course_code = api_get_course_id();
  1819. }
  1820. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1821. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1822. $sessionIsCoach = null;
  1823. if (!empty($course_code)) {
  1824. $sql = "SELECT DISTINCT id, name, date_start, date_end
  1825. FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  1826. ON session_rc_ru.id_user = '".api_get_user_id()."'
  1827. WHERE session_rc_ru.course_code = '$course_code' AND session_rc_ru.status = 2 AND session_rc_ru.id_session = '$session_id'";
  1828. $result = Database::query($sql);
  1829. $sessionIsCoach = Database::store_result($result);
  1830. }
  1831. if (!empty($session_id)) {
  1832. $sql = "SELECT DISTINCT id, name, date_start, date_end
  1833. FROM $session_table
  1834. WHERE session.id_coach = '".api_get_user_id()."' AND id = '$session_id'
  1835. ORDER BY date_start, date_end, name";
  1836. $result = Database::query($sql);
  1837. if (!empty($sessionIsCoach)) {
  1838. $sessionIsCoach = array_merge($sessionIsCoach , Database::store_result($result));
  1839. } else {
  1840. $sessionIsCoach = Database::store_result($result);
  1841. }
  1842. }
  1843. return (count($sessionIsCoach) > 0);
  1844. }
  1845. /**
  1846. * Checks whether the current user is a session administrator
  1847. * @return boolean True if current user is a course administrator
  1848. */
  1849. function api_is_session_admin() {
  1850. global $_user;
  1851. return $_user['status'] == SESSIONADMIN;
  1852. }
  1853. /**
  1854. * Checks whether the current user is a human resources manager
  1855. * @return boolean True if current user is a human resources manager
  1856. */
  1857. function api_is_drh() {
  1858. global $_user;
  1859. return $_user['status'] == DRH;
  1860. }
  1861. /**
  1862. * Checks whether the current user is a student
  1863. * @return boolean True if current user is a human resources manager
  1864. */
  1865. function api_is_student() {
  1866. global $_user;
  1867. return $_user['status'] == STUDENT;
  1868. }
  1869. /**
  1870. * Checks whether the current user is a teacher
  1871. * @return boolean True if current user is a human resources manager
  1872. */
  1873. function api_is_teacher() {
  1874. global $_user;
  1875. return $_user['status'] == COURSEMANAGER;
  1876. }
  1877. /**
  1878. * This function checks whether a session is assigned into a category
  1879. * @param int - session id
  1880. * @param string - category name
  1881. * @return bool - true if is found, otherwise false
  1882. */
  1883. function api_is_session_in_category($session_id, $category_name) {
  1884. $session_id = intval($session_id);
  1885. $category_name = Database::escape_string($category_name);
  1886. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1887. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1888. $sql = "select 1 FROM $tbl_session WHERE $session_id IN (SELECT s.id FROM $tbl_session s, $tbl_session_category sc WHERE s.session_category_id = sc.id AND sc.name LIKE '%$category_name' )";
  1889. $rs = Database::query($sql);
  1890. if (Database::num_rows($rs) > 0) {
  1891. return true;
  1892. } else {
  1893. return false;
  1894. }
  1895. }
  1896. /* DISPLAY OPTIONS
  1897. student view, title, message boxes,... */
  1898. /**
  1899. * Displays the title of a tool.
  1900. * Normal use: parameter is a string:
  1901. * api_display_tool_title("My Tool")
  1902. *
  1903. * Optionally, there can be a subtitle below
  1904. * the normal title, and / or a supra title above the normal title.
  1905. *
  1906. * e.g. supra title:
  1907. * group
  1908. * GROUP PROPERTIES
  1909. *
  1910. * e.g. subtitle:
  1911. * AGENDA
  1912. * calender & events tool
  1913. *
  1914. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1915. * @param mixed $title_element - it could either be a string or an array
  1916. * containing 'supraTitle', 'mainTitle',
  1917. * 'subTitle'
  1918. * @return void
  1919. */
  1920. function api_display_tool_title($title_element) {
  1921. if (is_string($title_element)) {
  1922. $tit = $title_element;
  1923. unset ($title_element);
  1924. $title_element['mainTitle'] = $tit;
  1925. }
  1926. echo '<h2>';
  1927. if (!empty($title_element['supraTitle'])) {
  1928. echo '<small>'.$title_element['supraTitle'].'</small><br />';
  1929. }
  1930. if (!empty($title_element['mainTitle'])) {
  1931. echo $title_element['mainTitle'];
  1932. }
  1933. if (!empty($title_element['subTitle'])) {
  1934. echo '<br /><small>'.$title_element['subTitle'].'</small>';
  1935. }
  1936. echo '</h2>';
  1937. }
  1938. /**
  1939. * Displays options for switching between student view and course manager view
  1940. *
  1941. * Changes in version 1.2 (Patrick Cool)
  1942. * Student view switch now behaves as a real switch. It maintains its current state until the state
  1943. * is changed explicitly
  1944. *
  1945. * Changes in version 1.1 (Patrick Cool)
  1946. * student view now works correctly in subfolders of the document tool
  1947. * student view works correctly in the new links tool
  1948. *
  1949. * Example code for using this in your tools:
  1950. * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
  1951. * // display_tool_view_option($isStudentView);
  1952. * //}
  1953. * //and in later sections, use api_is_allowed_to_edit()
  1954. *
  1955. * @author Roan Embrechts
  1956. * @author Patrick Cool
  1957. * @version 1.2
  1958. * @todo rewrite code so it is easier to understand
  1959. */
  1960. function api_display_tool_view_option() {
  1961. if (api_get_setting('student_view_enabled') != 'true') {
  1962. return '';
  1963. }
  1964. $output_string = '';
  1965. $sourceurl = '';
  1966. $is_framed = false;
  1967. // Exceptions apply for all multi-frames pages
  1968. 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
  1969. $is_framed = true;
  1970. return '';
  1971. }
  1972. /*// Uncomment to remove student view link from document view page
  1973. if (strpos($_SERVER['REQUEST_URI'], 'document/headerpage.php') !== false) {
  1974. $sourceurl = str_replace('document/headerpage.php', 'document/showinframes.php', $_SERVER['REQUEST_URI']);
  1975. //showinframes doesn't handle student view anyway...
  1976. //return '';
  1977. $is_framed = true;
  1978. }*/
  1979. // Uncomment to remove student view link from document view page
  1980. if (strpos($_SERVER['REQUEST_URI'], 'newscorm/lp_header.php') !== false) {
  1981. if (empty($_GET['lp_id'])) {
  1982. return '';
  1983. }
  1984. $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
  1985. $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);
  1986. //showinframes doesn't handle student view anyway...
  1987. //return '';
  1988. $is_framed = true;
  1989. }
  1990. // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  1991. if (!$is_framed) {
  1992. if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
  1993. $sourceurl = api_get_self().'?'.api_get_cidreq();
  1994. } else {
  1995. $sourceurl = $_SERVER['REQUEST_URI'];
  1996. //$sourceurl = str_replace('&', '&amp;', $sourceurl);
  1997. }
  1998. }
  1999. if (!empty($_SESSION['studentview'])) {
  2000. if ($_SESSION['studentview'] == 'studentview') {
  2001. // We have to remove the isStudentView=true from the $sourceurl
  2002. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2003. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2004. $output_string .= '<a href="'.$sourceurl.'&isStudentView=false" target="_self">'.get_lang('CourseManagerview').'</a>';
  2005. } elseif ($_SESSION['studentview'] == 'teacherview') {
  2006. // Switching to teacherview
  2007. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2008. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2009. $output_string .= '<a href="'.$sourceurl.'&isStudentView=true" target="_self">'.get_lang('StudentView').'</a>';
  2010. }
  2011. } else {
  2012. $output_string .= '<a href="'.$sourceurl.'&isStudentView=true" target="_self">'.get_lang('StudentView').'</a>';
  2013. }
  2014. echo $output_string;
  2015. }
  2016. /**
  2017. * Displays the contents of an array in a messagebox.
  2018. * @param array $info_array An array with the messages to show
  2019. */
  2020. function api_display_array($info_array) {
  2021. if(is_array($info_array)) {
  2022. foreach ($info_array as $element) {
  2023. $message .= $element.'<br />';
  2024. }
  2025. }
  2026. Display :: display_normal_message($message);
  2027. }
  2028. /**
  2029. * Displays debug info
  2030. * @param string $debug_info The message to display
  2031. * @author Roan Embrechts
  2032. * @version 1.1, March 2004
  2033. */
  2034. function api_display_debug_info($debug_info) {
  2035. $message = '<i>Debug info</i><br />';
  2036. $message .= $debug_info;
  2037. Display :: display_normal_message($message);
  2038. }
  2039. // TODO: This is for the permission section.
  2040. /**
  2041. * Function that removes the need to directly use is_courseAdmin global in
  2042. * tool scripts. It returns true or false depending on the user's rights in
  2043. * this particular course.
  2044. * Optionally checking for tutor and coach roles here allows us to use the
  2045. * student_view feature altogether with these roles as well.
  2046. * @param bool Whether to check if the user has the tutor role
  2047. * @param bool Whether to check if the user has the coach role
  2048. * @param bool Whether to check if the user has the session coach role
  2049. *
  2050. * @author Roan Embrechts
  2051. * @author Patrick Cool
  2052. * @version 1.1, February 2004
  2053. * @return boolean, true: the user has the rights to edit, false: he does not
  2054. */
  2055. function api_is_allowed_to_edit($tutor = false, $coach = false, $session_coach = false) {
  2056. $my_session_id = api_get_session_id();
  2057. $is_allowed_coach_to_edit = api_is_coach();
  2058. $session_visibility = api_get_session_visibility($my_session_id);
  2059. $is_courseAdmin = api_is_course_admin() || api_is_platform_admin();
  2060. if (!$is_courseAdmin && $tutor) { // If we also want to check if the user is a tutor...
  2061. $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
  2062. }
  2063. if (!$is_courseAdmin && $coach) { // If we also want to check if the user is a coach...';
  2064. // Check if session visibility is read only for coaches.
  2065. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  2066. $is_allowed_coach_to_edit = false;
  2067. }
  2068. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') { // Check if coach is allowed to edit a course.
  2069. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  2070. } else {
  2071. $is_courseAdmin = $is_courseAdmin;
  2072. }
  2073. }
  2074. if (!$is_courseAdmin && $session_coach) {
  2075. $is_courseAdmin = $is_courseAdmin || api_is_coach();
  2076. }
  2077. if (api_get_setting('student_view_enabled') == 'true') { // Check if the student_view is enabled, and if so, if it is activated.
  2078. if (!empty($my_session_id)) {
  2079. // Check if session visibility is read only for coachs
  2080. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  2081. $is_allowed_coach_to_edit = false;
  2082. }
  2083. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') { // Check if coach is allowed to edit a course.
  2084. $is_allowed = $is_allowed_coach_to_edit;
  2085. } else {
  2086. $is_allowed = false;
  2087. }
  2088. $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
  2089. } else {
  2090. $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
  2091. }
  2092. return $is_allowed;
  2093. } else {
  2094. return $is_courseAdmin;
  2095. }
  2096. }
  2097. /**
  2098. * Checks if a student can edit contents in a session depending
  2099. * on the session visibility
  2100. * @param bool Whether to check if the user has the tutor role
  2101. * @param bool Whether to check if the user has the coach role
  2102. * @return boolean, true: the user has the rights to edit, false: he does not
  2103. */
  2104. function api_is_allowed_to_session_edit($tutor = false, $coach = false) {
  2105. if (api_is_allowed_to_edit($tutor, $coach)) {
  2106. // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
  2107. return true;
  2108. } else {
  2109. if (api_get_session_id() == 0) {
  2110. // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
  2111. return true;
  2112. } else {
  2113. // I'm in a session and I'm a student
  2114. $session_id = api_get_session_id();
  2115. // Get the session visibility
  2116. $session_visibility = api_get_session_visibility($session_id); // if 0 the session is still available.
  2117. if ($session_visibility != 0) {
  2118. //@todo We could load the session_rel_course_rel_user permission to increase the level of detail.
  2119. //echo api_get_user_id();
  2120. //echo api_get_course_id();
  2121. switch ($session_visibility) {
  2122. case SESSION_VISIBLE_READ_ONLY: // 1
  2123. return false;
  2124. case SESSION_VISIBLE: // 2
  2125. return true;
  2126. case SESSION_INVISIBLE: // 3
  2127. return false;
  2128. }
  2129. } else {
  2130. return true;
  2131. }
  2132. }
  2133. }
  2134. }
  2135. /**
  2136. * Checks whether the user is allowed in a specific tool for a specific action
  2137. * @param $tool the tool we are checking if the user has a certain permission
  2138. * @param $action the action we are checking (add, edit, delete, move, visibility)
  2139. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2140. * @version 1.0
  2141. */
  2142. function api_is_allowed($tool, $action, $task_id = 0) {
  2143. global $_course;
  2144. global $_user;
  2145. if (api_is_course_admin()) {
  2146. return true;
  2147. }
  2148. //if (!$_SESSION['total_permissions'][$_course['code']] and $_course)
  2149. if (is_array($_course) and count($_course) > 0) {
  2150. require_once api_get_path(SYS_CODE_PATH).'permissions/permissions_functions.inc.php';
  2151. require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
  2152. // Getting the permissions of this user.
  2153. if ($task_id == 0) {
  2154. $user_permissions = get_permissions('user', $_user['user_id']);
  2155. $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
  2156. }
  2157. // Getting the permissions of the task.
  2158. if ($task_id != 0) {
  2159. $task_permissions = get_permissions('task', $task_id);
  2160. /* !!! */$_SESSION['total_permissions'][$_course['code']] = $task_permissions;
  2161. }
  2162. //print_r($_SESSION['total_permissions']);
  2163. // Getting the permissions of the groups of the user
  2164. //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  2165. //foreach($groups_of_user as $group)
  2166. // $this_group_permissions = get_permissions('group', $group);
  2167. // Getting the permissions of the courseroles of the user
  2168. $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
  2169. // Getting the permissions of the platformroles of the user
  2170. //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  2171. // Getting the permissions of the roles of the groups of the user
  2172. //foreach($groups_of_user as $group)
  2173. // $this_group_courserole_permissions = get_roles_permissions('group', $group);
  2174. // Getting the permissions of the platformroles of the groups of the user
  2175. //foreach($groups_of_user as $group)
  2176. // $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  2177. }
  2178. // If the permissions are limited, we have to map the extended ones to the limited ones.
  2179. if (api_get_setting('permissions') == 'limited') {
  2180. if ($action == 'Visibility') {
  2181. $action = 'Edit';
  2182. }
  2183. if ($action == 'Move') {
  2184. $action = 'Edit';
  2185. }
  2186. }
  2187. // The session that contains all the permissions already exists for this course
  2188. // so there is no need to requery everything.
  2189. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  2190. if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) {
  2191. if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) {
  2192. return true;
  2193. } else {
  2194. return false;
  2195. }
  2196. }
  2197. }
  2198. /**
  2199. * Tells whether this user is an anonymous user
  2200. * @param int User ID (optional, will take session ID if not provided)
  2201. * @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
  2202. * @return bool true if this user is anonymous, false otherwise
  2203. */
  2204. function api_is_anonymous($user_id = null, $db_check = false) {
  2205. if (!isset($user_id)) {
  2206. $user_id = api_get_user_id();
  2207. }
  2208. if ($db_check) {
  2209. $info = api_get_user_info($user_id);
  2210. if ($info['status'] == 6) {
  2211. return true;
  2212. }
  2213. }
  2214. global $_user;
  2215. if (!isset($_user)) {
  2216. // In some cases, api_set_anonymous doesn't seem to be triggered in local.inc.php. Make sure it is.
  2217. // Occurs in agenda for admin links - YW
  2218. global $use_anonymous;
  2219. if (isset($use_anonymous) && $use_anonymous) {
  2220. api_set_anonymous();
  2221. }
  2222. return true;
  2223. }
  2224. return isset($_user['is_anonymous']) && $_user['is_anonymous'] === true;
  2225. }
  2226. /**
  2227. * Displays message "You are not allowed here..." and exits the entire script.
  2228. * @param bool Whether or not to print headers (default = false -> does not print them)
  2229. *
  2230. * @author Roan Embrechts
  2231. * @author Yannick Warnier
  2232. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2233. *
  2234. * @version 1.0, February 2004
  2235. * @version dokeos 1.8, August 2006
  2236. */
  2237. function api_not_allowed($print_headers = false) {
  2238. $home_url = api_get_path(WEB_PATH);
  2239. $user = api_get_user_id(); //0 if not defined
  2240. $course = api_get_course_id();
  2241. global $this_section;
  2242. if (api_get_setting('use_custom_pages') == 'true') {
  2243. $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
  2244. require_once api_get_path(LIBRARY_PATH).'custompages.lib.php';
  2245. CustomPages::displayPage('index-unlogged');
  2246. exit;
  2247. }
  2248. $origin = isset($_GET['origin']) ? $_GET['origin'] : '';
  2249. if ($origin == 'learnpath') {
  2250. $htmlHeadXtra[]= '<style type="text/css" media="screen, projection">
  2251. /*<![CDATA[*/
  2252. @import "'.api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/default.css";
  2253. /*]]>*/
  2254. </style>';
  2255. }
  2256. $msg = Display::return_message(get_lang('NotAllowedClickBack'), 'error', false);
  2257. $msg = Display::div($msg, array('align'=>'center'));
  2258. $show_headers = 0;
  2259. if ((!headers_sent() || $print_headers) && $origin != 'learnpath') {
  2260. $show_headers = 1;
  2261. }
  2262. $tpl = new Template(null, $show_headers, $show_headers);
  2263. $tpl->assign('content', $msg);
  2264. if (($user!=0 && !api_is_anonymous()) && (!isset($course) || $course == -1) && empty($_GET['cidReq'])) {
  2265. // if the access is not authorized and there is some login information
  2266. // but the cidReq is not found, assume we are missing course data and send the user
  2267. // to the user_portal
  2268. $tpl->display_one_col_template();
  2269. exit;
  2270. }
  2271. if (!empty($_SERVER['REQUEST_URI']) && (!empty($_GET['cidReq']) || $this_section == SECTION_MYPROFILE)) {
  2272. //only display form and return to the previous URL if there was a course ID included
  2273. if ($user!=0 && !api_is_anonymous()) {
  2274. //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
  2275. $tpl->assign('content', $msg);
  2276. $tpl->display_one_col_template();
  2277. exit;
  2278. }
  2279. // If the user has no user ID, then his session has expired
  2280. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  2281. $form = new FormValidator('formLogin', 'post', api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']), null, array('class'=>'form-stacked'));
  2282. $form->addElement('text', 'login', get_lang('UserName'), array('size' => 17));
  2283. $form->addElement('password', 'password', get_lang('Password'), array('size' => 17));
  2284. $form->addElement('style_submit_button', 'submitAuth', get_lang('LoginEnter'),'class="a_button gray"');
  2285. $content = Display::return_message(get_lang('NotAllowed').'<br />'.get_lang('PleaseLoginAgainFromFormBelow').'<br />', 'error', false);
  2286. $content .= '<div style="margin: 0 auto; width: 200px;" class="menu-wrapper"><div class="menu" id="menu">';
  2287. $renderer =& $form->defaultRenderer();
  2288. //$renderer->setElementTemplate('<div><label>{label}</label></div><div>{element}</div>');
  2289. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}</div></div>');
  2290. $content .= $form->return_form();
  2291. $content .='</div></div>';
  2292. $tpl->assign('content', $content);
  2293. $tpl->display_one_col_template();
  2294. exit;
  2295. }
  2296. if ($user!=0 && !api_is_anonymous()) {
  2297. $tpl->display_one_col_template();
  2298. exit;
  2299. }
  2300. //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
  2301. $msg = Display::return_message(get_lang('NotAllowed').'<br /><br /><a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br />', 'error', false);
  2302. $msg = Display::div($msg, array('align'=>'center'));
  2303. $tpl->assign('content', $msg);
  2304. $tpl->display_one_col_template();
  2305. exit;
  2306. }
  2307. /* WHAT'S NEW
  2308. functions for the what's new icons
  2309. in the user course list */
  2310. /**
  2311. * Gets a UNIX timestamp from a MySQL datetime format string
  2312. * @param $last_post_datetime standard output date in a sql query
  2313. * @return unix timestamp
  2314. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  2315. * @version October 2003
  2316. * @desc convert sql date to unix timestamp
  2317. */
  2318. function convert_mysql_date($last_post_datetime) {
  2319. list ($last_post_date, $last_post_time) = split(' ', $last_post_datetime);
  2320. list ($year, $month, $day) = explode('-', $last_post_date);
  2321. list ($hour, $min, $sec) = explode(':', $last_post_time);
  2322. return mktime((int)$hour, (int)$min, (int)$sec, (int)$month, (int)$day, (int)$year);
  2323. }
  2324. /**
  2325. * Gets a MySQL datetime format string from a UNIX timestamp
  2326. * @param int UNIX timestamp, as generated by the time() function. Will be generated if parameter not provided
  2327. * @return string MySQL datetime format, like '2009-01-30 12:23:34'
  2328. */
  2329. function api_get_datetime($time = null) {
  2330. if (!isset($time)) { $time = time(); }
  2331. return date('Y-m-d H:i:s', $time);
  2332. }
  2333. /**
  2334. * Gets item visibility from the item_property table
  2335. *
  2336. * Getting the visibility is done by getting the last updated visibility entry,
  2337. * using the largest session ID found if session 0 and another was found (meaning
  2338. * the only one that is actually from the session, in case there are results from
  2339. * session 0 *AND* session n).
  2340. * @param array Course properties array (result of api_get_course_info())
  2341. * @param string Tool (learnpath, document, etc)
  2342. * @param int The item ID in the given tool
  2343. * @param int The session ID (optional)
  2344. * @return int -1 on error, 0 if invisible, 1 if visible
  2345. */
  2346. function api_get_item_visibility($_course, $tool, $id, $session=0) {
  2347. if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) { return -1; }
  2348. $tool = Database::escape_string($tool);
  2349. $id = Database::escape_string($id);
  2350. $session = (int) $session;
  2351. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2352. $course_id = $_course['real_id'];
  2353. $sql = "SELECT visibility FROM $TABLE_ITEMPROPERTY
  2354. WHERE c_id = $course_id AND
  2355. tool = '$tool' AND
  2356. ref = $id AND
  2357. (id_session = $session OR id_session = 0)
  2358. ORDER BY id_session DESC, lastedit_date DESC";
  2359. $res = Database::query($sql);
  2360. if ($res === false || Database::num_rows($res) == 0) { return -1; }
  2361. $row = Database::fetch_array($res);
  2362. return $row['visibility'];
  2363. }
  2364. /**
  2365. * Updates or adds item properties to the Item_propetry table
  2366. * Tool and lastedit_type are language independant strings (langvars->get_lang!)
  2367. *
  2368. * @param $_course : array with course properties
  2369. * @param $tool : tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2370. * @param $item_id : id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2371. * @param $lastedit_type : add or update action (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  2372. * (2) "delete"; (3) "visible"; (4) "invisible";
  2373. * @param $user_id : id of the editing/adding user
  2374. * @param $to_group_id : id of the intended group ( 0 = for everybody), only relevant for $type (1)
  2375. * @param $to_user_id : id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  2376. * @param string $start_visible 0000-00-00 00:00:00 format
  2377. * @param unknown_type $end_visible 0000-00-00 00:00:00 format
  2378. * @return boolean False if update fails.
  2379. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  2380. * @version January 2005
  2381. * @desc update the item_properties table (if entry not exists, insert) of the course
  2382. */
  2383. function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $user_id, $to_group_id = 0, $to_user_id = null, $start_visible = 0, $end_visible = 0, $session_id = 0) {
  2384. // Definition of variables.
  2385. $tool = Database::escape_string($tool);
  2386. $item_id = Database::escape_string($item_id);
  2387. $lastedit_type = Database::escape_string($lastedit_type);
  2388. $user_id = Database::escape_string($user_id);
  2389. $to_group_id = Database::escape_string($to_group_id);
  2390. $to_user_id = Database::escape_string($to_user_id);
  2391. $start_visible = Database::escape_string($start_visible);
  2392. $end_visible = Database::escape_string($end_visible);
  2393. $start_visible = ($start_visible == 0) ? '0000-00-00 00:00:00' : $start_visible;
  2394. $end_visible = ($end_visible == 0) ? '0000-00-00 00:00:00' : $end_visible;
  2395. $to_filter = '';
  2396. $time = api_get_utc_datetime();
  2397. if (!empty($session_id)) {
  2398. $session_id = intval($session_id);
  2399. } else {
  2400. $session_id = api_get_session_id();
  2401. }
  2402. // Definition of tables.
  2403. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2404. if ($to_user_id <= 0) {
  2405. $to_user_id = null; // No to_user_id set
  2406. }
  2407. if (!is_null($to_user_id)) {
  2408. // $to_user_id has more priority than $to_group_id
  2409. $to_field = 'to_user_id';
  2410. $to_value = $to_user_id;
  2411. } else {
  2412. // $to_user_id is not set.
  2413. $to_field = 'to_group_id';
  2414. $to_value = $to_group_id;
  2415. }
  2416. // Set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  2417. $condition_session = '';
  2418. if (!empty($session_id)) {
  2419. $condition_session = " AND id_session = '$session_id' ";
  2420. }
  2421. $course_id = $_course['real_id'];
  2422. $filter = "c_id = $course_id AND tool='$tool' AND ref='$item_id' $condition_session ";
  2423. if ($item_id == '*') {
  2424. $filter = "c_id = $course_id AND tool='$tool' AND visibility<>'2' $condition_session"; // For all (not deleted) items of the tool
  2425. }
  2426. // Check whether $to_user_id and $to_group_id are passed in the function call.
  2427. // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  2428. if (is_null($to_user_id) && is_null($to_group_id)) {
  2429. $to_group_id = 0;
  2430. }
  2431. if (!is_null($to_user_id)) {
  2432. $to_filter = " AND to_user_id='$to_user_id' $condition_session"; // Set filter to intended user.
  2433. } else {
  2434. if (($to_group_id != 0) && $to_group_id == strval(intval($to_group_id))) {
  2435. $to_filter = " AND to_group_id='$to_group_id' $condition_session"; // Set filter to intended group.
  2436. }
  2437. }
  2438. // Update if possible
  2439. $set_type = '';
  2440. switch ($lastedit_type) {
  2441. case 'delete' : // delete = make item only visible for the platform admin.
  2442. $visibility = '2';
  2443. if (!empty($session_id)) {
  2444. // Check whether session id already exist into itemp_properties for updating visibility or add it.
  2445. $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY
  2446. WHERE c_id = $course_id AND tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
  2447. $rs = Database::query($sql);
  2448. if (Database::num_rows($rs) > 0) {
  2449. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2450. SET lastedit_type = '".str_replace('_', '', ucwords($tool))."Deleted',
  2451. lastedit_date = '$time',
  2452. lastedit_user_id = '$user_id',
  2453. visibility = '$visibility',
  2454. id_session = '$session_id' $set_type
  2455. WHERE $filter";
  2456. } else {
  2457. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2458. VALUES ($course_id, '$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value', '$visibility', '$start_visible','$end_visible', '$session_id')";
  2459. }
  2460. } else {
  2461. $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  2462. WHERE $filter";
  2463. }
  2464. break;
  2465. case 'visible' : // Change item to visible.
  2466. $visibility = '1';
  2467. if (!empty($session_id)) {
  2468. // Check whether session id already exist into itemp_properties for updating visibility or add it.
  2469. $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
  2470. $rs = Database::query($sql);
  2471. if (Database::num_rows($rs) > 0) {
  2472. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2473. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Visible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
  2474. WHERE $filter";
  2475. } else {
  2476. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2477. VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
  2478. }
  2479. } else {
  2480. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2481. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Visible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  2482. WHERE $filter";
  2483. }
  2484. break;
  2485. case 'invisible' : // Change item to invisible.
  2486. $visibility = '0';
  2487. if (!empty($session_id)) {
  2488. // Check whether session id already exist into itemp_properties for updating visibility or add it
  2489. $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
  2490. $rs = Database::query($sql);
  2491. if (Database::num_rows($rs) > 0) {
  2492. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2493. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Invisible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
  2494. WHERE $filter";
  2495. } else {
  2496. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2497. VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
  2498. }
  2499. } else {
  2500. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2501. SET lastedit_type='".str_replace('_', '', ucwords($tool))."Invisible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility' $set_type
  2502. WHERE $filter";
  2503. }
  2504. break;
  2505. default : // The item will be added or updated.
  2506. $set_type = ", lastedit_type='$lastedit_type' ";
  2507. $visibility = '1';
  2508. $filter .= $to_filter;
  2509. $sql = "UPDATE $TABLE_ITEMPROPERTY
  2510. SET lastedit_date='$time', lastedit_user_id='$user_id' $set_type
  2511. WHERE $filter";
  2512. }
  2513. $res = Database::query($sql);
  2514. // Insert if no entries are found (can only happen in case of $lastedit_type switch is 'default').
  2515. if (Database::affected_rows() == 0) {
  2516. $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool,ref,insert_date,insert_user_id,lastedit_date,lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
  2517. VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
  2518. $res = Database::query($sql);
  2519. if (!$res) {
  2520. return false;
  2521. }
  2522. }
  2523. return true;
  2524. }
  2525. /**
  2526. * Gets item property by tool
  2527. * @param string course code
  2528. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2529. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2530. */
  2531. function api_get_item_property_by_tool($tool, $course_code, $session_id = null) {
  2532. $course_info = api_get_course_info($course_code);
  2533. $tool = Database::escape_string($tool);
  2534. // Definition of tables.
  2535. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2536. $session_condition = '';
  2537. $session_id = intval($session_id);
  2538. $session_condition = ' AND id_session = '.$session_id;
  2539. $course_id = $course_info['real_id'];
  2540. $sql = "SELECT * FROM $item_property_table WHERE c_id = $course_id AND tool = '$tool' $session_condition ";
  2541. $rs = Database::query($sql);
  2542. $item_property_id = '';
  2543. $list = array();
  2544. if (Database::num_rows($rs) > 0) {
  2545. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  2546. $list[] = $row;
  2547. }
  2548. }
  2549. return $list;
  2550. }
  2551. /**
  2552. * Gets item property id from tool of a course
  2553. * @param string course code
  2554. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2555. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2556. */
  2557. function api_get_item_property_id($course_code, $tool, $ref) {
  2558. $course_info = api_get_course_info($course_code);
  2559. $tool = Database::escape_string($tool);
  2560. $ref = intval($ref);
  2561. // Definition of tables.
  2562. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2563. $course_id = $course_info['real_id'];
  2564. $sql = "SELECT id FROM $TABLE_ITEMPROPERTY WHERE c_id = $course_id AND tool = '$tool' AND ref = '$ref'";
  2565. $rs = Database::query($sql);
  2566. $item_property_id = '';
  2567. if (Database::num_rows($rs) > 0) {
  2568. $row = Database::fetch_array($rs);
  2569. $item_property_id = $row['id'];
  2570. }
  2571. return $item_property_id;
  2572. }
  2573. /**
  2574. *
  2575. * Inserts a record in the track_e_item_property table (No update)
  2576. *
  2577. */
  2578. function api_track_item_property_update($tool, $ref, $title, $content, $progress) {
  2579. $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  2580. $course_id = api_get_real_course_id(); //numeric
  2581. $course_code = api_get_course_id(); //alphanumeric
  2582. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  2583. if (!empty($item_property_id)) {
  2584. $sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
  2585. course_id = '$course_id',
  2586. item_property_id = '$item_property_id',
  2587. title = '".Database::escape_string($title)."',
  2588. content = '".Database::escape_string($content)."',
  2589. progress = '".intval($progress)."',
  2590. lastedit_date = '".api_get_utc_datetime()."',
  2591. lastedit_user_id = '".api_get_user_id()."',
  2592. session_id = '".api_get_session_id()."'";
  2593. Database::query($sql);
  2594. $affected_rows = Database::affected_rows();
  2595. return $affected_rows;
  2596. }
  2597. return false;
  2598. }
  2599. function api_get_track_item_property_history($tool, $ref) {
  2600. $tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  2601. $course_id = api_get_real_course_id(); //numeric
  2602. $course_code = api_get_course_id(); //alphanumeric
  2603. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  2604. $sql = "SELECT * FROM $tbl_stats_item_property WHERE item_property_id = $item_property_id AND course_id = $course_id ORDER BY lastedit_date DESC";
  2605. $result = Database::query($sql);
  2606. $result = Database::store_result($result,'ASSOC');
  2607. return $result;
  2608. }
  2609. /**
  2610. * Gets item property data from tool of a course id
  2611. * @param int course id
  2612. * @param string tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  2613. * @param int id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  2614. */
  2615. function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0) {
  2616. $course_info = api_get_course_info_by_id($course_id);
  2617. if (empty($course_info)) {
  2618. return false;
  2619. }
  2620. $tool = Database::escape_string($tool);
  2621. $ref = intval($ref);
  2622. $course_id = intval($course_id);
  2623. // Definition of tables.
  2624. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2625. $course_id = $course_info['real_id'];
  2626. $sql = "SELECT * FROM $TABLE_ITEMPROPERTY WHERE c_id = $course_id AND tool = '$tool' AND ref = $ref ";
  2627. if (!empty($session_id)) {
  2628. $session_id = intval($session_id);
  2629. $sql .= "AND id_session = $session_id ";
  2630. }
  2631. $rs = Database::query($sql);
  2632. $row = array();
  2633. if (Database::num_rows($rs) > 0) {
  2634. $row = Database::fetch_array($rs,'ASSOC');
  2635. }
  2636. return $row;
  2637. }
  2638. /* Language Dropdown */
  2639. /**
  2640. * Displays a combobox so the user can select his/her preferred language.
  2641. * @param string The desired name= value for the select
  2642. * @return string
  2643. */
  2644. function api_get_languages_combo($name = 'language') {
  2645. $ret = '';
  2646. $platformLanguage = api_get_setting('platformLanguage');
  2647. // Retrieve a complete list of all the languages.
  2648. $language_list = api_get_languages();
  2649. if (count($language_list['name']) < 2) {
  2650. return $ret;
  2651. }
  2652. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  2653. if (isset($_SESSION['user_language_choice'])) {
  2654. $default = $_SESSION['user_language_choice'];
  2655. } else {
  2656. $default = $platformLanguage;
  2657. }
  2658. $languages = $language_list['name'];
  2659. $folder = $language_list['folder'];
  2660. $ret .= '<select name="'.$name.'" id="language_chosen" class="chzn-select" >';
  2661. foreach ($languages as $key => $value) {
  2662. if ($folder[$key] == $default) {
  2663. $selected = ' selected="selected"';
  2664. } else {
  2665. $selected = '';
  2666. }
  2667. $ret .= sprintf('<option value=%s" %s>%s</option>', $folder[$key], $selected, $value);
  2668. }
  2669. $ret .= '</select>';
  2670. return $ret;
  2671. }
  2672. /**
  2673. * Displays a form (drop down menu) so the user can select his/her preferred language.
  2674. * The form works with or without javascript
  2675. * @param boolean Hide form if only one language available (defaults to false = show the box anyway)
  2676. * @return void Display the box directly
  2677. */
  2678. function api_display_language_form($hide_if_no_choice = false) {
  2679. // Retrieve a complete list of all the languages.
  2680. $language_list = api_get_languages();
  2681. if (count($language_list['name']) <= 1 && $hide_if_no_choice) {
  2682. return; //don't show any form
  2683. }
  2684. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  2685. if (isset($_SESSION['user_language_choice'])) {
  2686. $user_selected_language = $_SESSION['user_language_choice'];
  2687. }
  2688. if (empty($user_selected_language)) {
  2689. $user_selected_language = api_get_setting('platformLanguage');
  2690. }
  2691. $original_languages = $language_list['name'];
  2692. $folder = $language_list['folder']; // This line is probably no longer needed.
  2693. $html = '
  2694. <script type="text/javascript">
  2695. <!--
  2696. function jumpMenu(targ,selObj,restore){ // v3.0
  2697. eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
  2698. if (restore) selObj.selectedIndex=0;
  2699. }
  2700. //-->
  2701. </script>';
  2702. $html .= '<form id="lang_form" name="lang_form" method="post" action="'.api_get_self().'">';
  2703. $html .= '<select id="language_list" class="chzn-select" name="language_list" onchange="javascript: jumpMenu(\'parent\',this,0);">';
  2704. foreach ($original_languages as $key => $value) {
  2705. if ($folder[$key] == $user_selected_language) {
  2706. $option_end = ' selected="selected" >';
  2707. } else {
  2708. $option_end = '>';
  2709. }
  2710. $html .= '<option value="'.api_get_self().'?language='.$folder[$key].'"'.$option_end;
  2711. //echo substr($value, 0, 16); // Cut string to keep 800x600 aspect.
  2712. $html .= $value.'</option>';
  2713. }
  2714. $html .= '</select>';
  2715. $html .= '<noscript><input type="submit" name="user_select_language" value="'.get_lang('Ok').'" /></noscript>';
  2716. $html .= '</form>';
  2717. return $html;
  2718. }
  2719. /**
  2720. * Returns a list of all the languages that are made available by the admin.
  2721. * @return array An array with all languages. Structure of the array is
  2722. * array['name'] = An array with the name of every language
  2723. * array['folder'] = An array with the corresponding names of the language-folders in the filesystem
  2724. */
  2725. function api_get_languages() {
  2726. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  2727. $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  2728. $result = Database::query($sql);
  2729. while ($row = Database::fetch_array($result)) {
  2730. $language_list['name'][] = $row['original_name'];
  2731. $language_list['folder'][] = $row['dokeos_folder'];
  2732. }
  2733. return $language_list;
  2734. }
  2735. /**
  2736. * Returns the id (the database id) of a language
  2737. * @param string language name (the corresponding name of the language-folder in the filesystem)
  2738. * @return int id of the language
  2739. */
  2740. function api_get_language_id($language) {
  2741. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  2742. if (empty($language)) {
  2743. return null;
  2744. }
  2745. $language = Database::escape_string($language);
  2746. $sql = "SELECT id FROM $tbl_language WHERE available='1' AND dokeos_folder = '$language' LIMIT 1";
  2747. $result = Database::query($sql);
  2748. $row = Database::fetch_array($result);
  2749. return $row['id'];
  2750. }
  2751. /**
  2752. * Gets language of the requested type for the current user. Types are :
  2753. * user_profil_lang : profile language of current user
  2754. * user_select_lang : language selected by user at login
  2755. * course_lang : language of the current course
  2756. * platform_lang : default platform language
  2757. * @param string lang_type
  2758. * @param return language of the requested type or false if the language is not available
  2759. **/
  2760. function api_get_language_from_type($lang_type){
  2761. global $_user;
  2762. global $_course;
  2763. $toreturn = false;
  2764. switch ($lang_type) {
  2765. case 'platform_lang' :
  2766. $temp_lang = api_get_setting('platformLanguage');
  2767. if (!empty($temp_lang))
  2768. $toreturn = $temp_lang;
  2769. break;
  2770. case 'user_profil_lang' :
  2771. if (isset($_user['language']) && !empty($_user['language']) )
  2772. $toreturn = $_user['language'];
  2773. break;
  2774. case 'user_selected_lang' :
  2775. if (isset($_SESSION['user_language_choice']) && !empty($_SESSION['user_language_choice']) )
  2776. $toreturn = ($_SESSION['user_language_choice']);
  2777. break;
  2778. case 'course_lang' :
  2779. if ($_course['language'] && !empty($_course['language']) )
  2780. $toreturn = $_course['language'];
  2781. break;
  2782. default :
  2783. $toreturn = false;
  2784. break;
  2785. }
  2786. return $toreturn;
  2787. }
  2788. function api_get_language_info($language_id) {
  2789. $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
  2790. $sql = 'SELECT * FROM '.$tbl_admin_languages.' WHERE id = "'.intval($language_id).'"';
  2791. $rs = Database::query($sql);
  2792. $language_info = array();
  2793. if (Database::num_rows($rs)) {
  2794. $language_info = Database::fetch_array($rs,'ASSOC');
  2795. }
  2796. return $language_info;
  2797. }
  2798. /**
  2799. * Returns the name of the visual (CSS) theme to be applied on the current page.
  2800. * The returned name depends on the platform, course or user -wide settings.
  2801. * @return string The visual theme's name, it is the name of a folder inside .../chamilo/main/css/
  2802. */
  2803. function api_get_visual_theme() {
  2804. static $visual_theme;
  2805. if (!isset($visual_theme)) {
  2806. $platform_theme = api_get_setting('stylesheets'); // Plataform's theme.
  2807. $visual_theme = $platform_theme;
  2808. if (api_get_setting('user_selected_theme') == 'true') {
  2809. $user_info = api_get_user_info();
  2810. $user_theme = $user_info['theme'];
  2811. if (!empty($user_theme)) {
  2812. $visual_theme = $user_theme; // User's theme.
  2813. }
  2814. }
  2815. $course_id = api_get_course_id();
  2816. if (!empty($course_id) && $course_id != -1) {
  2817. if (api_get_setting('allow_course_theme') == 'true') {
  2818. $course_theme = api_get_course_setting('course_theme');
  2819. if (!empty($course_theme) && $course_theme != -1) {
  2820. if (!empty($course_theme)) {
  2821. $visual_theme = $course_theme; // Course's theme.
  2822. }
  2823. }
  2824. $allow_lp_theme = api_get_course_setting('allow_learning_path_theme');
  2825. if ($allow_lp_theme == 1) {
  2826. global $lp_theme_css, $lp_theme_config; // These variables come from the file lp_controller.php.
  2827. if (!$lp_theme_config) {
  2828. if (!empty($lp_theme_css)) {
  2829. $visual_theme = $lp_theme_css; // LP's theme.
  2830. }
  2831. }
  2832. }
  2833. }
  2834. }
  2835. if (empty($visual_theme)) {
  2836. $visual_theme = 'chamilo';
  2837. }
  2838. global $lp_theme_log;
  2839. if ($lp_theme_log) {
  2840. $visual_theme = $platform_theme;
  2841. }
  2842. }
  2843. return $visual_theme;
  2844. }
  2845. /**
  2846. * Returns a list of CSS themes currently available in the CSS folder
  2847. * @return array List of themes directories from the css folder
  2848. * Note: Directory names (names of themes) in the file system should contain ASCII-characters only.
  2849. */
  2850. function api_get_themes() {
  2851. $cssdir = api_get_path(SYS_PATH).'main/css/';
  2852. $list_dir = array();
  2853. $list_name = array();
  2854. if (@is_dir($cssdir)) {
  2855. $themes = @scandir($cssdir);
  2856. if (is_array($themes)) {
  2857. if ($themes !== false) {
  2858. sort($themes);
  2859. foreach ($themes as & $theme) {
  2860. if (substr($theme, 0, 1) == '.') {
  2861. continue;
  2862. } else {
  2863. if (@is_dir($cssdir.$theme)) {
  2864. $list_dir[] = $theme;
  2865. $list_name[] = ucwords(str_replace('_', ' ', $theme));
  2866. }
  2867. }
  2868. }
  2869. }
  2870. }
  2871. }
  2872. return array($list_dir, $list_name);
  2873. }
  2874. /* WYSIWYG EDITOR
  2875. Functions for the WYSIWYG html editor.
  2876. Please, try to avoid using the following two functions. The preferable way to put
  2877. an editor's instance on a page is through using a FormValidator's class method. */
  2878. /**
  2879. * Displays the WYSIWYG editor for online editing of html
  2880. * @param string $name The name of the form-element
  2881. * @param string $content The default content of the html-editor
  2882. * @param int $height The height of the form element
  2883. * @param int $width The width of the form element
  2884. * @param string $attributes (optional) attributes for the form element
  2885. * @param array $editor_config (optional) Configuration options for the html-editor
  2886. */
  2887. function api_disp_html_area($name, $content = '', $height = '', $width = '100%', $attributes = null, $editor_config = null) {
  2888. global $_configuration, $_course, $fck_attribute;
  2889. require_once api_get_path(LIBRARY_PATH).'formvalidator/Element/html_editor.php';
  2890. $editor = new HTML_QuickForm_html_editor($name, null, $attributes, $editor_config);
  2891. $editor->setValue($content);
  2892. // The global variable $fck_attribute has been deprecated. It stays here for supporting old external code.
  2893. if( $height != '') {
  2894. $fck_attribute['Height'] = $height;
  2895. }
  2896. if( $width != '') {
  2897. $fck_attribute['Width'] = $width;
  2898. }
  2899. echo $editor->toHtml();
  2900. }
  2901. /**
  2902. * Returns generated html for showing the WYSIWYG editor on the page
  2903. * @param string $name The name of the form-element
  2904. * @param string $content The default content of the html-editor
  2905. * @param int $height The height of the form element
  2906. * @param int $width The width of the form element
  2907. * @param string $attributes (optional) attributes for the form element
  2908. * @param array $editor_config (optional) Configuration options for the html-editor
  2909. */
  2910. function api_return_html_area($name, $content = '', $height = '', $width = '100%', $attributes = null, $editor_config = null) {
  2911. global $_configuration, $_course, $fck_attribute;
  2912. require_once api_get_path(LIBRARY_PATH).'formvalidator/Element/html_editor.php';
  2913. $editor = new HTML_QuickForm_html_editor($name, null, $attributes, $editor_config);
  2914. $editor->setValue($content);
  2915. // The global variable $fck_attribute has been deprecated. It stays here for supporting old external code.
  2916. if ($height != '') {
  2917. $fck_attribute['Height'] = $height;
  2918. }
  2919. if ($width != '') {
  2920. $fck_attribute['Width'] = $width;
  2921. }
  2922. return $editor->toHtml();
  2923. }
  2924. /**
  2925. * Find the largest sort value in a given user_course_category
  2926. * This function is used when we are moving a course to a different category
  2927. * and also when a user subscribes to courses (the new course is added at the end of the main category
  2928. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2929. * @param int $user_course_category: the id of the user_course_category
  2930. * @return int the value of the highest sort of the user_course_category
  2931. */
  2932. function api_max_sort_value($user_course_category, $user_id) {
  2933. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2934. $sql_max = "SELECT max(sort) as max_sort FROM $tbl_course_user WHERE user_id='".intval($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND user_course_cat='".Database::escape_string($user_course_category)."'";
  2935. $result_max = Database::query($sql_max);
  2936. if (Database::num_rows($result_max) == 1) {
  2937. $row_max = Database::fetch_array($result_max);
  2938. return $row_max['max_sort'];
  2939. }
  2940. return 0;
  2941. }
  2942. /**
  2943. * This function converts the string "true" or "false" to a boolean true or false.
  2944. * This function is in the first place written for the Chamilo Config Settings (also named AWACS)
  2945. * @param string "true" or "false"
  2946. * @return boolean true or false
  2947. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2948. */
  2949. function string_2_boolean($string) {
  2950. if ($string == 'true') {
  2951. return true;
  2952. }
  2953. if ($string == 'false') {
  2954. return false;
  2955. }
  2956. return false;
  2957. }
  2958. /**
  2959. * Determines the number of plugins installed for a given location
  2960. */
  2961. function api_number_of_plugins($location) {
  2962. global $_plugins;
  2963. return isset($_plugins[$location]) && is_array($_plugins[$location]) ? count($_plugins[$location]) : 0;
  2964. }
  2965. /**
  2966. * Including the necessary plugins.
  2967. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2968. */
  2969. function api_plugin($location) {
  2970. global $_plugins;
  2971. if (isset($_plugins[$location]) && is_array($_plugins[$location])) {
  2972. foreach ($_plugins[$location] as $this_plugin) {
  2973. include api_get_path(SYS_PLUGIN_PATH)."$this_plugin/index.php";
  2974. }
  2975. }
  2976. }
  2977. /**
  2978. * Checks to see wether a certain plugin is installed.
  2979. * @return boolean true if the plugin is installed, false otherwise.
  2980. */
  2981. function api_is_plugin_installed($plugin_list, $plugin_name) {
  2982. if(is_array($plugin_list)) {
  2983. foreach ($plugin_list as $plugin_location) {
  2984. if (array_search($plugin_name, $plugin_location) !== false) { return true; }
  2985. }
  2986. }
  2987. return false;
  2988. }
  2989. /**
  2990. * Transforms a number of seconds in hh:mm:ss format
  2991. * @author Julian Prud'homme
  2992. * @param integer the number of seconds
  2993. * @return string the formated time
  2994. */
  2995. function api_time_to_hms($seconds) {
  2996. // $seconds = -1 means that we have wrong data in the db.
  2997. if ($seconds == -1) {
  2998. return get_lang('Unknown').Display::return_icon('info2.gif', get_lang('WrongDatasForTimeSpentOnThePlatform'), array('align' => 'absmiddle', 'hspace' => '3px'));
  2999. }
  3000. // How many hours ?
  3001. $hours = floor($seconds / 3600);
  3002. // How many minutes ?
  3003. $min = floor(($seconds - ($hours * 3600)) / 60);
  3004. // How many seconds
  3005. $sec = floor($seconds - ($hours * 3600) - ($min * 60));
  3006. if ($sec < 10) {
  3007. $sec = "0$sec";
  3008. }
  3009. if ($min < 10) {
  3010. $min = "0$min";
  3011. }
  3012. return "$hours:$min:$sec";
  3013. }
  3014. /* FILE SYSTEM RELATED FUNCTIONS */
  3015. /**
  3016. * Returns the permissions to be assigned to every newly created directory by the web-server.
  3017. * The returnd value is based on the platform administrator's setting "Administration > Configuration settings > Security > Permissions for new directories".
  3018. * @return int Returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value.
  3019. */
  3020. function api_get_permissions_for_new_directories() {
  3021. static $permissions;
  3022. if (!isset($permissions)) {
  3023. $permissions = trim(api_get_setting('permissions_for_new_directories'));
  3024. // The default value 0777 is according to that in the platform administration panel after fresh system installation.
  3025. $permissions = octdec(!empty($permissions) ? $permissions : '0777');
  3026. }
  3027. return $permissions;
  3028. }
  3029. /**
  3030. * Returns the permissions to be assigned to every newly created directory by the web-server.
  3031. * The returnd value is based on the platform administrator's setting "Administration > Configuration settings > Security > Permissions for new files".
  3032. * @return int Returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value.
  3033. */
  3034. function api_get_permissions_for_new_files() {
  3035. static $permissions;
  3036. if (!isset($permissions)) {
  3037. $permissions = trim(api_get_setting('permissions_for_new_files'));
  3038. // The default value 0666 is according to that in the platform administration panel after fresh system installation.
  3039. $permissions = octdec(!empty($permissions) ? $permissions : '0666');
  3040. }
  3041. return $permissions;
  3042. }
  3043. /**
  3044. * sys_get_temp_dir() was introduced as of PHP 5.2.1
  3045. * For older PHP versions the following implementation is to be activated.
  3046. * @link Based on http://www.phpit.net/article/creating-zip-tar-archives-dynamically-php/2/
  3047. */
  3048. if (!function_exists('sys_get_temp_dir')) {
  3049. function sys_get_temp_dir() {
  3050. // Try to get from environment variable.
  3051. if (!empty($_ENV['TMP'])) {
  3052. return realpath($_ENV['TMP']);
  3053. }
  3054. if (!empty($_ENV['TMPDIR'])) {
  3055. return realpath($_ENV['TMPDIR']);
  3056. }
  3057. if (!empty($_ENV['TEMP'])) {
  3058. return realpath($_ENV['TEMP']);
  3059. }
  3060. // Detect by creating a temporary file.
  3061. // Try to use system's temporary directory
  3062. // as random name shouldn't exist.
  3063. $temp_file = tempnam(md5(uniqid(rand(), true)), '');
  3064. if ($temp_file) {
  3065. $temp_dir = realpath(dirname($temp_file));
  3066. @unlink( $temp_file );
  3067. return $temp_dir;
  3068. }
  3069. return false;
  3070. }
  3071. }
  3072. /**
  3073. * Deletes a file, or a folder and its contents
  3074. *
  3075. * @author Aidan Lister <aidan@php.net>
  3076. * @version 1.0.3
  3077. * @param string $dirname Directory to delete
  3078. * @param bool Deletes only the content or not
  3079. * @return bool Returns TRUE on success, FALSE on failure
  3080. * @link http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
  3081. * @author Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
  3082. * @author Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
  3083. */
  3084. function rmdirr($dirname, $delete_only_content_in_folder = false) {
  3085. $res = true;
  3086. // A sanity check.
  3087. if (!file_exists($dirname)) {
  3088. return false;
  3089. }
  3090. $php_errormsg = '';
  3091. // Simple delete for a file.
  3092. if (is_file($dirname) || is_link($dirname)) {
  3093. $res = unlink($dirname);
  3094. if ($res === false) {
  3095. 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);
  3096. }
  3097. return $res;
  3098. }
  3099. // Loop through the folder.
  3100. $dir = dir($dirname);
  3101. // A sanity check.
  3102. $is_object_dir = is_object($dir);
  3103. if ($is_object_dir) {
  3104. while (false !== $entry = $dir->read()) {
  3105. // Skip pointers.
  3106. if ($entry == '.' || $entry == '..') {
  3107. continue;
  3108. }
  3109. // Recurse.
  3110. rmdirr("$dirname/$entry");
  3111. }
  3112. }
  3113. // Clean up.
  3114. if ($is_object_dir) {
  3115. $dir->close();
  3116. }
  3117. if ($delete_only_content_in_folder == false) {
  3118. $res = rmdir($dirname);
  3119. if ($res === false) {
  3120. 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);
  3121. }
  3122. }
  3123. return $res;
  3124. }
  3125. // TODO: This function is to be simplified. File access modes to be implemented.
  3126. /**
  3127. * function adapted from a php.net comment
  3128. * copy recursively a folder
  3129. * @param the source folder
  3130. * @param the dest folder
  3131. * @param an array of excluded file_name (without extension)
  3132. * @param copied_files the returned array of copied files
  3133. */
  3134. function copyr($source, $dest, $exclude = array(), $copied_files = array()) {
  3135. if (empty($dest)) { return false; }
  3136. // Simple copy for a file
  3137. if (is_file($source)) {
  3138. $path_info = pathinfo($source);
  3139. if (!in_array($path_info['filename'], $exclude)) {
  3140. copy($source, $dest);
  3141. }
  3142. return true;
  3143. } elseif (!is_dir($source)) {
  3144. //then source is not a dir nor a file, return
  3145. return false;
  3146. }
  3147. // Make destination directory.
  3148. if (!is_dir($dest)) {
  3149. mkdir($dest, api_get_permissions_for_new_directories());
  3150. }
  3151. // Loop through the folder.
  3152. $dir = dir($source);
  3153. while (false !== $entry = $dir->read()) {
  3154. // Skip pointers
  3155. if ($entry == '.' || $entry == '..') {
  3156. continue;
  3157. }
  3158. // Deep copy directories.
  3159. if ($dest !== "$source/$entry") {
  3160. $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
  3161. }
  3162. }
  3163. // Clean up.
  3164. $dir->close();
  3165. return true;
  3166. }
  3167. // TODO: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach. Documentation header to be added here.
  3168. function copy_folder_course_session($pathname, $base_path_document, $session_id, $course_info, $document) {
  3169. $table = Database :: get_course_table(TABLE_DOCUMENT);
  3170. $session_id = intval($session_id);
  3171. // Check whether directory already exists.
  3172. if (is_dir($pathname) || empty($pathname)) {
  3173. return true;
  3174. }
  3175. // Ensure that a file with the same name does not already exist.
  3176. if (is_file($pathname)) {
  3177. trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
  3178. return false;
  3179. }
  3180. $course_id = $course_info['real_id'];
  3181. $folders = explode(DIRECTORY_SEPARATOR,str_replace($base_path_document.DIRECTORY_SEPARATOR,'',$pathname));
  3182. $new_pathname = $base_path_document;
  3183. $path = '';
  3184. foreach ($folders as $folder) {
  3185. $new_pathname .= DIRECTORY_SEPARATOR.$folder;
  3186. $path .= DIRECTORY_SEPARATOR.$folder;
  3187. if (!file_exists($new_pathname)) {
  3188. $path = Database::escape_string($path);
  3189. $sql = "SELECT * FROM $table WHERE path = '$path' AND filetype = 'folder' AND session_id = '$session_id'";
  3190. $rs1 = Database::query($sql);
  3191. $num_rows = Database::num_rows($rs1);
  3192. if ($num_rows == 0) {
  3193. mkdir($new_pathname, api_get_permissions_for_new_directories());
  3194. // Insert new folder with destination session_id.
  3195. $sql = "INSERT INTO ".$table." SET
  3196. c_id = $course_id,
  3197. path = '$path',
  3198. comment = '".Database::escape_string($document->comment)."',
  3199. title = '".Database::escape_string(basename($new_pathname))."' ,
  3200. filetype='folder',
  3201. size= '0',
  3202. session_id = '$session_id'";
  3203. Database::query($sql);
  3204. $document_id = Database::insert_id();
  3205. api_item_property_update($course_info,TOOL_DOCUMENT,$document_id,'FolderCreated',api_get_user_id(),0,0,null,null,$session_id);
  3206. }
  3207. }
  3208. } // en foreach
  3209. }
  3210. // TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
  3211. function api_chmod_R($path, $filemode) {
  3212. if (!is_dir($path)) {
  3213. return chmod($path, $filemode);
  3214. }
  3215. $handler = opendir($path);
  3216. while ($file = readdir($handler)) {
  3217. if ($file != '.' && $file != '..') {
  3218. $fullpath = "$path/$file";
  3219. if (!is_dir($fullpath)) {
  3220. if (!chmod($fullpath, $filemode)) {
  3221. return false;
  3222. }
  3223. } else {
  3224. if (!api_chmod_R($fullpath, $filemode)) {
  3225. return false;
  3226. }
  3227. }
  3228. }
  3229. }
  3230. closedir($handler);
  3231. return chmod($path, $filemode);
  3232. }
  3233. // TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
  3234. /**
  3235. * Parse info file format. (e.g: file.info)
  3236. *
  3237. * Files should use an ini-like format to specify values.
  3238. * White-space generally doesn't matter, except inside values.
  3239. * e.g.
  3240. *
  3241. * @verbatim
  3242. * key = value
  3243. * key = "value"
  3244. * key = 'value'
  3245. * key = "multi-line
  3246. *
  3247. * value"
  3248. * key = 'multi-line
  3249. *
  3250. * value'
  3251. * key
  3252. * =
  3253. * 'value'
  3254. * @endverbatim
  3255. *
  3256. * Arrays are created using a GET-like syntax:
  3257. *
  3258. * @verbatim
  3259. * key[] = "numeric array"
  3260. * key[index] = "associative array"
  3261. * key[index][] = "nested numeric array"
  3262. * key[index][index] = "nested associative array"
  3263. * @endverbatim
  3264. *
  3265. * PHP constants are substituted in, but only when used as the entire value:
  3266. *
  3267. * Comments should start with a semi-colon at the beginning of a line.
  3268. *
  3269. * This function is NOT for placing arbitrary module-specific settings. Use
  3270. * variable_get() and variable_set() for that.
  3271. *
  3272. * Information stored in the module.info file:
  3273. * - name: The real name of the module for display purposes.
  3274. * - description: A brief description of the module.
  3275. * - dependencies: An array of shortnames of other modules this module depends on.
  3276. * - package: The name of the package of modules this module belongs to.
  3277. *
  3278. * Example of .info file:
  3279. * <code>
  3280. * @verbatim
  3281. * name = Forum
  3282. * description = Enables threaded discussions about general topics.
  3283. * dependencies[] = taxonomy
  3284. * dependencies[] = comment
  3285. * package = Core - optional
  3286. * version = VERSION
  3287. * @endverbatim
  3288. * </code>
  3289. * @param $filename
  3290. * The file we are parsing. Accepts file with relative or absolute path.
  3291. * @return
  3292. * The info array.
  3293. */
  3294. function parse_info_file($filename) {
  3295. $info = array();
  3296. if (!file_exists($filename)) {
  3297. return $info;
  3298. }
  3299. $data = file_get_contents($filename);
  3300. if (preg_match_all('
  3301. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  3302. ((?:
  3303. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  3304. \[[^\[\]]*\] # unless they are balanced and not nested
  3305. )+?)
  3306. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  3307. (?:
  3308. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  3309. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  3310. ([^\r\n]*?) # Non-quoted string
  3311. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  3312. @msx', $data, $matches, PREG_SET_ORDER)) {
  3313. $key = $value1 = $value2 = $value3 = '';
  3314. foreach ($matches as $match) {
  3315. // Fetch the key and value string.
  3316. $i = 0;
  3317. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  3318. $$var = isset($match[++$i]) ? $match[$i] : '';
  3319. }
  3320. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  3321. // Parse array syntax.
  3322. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  3323. $last = array_pop($keys);
  3324. $parent = &$info;
  3325. // Create nested arrays.
  3326. foreach ($keys as $key) {
  3327. if ($key == '') {
  3328. $key = count($parent);
  3329. }
  3330. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  3331. $parent[$key] = array();
  3332. }
  3333. $parent = &$parent[$key];
  3334. }
  3335. // Handle PHP constants.
  3336. if (defined($value)) {
  3337. $value = constant($value);
  3338. }
  3339. // Insert actual value.
  3340. if ($last == '') {
  3341. $last = count($parent);
  3342. }
  3343. $parent[$last] = $value;
  3344. }
  3345. }
  3346. return $info;
  3347. }
  3348. /**
  3349. * Gets Chamilo version from the configuration files
  3350. * @return string A string of type "1.8.4", or an empty string if the version could not be found
  3351. */
  3352. function api_get_version() {
  3353. global $_configuration;
  3354. return (string)$_configuration['system_version'];
  3355. }
  3356. /**
  3357. * Gets the software name (the name/brand of the Chamilo-based customized system)
  3358. * @return string
  3359. */
  3360. function api_get_software_name() {
  3361. global $_configuration;
  3362. if (isset($_configuration['software_name']) && !empty($_configuration['software_name'])) {
  3363. return $_configuration['software_name'];
  3364. } else {
  3365. return 'Chamilo';
  3366. }
  3367. }
  3368. /**
  3369. * Checks whether status given in parameter exists in the platform
  3370. * @param mixed the status (can be either int either string)
  3371. * @return true if the status exists, else returns false
  3372. */
  3373. function api_status_exists($status_asked) {
  3374. global $_status_list;
  3375. return in_array($status_asked, $_status_list) ? true : isset($_status_list[$status_asked]);
  3376. }
  3377. /**
  3378. * Checks whether status given in parameter exists in the platform. The function
  3379. * returns the status ID or false if it does not exist, but given the fact there
  3380. * is no "0" status, the return value can be checked against
  3381. * if(api_status_key()) to know if it exists.
  3382. * @param mixed The status (can be either int or string)
  3383. * @return mixed Status ID if exists, false otherwise
  3384. */
  3385. function api_status_key($status) {
  3386. global $_status_list;
  3387. return isset($_status_list[$status]) ? $status : array_search($status, $_status_list);
  3388. }
  3389. /**
  3390. * Gets the status langvars list
  3391. * @return array the list of status with their translations
  3392. */
  3393. function api_get_status_langvars() {
  3394. return array(
  3395. COURSEMANAGER => get_lang('Teacher', ''),
  3396. SESSIONADMIN => get_lang('SessionsAdmin', ''),
  3397. DRH => get_lang('Drh', ''),
  3398. STUDENT => get_lang('Student', ''),
  3399. ANONYMOUS => get_lang('Anonymous', '')
  3400. );
  3401. }
  3402. /**
  3403. * The function that retrieves all the possible settings for a certain config setting
  3404. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3405. */
  3406. function api_get_settings_options($var) {
  3407. $table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  3408. $sql = "SELECT * FROM $table_settings_options WHERE variable = '$var' ORDER BY id";
  3409. $result = Database::query($sql);
  3410. $settings_options_array = array();
  3411. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3412. //$temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
  3413. $settings_options_array[] = $row;
  3414. }
  3415. return $settings_options_array;
  3416. }
  3417. function api_set_setting_option($params) {
  3418. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  3419. if (empty($params['id'])) {
  3420. Database::insert($table, $params);
  3421. } else {
  3422. Database::update($table, $params, array('id = ? '=> $params['id']));
  3423. }
  3424. }
  3425. function api_delete_setting_option($id) {
  3426. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  3427. if (!empty($id)) {
  3428. Database::delete($table, array('id = ? '=> $id));
  3429. }
  3430. }
  3431. /**
  3432. * Sets a platform configuration setting to a given value
  3433. * @param string The variable we want to update
  3434. * @param string The value we want to record
  3435. * @param string The sub-variable if any (in most cases, this will remain null)
  3436. * @param string The category if any (in most cases, this will remain null)
  3437. * @param int The access_url for which this parameter is valid
  3438. */
  3439. function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1) {
  3440. if (empty($var)) { return false; }
  3441. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3442. $var = Database::escape_string($var);
  3443. $value = Database::escape_string($value);
  3444. $access_url = (int)$access_url;
  3445. if (empty($access_url)) { $access_url = 1; }
  3446. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  3447. if (!empty($subvar)) {
  3448. $subvar = Database::escape_string($subvar);
  3449. $select .= " AND subkey = '$subvar'";
  3450. }
  3451. if (!empty($cat)) {
  3452. $cat = Database::escape_string($cat);
  3453. $select .= " AND category = '$cat'";
  3454. }
  3455. if ($access_url > 1) {
  3456. $select .= " AND access_url = $access_url";
  3457. } else {
  3458. $select .= " AND access_url = 1 ";
  3459. }
  3460. $res = Database::query($select);
  3461. if (Database::num_rows($res) > 0) {
  3462. // Found item for this access_url.
  3463. $row = Database::fetch_array($res);
  3464. $update = "UPDATE $t_settings SET selected_value = '$value' WHERE id = ".$row['id'] ;
  3465. $res = Database::query($update);
  3466. } else {
  3467. // Item not found for this access_url, we have to check if it exist with access_url = 1
  3468. $select = "SELECT * FROM $t_settings WHERE variable = '$var' AND access_url = 1 ";
  3469. // Just in case
  3470. if ($access_url == 1) {
  3471. if (!empty($subvar)) {
  3472. $select .= " AND subkey = '$subvar'";
  3473. }
  3474. if (!empty($cat)) {
  3475. $select .= " AND category = '$cat'";
  3476. }
  3477. $res = Database::query($select);
  3478. if (Database::num_rows($res) > 0) { // We have a setting for access_url 1, but none for the current one, so create one.
  3479. $row = Database::fetch_array($res);
  3480. $insert = "INSERT INTO $t_settings " .
  3481. "(variable,subkey," .
  3482. "type,category," .
  3483. "selected_value,title," .
  3484. "comment,scope," .
  3485. "subkeytext,access_url)" .
  3486. " VALUES " .
  3487. "('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," .
  3488. "'".$row['type']."','".$row['category']."'," .
  3489. "'$value','".$row['title']."'," .
  3490. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," .
  3491. "".(!empty($row['subkeytext'])?"'".$row['subkeytext']."'":"NULL").",$access_url)";
  3492. $res = Database::query($insert);
  3493. } else { // Such a setting does not exist.
  3494. error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
  3495. }
  3496. } else {
  3497. // Other access url.
  3498. if (!empty($subvar)) {
  3499. $select .= " AND subkey = '$subvar'";
  3500. }
  3501. if (!empty($cat)) {
  3502. $select .= " AND category = '$cat'";
  3503. }
  3504. $res = Database::query($select);
  3505. if (Database::num_rows($res) > 0) { // We have a setting for access_url 1, but none for the current one, so create one.
  3506. $row = Database::fetch_array($res);
  3507. if ($row['access_url_changeable'] == 1) {
  3508. $insert = "INSERT INTO $t_settings " .
  3509. "(variable,subkey," .
  3510. "type,category," .
  3511. "selected_value,title," .
  3512. "comment,scope," .
  3513. "subkeytext,access_url, access_url_changeable)" .
  3514. " VALUES " .
  3515. "('".$row['variable']."',".
  3516. (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," .
  3517. "'".$row['type']."','".$row['category']."'," .
  3518. "'$value','".$row['title']."'," .
  3519. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
  3520. (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," .
  3521. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
  3522. $res = Database::query($insert);
  3523. }
  3524. } else { // Such a setting does not exist.
  3525. error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
  3526. }
  3527. }
  3528. }
  3529. }
  3530. /**
  3531. * Sets a whole category of settings to one specific value
  3532. * @param string Category
  3533. * @param string Value
  3534. * @param int Access URL. Optional. Defaults to 1
  3535. * @param array Optional array of filters on field type
  3536. */
  3537. function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = array()) {
  3538. if (empty($category)) { return false; }
  3539. $category = Database::escape_string($category);
  3540. $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3541. $access_url = (int) $access_url;
  3542. if (empty($access_url)) { $access_url = 1; }
  3543. if (isset($value)) {
  3544. $value = Database::escape_string($value);
  3545. $sql = "UPDATE $t_s SET selected_value = '$value' WHERE category = '$category' AND access_url = $access_url";
  3546. if (is_array($fieldtype) && count($fieldtype)>0) {
  3547. $sql .= " AND ( ";
  3548. $i = 0;
  3549. foreach ($fieldtype as $type){
  3550. if ($i > 0) {
  3551. $sql .= ' OR ';
  3552. }
  3553. $type = Database::escape_string($type);
  3554. $sql .= " type='".$type."' ";
  3555. $i++;
  3556. }
  3557. $sql .= ")";
  3558. }
  3559. $res = Database::query($sql);
  3560. return $res !== false;
  3561. } else {
  3562. $sql = "UPDATE $t_s SET selected_value = NULL WHERE category = '$category' AND access_url = $access_url";
  3563. if (is_array($fieldtype) && count($fieldtype)>0) {
  3564. $sql .= " AND ( ";
  3565. $i = 0;
  3566. foreach ($fieldtype as $type){
  3567. if ($i > 0) {
  3568. $sql .= ' OR ';
  3569. }
  3570. $type = Database::escape_string($type);
  3571. $sql .= " type='".$type."' ";
  3572. $i++;
  3573. }
  3574. $sql .= ")";
  3575. }
  3576. $res = Database::query($sql);
  3577. return $res !== false;
  3578. }
  3579. }
  3580. /**
  3581. * Gets all available access urls in an array (as in the database)
  3582. * @return array An array of database records
  3583. */
  3584. function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC') {
  3585. $t_au = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  3586. $from = (int) $from;
  3587. $to = (int) $to;
  3588. $order = Database::escape_string($order);
  3589. $direction = Database::escape_string($direction);
  3590. $sql = "SELECT id, url, description, active, created_by, tms FROM $t_au ORDER BY $order $direction LIMIT $to OFFSET $from";
  3591. $res = Database::query($sql);
  3592. return Database::store_result($res);
  3593. }
  3594. /**
  3595. * Gets the access url info in an array
  3596. * @param id of the access url
  3597. * @return array Array with all the info (url, description, active, created_by, tms) from the access_url table
  3598. * @author Julio Montoya Armas
  3599. */
  3600. function api_get_access_url($id) {
  3601. global $_configuration;
  3602. $id = Database::escape_string(intval($id));
  3603. // Calling the Database:: library dont work this is handmade.
  3604. //$table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  3605. $table = 'access_url';
  3606. $database = $_configuration['main_database'];
  3607. $table_access_url = "".$database.".".$table."";
  3608. $sql = "SELECT url, description, active, created_by, tms
  3609. FROM $table_access_url WHERE id = '$id' ";
  3610. $res = Database::query($sql);
  3611. $result = @Database::fetch_array($res);
  3612. return $result;
  3613. }
  3614. /**
  3615. * Adds an access URL into the database
  3616. * @param string URL
  3617. * @param string Description
  3618. * @param int Active (1= active, 0=disabled)
  3619. * @return int The new database id, or the existing database id if this url already exists
  3620. */
  3621. function api_add_access_url($u, $d = '', $a = 1) {
  3622. $t_au = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  3623. $u = Database::escape_string($u);
  3624. $d = Database::escape_string($d);
  3625. $a = (int) $a;
  3626. $sql = "SELECT id FROM $t_au WHERE url LIKE '$u'";
  3627. $res = Database::query($sql);
  3628. if ($res === false) {
  3629. // Problem querying the database - return false.
  3630. return false;
  3631. }
  3632. if (Database::num_rows($res) > 0) {
  3633. return Database::result($res, 0, 'id');
  3634. }
  3635. $ui = api_get_user_id();
  3636. $sql = "INSERT INTO $t_au (url,description,active,created_by,tms) VALUES ('$u','$d',$a,$ui,'')";
  3637. $res = Database::query($sql);
  3638. return ($res === false) ? false : Database::insert_id();
  3639. }
  3640. /**
  3641. * Gets all the current settings for a specific access url
  3642. * @param string The category, if any, that we want to get
  3643. * @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'
  3644. * @param int Access URL's ID. Optional. Uses 1 by default, which is the unique URL
  3645. * @return array Array of database results for the current settings of the current access URL
  3646. */
  3647. function & api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0) {
  3648. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3649. $access_url = (int) $access_url;
  3650. $url_changeable_where = '';
  3651. if ($url_changeable == 1) {
  3652. $url_changeable_where= " AND access_url_changeable= '1' ";
  3653. }
  3654. if (empty($access_url) or $access_url == -1) { $access_url = 1; }
  3655. $sql = "SELECT id, variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable " .
  3656. " FROM $t_cs WHERE access_url = $access_url $url_changeable_where ";
  3657. if (!empty($cat)) {
  3658. $cat = Database::escape_string($cat);
  3659. $sql .= " AND category='$cat' ";
  3660. }
  3661. if ($ordering == 'group') {
  3662. $sql .= " GROUP BY variable ORDER BY id ASC";
  3663. } else {
  3664. $sql .= " ORDER BY 1,2 ASC";
  3665. }
  3666. $result = Database::store_result(Database::query($sql));
  3667. return $result;
  3668. }
  3669. /**
  3670. * Gets the distinct settings categories
  3671. * @param array Array of strings giving the categories we want to exclude
  3672. * @param int Access URL. Optional. Defaults to 1
  3673. * @return array A list of categories
  3674. */
  3675. function & api_get_settings_categories($exceptions = array(), $access_url = 1) {
  3676. $access_url = (int) $access_url;
  3677. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3678. $list = "'".implode("','",$exceptions)."'";
  3679. $sql = "SELECT DISTINCT category FROM $t_cs";
  3680. if ($list != "'',''" and $list != "''" and !empty($list)) {
  3681. $sql .= " WHERE category NOT IN ($list)";
  3682. }
  3683. $result = Database::store_result(Database::query($sql));
  3684. return $result;
  3685. }
  3686. /**
  3687. * Deletes a setting
  3688. * @param string Variable
  3689. * @param string Subkey
  3690. * @param int Access URL
  3691. * @return boolean False on failure, true on success
  3692. */
  3693. function api_delete_setting($v, $s = null, $a = 1) {
  3694. if (empty($v)) { return false; }
  3695. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3696. $v = Database::escape_string($v);
  3697. $a = (int) $a;
  3698. if (empty($a)) { $a = 1; }
  3699. if (!empty($s)) {
  3700. $s = Database::escape_string($s);
  3701. $sql = "DELETE FROM $t_cs WHERE variable = '$v' AND subkey = '$s' AND access_url = $a";
  3702. $r = Database::query($sql);
  3703. return $r;
  3704. }
  3705. $sql = "DELETE FROM $t_cs WHERE variable = '$v' AND access_url = $a";
  3706. $r = Database::query($sql);
  3707. return $r;
  3708. }
  3709. /**
  3710. * Deletes all the settings from one category
  3711. * @param string Category
  3712. * @param int Access URL
  3713. * @return boolean False on failure, true on success
  3714. */
  3715. function api_delete_category_settings($c, $a = 1) {
  3716. if (empty($c)) { return false; }
  3717. $t_cs = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3718. $c = Database::escape_string($c);
  3719. $a = (int) $a;
  3720. if (empty($a)) { $a = 1; }
  3721. $sql = "DELETE FROM $t_cs WHERE category = '$c' AND access_url = $a";
  3722. $r = Database::query($sql);
  3723. return $r;
  3724. }
  3725. /**
  3726. * Sets a platform configuration setting to a given value
  3727. * @param string The value we want to record
  3728. * @param string The variable name we want to insert
  3729. * @param string The subkey for the variable we want to insert
  3730. * @param string The type for the variable we want to insert
  3731. * @param string The category for the variable we want to insert
  3732. * @param string The title
  3733. * @param string The comment
  3734. * @param string The scope
  3735. * @param string The subkey text
  3736. * @param int The access_url for which this parameter is valid
  3737. * @param int The changeability of this setting for non-master urls
  3738. * @return boolean true on success, false on failure
  3739. */
  3740. function api_add_setting($val, $var, $sk = null, $type = 'textfield', $c = null, $title = '', $com = '', $sc = null, $skt = null, $a = 1, $v = 0) {
  3741. if (empty($var) || !isset($val)) { return false; }
  3742. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  3743. $var = Database::escape_string($var);
  3744. $val = Database::escape_string($val);
  3745. $a = (int) $a;
  3746. if (empty($a)) { $a = 1; }
  3747. // Check if this variable doesn't exist already
  3748. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  3749. if (!empty($sk)) {
  3750. $sk = Database::escape_string($sk);
  3751. $select .= " AND subkey = '$sk'";
  3752. }
  3753. if ($a > 1) {
  3754. $select .= " AND access_url = $a";
  3755. } else {
  3756. $select .= " AND access_url = 1 ";
  3757. }
  3758. $res = Database::query($select);
  3759. if (Database::num_rows($res) > 0) { // Found item for this access_url.
  3760. $row = Database::fetch_array($res);
  3761. return $row['id'];
  3762. }
  3763. // Item not found for this access_url, we have to check if the whole thing is missing
  3764. // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
  3765. $insert = "INSERT INTO $t_settings " .
  3766. "(variable,selected_value," .
  3767. "type,category," .
  3768. "subkey,title," .
  3769. "comment,scope," .
  3770. "subkeytext,access_url,access_url_changeable)" .
  3771. " VALUES ('$var','$val',";
  3772. if (isset($type)) {
  3773. $type = Database::escape_string($type);
  3774. $insert .= "'$type',";
  3775. } else {
  3776. $insert .= "NULL,";
  3777. }
  3778. if (isset($c)) { // Category
  3779. $c = Database::escape_string($c);
  3780. $insert .= "'$c',";
  3781. } else {
  3782. $insert .= "NULL,";
  3783. }
  3784. if (isset($sk)) { // Subkey
  3785. $sk = Database::escape_string($sk);
  3786. $insert .= "'$sk',";
  3787. } else {
  3788. $insert .= "NULL,";
  3789. }
  3790. if (isset($title)) { // Title
  3791. $title = Database::escape_string($title);
  3792. $insert .= "'$title',";
  3793. } else {
  3794. $insert .= "NULL,";
  3795. }
  3796. if (isset($com)) { // Comment
  3797. $com = Database::escape_string($com);
  3798. $insert .= "'$com',";
  3799. } else {
  3800. $insert .= "NULL,";
  3801. }
  3802. if (isset($sc)) { // Scope
  3803. $sc = Database::escape_string($sc);
  3804. $insert .= "'$sc',";
  3805. } else {
  3806. $insert .= "NULL,";
  3807. }
  3808. if (isset($skt)) { // Subkey text
  3809. $skt = Database::escape_string($skt);
  3810. $insert .= "'$skt',";
  3811. } else {
  3812. $insert .= "NULL,";
  3813. }
  3814. $insert .= "$a,$v)";
  3815. $res = Database::query($insert);
  3816. return $res;
  3817. }
  3818. /**
  3819. * Checks wether a user can or can't view the contents of a course.
  3820. *
  3821. * @param int $userid User id or NULL to get it from $_SESSION
  3822. * @param int $cid Course id to check whether the user is allowed.
  3823. * @return bool
  3824. */
  3825. function api_is_course_visible_for_user($userid = null, $cid = null) {
  3826. if ($userid == null) {
  3827. $userid = api_get_user_id();
  3828. }
  3829. if (empty($userid) || strval(intval($userid)) != $userid) {
  3830. if (api_is_anonymous()) {
  3831. $userid = api_get_anonymous_id();
  3832. } else {
  3833. return false;
  3834. }
  3835. }
  3836. $cid = Database::escape_string($cid);
  3837. global $is_platformAdmin;
  3838. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  3839. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  3840. $sql = "SELECT
  3841. $course_table.category_code,
  3842. $course_table.visibility,
  3843. $course_table.code,
  3844. $course_cat_table.code
  3845. FROM $course_table
  3846. LEFT JOIN $course_cat_table
  3847. ON $course_table.category_code = $course_cat_table.code
  3848. WHERE
  3849. $course_table.code = '$cid'
  3850. LIMIT 1";
  3851. $result = Database::query($sql);
  3852. if (Database::num_rows($result) > 0) {
  3853. $visibility = Database::fetch_array($result);
  3854. $visibility = $visibility['visibility'];
  3855. } else {
  3856. $visibility = 0;
  3857. }
  3858. // Shortcut permissions in case the visibility is "open to the world".
  3859. if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
  3860. return true;
  3861. }
  3862. if (api_get_setting('use_session_mode') != 'true') {
  3863. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3864. $sql = "SELECT tutor_id, status
  3865. FROM $course_user_table
  3866. WHERE user_id = '$userid' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."
  3867. AND course_code = '$cid'
  3868. LIMIT 1";
  3869. $result = Database::query($sql);
  3870. if (Database::num_rows($result) > 0) {
  3871. // This user have a recorded state for this course.
  3872. $cuData = Database::fetch_array($result);
  3873. $is_courseMember = true;
  3874. $is_courseTutor = ($cuData['tutor_id' ] == 1);
  3875. $is_courseAdmin = ($cuData['status'] == 1);
  3876. } else {
  3877. // This user has no status related to this course.
  3878. $is_courseMember = false;
  3879. $is_courseAdmin = false;
  3880. $is_courseTutor = false;
  3881. }
  3882. $is_courseAdmin = ($is_courseAdmin || $is_platformAdmin);
  3883. } else {
  3884. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  3885. $sql = "SELECT
  3886. tutor_id, status, role
  3887. FROM $tbl_course_user
  3888. WHERE
  3889. user_id = '$userid'
  3890. AND
  3891. relation_type <> '".COURSE_RELATION_TYPE_RRHH."'
  3892. AND
  3893. course_code = '$cid'
  3894. LIMIT 1";
  3895. $result = Database::query($sql);
  3896. if (Database::num_rows($result) > 0) {
  3897. // This user has got a recorded state for this course.
  3898. $cuData = Database::fetch_array($result);
  3899. $_courseUser['role'] = $cuData['role'];
  3900. $is_courseMember = true;
  3901. $is_courseTutor = ($cuData['tutor_id' ] == 1);
  3902. $is_courseAdmin = ($cuData['status'] == 1);
  3903. }
  3904. if (!$is_courseAdmin) {
  3905. // This user has no status related to this course.
  3906. // Is it the session coach or the session admin?
  3907. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3908. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3909. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3910. $sql = "SELECT
  3911. session.id_coach, session_admin_id, session.id
  3912. FROM
  3913. $tbl_session as session
  3914. INNER JOIN $tbl_session_course
  3915. ON session_rel_course.id_session = session.id
  3916. AND session_rel_course.course_code = '$cid'
  3917. LIMIT 1";
  3918. $result = Database::query($sql);
  3919. $row = Database::store_result($result);
  3920. if ($row[0]['id_coach'] == $userid) {
  3921. $_courseUser['role'] = 'Professor';
  3922. $is_courseMember = true;
  3923. $is_courseTutor = true;
  3924. $is_courseAdmin = false;
  3925. $is_courseCoach = true;
  3926. $is_sessionAdmin = false;
  3927. api_session_register('_courseUser');
  3928. }
  3929. elseif ($row[0]['session_admin_id'] == $userid) {
  3930. $_courseUser['role'] = 'Professor';
  3931. $is_courseMember = false;
  3932. $is_courseTutor = false;
  3933. $is_courseAdmin = false;
  3934. $is_courseCoach = false;
  3935. $is_sessionAdmin = true;
  3936. } else {
  3937. // Check if the current user is the course coach.
  3938. $sql = "SELECT 1
  3939. FROM $tbl_session_course
  3940. WHERE session_rel_course.course_code = '$cid'
  3941. AND session_rel_course.id_coach = '$userid'
  3942. LIMIT 1";
  3943. $result = Database::query($sql);
  3944. //if ($row = Database::fetch_array($result)) {
  3945. if (Database::num_rows($result) > 0 ) {
  3946. $_courseUser['role'] = 'Professor';
  3947. $is_courseMember = true;
  3948. $is_courseTutor = true;
  3949. $is_courseCoach = true;
  3950. $is_sessionAdmin = false;
  3951. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  3952. $sql = "SELECT status FROM $tbl_user
  3953. WHERE user_id = $userid LIMIT 1";
  3954. $result = Database::query($sql);
  3955. if (Database::result($result, 0, 0) == 1) {
  3956. $is_courseAdmin = true;
  3957. } else {
  3958. $is_courseAdmin = false;
  3959. }
  3960. } else {
  3961. // Check if the user is a student is this session.
  3962. $sql = "SELECT id
  3963. FROM $tbl_session_course_user
  3964. WHERE id_user = '$userid'
  3965. AND course_code = '$cid'
  3966. LIMIT 1";
  3967. if (Database::num_rows($result) > 0) {
  3968. // This user haa got a recorded state for this course.
  3969. while ($row = Database::fetch_array($result)) {
  3970. $is_courseMember = true;
  3971. $is_courseTutor = false;
  3972. $is_courseAdmin = false;
  3973. $is_sessionAdmin = false;
  3974. }
  3975. }
  3976. }
  3977. }
  3978. }
  3979. }
  3980. switch ($visibility) {
  3981. case COURSE_VISIBILITY_OPEN_WORLD:
  3982. return true;
  3983. case COURSE_VISIBILITY_OPEN_PLATFORM:
  3984. return isset($userid);
  3985. case COURSE_VISIBILITY_REGISTERED:
  3986. case COURSE_VISIBILITY_CLOSED:
  3987. return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
  3988. }
  3989. return false;
  3990. }
  3991. /**
  3992. * Returns whether an element (forum, message, survey ...) belongs to a session or not
  3993. * @param String the tool of the element
  3994. * @param int the element id in database
  3995. * @param int the session_id to compare with element session id
  3996. * @return boolean true if the element is in the session, false else
  3997. */
  3998. function api_is_element_in_the_session($tool, $element_id, $session_id = null) {
  3999. if (is_null($session_id)) {
  4000. $session_id = intval($_SESSION['id_session']);
  4001. }
  4002. // Get information to build query depending of the tool.
  4003. switch ($tool) {
  4004. case TOOL_SURVEY :
  4005. $table_tool = Database::get_course_table(TABLE_SURVEY);
  4006. $key_field = 'survey_id';
  4007. break;
  4008. case TOOL_ANNOUNCEMENT :
  4009. $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
  4010. $key_field = 'id';
  4011. break;
  4012. case TOOL_AGENDA :
  4013. $table_tool = Database::get_course_table(TABLE_AGENDA);
  4014. $key_field = 'id';
  4015. break;
  4016. case TOOL_GROUP :
  4017. $table_tool = Database::get_course_table(TABLE_GROUP);
  4018. $key_field = 'id';
  4019. break;
  4020. default: return false;
  4021. }
  4022. $course_id = api_get_course_int_id();
  4023. $sql = "SELECT session_id FROM $table_tool WHERE c_id = $course_id AND $key_field = ".intval($element_id);
  4024. $rs = Database::query($sql);
  4025. if ($element_session_id = Database::result($rs, 0, 0)) {
  4026. if ($element_session_id == intval($session_id)) { // The element belongs to the session.
  4027. return true;
  4028. }
  4029. }
  4030. return false;
  4031. }
  4032. /**
  4033. * Replaces "forbidden" characters in a filename string.
  4034. *
  4035. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  4036. * @author René Haentjens, UGent (RH)
  4037. * @author Ivan Tcholakov, JUN-2009. Transliteration functionality has been added.
  4038. * @param string $filename The filename string.
  4039. * @param string $strict (optional) When it is 'strict', all non-ASCII charaters will be replaced. Additional ASCII replacemets will be done too.
  4040. * @return string The cleaned filename.
  4041. */
  4042. function replace_dangerous_char($filename, $strict = 'loose') {
  4043. // Safe replacements for some non-letter characters.
  4044. static $search = array("\0", ' ', "\t", "\n", "\r", "\x0B", '/', "\\", '"', "'", '?', '*', '>', '<', '|', ':', '$', '(', ')', '^', '[', ']', '#', '+', '&', '%');
  4045. static $replace = array('', '_', '_', '_', '_', '_', '-', '-', '-', '_', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-');
  4046. // Encoding detection.
  4047. $encoding = api_detect_encoding($filename);
  4048. // Converting html-entities into encoded characters.
  4049. $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
  4050. // Transliteration to ASCII letters, they are not dangerous for filesystems.
  4051. $filename = api_transliterate($filename, 'x', $encoding);
  4052. // Trimming leading/trailing whitespace.
  4053. $filename = trim($filename);
  4054. // Trimming any leading/trailing dots.
  4055. $filename = trim($filename, '.');
  4056. $filename = trim($filename);
  4057. // Replacing remaining dangerous non-letter characters.
  4058. $filename = str_replace($search, $replace, $filename);
  4059. if ($strict == 'strict') {
  4060. //$filename = str_replace('-', '_', $filename); // See task #1848.
  4061. $filename = preg_replace('/[^0-9A-Za-z_.\-]/', '', $filename);
  4062. }
  4063. // Length is to be limited, so the file name to be acceptable by some operating systems.
  4064. $extension = (string)strrchr($filename, '.');
  4065. $extension_len = strlen($extension);
  4066. if ($extension_len > 0 && $extension_len < 250) {
  4067. $filename = substr($filename, 0, -$extension_len);
  4068. return substr($filename, 0, 250 - $extension_len).$extension;
  4069. }
  4070. return substr($filename, 0, 250);
  4071. }
  4072. /**
  4073. * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
  4074. * @author Ivan Tcholakov, 28-JUN-2006.
  4075. */
  4076. function api_request_uri() {
  4077. if (!empty($_SERVER['REQUEST_URI'])) {
  4078. return $_SERVER['REQUEST_URI'];
  4079. }
  4080. $uri = $_SERVER['SCRIPT_NAME'];
  4081. if (!empty($_SERVER['QUERY_STRING'])) {
  4082. $uri .= '?'.$_SERVER['QUERY_STRING'];
  4083. }
  4084. $_SERVER['REQUEST_URI'] = $uri;
  4085. return $uri;
  4086. }
  4087. /**
  4088. * Creates the "include_path" php-setting, following the rule that
  4089. * PEAR packages of Chamilo should be read before other external packages.
  4090. * To be used in global.inc.php only.
  4091. * @author Ivan Tcholakov, 06-NOV-2008.
  4092. */
  4093. function api_create_include_path_setting() {
  4094. $include_path = ini_get('include_path');
  4095. if (!empty($include_path)) {
  4096. $include_path_array = explode(PATH_SEPARATOR, $include_path);
  4097. $dot_found = array_search('.', $include_path_array);
  4098. if ($dot_found !== false) {
  4099. $result = array();
  4100. foreach ($include_path_array as $path) {
  4101. $result[] = $path;
  4102. if ($path == '.') {
  4103. // The path of Chamilo PEAR packages is to be inserted after the current directory path.
  4104. $result[] = api_get_path(LIBRARY_PATH).'pear';
  4105. }
  4106. }
  4107. return implode(PATH_SEPARATOR, $result);
  4108. }
  4109. // Current directory is not listed in the include_path setting, low probability is here.
  4110. return api_get_path(LIBRARY_PATH).'pear'.PATH_SEPARATOR.$include_path;
  4111. }
  4112. // The include_path setting is empty, low probability is here.
  4113. return api_get_path(LIBRARY_PATH).'pear';
  4114. }
  4115. /** Gets the current access_url id of the Chamilo Platform
  4116. * @author Julio Montoya <gugli100@gmail.com>
  4117. * @return int access_url_id of the current Chamilo Installation
  4118. */
  4119. function api_get_current_access_url_id() {
  4120. $access_url_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
  4121. $path = Database::escape_string(api_get_path(WEB_PATH));
  4122. $sql = "SELECT id FROM $access_url_table WHERE url = '".$path."'";
  4123. $result = Database::query($sql);
  4124. if (Database::num_rows($result) > 0) {
  4125. $access_url_id = Database::result($result, 0, 0);
  4126. return $access_url_id;
  4127. }
  4128. //if the url in WEB_PATH was not found, it can only mean that there is
  4129. // either a configuration problem or the first URL has not been defined yet
  4130. // (by default it is http://localhost/). Thus the more sensible thing we can
  4131. // do is return 1 (the main URL) as the user cannot hack this value anyway
  4132. return 1;
  4133. }
  4134. /**
  4135. * Gets the registered urls from a given user id
  4136. * @author Julio Montoya <gugli100@gmail.com>
  4137. * @return int user id
  4138. */
  4139. function api_get_access_url_from_user($user_id) {
  4140. $user_id = intval($user_id);
  4141. $table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  4142. $table_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
  4143. $sql = "SELECT access_url_id FROM $table_url_rel_user url_rel_user INNER JOIN $table_url u
  4144. ON (url_rel_user.access_url_id = u.id)
  4145. WHERE user_id = ".Database::escape_string($user_id);
  4146. $result = Database::query($sql);
  4147. $url_list = array();
  4148. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4149. $url_list[] = $row['access_url_id'];
  4150. }
  4151. return $url_list;
  4152. }
  4153. /**
  4154. * Gets the status of a user in a course
  4155. * @param int user_id
  4156. * @param string course_code
  4157. * @return int user status
  4158. */
  4159. function api_get_status_of_user_in_course ($user_id, $course_code) {
  4160. $tbl_rel_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  4161. if (!empty($user_id) && !empty($course_code)) {
  4162. $user_id = Database::escape_string(intval($user_id));
  4163. $course_code = Database::escape_string($course_code);
  4164. $sql = 'SELECT status FROM '.$tbl_rel_course_user.'
  4165. WHERE user_id='.$user_id.' AND course_code="'.$course_code.'";';
  4166. $result = Database::query($sql);
  4167. $row_status = Database::fetch_array($result, 'ASSOC');
  4168. return $row_status['status'];
  4169. } else {
  4170. return 0;
  4171. }
  4172. }
  4173. /**
  4174. * Checks whether the curent user is in a course or not.
  4175. *
  4176. * @param string The course code - optional (takes it from session if not given)
  4177. * @return boolean
  4178. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  4179. */
  4180. function api_is_in_course($course_code = null) {
  4181. if (isset($_SESSION['_course']['sysCode'])) {
  4182. if (!empty($course_code)) {
  4183. return $course_code == $_SESSION['_course']['sysCode'];
  4184. }
  4185. return true;
  4186. }
  4187. return false;
  4188. }
  4189. /**
  4190. * Checks whether the curent user is in a group or not.
  4191. *
  4192. * @param string The group id - optional (takes it from session if not given)
  4193. * @param string The course code - optional (no additional check by course if course code is not given)
  4194. * @return boolean
  4195. * @author Ivan Tcholakov
  4196. */
  4197. function api_is_in_group($group_id = null, $course_code = null) {
  4198. if (!empty($course_code)) {
  4199. if (isset($_SESSION['_course']['sysCode'])) {
  4200. if ($course_code != $_SESSION['_course']['sysCode']) return false;
  4201. } else {
  4202. return false;
  4203. }
  4204. }
  4205. if (isset($_SESSION['_gid']) && $_SESSION['_gid'] != '') {
  4206. if (!empty($group_id)) {
  4207. return $group_id == $_SESSION['_gid'];
  4208. } else {
  4209. return true;
  4210. }
  4211. }
  4212. return false;
  4213. }
  4214. /**
  4215. * This function gets the hash in md5 or sha1 (it depends in the platform config) of a given password
  4216. * @param string password
  4217. * @return string password with the applied hash
  4218. */
  4219. function api_get_encrypted_password($password, $salt = '') {
  4220. global $_configuration;
  4221. $password_encryption = isset($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1';
  4222. switch ($password_encryption) {
  4223. case 'sha1':
  4224. return empty($salt) ? sha1($password) : sha1($password.$salt);
  4225. case 'none':
  4226. return $password;
  4227. case 'md5':
  4228. default:
  4229. return empty($salt) ? md5($password) : md5($password.$salt);
  4230. }
  4231. }
  4232. /**
  4233. * Checks whether a secret key is valid
  4234. * @param string $original_key_secret - secret key from (webservice) client
  4235. * @param string $security_key - security key from Chamilo
  4236. * @return boolean - true if secret key is valid, false otherwise
  4237. */
  4238. function api_is_valid_secret_key($original_key_secret, $security_key) {
  4239. global $_configuration;
  4240. return $original_key_secret == sha1($security_key);
  4241. }
  4242. /**
  4243. * Checks whether a user is into course
  4244. * @param string $course_id - the course id
  4245. * @param string $user_id - the user id
  4246. */
  4247. function api_is_user_of_course($course_id, $user_id) {
  4248. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4249. $sql = 'SELECT user_id FROM '.$tbl_course_rel_user.' WHERE course_code="'.Database::escape_string($course_id).'" AND user_id="'.Database::escape_string($user_id).'" AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' ';
  4250. $result = Database::query($sql);
  4251. return Database::num_rows($result) == 1;
  4252. }
  4253. /**
  4254. * Checks whether the server's operating system is Windows (TM).
  4255. * @return boolean - true if the operating system is Windows, false otherwise
  4256. */
  4257. function api_is_windows_os() {
  4258. if (function_exists('php_uname')) {
  4259. // php_uname() exists as of PHP 4.0.2, according to the documentation.
  4260. // We expect that this function will always work for Chamilo 1.8.x.
  4261. $os = php_uname();
  4262. }
  4263. // The following methods are not needed, but let them stay, just in case.
  4264. elseif (isset($_ENV['OS'])) {
  4265. // Sometimes $_ENV['OS'] may not be present (bugs?)
  4266. $os = $_ENV['OS'];
  4267. }
  4268. elseif (defined('PHP_OS')) {
  4269. // PHP_OS means on which OS PHP was compiled, this is why
  4270. // using PHP_OS is the last choice for detection.
  4271. $os = PHP_OS;
  4272. } else {
  4273. return false;
  4274. }
  4275. return strtolower(substr((string)$os, 0, 3 )) == 'win';
  4276. }
  4277. /**
  4278. * This function informs whether the sent request is XMLHttpRequest
  4279. */
  4280. function api_is_xml_http_request() {
  4281. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  4282. }
  4283. /**
  4284. * Substitute for json_encode function for PHP version < 5.2.
  4285. *
  4286. * The following function has been adopted from Drupal's "Image Browser" project,
  4287. * @link http://drupal.org/project/imagebrowser
  4288. * version 6.x-2.x-dev, 2010-Mar-11,
  4289. * @link http://ftp.drupal.org/files/projects/imagebrowser-6.x-2.x-dev.tar.gz
  4290. */
  4291. if (!function_exists('json_encode')) {
  4292. function json_encode($a = false) {
  4293. if (is_null($a)) return 'null';
  4294. if ($a === false) return 'false';
  4295. if ($a === true) return 'true';
  4296. if (is_scalar($a)) {
  4297. if (is_float($a)) {
  4298. // Always use "." for floats.
  4299. return floatval(str_replace(",", ".", strval($a)));
  4300. }
  4301. if (is_string($a)) {
  4302. static $json_replaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
  4303. return '"' . str_replace($json_replaces[0], $json_replaces[1], $a) . '"';
  4304. }
  4305. else
  4306. return $a;
  4307. }
  4308. $is_list = true;
  4309. for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
  4310. if (key($a) !== $i) {
  4311. $is_list = false;
  4312. break;
  4313. }
  4314. }
  4315. $result = array();
  4316. if ($is_list) {
  4317. foreach ($a as $v) $result[] = json_encode($v);
  4318. return '[' . join(',', $result) . ']';
  4319. }
  4320. else {
  4321. foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
  4322. return '{' . join(',', $result) . '}';
  4323. }
  4324. }
  4325. }
  4326. /**
  4327. * This wrapper function has been implemented for avoiding some known problems about the function getimagesize().
  4328. * @link http://php.net/manual/en/function.getimagesize.php
  4329. * @link http://www.dokeos.com/forum/viewtopic.php?t=12345
  4330. * @link http://www.dokeos.com/forum/viewtopic.php?t=16355
  4331. */
  4332. function api_getimagesize($path) {
  4333. $image = new Image($path);
  4334. return $image->get_image_size();
  4335. }
  4336. /**
  4337. * This function resizes an image, with preserving its proportions (or aspect ratio).
  4338. * @author Ivan Tcholakov, MAY-2009.
  4339. * @param int $image System path or URL of the image
  4340. * @param int $target_width Targeted width
  4341. * @param int $target_height Targeted height
  4342. * @return array Calculated new width and height
  4343. */
  4344. function api_resize_image($image, $target_width, $target_height) {
  4345. $image_properties = api_getimagesize($image);
  4346. return api_calculate_image_size($image_properties['width'], $image_properties['height'], $target_width, $target_height);
  4347. }
  4348. /**
  4349. * This function calculates new image size, with preserving image's proportions (or aspect ratio).
  4350. * @author Ivan Tcholakov, MAY-2009.
  4351. * @author The initial idea has been taken from code by Patrick Cool, MAY-2004.
  4352. * @param int $image_width Initial width
  4353. * @param int $image_height Initial height
  4354. * @param int $target_width Targeted width
  4355. * @param int $target_height Targeted height
  4356. * @return array Calculated new width and height
  4357. */
  4358. function api_calculate_image_size($image_width, $image_height, $target_width, $target_height) {
  4359. // Only maths is here.
  4360. $result = array('width' => $image_width, 'height' => $image_height);
  4361. if ($image_width <= 0 || $image_height <= 0) {
  4362. return $result;
  4363. }
  4364. $resize_factor_width = $target_width / $image_width;
  4365. $resize_factor_height = $target_height / $image_height;
  4366. $delta_width = $target_width - $image_width * $resize_factor_height;
  4367. $delta_height = $target_height - $image_height * $resize_factor_width;
  4368. if ($delta_width > $delta_height) {
  4369. $result['width'] = ceil($image_width * $resize_factor_height);
  4370. $result['height'] = ceil($image_height * $resize_factor_height);
  4371. }
  4372. elseif ($delta_width < $delta_height) {
  4373. $result['width'] = ceil($image_width * $resize_factor_width);
  4374. $result['height'] = ceil($image_height * $resize_factor_width);
  4375. }
  4376. else {
  4377. $result['width'] = ceil($target_width);
  4378. $result['height'] = ceil($target_height);
  4379. }
  4380. return $result;
  4381. }
  4382. /**
  4383. * Returns a list of Chamilo's tools or
  4384. * checks whether a given identificator is a valid Chamilo's tool.
  4385. * @author Isaac flores paz
  4386. * @param string The tool name to filter
  4387. * @return mixed Filtered string or array
  4388. */
  4389. function api_get_tools_lists($my_tool = null) {
  4390. $tools_list = array(
  4391. TOOL_DOCUMENT, TOOL_THUMBNAIL, TOOL_HOTPOTATOES,
  4392. TOOL_CALENDAR_EVENT, TOOL_LINK, TOOL_COURSE_DESCRIPTION, TOOL_SEARCH,
  4393. TOOL_LEARNPATH, TOOL_ANNOUNCEMENT, TOOL_FORUM, TOOL_THREAD, TOOL_POST,
  4394. TOOL_DROPBOX, TOOL_QUIZ, TOOL_USER, TOOL_GROUP, TOOL_BLOGS, TOOL_CHAT,
  4395. TOOL_CONFERENCE, TOOL_STUDENTPUBLICATION, TOOL_TRACKING, TOOL_HOMEPAGE_LINK,
  4396. TOOL_COURSE_SETTING, TOOL_BACKUP, TOOL_COPY_COURSE_CONTENT, TOOL_RECYCLE_COURSE,
  4397. TOOL_COURSE_HOMEPAGE, TOOL_COURSE_RIGHTS_OVERVIEW, TOOL_UPLOAD, TOOL_COURSE_MAINTENANCE,
  4398. TOOL_VISIO, TOOL_VISIO_CONFERENCE, TOOL_VISIO_CLASSROOM, TOOL_SURVEY, TOOL_WIKI,
  4399. TOOL_GLOSSARY, TOOL_GRADEBOOK, TOOL_NOTEBOOK, TOOL_ATTENDANCE, TOOL_COURSE_PROGRESS
  4400. );
  4401. if (empty($my_tool)) {
  4402. return $tools_list;
  4403. }
  4404. return in_array($my_tool, $tools_list) ? $my_tool : '';
  4405. }
  4406. /**
  4407. * Checks whether we already approved the last version term and condition
  4408. * @param int user id
  4409. * @return bool true if we pass false otherwise
  4410. */
  4411. function api_check_term_condition($user_id) {
  4412. if (api_get_setting('allow_terms_conditions') == 'true') {
  4413. require_once api_get_path(LIBRARY_PATH).'legal.lib.php';
  4414. $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
  4415. $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  4416. //check if exists terms and conditions
  4417. if (LegalManager::count() == 0) {
  4418. return true;
  4419. }
  4420. // Check the last user version_id passed
  4421. $sqlv = "SELECT field_value FROM $t_ufv ufv inner join $t_uf uf on ufv.field_id= uf.id
  4422. WHERE field_variable = 'legal_accept' AND user_id = ".intval($user_id);
  4423. $resv = Database::query($sqlv);
  4424. if (Database::num_rows($resv) > 0) {
  4425. $rowv = Database::fetch_row($resv);
  4426. $rowv = $rowv[0];
  4427. $user_conditions = explode(':', $rowv);
  4428. $version = $user_conditions[0];
  4429. $lang_id = $user_conditions[1];
  4430. $real_version = LegalManager::get_last_version($lang_id);
  4431. return $version >= $real_version;
  4432. }
  4433. return false;
  4434. }
  4435. return false;
  4436. }
  4437. /**
  4438. * Gets all information of a tool into course
  4439. * @param int The tool id
  4440. * @return array
  4441. */
  4442. function api_get_tool_information($tool_id) {
  4443. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4444. $course_id = api_get_course_int_id();
  4445. $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id AND id = ".intval($tool_id);
  4446. $rs = Database::query($sql);
  4447. return Database::fetch_array($rs);
  4448. }
  4449. /**
  4450. * Gets all information of a tool into course
  4451. * @param int The tool id
  4452. * @return array
  4453. */
  4454. function api_get_tool_information_by_name($name) {
  4455. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4456. $course_id = api_get_course_int_id();
  4457. $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  4458. $rs = Database::query($sql);
  4459. return Database::fetch_array($rs, 'ASSOC');
  4460. }
  4461. /* DEPRECATED FUNCTIONS */
  4462. /**
  4463. * Deprecated, use api_trunc_str() instead.
  4464. */
  4465. function shorten($input, $length = 15, $encoding = null) {
  4466. $length = intval($length);
  4467. if (!$length) {
  4468. $length = 15;
  4469. }
  4470. return api_trunc_str($input, $length, '...', false, $encoding);
  4471. }
  4472. /**
  4473. * DEPRECATED, use api_get_setting instead
  4474. */
  4475. function get_setting($variable, $key = NULL) {
  4476. global $_setting;
  4477. return api_get_setting($variable, $key);
  4478. }
  4479. /**
  4480. * deprecated: use api_is_allowed_to_edit() instead
  4481. */
  4482. function is_allowed_to_edit() {
  4483. return api_is_allowed_to_edit();
  4484. }
  4485. /**
  4486. * deprecated: 19-SEP-2009: Use api_get_path(TO_SYS, $url) instead.
  4487. */
  4488. function api_url_to_local_path($url) {
  4489. return api_get_path(TO_SYS, $url);
  4490. }
  4491. /**
  4492. * @deprecated 27-SEP-2009: Use Database::store_result($result) instead.
  4493. */
  4494. function api_store_result($result) {
  4495. return Database::store_result($result);
  4496. }
  4497. /**
  4498. * @deprecated 28-SEP-2009: Use Database::query($query, $file, $line) instead.
  4499. */
  4500. function api_sql_query($query, $file = '', $line = 0) {
  4501. return Database::query($query, $file, $line);
  4502. }
  4503. /**
  4504. * @deprecated 25-JAN-2010: See api_mail() and api_mail_html(), mail.lib.inc.php
  4505. *
  4506. * Send an email.
  4507. *
  4508. * Wrapper function for the standard php mail() function. Change this function
  4509. * to your needs. The parameters must follow the same rules as the standard php
  4510. * mail() function. Please look at the documentation on http://php.net/manual/en/function.mail.php
  4511. * @param string $to
  4512. * @param string $subject
  4513. * @param string $message
  4514. * @param string $additional_headers
  4515. * @param string $additional_parameters
  4516. * @author Ivan Tcholakov, 04-OCT-2009, a reworked version of this function.
  4517. * @link http://www.dokeos.com/forum/viewtopic.php?t=15557
  4518. */
  4519. function api_send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) {
  4520. require_once api_get_path(LIBRARY_PATH).'phpmailer/class.phpmailer.php';
  4521. if (empty($platform_email['SMTP_FROM_NAME'])) {
  4522. $platform_email['SMTP_FROM_NAME'] = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  4523. }
  4524. if (empty($platform_email['SMTP_FROM_EMAIL'])) {
  4525. $platform_email['SMTP_FROM_EMAIL'] = api_get_setting('emailAdministrator');
  4526. }
  4527. $matches = array();
  4528. if (preg_match('/([^<]*)<(.+)>/si', $to, $matches)) {
  4529. $recipient_name = trim($matches[1]);
  4530. $recipient_email = trim($matches[2]);
  4531. } else {
  4532. $recipient_name = '';
  4533. $recipient_email = trim($to);
  4534. }
  4535. $sender_name = '';
  4536. $sender_email = '';
  4537. $extra_headers = $additional_headers;
  4538. // Regular expression to test for valid email address.
  4539. // This should actually be revised to use the complete RFC3696 description.
  4540. // http://tools.ietf.org/html/rfc3696#section-3
  4541. //$regexp = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,3})$"; // Deprecated, 13-OCT-2010.
  4542. $mail = new PHPMailer();
  4543. $mail->CharSet = $platform_email['SMTP_CHARSET'];
  4544. $mail->Mailer = $platform_email['SMTP_MAILER'];
  4545. $mail->Host = $platform_email['SMTP_HOST'];
  4546. $mail->Port = $platform_email['SMTP_PORT'];
  4547. if ($platform_email['SMTP_AUTH']) {
  4548. $mail->SMTPAuth = 1;
  4549. $mail->Username = $platform_email['SMTP_USER'];
  4550. $mail->Password = $platform_email['SMTP_PASS'];
  4551. }
  4552. $mail->Priority = 3; // 5 = low, 1 = high
  4553. $mail->AddCustomHeader('Errors-To: '.$platform_email['SMTP_FROM_EMAIL']);
  4554. $mail->IsHTML(0);
  4555. $mail->SMTPKeepAlive = true;
  4556. // Attachments.
  4557. // $mail->AddAttachment($path);
  4558. // $mail->AddAttachment($path, $filename);
  4559. if ($sender_email != '') {
  4560. $mail->From = $sender_email;
  4561. $mail->Sender = $sender_email;
  4562. //$mail->ConfirmReadingTo = $sender_email; // Disposition-Notification
  4563. } else {
  4564. $mail->From = $platform_email['SMTP_FROM_EMAIL'];
  4565. $mail->Sender = $platform_email['SMTP_FROM_EMAIL'];
  4566. //$mail->ConfirmReadingTo = $platform_email['SMTP_FROM_EMAIL']; // Disposition-Notification
  4567. }
  4568. if ($sender_name != '') {
  4569. $mail->FromName = $sender_name;
  4570. } else {
  4571. $mail->FromName = $platform_email['SMTP_FROM_NAME'];
  4572. }
  4573. $mail->Subject = $subject;
  4574. $mail->Body = $message;
  4575. // Only valid address are to be accepted.
  4576. //if (eregi( $regexp, $recipient_email )) { // Deprecated, 13-OCT-2010.
  4577. if (api_valid_email($recipient_email)) {
  4578. $mail->AddAddress($recipient_email, $recipient_name);
  4579. }
  4580. if ($extra_headers != '') {
  4581. $mail->AddCustomHeader($extra_headers);
  4582. }
  4583. // Send mail.
  4584. if (!$mail->Send()) {
  4585. return 0;
  4586. }
  4587. // Clear all the addresses.
  4588. $mail->ClearAddresses();
  4589. return 1;
  4590. }
  4591. /* END OF DEPRECATED FUNCTIONS SECTION */
  4592. /**
  4593. * Function used to protect a "global" admin script.
  4594. * The function blocks access when the user has no global platform admin rights.
  4595. * Global admins are the admins that are registered in the main.admin table AND the users who have access to the "principal" portal.
  4596. * 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
  4597. *
  4598. * @author Julio Montoya
  4599. */
  4600. function api_is_global_platform_admin() {
  4601. if (api_is_platform_admin()) {
  4602. $my_url_list = api_get_access_url_from_user(api_get_user_id());
  4603. // The admin is registered in the first "main" site with access_url_id = 1
  4604. if (in_array(1, $my_url_list)) {
  4605. return true;
  4606. } else {
  4607. return false;
  4608. }
  4609. }
  4610. return false;
  4611. }
  4612. /**
  4613. * Function used to protect a global admin script.
  4614. * The function blocks access when the user has no global platform admin rights.
  4615. * See also the api_is_global_platform_admin() function wich defines who's a "global" admin
  4616. *
  4617. * @author Julio Montoya
  4618. */
  4619. function api_protect_global_admin_script() {
  4620. if (!api_is_global_platform_admin()) {
  4621. api_not_allowed();
  4622. return false;
  4623. }
  4624. return true;
  4625. }
  4626. /**
  4627. * Get actived template
  4628. * @param string theme type (optional: default)
  4629. * @param string path absolute(abs) or relative(rel) (optional:rel)
  4630. * @return string actived template path
  4631. */
  4632. function api_get_template($path_type = 'rel') {
  4633. $path_types = array('rel', 'abs');
  4634. $template_path = '';
  4635. if (in_array($path_type, $path_types)) {
  4636. if ($path_type == 'rel') {
  4637. $template_path = api_get_path(SYS_TEMPLATE_PATH);
  4638. } else {
  4639. $template_path = api_get_path(WEB_TEMPLATE_PATH);
  4640. }
  4641. }
  4642. $actived_theme = 'default';
  4643. if (api_get_setting('active_template')) {
  4644. $actived_theme = api_get_setting('active_template');
  4645. }
  4646. $actived_theme_path = $template_path.$actived_theme.DIRECTORY_SEPARATOR;
  4647. return $actived_theme_path;
  4648. }
  4649. /**
  4650. * Check browser support for type files
  4651. ** This function check if the users browser support a file format or return the current browser and major ver when $format=check_browser
  4652. * @param string $format
  4653. *
  4654. * @return bool, or return text array if $format=check_browser
  4655. *
  4656. * @author Juan Carlos Raña Trabado
  4657. */
  4658. function api_browser_support($format="") {
  4659. require_once api_get_path(LIBRARY_PATH).'browser/Browser.php';
  4660. $browser = new Browser();
  4661. //print_r($browser);
  4662. $current_browser = $browser->getBrowser();
  4663. $a_versiontemp = explode('.', $browser->getVersion());
  4664. $current_majorver= $a_versiontemp[0];
  4665. //native svg support
  4666. if ($format=='svg'){
  4667. 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)) {
  4668. return true;
  4669. }
  4670. else {
  4671. return false;
  4672. }
  4673. }
  4674. elseif($format=='pdf'){
  4675. //native pdf support
  4676. if($current_browser == 'Chrome' && $current_majorver >= 6){
  4677. return true;
  4678. }
  4679. else{
  4680. return false;
  4681. }
  4682. }
  4683. elseif($format=='tif' || $format=='tiff'){
  4684. //native tif support
  4685. if($current_browser == 'Safari' && $current_majorver >= 5){
  4686. return true;
  4687. }
  4688. else{
  4689. return false;
  4690. }
  4691. }
  4692. elseif($format=='ogg' || $format=='ogx'|| $format=='ogv' || $format=='oga'){
  4693. //native ogg, ogv,oga support
  4694. if (($current_browser == 'Firefox' && $current_majorver >= 3) || ($current_browser == 'Chrome' && $current_majorver >= 3) || ($current_browser == 'Opera' && $current_majorver >= 9)) {
  4695. return true;
  4696. }
  4697. else {
  4698. return false;
  4699. }
  4700. }
  4701. elseif($format=='mpg' || $format=='mpeg'){
  4702. //native mpg support
  4703. if(($current_browser == 'Safari' && $current_majorver >= 5)){
  4704. return true;
  4705. }
  4706. else{
  4707. return false;
  4708. }
  4709. }
  4710. elseif($format=='mp4'){
  4711. //native mp4 support (TODO: Android, iPhone)
  4712. if($current_browser == 'Android' || $current_browser == 'iPhone') {
  4713. return true;
  4714. }
  4715. else{
  4716. return false;
  4717. }
  4718. }
  4719. elseif($format=='mov'){
  4720. //native mov support( TODO:check iPhone)
  4721. if($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone'){
  4722. return true;
  4723. }
  4724. else{
  4725. return false;
  4726. }
  4727. }
  4728. elseif($format=='avi'){
  4729. //native avi support
  4730. if($current_browser == 'Safari' && $current_majorver >= 5){
  4731. return true;
  4732. }
  4733. else{
  4734. return false;
  4735. }
  4736. }
  4737. elseif($format=='wmv'){
  4738. //native wmv support
  4739. if($current_browser == 'Firefox' && $current_majorver >= 4){
  4740. return true;
  4741. }
  4742. else{
  4743. return false;
  4744. }
  4745. }
  4746. elseif($format=='webm'){
  4747. //native webm support (TODO:check IE9, Chrome9, Android)
  4748. 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'){
  4749. return true;
  4750. }
  4751. else{
  4752. return false;
  4753. }
  4754. }
  4755. elseif($format=='wav'){
  4756. //native wav support (only some codecs !)
  4757. 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'){
  4758. return true;
  4759. }
  4760. else{
  4761. return false;
  4762. }
  4763. }
  4764. elseif($format=='mid' || $format=='kar'){
  4765. //native midi support (TODO:check Android)
  4766. if($current_browser == 'Opera'&& $current_majorver >= 9 || $current_browser == 'Android'){
  4767. return true;
  4768. }
  4769. else{
  4770. return false;
  4771. }
  4772. }
  4773. elseif($format=='wma'){
  4774. //native wma support
  4775. if($current_browser == 'Firefox' && $current_majorver >= 4){
  4776. return true;
  4777. }
  4778. else{
  4779. return false;
  4780. }
  4781. }
  4782. elseif($format=='au'){
  4783. //native au support
  4784. if($current_browser == 'Safari' && $current_majorver >= 5){
  4785. return true;
  4786. }
  4787. else{
  4788. return false;
  4789. }
  4790. }
  4791. elseif($format=='mp3'){
  4792. //native mp3 support (TODO:check Android, iPhone)
  4793. 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'){
  4794. return true;
  4795. }
  4796. else{
  4797. return false;
  4798. }
  4799. }
  4800. elseif($format=="check_browser"){
  4801. $array_check_browser=array($current_browser, $current_majorver);
  4802. return $array_check_browser;
  4803. }
  4804. else{
  4805. return false;
  4806. }
  4807. }
  4808. /**
  4809. * This function checks if exist path and file browscap.ini
  4810. * 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
  4811. * http://php.net/manual/en/function.get-browser.php
  4812. *
  4813. * @return bool
  4814. *
  4815. * @author Juan Carlos Raña Trabado
  4816. */
  4817. function api_check_browscap() {
  4818. $setting = ini_get('browscap');
  4819. if ($setting) {
  4820. $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
  4821. if (strpos($setting, 'browscap.ini') && !empty($browser)) {
  4822. return true;
  4823. }
  4824. }
  4825. return false;
  4826. }
  4827. function api_get_js($file) {
  4828. return '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>';
  4829. }
  4830. function api_get_css($file) {
  4831. $media = '';
  4832. return '<link rel="stylesheet" href="'.$file.'" type="text/css" media="'.$media.'" />';
  4833. }
  4834. /**
  4835. * Returns the js header to include the jquery library
  4836. */
  4837. function api_get_jquery_js() {
  4838. return api_get_js('jquery.min.js');
  4839. }
  4840. /**
  4841. * Returns the jquery-ui library js headers
  4842. * @param bool add the jqgrid library
  4843. * @return string html tags
  4844. *
  4845. */
  4846. function api_get_jquery_ui_js($include_jqgrid = false) {
  4847. $libraries[]='jquery-ui';
  4848. if ($include_jqgrid) {
  4849. $libraries[]='jqgrid';
  4850. }
  4851. return api_get_jquery_libraries_js($libraries);
  4852. }
  4853. /**
  4854. * Returns the jquery library js and css headers
  4855. *
  4856. * @param array list of jquery libraries supported jquery-ui, jqgrid
  4857. * @param bool add the jquery library
  4858. * @return string html tags
  4859. *
  4860. */
  4861. function api_get_jquery_libraries_js($libraries) {
  4862. $js = '';
  4863. $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
  4864. //jquery-ui js and css
  4865. if (in_array('jquery-ui', $libraries)) {
  4866. //Jquery ui
  4867. $theme = 'smoothness'; // Current themes: cupertino, smoothness, ui-lightness. Find the themes folder in main/inc/lib/javascript/jquery-ui
  4868. $jquery_ui_version = '1.8.16';
  4869. //$js .= '<link rel="stylesheet" href="'.$js_path.'jquery-ui/'.$theme.'/jquery-ui-'.$jquery_ui_version.'.custom.css" type="text/css">';
  4870. $js .= api_get_css($js_path.'jquery-ui/'.$theme.'/jquery-ui-'.$jquery_ui_version.'.custom.css');
  4871. $js .= api_get_js('jquery-ui/'.$theme.'/jquery-ui-'.$jquery_ui_version.'.custom.min.js');
  4872. }
  4873. //jqgrid js and css
  4874. if (in_array('jqgrid', $libraries)) {
  4875. $languaje = 'en';
  4876. $platform_isocode = strtolower(api_get_language_isocode());
  4877. //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  4878. $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');
  4879. if (in_array($platform_isocode, $jqgrid_langs)) {
  4880. $languaje = $platform_isocode;
  4881. }
  4882. //$js .= '<link rel="stylesheet" href="'.$js_path.'jqgrid/css/ui.jqgrid.css" type="text/css">';
  4883. $js .= api_get_css($js_path.'jqgrid/css/ui.jqgrid.css');
  4884. $js .= api_get_js('jqgrid/js/i18n/grid.locale-'.$languaje.'.js');
  4885. $js .= api_get_js('jqgrid/js/jquery.jqGrid.min.js');
  4886. }
  4887. //Document multiple upload funcionality
  4888. if (in_array('jquery-upload', $libraries)) {
  4889. $js .= api_get_js('jquery-upload/jquery.fileupload.js');
  4890. $js .= api_get_js('jquery-upload/jquery.fileupload-ui.js');
  4891. $js .= api_get_css($js_path.'jquery-upload/jquery.fileupload-ui.css');
  4892. }
  4893. //jquery-ui css changes for Chamilo
  4894. if (in_array('jquery-ui',$libraries)) {
  4895. //Adding default CSS changes of the jquery-ui themes for Chamilo in order to preserve the original jquery-ui css
  4896. $js .= api_get_css($js_path.'jquery-ui/default.css');
  4897. }
  4898. if (in_array('bxslider',$libraries)) {
  4899. $js .= api_get_js('bxslider/jquery.bxSlider.min.js');
  4900. $js .= api_get_css($js_path.'bxslider/bx_styles/bx_styles.css');
  4901. }
  4902. return $js;
  4903. }
  4904. /**
  4905. * Returns the course's URL
  4906. *
  4907. * This function relies on api_get_course_info()
  4908. * @param string The course code - optional (takes it from session if not given)
  4909. * @param int The session id - optional (takes it from session if not given)
  4910. * @return mixed The URL of the course or null if something does not work
  4911. * @author Julio Montoya <gugli100@gmail.com>
  4912. */
  4913. function api_get_course_url($course_code = null, $session_id = null) {
  4914. $session_url = '';
  4915. if (empty($course_code)) {
  4916. $course_info = api_get_course_info();
  4917. } else {
  4918. $course_info = api_get_course_info($course_code);
  4919. }
  4920. if (empty($session_id)) {
  4921. if (api_get_session_id() != 0)
  4922. $session_url = '?id_session='.api_get_session_id();
  4923. } else {
  4924. $session_url = '?id_session='.intval($session_id);
  4925. }
  4926. if (!empty($course_info['path'])) {
  4927. return api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.$session_url;
  4928. }
  4929. return null;
  4930. }
  4931. /**
  4932. *
  4933. * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on
  4934. * @return bool true if multi site is enabled
  4935. *
  4936. * */
  4937. function api_get_multiple_access_url() {
  4938. global $_configuration;
  4939. if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
  4940. return true;
  4941. }
  4942. return false;
  4943. }
  4944. /**
  4945. * Returns a md5 unique id
  4946. * @todo add more parameters
  4947. */
  4948. function api_get_unique_id() {
  4949. $id = md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
  4950. return $id;
  4951. }
  4952. function api_get_home_path() {
  4953. $home = 'home/';
  4954. if (api_get_multiple_access_url()) {
  4955. $access_url_id = api_get_current_access_url_id();
  4956. $url_info = api_get_access_url($access_url_id);
  4957. $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
  4958. $clean_url = replace_dangerous_char($url);
  4959. $clean_url = str_replace('/', '-', $clean_url);
  4960. $clean_url .= '/';
  4961. // if $clean_url == "localhost/" means that the multiple URL was not well configured we don't rename the $home variable
  4962. if ($clean_url != 'localhost/')
  4963. $home = 'home/'.$clean_url;
  4964. }
  4965. return $home;
  4966. }
  4967. function api_get_course_table_condition($and = true) {
  4968. $course_id = api_get_course_int_id();
  4969. $condition = '';
  4970. $condition_add = $and ? " AND " : " WHERE ";
  4971. if (!empty($course_id)) {
  4972. $condition = " $condition_add c_id = $course_id";
  4973. }
  4974. return $condition;
  4975. }
  4976. function api_grading_model_functions($grading_model, $action = 'to_array') {
  4977. $return = null;
  4978. if (empty($grading_model)) {
  4979. return null;
  4980. }
  4981. $elements = array('A','B','C','D','E','F','G','H','I','J','K','L','M');
  4982. if (in_array($action, array('to_array', 'decorate'))) {
  4983. $parts = explode('/', $grading_model);
  4984. $return['denominator'] = $parts[1];
  4985. $sums = explode('+', $parts[0]);
  4986. $j = 0;
  4987. foreach($sums as $item) {
  4988. $item = explode('*', $item);
  4989. $per = 0;
  4990. if (!empty($return['denominator'])) {
  4991. $per = $item[0]/$return['denominator']*100;
  4992. }
  4993. $return['items'][] =array( 'letter' => $elements[$j],
  4994. 'value' => $item[0],
  4995. 'percentage'=> $per.'%');
  4996. $j++;
  4997. }
  4998. if ($action == 'decorate') {
  4999. $return_value = '';
  5000. $items = $return['items'];
  5001. $j = 1;
  5002. foreach ($items as $item) {
  5003. $letter = $item['letter'];
  5004. $value = $item['value'];
  5005. $sum = '+';
  5006. if (count($items) == $j){
  5007. $sum = '';
  5008. }
  5009. $return_value = $return_value.' '.$value.'*'.$letter." $sum ";
  5010. $j++;
  5011. }
  5012. $return = ' ('.$return_value.') / '.$return['denominator'];
  5013. }
  5014. }
  5015. return $return;
  5016. }