main_api.lib.php 267 KB

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