main_api.lib.php 257 KB

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