main_api.lib.php 151 KB

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