api.lib.php 256 KB

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