api.lib.php 273 KB

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