main_api.lib.php 228 KB

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