main_api.lib.php 210 KB

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