main_api.lib.php 196 KB

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