api.lib.php 275 KB

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