main_api.lib.php 153 KB

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