main_api.lib.php 262 KB

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