main_api.lib.php 183 KB

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