api.lib.php 280 KB

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