api.lib.php 305 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\SettingsCurrent;
  4. use Chamilo\CourseBundle\Entity\CItemProperty;
  5. use Chamilo\UserBundle\Entity\User;
  6. use ChamiloSession as Session;
  7. use Symfony\Component\Finder\Finder;
  8. /**
  9. * This is a code library for Chamilo.
  10. * It is included by default in every Chamilo file (through including the global.inc.php)
  11. * This library is in process of being transferred to src/Chamilo/CoreBundle/Component/Utils/ChamiloApi.
  12. * Whenever a function is transferred to the ChamiloApi class, the places where it is used should include
  13. * the "use Chamilo\CoreBundle\Component\Utils\ChamiloApi;" statement.
  14. *
  15. * @package chamilo.library
  16. */
  17. // PHP version requirement.
  18. define('REQUIRED_PHP_VERSION', '5.6');
  19. define('REQUIRED_MIN_MEMORY_LIMIT', '128');
  20. define('REQUIRED_MIN_UPLOAD_MAX_FILESIZE', '10');
  21. define('REQUIRED_MIN_POST_MAX_SIZE', '10');
  22. // USER STATUS CONSTANTS
  23. /** global status of a user: student */
  24. define('STUDENT', 5);
  25. /** global status of a user: course manager */
  26. define('COURSEMANAGER', 1);
  27. /** global status of a user: session admin */
  28. define('SESSIONADMIN', 3);
  29. /** global status of a user: human ressource manager */
  30. define('DRH', 4);
  31. /** global status of a user: human ressource manager */
  32. define('ANONYMOUS', 6);
  33. /** global status of a user: low security, necessary for inserting data from
  34. * the teacher through HTMLPurifier */
  35. define('COURSEMANAGERLOWSECURITY', 10);
  36. // Soft user status
  37. define('PLATFORM_ADMIN', 11);
  38. define('SESSION_COURSE_COACH', 12);
  39. define('SESSION_GENERAL_COACH', 13);
  40. define('COURSE_STUDENT', 14); //student subscribed in a course
  41. define('SESSION_STUDENT', 15); //student subscribed in a session course
  42. define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
  43. define('STUDENT_BOSS', 17); // student is boss
  44. define('INVITEE', 20);
  45. define('HRM_REQUEST', 21); //HRM has request for vinculation with user
  46. // Table of status
  47. $_status_list[COURSEMANAGER] = 'teacher'; // 1
  48. $_status_list[SESSIONADMIN] = 'session_admin'; // 3
  49. $_status_list[DRH] = 'drh'; // 4
  50. $_status_list[STUDENT] = 'user'; // 5
  51. $_status_list[ANONYMOUS] = 'anonymous'; // 6
  52. $_status_list[INVITEE] = 'invited'; // 20
  53. // COURSE VISIBILITY CONSTANTS
  54. /** only visible for course admin */
  55. define('COURSE_VISIBILITY_CLOSED', 0);
  56. /** only visible for users registered in the course */
  57. define('COURSE_VISIBILITY_REGISTERED', 1);
  58. /** Open for all registered users on the platform */
  59. define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
  60. /** Open for the whole world */
  61. define('COURSE_VISIBILITY_OPEN_WORLD', 3);
  62. /** Invisible to all except admin */
  63. define('COURSE_VISIBILITY_HIDDEN', 4);
  64. define('COURSE_REQUEST_PENDING', 0);
  65. define('COURSE_REQUEST_ACCEPTED', 1);
  66. define('COURSE_REQUEST_REJECTED', 2);
  67. define('DELETE_ACTION_ENABLED', false);
  68. // EMAIL SENDING RECIPIENT CONSTANTS
  69. define('SEND_EMAIL_EVERYONE', 1);
  70. define('SEND_EMAIL_STUDENTS', 2);
  71. define('SEND_EMAIL_TEACHERS', 3);
  72. // SESSION VISIBILITY CONSTANTS
  73. define('SESSION_VISIBLE_READ_ONLY', 1);
  74. define('SESSION_VISIBLE', 2);
  75. define('SESSION_INVISIBLE', 3); // not available
  76. define('SESSION_AVAILABLE', 4);
  77. define('SESSION_LINK_TARGET', '_self');
  78. define('SUBSCRIBE_ALLOWED', 1);
  79. define('SUBSCRIBE_NOT_ALLOWED', 0);
  80. define('UNSUBSCRIBE_ALLOWED', 1);
  81. define('UNSUBSCRIBE_NOT_ALLOWED', 0);
  82. // SURVEY VISIBILITY CONSTANTS
  83. define('SURVEY_VISIBLE_TUTOR', 0);
  84. define('SURVEY_VISIBLE_TUTOR_STUDENT', 1);
  85. define('SURVEY_VISIBLE_PUBLIC', 2);
  86. // CONSTANTS defining all tools, using the english version
  87. /* When you add a new tool you must add it into function api_get_tools_lists() too */
  88. define('TOOL_DOCUMENT', 'document');
  89. define('TOOL_LP_FINAL_ITEM', 'final_item');
  90. define('TOOL_READOUT_TEXT', 'readout_text');
  91. define('TOOL_THUMBNAIL', 'thumbnail');
  92. define('TOOL_HOTPOTATOES', 'hotpotatoes');
  93. define('TOOL_CALENDAR_EVENT', 'calendar_event');
  94. define('TOOL_LINK', 'link');
  95. define('TOOL_LINK_CATEGORY', 'link_category');
  96. define('TOOL_COURSE_DESCRIPTION', 'course_description');
  97. define('TOOL_SEARCH', 'search');
  98. define('TOOL_LEARNPATH', 'learnpath');
  99. define('TOOL_LEARNPATH_CATEGORY', 'learnpath_category');
  100. define('TOOL_AGENDA', 'agenda');
  101. define('TOOL_ANNOUNCEMENT', 'announcement');
  102. define('TOOL_FORUM', 'forum');
  103. define('TOOL_FORUM_CATEGORY', 'forum_category');
  104. define('TOOL_FORUM_THREAD', 'forum_thread');
  105. define('TOOL_FORUM_POST', 'forum_post');
  106. define('TOOL_FORUM_ATTACH', 'forum_attachment');
  107. define('TOOL_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
  108. define('TOOL_THREAD', 'thread');
  109. define('TOOL_POST', 'post');
  110. define('TOOL_DROPBOX', 'dropbox');
  111. define('TOOL_QUIZ', 'quiz');
  112. define('TOOL_TEST_CATEGORY', 'test_category');
  113. define('TOOL_USER', 'user');
  114. define('TOOL_GROUP', 'group');
  115. define('TOOL_BLOGS', 'blog_management');
  116. define('TOOL_CHAT', 'chat');
  117. define('TOOL_STUDENTPUBLICATION', 'student_publication');
  118. define('TOOL_TRACKING', 'tracking');
  119. define('TOOL_HOMEPAGE_LINK', 'homepage_link');
  120. define('TOOL_COURSE_SETTING', 'course_setting');
  121. define('TOOL_BACKUP', 'backup');
  122. define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
  123. define('TOOL_RECYCLE_COURSE', 'recycle_course');
  124. define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
  125. define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
  126. define('TOOL_UPLOAD', 'file_upload');
  127. define('TOOL_COURSE_MAINTENANCE', 'course_maintenance');
  128. define('TOOL_SURVEY', 'survey');
  129. define('TOOL_WIKI', 'wiki');
  130. define('TOOL_GLOSSARY', 'glossary');
  131. define('TOOL_GRADEBOOK', 'gradebook');
  132. define('TOOL_NOTEBOOK', 'notebook');
  133. define('TOOL_ATTENDANCE', 'attendance');
  134. define('TOOL_COURSE_PROGRESS', 'course_progress');
  135. define('TOOL_PORTFOLIO', 'portfolio');
  136. define('TOOL_PLAGIARISM', 'compilatio');
  137. // CONSTANTS defining Chamilo interface sections
  138. define('SECTION_CAMPUS', 'mycampus');
  139. define('SECTION_COURSES', 'mycourses');
  140. define('SECTION_CATALOG', 'catalog');
  141. define('SECTION_MYPROFILE', 'myprofile');
  142. define('SECTION_MYAGENDA', 'myagenda');
  143. define('SECTION_COURSE_ADMIN', 'course_admin');
  144. define('SECTION_PLATFORM_ADMIN', 'platform_admin');
  145. define('SECTION_MYGRADEBOOK', 'mygradebook');
  146. define('SECTION_TRACKING', 'session_my_space');
  147. define('SECTION_SOCIAL', 'social-network');
  148. define('SECTION_DASHBOARD', 'dashboard');
  149. define('SECTION_REPORTS', 'reports');
  150. define('SECTION_GLOBAL', 'global');
  151. define('SECTION_INCLUDE', 'include');
  152. // CONSTANT name for local authentication source
  153. define('PLATFORM_AUTH_SOURCE', 'platform');
  154. define('CAS_AUTH_SOURCE', 'cas');
  155. define('LDAP_AUTH_SOURCE', 'extldap');
  156. // CONSTANT defining the default HotPotatoes files directory
  157. define('DIR_HOTPOTATOES', '/HotPotatoes_files');
  158. // event logs types
  159. define('LOG_COURSE_DELETE', 'course_deleted');
  160. define('LOG_COURSE_CREATE', 'course_created');
  161. // @todo replace 'soc_gr' with social_group
  162. define('LOG_GROUP_PORTAL_CREATED', 'soc_gr_created');
  163. define('LOG_GROUP_PORTAL_UPDATED', 'soc_gr_updated');
  164. define('LOG_GROUP_PORTAL_DELETED', 'soc_gr_deleted');
  165. define('LOG_GROUP_PORTAL_USER_DELETE_ALL', 'soc_gr_delete_users');
  166. define('LOG_GROUP_PORTAL_ID', 'soc_gr_portal_id');
  167. define('LOG_GROUP_PORTAL_REL_USER_ARRAY', 'soc_gr_user_array');
  168. define('LOG_GROUP_PORTAL_USER_SUBSCRIBED', 'soc_gr_u_subs');
  169. define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED', 'soc_gr_u_unsubs');
  170. define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE', 'soc_gr_update_role');
  171. define('LOG_USER_DELETE', 'user_deleted');
  172. define('LOG_USER_CREATE', 'user_created');
  173. define('LOG_USER_ENABLE', 'user_enable');
  174. define('LOG_USER_DISABLE', 'user_disable');
  175. define('LOG_USER_ANONYMIZE', 'user_anonymized');
  176. define('LOG_USER_FIELD_CREATE', 'user_field_created');
  177. define('LOG_USER_FIELD_DELETE', 'user_field_deleted');
  178. define('LOG_SESSION_CREATE', 'session_created');
  179. define('LOG_SESSION_DELETE', 'session_deleted');
  180. define('LOG_SESSION_ADD_USER_COURSE', 'session_add_user_course');
  181. define('LOG_SESSION_DELETE_USER_COURSE', 'session_delete_user_course');
  182. define('LOG_SESSION_ADD_USER', 'session_add_user');
  183. define('LOG_SESSION_DELETE_USER', 'session_delete_user');
  184. define('LOG_SESSION_ADD_COURSE', 'session_add_course');
  185. define('LOG_SESSION_DELETE_COURSE', 'session_delete_course');
  186. define('LOG_SESSION_CATEGORY_CREATE', 'session_cat_created'); //changed in 1.9.8
  187. define('LOG_SESSION_CATEGORY_DELETE', 'session_cat_deleted'); //changed in 1.9.8
  188. define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
  189. define('LOG_PLATFORM_LANGUAGE_CHANGE', 'platform_lng_changed'); //changed in 1.9.8
  190. define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
  191. define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
  192. define('LOG_ATTEMPTED_FORCED_LOGIN', 'attempted_forced_login');
  193. define('LOG_HOMEPAGE_CHANGED', 'homepage_changed');
  194. define('LOG_PROMOTION_CREATE', 'promotion_created');
  195. define('LOG_PROMOTION_DELETE', 'promotion_deleted');
  196. define('LOG_CAREER_CREATE', 'career_created');
  197. define('LOG_CAREER_DELETE', 'career_deleted');
  198. define('LOG_USER_PERSONAL_DOC_DELETED', 'user_doc_deleted');
  199. define('LOG_WIKI_ACCESS', 'wiki_page_view');
  200. // All results from an exercise
  201. define('LOG_EXERCISE_RESULT_DELETE', 'exe_result_deleted');
  202. // Logs only the one attempt
  203. define('LOG_EXERCISE_ATTEMPT_DELETE', 'exe_attempt_deleted');
  204. define('LOG_LP_ATTEMPT_DELETE', 'lp_attempt_deleted');
  205. define('LOG_QUESTION_RESULT_DELETE', 'qst_attempt_deleted');
  206. define('LOG_MY_FOLDER_CREATE', 'my_folder_created');
  207. define('LOG_MY_FOLDER_CHANGE', 'my_folder_changed');
  208. define('LOG_MY_FOLDER_DELETE', 'my_folder_deleted');
  209. define('LOG_MY_FOLDER_COPY', 'my_folder_copied');
  210. define('LOG_MY_FOLDER_CUT', 'my_folder_cut');
  211. define('LOG_MY_FOLDER_PASTE', 'my_folder_pasted');
  212. define('LOG_MY_FOLDER_UPLOAD', 'my_folder_uploaded');
  213. // Event logs data types (max 20 chars)
  214. define('LOG_COURSE_CODE', 'course_code');
  215. define('LOG_COURSE_ID', 'course_id');
  216. define('LOG_USER_ID', 'user_id');
  217. define('LOG_USER_OBJECT', 'user_object');
  218. define('LOG_USER_FIELD_VARIABLE', 'user_field_variable');
  219. define('LOG_SESSION_ID', 'session_id');
  220. define('LOG_QUESTION_ID', 'question_id');
  221. define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
  222. define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
  223. define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
  224. define('LOG_PLATFORM_LANGUAGE', 'default_platform_language');
  225. define('LOG_CAREER_ID', 'career_id');
  226. define('LOG_PROMOTION_ID', 'promotion_id');
  227. define('LOG_GRADEBOOK_LOCKED', 'gradebook_locked');
  228. define('LOG_GRADEBOOK_UNLOCKED', 'gradebook_unlocked');
  229. define('LOG_GRADEBOOK_ID', 'gradebook_id');
  230. define('LOG_WIKI_PAGE_ID', 'wiki_page_id');
  231. define('LOG_EXERCISE_ID', 'exercise_id');
  232. define('LOG_EXERCISE_AND_USER_ID', 'exercise_and_user_id');
  233. define('LOG_LP_ID', 'lp_id');
  234. define('LOG_EXERCISE_ATTEMPT_QUESTION_ID', 'exercise_a_q_id');
  235. define('LOG_EXERCISE_ATTEMPT', 'exe_id');
  236. define('LOG_WORK_DIR_DELETE', 'work_dir_delete');
  237. define('LOG_WORK_FILE_DELETE', 'work_file_delete');
  238. define('LOG_WORK_DATA', 'work_data_array');
  239. define('LOG_MY_FOLDER_PATH', 'path');
  240. define('LOG_MY_FOLDER_NEW_PATH', 'new_path');
  241. define('LOG_TERM_CONDITION_ACCEPTED', 'term_condition_accepted');
  242. define('LOG_USER_CONFIRMED_EMAIL', 'user_confirmed_email');
  243. define('LOG_USER_REMOVED_LEGAL_ACCEPT', 'user_removed_legal_accept');
  244. define('LOG_USER_DELETE_ACCOUNT_REQUEST', 'user_delete_account_request');
  245. define('LOG_QUESTION_CREATED', 'question_created');
  246. define('LOG_QUESTION_UPDATED', 'question_updated');
  247. define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.]/');
  248. //used when login_is_email setting is true
  249. define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
  250. define('USERNAME_PURIFIER_SHALLOW', '/\s/');
  251. // This constant is a result of Windows OS detection, it has a boolean value:
  252. // true whether the server runs on Windows OS, false otherwise.
  253. define('IS_WINDOWS_OS', api_is_windows_os());
  254. // Checks for installed optional php-extensions.
  255. // intl extension (from PECL), it is installed by default as of PHP 5.3.0.
  256. define('INTL_INSTALLED', function_exists('intl_get_error_code'));
  257. // iconv extension, for PHP5 on Windows it is installed by default.
  258. define('ICONV_INSTALLED', function_exists('iconv'));
  259. define('MBSTRING_INSTALLED', function_exists('mb_strlen')); // mbstring extension.
  260. // Patterns for processing paths. Examples.
  261. define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  262. define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
  263. // $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
  264. define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i');
  265. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  266. // basic (leaf elements)
  267. define('REL_CODE_PATH', 'REL_CODE_PATH');
  268. define('REL_COURSE_PATH', 'REL_COURSE_PATH');
  269. define('REL_HOME_PATH', 'REL_HOME_PATH');
  270. // Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
  271. define('WEB_PATH', 'WEB_PATH');
  272. define('WEB_APP_PATH', 'WEB_APP_PATH');
  273. define('SYS_PATH', 'SYS_PATH');
  274. define('SYS_APP_PATH', 'SYS_APP_PATH');
  275. define('SYS_UPLOAD_PATH', 'SYS_UPLOAD_PATH');
  276. define('WEB_UPLOAD_PATH', 'WEB_UPLOAD_PATH');
  277. define('REL_PATH', 'REL_PATH');
  278. define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
  279. define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
  280. define('WEB_CODE_PATH', 'WEB_CODE_PATH');
  281. define('SYS_CODE_PATH', 'SYS_CODE_PATH');
  282. define('SYS_LANG_PATH', 'SYS_LANG_PATH');
  283. define('WEB_IMG_PATH', 'WEB_IMG_PATH');
  284. define('WEB_CSS_PATH', 'WEB_CSS_PATH');
  285. define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
  286. define('SYS_CSS_PATH', 'SYS_CSS_PATH');
  287. define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
  288. define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
  289. define('WEB_PLUGIN_ASSET_PATH', 'WEB_PLUGIN_ASSET_PATH');
  290. define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
  291. define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
  292. define('SYS_INC_PATH', 'SYS_INC_PATH');
  293. define('LIBRARY_PATH', 'LIBRARY_PATH');
  294. define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
  295. define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
  296. define('WEB_LIBRARY_JS_PATH', 'WEB_LIBRARY_JS_PATH');
  297. define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
  298. define('SYS_TEST_PATH', 'SYS_TEST_PATH');
  299. define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
  300. define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
  301. define('SYS_PUBLIC_PATH', 'SYS_PUBLIC_PATH');
  302. define('SYS_HOME_PATH', 'SYS_HOME_PATH');
  303. define('WEB_HOME_PATH', 'WEB_HOME_PATH');
  304. define('WEB_FONTS_PATH', 'WEB_FONTS_PATH');
  305. define('SYS_FONTS_PATH', 'SYS_FONTS_PATH');
  306. define('SYS_DEFAULT_COURSE_DOCUMENT_PATH', 'SYS_DEFAULT_COURSE_DOCUMENT_PATH');
  307. define('REL_DEFAULT_COURSE_DOCUMENT_PATH', 'REL_DEFAULT_COURSE_DOCUMENT_PATH');
  308. define('WEB_DEFAULT_COURSE_DOCUMENT_PATH', 'WEB_DEFAULT_COURSE_DOCUMENT_PATH');
  309. // Relations type with Course manager
  310. define('COURSE_RELATION_TYPE_COURSE_MANAGER', 1);
  311. define('SESSION_RELATION_TYPE_COURSE_MANAGER', 1);
  312. // Relations type with Human resources manager
  313. define('COURSE_RELATION_TYPE_RRHH', 1);
  314. define('SESSION_RELATION_TYPE_RRHH', 1);
  315. //User image sizes
  316. define('USER_IMAGE_SIZE_ORIGINAL', 1);
  317. define('USER_IMAGE_SIZE_BIG', 2);
  318. define('USER_IMAGE_SIZE_MEDIUM', 3);
  319. define('USER_IMAGE_SIZE_SMALL', 4);
  320. // Relation type between users
  321. define('USER_UNKNOWN', 0);
  322. define('USER_RELATION_TYPE_UNKNOWN', 1);
  323. define('USER_RELATION_TYPE_PARENT', 2); // should be deprecated is useless
  324. define('USER_RELATION_TYPE_FRIEND', 3);
  325. define('USER_RELATION_TYPE_GOODFRIEND', 4); // should be deprecated is useless
  326. define('USER_RELATION_TYPE_ENEMY', 5); // should be deprecated is useless
  327. define('USER_RELATION_TYPE_DELETED', 6);
  328. define('USER_RELATION_TYPE_RRHH', 7);
  329. define('USER_RELATION_TYPE_BOSS', 8);
  330. define('USER_RELATION_TYPE_HRM_REQUEST', 9);
  331. // Gradebook link constants
  332. // Please do not change existing values, they are used in the database !
  333. define('GRADEBOOK_ITEM_LIMIT', 1000);
  334. define('LINK_EXERCISE', 1);
  335. define('LINK_DROPBOX', 2);
  336. define('LINK_STUDENTPUBLICATION', 3);
  337. define('LINK_LEARNPATH', 4);
  338. define('LINK_FORUM_THREAD', 5);
  339. //define('LINK_WORK',6);
  340. define('LINK_ATTENDANCE', 7);
  341. define('LINK_SURVEY', 8);
  342. define('LINK_HOTPOTATOES', 9);
  343. // Score display types constants
  344. define('SCORE_DIV', 1); // X / Y
  345. define('SCORE_PERCENT', 2); // XX %
  346. define('SCORE_DIV_PERCENT', 3); // X / Y (XX %)
  347. define('SCORE_AVERAGE', 4); // XX %
  348. define('SCORE_DECIMAL', 5); // 0.50 (X/Y)
  349. define('SCORE_BAR', 6); // Uses the Display::bar_progress function
  350. define('SCORE_SIMPLE', 7); // X
  351. define('SCORE_IGNORE_SPLIT', 8); // ??
  352. define('SCORE_DIV_PERCENT_WITH_CUSTOM', 9); // X / Y (XX %) - Good!
  353. define('SCORE_CUSTOM', 10); // Good!
  354. define('SCORE_DIV_SIMPLE_WITH_CUSTOM', 11); // X - Good!
  355. define('SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS', 12); // X - Good!
  356. define('SCORE_ONLY_SCORE', 13); // X - Good!
  357. define('SCORE_NUMERIC', 14);
  358. define('SCORE_BOTH', 1);
  359. define('SCORE_ONLY_DEFAULT', 2);
  360. define('SCORE_ONLY_CUSTOM', 3);
  361. // From display.lib.php
  362. define('MAX_LENGTH_BREADCRUMB', 100);
  363. define('ICON_SIZE_ATOM', 8);
  364. define('ICON_SIZE_TINY', 16);
  365. define('ICON_SIZE_SMALL', 22);
  366. define('ICON_SIZE_MEDIUM', 32);
  367. define('ICON_SIZE_LARGE', 48);
  368. define('ICON_SIZE_BIG', 64);
  369. define('ICON_SIZE_HUGE', 128);
  370. define('SHOW_TEXT_NEAR_ICONS', false);
  371. // Session catalog
  372. define('CATALOG_COURSES', 0);
  373. define('CATALOG_SESSIONS', 1);
  374. define('CATALOG_COURSES_SESSIONS', 2);
  375. // Hook type events, pre-process and post-process.
  376. // All means to be executed for both hook event types
  377. define('HOOK_EVENT_TYPE_PRE', 0);
  378. define('HOOK_EVENT_TYPE_POST', 1);
  379. define('HOOK_EVENT_TYPE_ALL', 10);
  380. define('CAREER_STATUS_ACTIVE', 1);
  381. define('CAREER_STATUS_INACTIVE', 0);
  382. define('PROMOTION_STATUS_ACTIVE', 1);
  383. define('PROMOTION_STATUS_INACTIVE', 0);
  384. // Group permissions
  385. define('GROUP_PERMISSION_OPEN', '1');
  386. define('GROUP_PERMISSION_CLOSED', '2');
  387. // Group user permissions
  388. define('GROUP_USER_PERMISSION_ADMIN', '1'); // the admin of a group
  389. define('GROUP_USER_PERMISSION_READER', '2'); // a normal user
  390. define('GROUP_USER_PERMISSION_PENDING_INVITATION', '3'); // When an admin/moderator invites a user
  391. define('GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER', '4'); // an user joins a group
  392. define('GROUP_USER_PERMISSION_MODERATOR', '5'); // a moderator
  393. define('GROUP_USER_PERMISSION_ANONYMOUS', '6'); // an anonymous user
  394. define('GROUP_USER_PERMISSION_HRM', '7'); // a human resources manager
  395. define('GROUP_IMAGE_SIZE_ORIGINAL', 1);
  396. define('GROUP_IMAGE_SIZE_BIG', 2);
  397. define('GROUP_IMAGE_SIZE_MEDIUM', 3);
  398. define('GROUP_IMAGE_SIZE_SMALL', 4);
  399. define('GROUP_TITLE_LENGTH', 50);
  400. // Exercise
  401. // @todo move into a class
  402. define('ALL_ON_ONE_PAGE', 1);
  403. define('ONE_PER_PAGE', 2);
  404. define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback - show score and expected answers
  405. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
  406. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); // NoFeedback - Show score only
  407. define('EXERCISE_FEEDBACK_TYPE_POPUP', 3); // Popup BT#15827
  408. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
  409. define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
  410. define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
  411. define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
  412. define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4);
  413. define('RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK', 5);
  414. define('RESULT_DISABLE_RANKING', 6);
  415. define('RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER', 7);
  416. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING', 8);
  417. define('EXERCISE_MAX_NAME_SIZE', 80);
  418. // Question types (edit next array as well when adding values)
  419. // @todo move into a class
  420. define('UNIQUE_ANSWER', 1);
  421. define('MULTIPLE_ANSWER', 2);
  422. define('FILL_IN_BLANKS', 3);
  423. define('MATCHING', 4);
  424. define('FREE_ANSWER', 5);
  425. define('HOT_SPOT', 6);
  426. define('HOT_SPOT_ORDER', 7);
  427. define('HOT_SPOT_DELINEATION', 8);
  428. define('MULTIPLE_ANSWER_COMBINATION', 9);
  429. define('UNIQUE_ANSWER_NO_OPTION', 10);
  430. define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
  431. define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
  432. define('ORAL_EXPRESSION', 13);
  433. define('GLOBAL_MULTIPLE_ANSWER', 14);
  434. define('MEDIA_QUESTION', 15);
  435. define('CALCULATED_ANSWER', 16);
  436. define('UNIQUE_ANSWER_IMAGE', 17);
  437. define('DRAGGABLE', 18);
  438. define('MATCHING_DRAGGABLE', 19);
  439. define('ANNOTATION', 20);
  440. define('READING_COMPREHENSION', 21);
  441. define('MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY', 22);
  442. define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
  443. define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
  444. define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
  445. // Question selection type
  446. define('EX_Q_SELECTION_ORDERED', 1);
  447. define('EX_Q_SELECTION_RANDOM', 2);
  448. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
  449. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
  450. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
  451. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
  452. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
  453. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
  454. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
  455. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
  456. // Used to save the skill_rel_item table
  457. define('ITEM_TYPE_EXERCISE', 1);
  458. define('ITEM_TYPE_HOTPOTATOES', 2);
  459. define('ITEM_TYPE_LINK', 3);
  460. define('ITEM_TYPE_LEARNPATH', 4);
  461. define('ITEM_TYPE_GRADEBOOK', 5);
  462. define('ITEM_TYPE_STUDENT_PUBLICATION', 6);
  463. //define('ITEM_TYPE_FORUM', 7);
  464. define('ITEM_TYPE_ATTENDANCE', 8);
  465. define('ITEM_TYPE_SURVEY', 9);
  466. define('ITEM_TYPE_FORUM_THREAD', 10);
  467. // one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
  468. define(
  469. 'QUESTION_TYPES',
  470. UNIQUE_ANSWER.':'.
  471. MULTIPLE_ANSWER.':'.
  472. FILL_IN_BLANKS.':'.
  473. MATCHING.':'.
  474. FREE_ANSWER.':'.
  475. HOT_SPOT.':'.
  476. HOT_SPOT_ORDER.':'.
  477. HOT_SPOT_DELINEATION.':'.
  478. MULTIPLE_ANSWER_COMBINATION.':'.
  479. UNIQUE_ANSWER_NO_OPTION.':'.
  480. MULTIPLE_ANSWER_TRUE_FALSE.':'.
  481. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
  482. ORAL_EXPRESSION.':'.
  483. GLOBAL_MULTIPLE_ANSWER.':'.
  484. MEDIA_QUESTION.':'.
  485. CALCULATED_ANSWER.':'.
  486. UNIQUE_ANSWER_IMAGE.':'.
  487. DRAGGABLE.':'.
  488. MATCHING_DRAGGABLE.':'.
  489. MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY.':'.
  490. ANNOTATION
  491. );
  492. //Some alias used in the QTI exports
  493. define('MCUA', 1);
  494. define('TF', 1);
  495. define('MCMA', 2);
  496. define('FIB', 3);
  497. // Skills
  498. define('SKILL_TYPE_REQUIREMENT', 'required');
  499. define('SKILL_TYPE_ACQUIRED', 'acquired');
  500. define('SKILL_TYPE_BOTH', 'both');
  501. // Message
  502. define('MESSAGE_STATUS_NEW', '0');
  503. define('MESSAGE_STATUS_UNREAD', '1');
  504. //2 ??
  505. define('MESSAGE_STATUS_DELETED', '3');
  506. define('MESSAGE_STATUS_OUTBOX', '4');
  507. define('MESSAGE_STATUS_INVITATION_PENDING', '5');
  508. define('MESSAGE_STATUS_INVITATION_ACCEPTED', '6');
  509. define('MESSAGE_STATUS_INVITATION_DENIED', '7');
  510. define('MESSAGE_STATUS_WALL', '8');
  511. define('MESSAGE_STATUS_WALL_DELETE', '9');
  512. define('MESSAGE_STATUS_WALL_POST', '10');
  513. define('MESSAGE_STATUS_CONVERSATION', '11');
  514. define('MESSAGE_STATUS_FORUM', '12');
  515. define('MESSAGE_STATUS_PROMOTED', '13');
  516. // Images
  517. define('IMAGE_WALL_SMALL_SIZE', 200);
  518. define('IMAGE_WALL_MEDIUM_SIZE', 500);
  519. define('IMAGE_WALL_BIG_SIZE', 2000);
  520. define('IMAGE_WALL_SMALL', 'small');
  521. define('IMAGE_WALL_MEDIUM', 'medium');
  522. define('IMAGE_WALL_BIG', 'big');
  523. // Social PLUGIN PLACES
  524. define('SOCIAL_LEFT_PLUGIN', 1);
  525. define('SOCIAL_CENTER_PLUGIN', 2);
  526. define('SOCIAL_RIGHT_PLUGIN', 3);
  527. define('CUT_GROUP_NAME', 50);
  528. /**
  529. * FormValidator Filter.
  530. */
  531. define('NO_HTML', 1);
  532. define('STUDENT_HTML', 2);
  533. define('TEACHER_HTML', 3);
  534. define('STUDENT_HTML_FULLPAGE', 4);
  535. define('TEACHER_HTML_FULLPAGE', 5);
  536. // Timeline
  537. define('TIMELINE_STATUS_ACTIVE', '1');
  538. define('TIMELINE_STATUS_INACTIVE', '2');
  539. // Event email template class
  540. define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
  541. define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
  542. // Course home
  543. define('SHORTCUTS_HORIZONTAL', 0);
  544. define('SHORTCUTS_VERTICAL', 1);
  545. // Image class
  546. define('IMAGE_PROCESSOR', 'gd'); // 'imagick' or 'gd' strings
  547. // Course copy
  548. define('FILE_SKIP', 1);
  549. define('FILE_RENAME', 2);
  550. define('FILE_OVERWRITE', 3);
  551. define('UTF8_CONVERT', false); //false by default
  552. define('DOCUMENT', 'file');
  553. define('FOLDER', 'folder');
  554. define('RESOURCE_ASSET', 'asset');
  555. define('RESOURCE_DOCUMENT', 'document');
  556. define('RESOURCE_GLOSSARY', 'glossary');
  557. define('RESOURCE_EVENT', 'calendar_event');
  558. define('RESOURCE_LINK', 'link');
  559. define('RESOURCE_COURSEDESCRIPTION', 'course_description');
  560. define('RESOURCE_LEARNPATH', 'learnpath');
  561. define('RESOURCE_LEARNPATH_CATEGORY', 'learnpath_category');
  562. define('RESOURCE_ANNOUNCEMENT', 'announcement');
  563. define('RESOURCE_FORUM', 'forum');
  564. define('RESOURCE_FORUMTOPIC', 'thread');
  565. define('RESOURCE_FORUMPOST', 'post');
  566. define('RESOURCE_QUIZ', 'quiz');
  567. define('RESOURCE_TEST_CATEGORY', 'test_category');
  568. define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
  569. define('RESOURCE_TOOL_INTRO', 'Tool introduction');
  570. define('RESOURCE_LINKCATEGORY', 'Link_Category');
  571. define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
  572. define('RESOURCE_SCORM', 'Scorm');
  573. define('RESOURCE_SURVEY', 'survey');
  574. define('RESOURCE_SURVEYQUESTION', 'survey_question');
  575. define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
  576. define('RESOURCE_WIKI', 'wiki');
  577. define('RESOURCE_THEMATIC', 'thematic');
  578. define('RESOURCE_ATTENDANCE', 'attendance');
  579. define('RESOURCE_WORK', 'work');
  580. define('RESOURCE_SESSION_COURSE', 'session_course');
  581. define('RESOURCE_GRADEBOOK', 'gradebook');
  582. define('ADD_THEMATIC_PLAN', 6);
  583. // Max online users to show per page (whoisonline)
  584. define('MAX_ONLINE_USERS', 12);
  585. // Number of characters maximum to show in preview of course blog posts
  586. define('BLOG_MAX_PREVIEW_CHARS', 800);
  587. // HTML string to replace with a 'Read more...' link
  588. define('BLOG_PAGE_BREAK', '<div style="page-break-after: always"><span style="display: none;">&nbsp;</span></div>');
  589. // Make sure the CHAMILO_LOAD_WYSIWYG constant is defined
  590. // To remove CKeditor libs from HTML, set this constant to true before loading
  591. if (!defined('CHAMILO_LOAD_WYSIWYG')) {
  592. define('CHAMILO_LOAD_WYSIWYG', true);
  593. }
  594. /* Constants for course home */
  595. define('TOOL_PUBLIC', 'Public');
  596. define('TOOL_PUBLIC_BUT_HIDDEN', 'PublicButHide');
  597. define('TOOL_COURSE_ADMIN', 'courseAdmin');
  598. define('TOOL_PLATFORM_ADMIN', 'platformAdmin');
  599. define('TOOL_AUTHORING', 'toolauthoring');
  600. define('TOOL_INTERACTION', 'toolinteraction');
  601. define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
  602. define('TOOL_ADMIN', 'tooladmin');
  603. define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
  604. define('TOOL_DRH', 'tool_drh');
  605. define('TOOL_STUDENT_VIEW', 'toolstudentview');
  606. define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
  607. /**
  608. * Inclusion of internationalization libraries.
  609. */
  610. require_once __DIR__.'/internationalization.lib.php';
  611. /**
  612. * Returns a path to a certain resource within the Chamilo area, specifyed through a parameter.
  613. * Also, this function provides conversion between path types, in this case the input path points inside the Chamilo area too.
  614. *
  615. * See $_configuration['course_folder'] in the configuration.php to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
  616. *
  617. * @param string $path (optional) A path which type is to be converted. Also, it may be a defined constant for a path.
  618. * This parameter has meaning when $type parameter has one of the following values: TO_WEB, TO_SYS, TO_REL. Otherwise it is ignored.
  619. *
  620. * @return string the requested path or the converted path
  621. *
  622. *
  623. * Notes about the current behaviour model:
  624. * 1. Windows back-slashes are converted to slashes in the result.
  625. * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
  626. * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
  627. * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
  628. * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
  629. * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
  630. * It has not been identified as needed yet.
  631. * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
  632. *
  633. * For examples go to: *
  634. * See main/admin/system_status.php?section=paths
  635. *
  636. * Vchamilo changes : allow using an alternate configuration
  637. * to get vchamilo instance paths
  638. */
  639. function api_get_path($path = '', $configuration = [])
  640. {
  641. global $paths;
  642. // get proper configuration data if exists
  643. global $_configuration;
  644. $emptyConfigurationParam = false;
  645. if (empty($configuration)) {
  646. $configuration = (array) $_configuration;
  647. $emptyConfigurationParam = true;
  648. }
  649. $course_folder = 'courses/';
  650. static $root_web = '';
  651. $root_sys = $_configuration['root_sys'];
  652. // If no $root_web has been set so far *and* no custom config has been passed to the function
  653. // then re-use the previously-calculated (run-specific) $root_web and skip this complex calculation
  654. if (empty($root_web) || $emptyConfigurationParam === false || empty($configuration)) {
  655. // Resolve master hostname.
  656. if (!empty($configuration) && array_key_exists('root_web', $configuration)) {
  657. $root_web = $configuration['root_web'];
  658. } else {
  659. $root_web = '';
  660. // Try guess it from server.
  661. if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) {
  662. if (($pos = strpos(($requested_page_rel = api_get_self()), 'main/install')) !== false) {
  663. $root_rel = substr($requested_page_rel, 0, $pos);
  664. // See http://www.mediawiki.org/wiki/Manual:$wgServer
  665. $server_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
  666. $server_name =
  667. isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME']
  668. : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
  669. : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
  670. : (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR']
  671. : 'localhost')));
  672. if (isset($_SERVER['SERVER_PORT']) &&
  673. !strpos($server_name, ':') &&
  674. (($server_protocol == 'http' && $_SERVER['SERVER_PORT'] != 80) ||
  675. ($server_protocol == 'https' && $_SERVER['SERVER_PORT'] != 443))
  676. ) {
  677. $server_name .= ":".$_SERVER['SERVER_PORT'];
  678. }
  679. $root_web = $server_protocol.'://'.$server_name.$root_rel;
  680. $root_sys = str_replace('\\', '/', realpath(__DIR__.'/../../../')).'/';
  681. }
  682. // Here we give up, so we don't touch anything.
  683. }
  684. }
  685. }
  686. if (isset($configuration['multiple_access_urls']) &&
  687. $configuration['multiple_access_urls']
  688. ) {
  689. // To avoid that the api_get_access_url() function fails since global.inc.php also calls the api.lib.php.
  690. if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
  691. // We look into the DB the function api_get_access_url
  692. $urlInfo = api_get_access_url($configuration['access_url']);
  693. // Avoid default value
  694. $defaultValues = ['http://localhost/', 'https://localhost/'];
  695. if (!empty($urlInfo['url']) && !in_array($urlInfo['url'], $defaultValues)) {
  696. $root_web = $urlInfo['active'] == 1 ? $urlInfo['url'] : $configuration['root_web'];
  697. }
  698. }
  699. }
  700. $paths = [];
  701. // Initialise cache with default values.
  702. if (!array_key_exists($root_web, $paths)) {
  703. $paths[$root_web] = [
  704. WEB_PATH => '',
  705. SYS_PATH => '',
  706. REL_PATH => '',
  707. WEB_COURSE_PATH => '',
  708. SYS_COURSE_PATH => '',
  709. REL_COURSE_PATH => '',
  710. WEB_CODE_PATH => 'main/',
  711. SYS_CODE_PATH => 'main/',
  712. REL_CODE_PATH => '/main/',
  713. SYS_LANG_PATH => 'lang/',
  714. WEB_IMG_PATH => 'img/',
  715. WEB_CSS_PATH => 'web/css/',
  716. SYS_CSS_PATH => 'app/Resources/public/css/',
  717. SYS_PLUGIN_PATH => 'plugin/',
  718. WEB_PLUGIN_PATH => 'plugin/',
  719. WEB_PLUGIN_ASSET_PATH => 'public/plugins/',
  720. SYS_ARCHIVE_PATH => 'app/cache/',
  721. WEB_ARCHIVE_PATH => 'app/cache/',
  722. SYS_HOME_PATH => 'app/home/',
  723. WEB_HOME_PATH => 'app/home/',
  724. REL_HOME_PATH => 'app/home/',
  725. SYS_APP_PATH => 'app/',
  726. WEB_APP_PATH => 'app/',
  727. SYS_UPLOAD_PATH => 'app/upload/',
  728. SYS_INC_PATH => 'inc/',
  729. CONFIGURATION_PATH => 'app/config/',
  730. LIBRARY_PATH => 'inc/lib/',
  731. WEB_LIBRARY_PATH => 'inc/lib/',
  732. WEB_LIBRARY_JS_PATH => 'inc/lib/javascript/',
  733. WEB_AJAX_PATH => 'inc/ajax/',
  734. SYS_TEST_PATH => 'tests/',
  735. WEB_TEMPLATE_PATH => 'template/',
  736. SYS_TEMPLATE_PATH => 'template/',
  737. WEB_UPLOAD_PATH => 'app/upload/',
  738. WEB_PUBLIC_PATH => 'web/',
  739. SYS_PUBLIC_PATH => 'web/',
  740. WEB_FONTS_PATH => 'fonts/',
  741. SYS_FONTS_PATH => 'fonts/',
  742. ];
  743. }
  744. $isInitialized = [];
  745. $course_folder = isset($configuration['course_folder']) ? $configuration['course_folder'] : $course_folder;
  746. $root_rel = isset($configuration['url_append']) ? $configuration['url_append'] : '';
  747. if (!empty($root_rel)) {
  748. // Adds "/" to the root_rel
  749. $hasSlash = substr($configuration['url_append'], 0, 1);
  750. if ($hasSlash !== '/') {
  751. $root_rel = '/'.$root_rel;
  752. }
  753. }
  754. // Web server base and system server base.
  755. if (!array_key_exists($root_web, $isInitialized)) {
  756. // process absolute global roots
  757. if (!empty($configuration)) {
  758. $code_folder = 'main';
  759. } else {
  760. $code_folder = $paths[$root_web][REL_CODE_PATH];
  761. }
  762. // Support for the installation process.
  763. // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
  764. // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
  765. // Dealing with trailing slashes.
  766. $slashed_root_web = api_add_trailing_slash($root_web);
  767. $root_sys = api_add_trailing_slash($root_sys);
  768. $root_rel = api_add_trailing_slash($root_rel);
  769. $code_folder = api_add_trailing_slash($code_folder);
  770. $course_folder = api_add_trailing_slash($course_folder);
  771. // Initialization of a table that contains common-purpose paths.
  772. $paths[$root_web][REL_PATH] = $root_rel;
  773. $paths[$root_web][REL_COURSE_PATH] = $root_rel.$course_folder;
  774. $paths[$root_web][REL_CODE_PATH] = $root_rel.$code_folder;
  775. $paths[$root_web][REL_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][REL_PATH].'main/default_course_document/';
  776. $paths[$root_web][WEB_PATH] = $slashed_root_web;
  777. $paths[$root_web][WEB_CODE_PATH] = $paths[$root_web][WEB_PATH].$code_folder;
  778. $paths[$root_web][WEB_COURSE_PATH] = $paths[$root_web][WEB_PATH].$course_folder;
  779. $paths[$root_web][WEB_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][WEB_CODE_PATH].'default_course_document/';
  780. $paths[$root_web][WEB_APP_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_APP_PATH];
  781. $paths[$root_web][WEB_PLUGIN_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_PATH];
  782. $paths[$root_web][WEB_PLUGIN_ASSET_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_ASSET_PATH];
  783. $paths[$root_web][WEB_ARCHIVE_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_ARCHIVE_PATH];
  784. $paths[$root_web][WEB_CSS_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_CSS_PATH];
  785. $paths[$root_web][WEB_IMG_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_IMG_PATH];
  786. $paths[$root_web][WEB_LIBRARY_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_PATH];
  787. $paths[$root_web][WEB_LIBRARY_JS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_JS_PATH];
  788. $paths[$root_web][WEB_AJAX_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_AJAX_PATH];
  789. $paths[$root_web][WEB_FONTS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_FONTS_PATH];
  790. $paths[$root_web][WEB_TEMPLATE_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_TEMPLATE_PATH];
  791. $paths[$root_web][WEB_UPLOAD_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_UPLOAD_PATH];
  792. $paths[$root_web][WEB_PUBLIC_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PUBLIC_PATH];
  793. $paths[$root_web][WEB_HOME_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][REL_HOME_PATH];
  794. $paths[$root_web][SYS_PATH] = $root_sys;
  795. $paths[$root_web][SYS_CODE_PATH] = $root_sys.$code_folder;
  796. $paths[$root_web][SYS_TEST_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_TEST_PATH];
  797. $paths[$root_web][SYS_TEMPLATE_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_TEMPLATE_PATH];
  798. $paths[$root_web][SYS_PUBLIC_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PUBLIC_PATH];
  799. $paths[$root_web][SYS_CSS_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_CSS_PATH];
  800. $paths[$root_web][SYS_FONTS_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_FONTS_PATH];
  801. $paths[$root_web][SYS_ARCHIVE_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_ARCHIVE_PATH];
  802. $paths[$root_web][SYS_APP_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_APP_PATH];
  803. $paths[$root_web][SYS_COURSE_PATH] = $paths[$root_web][SYS_APP_PATH].$course_folder;
  804. $paths[$root_web][SYS_UPLOAD_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_UPLOAD_PATH];
  805. $paths[$root_web][SYS_LANG_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_LANG_PATH];
  806. $paths[$root_web][SYS_HOME_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_HOME_PATH];
  807. $paths[$root_web][SYS_PLUGIN_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PLUGIN_PATH];
  808. $paths[$root_web][SYS_INC_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_INC_PATH];
  809. $paths[$root_web][LIBRARY_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][LIBRARY_PATH];
  810. $paths[$root_web][CONFIGURATION_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][CONFIGURATION_PATH];
  811. global $virtualChamilo;
  812. if (!empty($virtualChamilo)) {
  813. $paths[$root_web][SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
  814. $paths[$root_web][SYS_HOME_PATH] = api_add_trailing_slash($virtualChamilo[SYS_HOME_PATH]);
  815. $paths[$root_web][SYS_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_COURSE_PATH]);
  816. $paths[$root_web][SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
  817. $paths[$root_web][WEB_HOME_PATH] = api_add_trailing_slash($virtualChamilo[WEB_HOME_PATH]);
  818. $paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
  819. $paths[$root_web][WEB_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_ARCHIVE_PATH]);
  820. //$paths[$root_web][WEB_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_COURSE_PATH]);
  821. // WEB_UPLOAD_PATH should be handle by apache htaccess in the vhost
  822. // RewriteEngine On
  823. // RewriteRule /app/upload/(.*)$ http://localhost/other/upload/my-chamilo111-net/$1 [QSA,L]
  824. //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
  825. //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
  826. //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
  827. }
  828. $isInitialized[$root_web] = true;
  829. }
  830. $path = trim($path);
  831. // Retrieving a common-purpose path.
  832. if (isset($paths[$root_web][$path])) {
  833. return $paths[$root_web][$path];
  834. }
  835. // Second purification.
  836. // Replacing Windows back slashes.
  837. $path = str_replace('\\', '/', $path);
  838. // Query strings sometimes mighth wrongly appear in non-URLs.
  839. // Let us check remove them from all types of paths.
  840. if (($pos = strpos($path, '?')) !== false) {
  841. $path = substr($path, 0, $pos);
  842. }
  843. // Detection of the input path type. Conversion to semi-absolute type ( /chamilo/main/inc/.... ).
  844. if (preg_match(VALID_WEB_PATH, $path)) {
  845. // A special case: When a URL points to the document download script directly, without
  846. // mod-rewrite translation, we have to translate it into an "ordinary" web path.
  847. // For example:
  848. // http://localhost/chamilo/main/document/download.php?doc_url=/image.png&cDir=/
  849. // becomes
  850. // http://localhost/chamilo/courses/TEST/document/image.png
  851. // TEST is a course directory name, so called "system course code".
  852. if (strpos($path, 'download.php') !== false) { // Fast detection first.
  853. $path = urldecode($path);
  854. if (preg_match('/(.*)main\/document\/download.php\?doc_url=\/(.*)&cDir=\/(.*)?/', $path, $matches)) {
  855. $sys_course_code =
  856. isset($_SESSION['_course']['sysCode']) // User is inside a course?
  857. ? $_SESSION['_course']['sysCode'] // Yes, then use course's directory name.
  858. : '{SYS_COURSE_CODE}'; // No, then use a fake code, it may be processed later.
  859. $path = $matches[1].'courses/'.$sys_course_code.'/document/'.str_replace('//', '/', $matches[3].'/'.$matches[2]);
  860. }
  861. }
  862. // Replacement of the present web server base with a slash '/'.
  863. $path = preg_replace(VALID_WEB_SERVER_BASE, '/', $path);
  864. }
  865. // Path now is semi-absolute. It is convenient at this moment repeated slashes to be removed.
  866. $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
  867. return $path;
  868. }
  869. /**
  870. * Gets a modified version of the path for the CDN, if defined in
  871. * configuration.php.
  872. *
  873. * @param string $web_path The path of the resource without CDN
  874. *
  875. * @return string The path of the resource converted to CDN
  876. *
  877. * @author Yannick Warnier <ywarnier@beeznst.org>
  878. */
  879. function api_get_cdn_path($web_path)
  880. {
  881. global $_configuration;
  882. if (!empty($_configuration['cdn_enable'])) {
  883. $web_root = api_get_path(WEB_PATH);
  884. $ext = substr($web_path, strrpos($web_path, '.'));
  885. if (isset($ext[2])) { // faster version of strlen to check if len>2
  886. // Check for CDN definitions
  887. if (!empty($ext)) {
  888. foreach ($_configuration['cdn'] as $host => $exts) {
  889. if (in_array($ext, $exts)) {
  890. //Use host as defined in $_configuration['cdn'], without
  891. // trailing slash
  892. return str_replace($web_root, $host.'/', $web_path);
  893. }
  894. }
  895. }
  896. }
  897. }
  898. return $web_path;
  899. }
  900. /**
  901. * @return bool Return true if CAS authentification is activated
  902. */
  903. function api_is_cas_activated()
  904. {
  905. return api_get_setting('cas_activate') == "true";
  906. }
  907. /**
  908. * @return bool Return true if LDAP authentification is activated
  909. */
  910. function api_is_ldap_activated()
  911. {
  912. global $extAuthSource;
  913. return is_array($extAuthSource[LDAP_AUTH_SOURCE]);
  914. }
  915. /**
  916. * @return bool Return true if Facebook authentification is activated
  917. */
  918. function api_is_facebook_auth_activated()
  919. {
  920. global $_configuration;
  921. return isset($_configuration['facebook_auth']) && $_configuration['facebook_auth'] == 1;
  922. }
  923. /**
  924. * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
  925. *
  926. * @param string $path the input path
  927. *
  928. * @return string returns the modified path
  929. */
  930. function api_add_trailing_slash($path)
  931. {
  932. return substr($path, -1) == '/' ? $path : $path.'/';
  933. }
  934. /**
  935. * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
  936. *
  937. * @param string $path the input path
  938. *
  939. * @return string returns the modified path
  940. */
  941. function api_remove_trailing_slash($path)
  942. {
  943. return substr($path, -1) == '/' ? substr($path, 0, -1) : $path;
  944. }
  945. /**
  946. * Checks the RFC 3986 syntax of a given URL.
  947. *
  948. * @param string $url the URL to be checked
  949. * @param bool $absolute whether the URL is absolute (beginning with a scheme such as "http:")
  950. *
  951. * @return string|false Returns the URL if it is valid, FALSE otherwise.
  952. * This function is an adaptation from the function valid_url(), Drupal CMS.
  953. *
  954. * @see http://drupal.org
  955. * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
  956. * @see http://bugs.php.net/51192
  957. */
  958. function api_valid_url($url, $absolute = false)
  959. {
  960. if ($absolute) {
  961. if (preg_match("
  962. /^ # Start at the beginning of the text
  963. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  964. (?: # Userinfo (optional) which is typically
  965. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  966. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  967. )?
  968. (?:
  969. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  970. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  971. )
  972. (?::[0-9]+)? # Server port number (optional)
  973. (?:[\/|\?]
  974. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  975. *)?
  976. $/xi", $url)) {
  977. return $url;
  978. }
  979. return false;
  980. } else {
  981. return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
  982. }
  983. }
  984. /**
  985. * Checks whether a given string looks roughly like an email address.
  986. *
  987. * @param string $address the e-mail address to be checked
  988. *
  989. * @return mixed returns the e-mail if it is valid, FALSE otherwise
  990. */
  991. function api_valid_email($address)
  992. {
  993. return filter_var($address, FILTER_VALIDATE_EMAIL);
  994. }
  995. /* PROTECTION FUNCTIONS
  996. Use these functions to protect your scripts. */
  997. /**
  998. * Function used to protect a course script.
  999. * The function blocks access when
  1000. * - there is no $_SESSION["_course"] defined; or
  1001. * - $is_allowed_in_course is set to false (this depends on the course
  1002. * visibility and user status).
  1003. *
  1004. * This is only the first proposal, test and improve!
  1005. *
  1006. * @param bool Option to print headers when displaying error message. Default: false
  1007. * @param bool whether session admins should be allowed or not
  1008. * @param bool $checkTool check if tool is available for users (user, group)
  1009. *
  1010. * @return bool True if the user has access to the current course or is out of a course context, false otherwise
  1011. *
  1012. * @todo replace global variable
  1013. *
  1014. * @author Roan Embrechts
  1015. */
  1016. function api_protect_course_script($print_headers = false, $allow_session_admins = false, $checkTool = '')
  1017. {
  1018. $course_info = api_get_course_info();
  1019. if (empty($course_info)) {
  1020. api_not_allowed($print_headers);
  1021. return false;
  1022. }
  1023. if (api_is_drh()) {
  1024. return true;
  1025. }
  1026. // Session admin has access to course
  1027. $sessionAccess = api_get_configuration_value('session_admins_access_all_content');
  1028. if ($sessionAccess) {
  1029. $allow_session_admins = true;
  1030. }
  1031. if (api_is_platform_admin($allow_session_admins)) {
  1032. return true;
  1033. }
  1034. $isAllowedInCourse = api_is_allowed_in_course();
  1035. $is_visible = false;
  1036. if (isset($course_info) && isset($course_info['visibility'])) {
  1037. switch ($course_info['visibility']) {
  1038. default:
  1039. case COURSE_VISIBILITY_CLOSED:
  1040. // Completely closed: the course is only accessible to the teachers. - 0
  1041. if (api_get_user_id() && !api_is_anonymous() && $isAllowedInCourse) {
  1042. $is_visible = true;
  1043. }
  1044. break;
  1045. case COURSE_VISIBILITY_REGISTERED:
  1046. // Private - access authorized to course members only - 1
  1047. if (api_get_user_id() && !api_is_anonymous() && $isAllowedInCourse) {
  1048. $is_visible = true;
  1049. }
  1050. break;
  1051. case COURSE_VISIBILITY_OPEN_PLATFORM:
  1052. // Open - access allowed for users registered on the platform - 2
  1053. if (api_get_user_id() && !api_is_anonymous() && $isAllowedInCourse) {
  1054. $is_visible = true;
  1055. }
  1056. break;
  1057. case COURSE_VISIBILITY_OPEN_WORLD:
  1058. //Open - access allowed for the whole world - 3
  1059. $is_visible = true;
  1060. break;
  1061. case COURSE_VISIBILITY_HIDDEN:
  1062. //Completely closed: the course is only accessible to the teachers. - 0
  1063. if (api_is_platform_admin()) {
  1064. $is_visible = true;
  1065. }
  1066. break;
  1067. }
  1068. //If password is set and user is not registered to the course then the course is not visible
  1069. if ($isAllowedInCourse == false &&
  1070. isset($course_info['registration_code']) &&
  1071. !empty($course_info['registration_code'])
  1072. ) {
  1073. $is_visible = false;
  1074. }
  1075. }
  1076. if (!empty($checkTool)) {
  1077. if (!api_is_allowed_to_edit(true, true, true)) {
  1078. $toolInfo = api_get_tool_information_by_name($checkTool);
  1079. if (!empty($toolInfo) && isset($toolInfo['visibility']) && $toolInfo['visibility'] == 0) {
  1080. api_not_allowed(true);
  1081. return false;
  1082. }
  1083. }
  1084. }
  1085. // Check session visibility
  1086. $session_id = api_get_session_id();
  1087. if (!empty($session_id)) {
  1088. // $isAllowedInCourse was set in local.inc.php
  1089. if (!$isAllowedInCourse) {
  1090. $is_visible = false;
  1091. }
  1092. }
  1093. if (!$is_visible) {
  1094. api_not_allowed($print_headers);
  1095. return false;
  1096. }
  1097. return true;
  1098. }
  1099. /**
  1100. * Function used to protect an admin script.
  1101. *
  1102. * The function blocks access when the user has no platform admin rights
  1103. * with an error message printed on default output
  1104. *
  1105. * @param bool Whether to allow session admins as well
  1106. * @param bool Whether to allow HR directors as well
  1107. * @param string An optional message (already passed through get_lang)
  1108. *
  1109. * @return bool True if user is allowed, false otherwise.
  1110. * The function also outputs an error message in case not allowed
  1111. *
  1112. * @author Roan Embrechts (original author)
  1113. */
  1114. function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
  1115. {
  1116. if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
  1117. api_not_allowed(true, $message);
  1118. return false;
  1119. }
  1120. return true;
  1121. }
  1122. /**
  1123. * Function used to protect a teacher script.
  1124. * The function blocks access when the user has no teacher rights.
  1125. *
  1126. * @return bool True if the current user can access the script, false otherwise
  1127. *
  1128. * @author Yoselyn Castillo
  1129. */
  1130. function api_protect_teacher_script()
  1131. {
  1132. if (!api_is_allowed_to_edit()) {
  1133. api_not_allowed(true);
  1134. return false;
  1135. }
  1136. return true;
  1137. }
  1138. /**
  1139. * Function used to prevent anonymous users from accessing a script.
  1140. *
  1141. * @param bool|true $printHeaders
  1142. *
  1143. * @author Roan Embrechts
  1144. *
  1145. * @return bool
  1146. */
  1147. function api_block_anonymous_users($printHeaders = true)
  1148. {
  1149. $user = api_get_user_info();
  1150. if (!(isset($user['user_id']) && $user['user_id']) || api_is_anonymous($user['user_id'], true)) {
  1151. api_not_allowed($printHeaders);
  1152. return false;
  1153. }
  1154. return true;
  1155. }
  1156. /**
  1157. * Returns a rough evaluation of the browser's name and version based on very
  1158. * simple regexp.
  1159. *
  1160. * @return array with the navigator name and version ['name' => '...', 'version' => '...']
  1161. */
  1162. function api_get_navigator()
  1163. {
  1164. $navigator = 'Unknown';
  1165. $version = 0;
  1166. if (!isset($_SERVER['HTTP_USER_AGENT'])) {
  1167. return ['name' => 'Unknown', 'version' => '0.0.0'];
  1168. }
  1169. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
  1170. $navigator = 'Opera';
  1171. list(, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
  1172. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Edge') !== false) {
  1173. $navigator = 'Edge';
  1174. list(, $version) = explode('Edge', $_SERVER['HTTP_USER_AGENT']);
  1175. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
  1176. $navigator = 'Internet Explorer';
  1177. list(, $version) = explode('MSIE ', $_SERVER['HTTP_USER_AGENT']);
  1178. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
  1179. $navigator = 'Chrome';
  1180. list(, $version) = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
  1181. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false) {
  1182. $navigator = 'Safari';
  1183. if (stripos($_SERVER['HTTP_USER_AGENT'], 'Version/') !== false) {
  1184. // If this Safari does have the "Version/" string in its user agent
  1185. // then use that as a version indicator rather than what's after
  1186. // "Safari/" which is rather a "build number" or something
  1187. list(, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  1188. } else {
  1189. list(, $version) = explode('Safari/', $_SERVER['HTTP_USER_AGENT']);
  1190. }
  1191. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false) {
  1192. $navigator = 'Firefox';
  1193. list(, $version) = explode('Firefox', $_SERVER['HTTP_USER_AGENT']);
  1194. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') !== false) {
  1195. $navigator = 'Netscape';
  1196. if (stripos($_SERVER['HTTP_USER_AGENT'], 'Netscape/') !== false) {
  1197. list(, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
  1198. } else {
  1199. list(, $version) = explode('Navigator', $_SERVER['HTTP_USER_AGENT']);
  1200. }
  1201. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false) {
  1202. $navigator = 'Konqueror';
  1203. list(, $version) = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
  1204. } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit') !== false) {
  1205. $navigator = 'AppleWebKit';
  1206. list(, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
  1207. } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
  1208. $navigator = 'Mozilla';
  1209. list(, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
  1210. }
  1211. // Now cut extra stuff around (mostly *after*) the version number
  1212. $version = preg_replace('/^([\/\s])?([\d\.]+)?.*/', '\2', $version);
  1213. if (strpos($version, '.') === false) {
  1214. $version = number_format(doubleval($version), 1);
  1215. }
  1216. $return = ['name' => $navigator, 'version' => $version];
  1217. return $return;
  1218. }
  1219. /**
  1220. * @return true if user self registration is allowed, false otherwise
  1221. */
  1222. function api_is_self_registration_allowed()
  1223. {
  1224. return isset($GLOBALS['allowSelfReg']) ? $GLOBALS['allowSelfReg'] : false;
  1225. }
  1226. /**
  1227. * This function returns the id of the user which is stored in the $_user array.
  1228. *
  1229. * example: The function can be used to check if a user is logged in
  1230. * if (api_get_user_id())
  1231. *
  1232. * @return int the id of the current user, 0 if is empty
  1233. */
  1234. function api_get_user_id()
  1235. {
  1236. $userInfo = Session::read('_user');
  1237. if ($userInfo && isset($userInfo['user_id'])) {
  1238. return (int) $userInfo['user_id'];
  1239. }
  1240. return 0;
  1241. }
  1242. /**
  1243. * Gets the list of courses a specific user is subscribed to.
  1244. *
  1245. * @param int User ID
  1246. * @param bool $fetch_session Whether to get session courses or not - NOT YET IMPLEMENTED
  1247. *
  1248. * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
  1249. *
  1250. * @deprecated use CourseManager::get_courses_list_by_user_id()
  1251. */
  1252. function api_get_user_courses($userId, $fetch_session = true)
  1253. {
  1254. // Get out if not integer
  1255. if ($userId != strval(intval($userId))) {
  1256. return [];
  1257. }
  1258. $t_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1259. $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1260. $sql = "SELECT cc.id as real_id, cc.code code, cc.directory dir, cu.status status
  1261. FROM $t_course cc, $t_course_user cu
  1262. WHERE
  1263. cc.id = cu.c_id AND
  1264. cu.user_id = $userId AND
  1265. cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH;
  1266. $result = Database::query($sql);
  1267. if ($result === false) {
  1268. return [];
  1269. }
  1270. $courses = [];
  1271. while ($row = Database::fetch_array($result)) {
  1272. // we only need the database name of the course
  1273. $courses[] = $row;
  1274. }
  1275. return $courses;
  1276. }
  1277. /**
  1278. * Formats user information into a standard array
  1279. * This function should be only used inside api_get_user_info().
  1280. *
  1281. * @param array Non-standard user array
  1282. * @param bool $add_password
  1283. * @param bool $loadAvatars turn off to improve performance
  1284. *
  1285. * @return array Standard user array
  1286. */
  1287. function _api_format_user($user, $add_password = false, $loadAvatars = true)
  1288. {
  1289. $result = [];
  1290. $result['firstname'] = null;
  1291. $result['lastname'] = null;
  1292. if (isset($user['firstname']) && isset($user['lastname'])) { // with only lowercase
  1293. $result['firstname'] = $user['firstname'];
  1294. $result['lastname'] = $user['lastname'];
  1295. } elseif (isset($user['firstName']) && isset($user['lastName'])) { // with uppercase letters
  1296. $result['firstname'] = isset($user['firstName']) ? $user['firstName'] : null;
  1297. $result['lastname'] = isset($user['lastName']) ? $user['lastName'] : null;
  1298. }
  1299. if (isset($user['email'])) {
  1300. $result['mail'] = isset($user['email']) ? $user['email'] : null;
  1301. $result['email'] = isset($user['email']) ? $user['email'] : null;
  1302. } else {
  1303. $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
  1304. $result['email'] = isset($user['mail']) ? $user['mail'] : null;
  1305. }
  1306. $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
  1307. $result['complete_name_with_username'] = $result['complete_name'];
  1308. if (!empty($user['username']) && !api_get_configuration_value('hide_username_with_complete_name')) {
  1309. $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
  1310. }
  1311. $showEmail = api_get_setting('show_email_addresses') === 'true';
  1312. if (!empty($user['email'])) {
  1313. $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$user['email'].')';
  1314. if ($showEmail) {
  1315. $result['complete_name_with_email'] = $result['complete_name'].' ('.$user['email'].')';
  1316. }
  1317. } else {
  1318. $result['complete_name_with_email'] = $result['complete_name'];
  1319. $result['complete_name_with_email_forced'] = $result['complete_name'];
  1320. }
  1321. // Kept for historical reasons
  1322. $result['firstName'] = $result['firstname'];
  1323. $result['lastName'] = $result['lastname'];
  1324. $attributes = [
  1325. 'phone',
  1326. 'address',
  1327. 'picture_uri',
  1328. 'official_code',
  1329. 'status',
  1330. 'active',
  1331. 'auth_source',
  1332. 'username',
  1333. 'theme',
  1334. 'language',
  1335. 'creator_id',
  1336. 'registration_date',
  1337. 'hr_dept_id',
  1338. 'expiration_date',
  1339. 'last_login',
  1340. 'user_is_online',
  1341. ];
  1342. if (api_get_setting('extended_profile') === 'true') {
  1343. $attributes[] = 'competences';
  1344. $attributes[] = 'diplomas';
  1345. $attributes[] = 'teach';
  1346. $attributes[] = 'openarea';
  1347. }
  1348. foreach ($attributes as $attribute) {
  1349. $result[$attribute] = isset($user[$attribute]) ? $user[$attribute] : null;
  1350. }
  1351. $user_id = (int) $user['user_id'];
  1352. // Maintain the user_id index for backwards compatibility
  1353. $result['user_id'] = $result['id'] = $user_id;
  1354. $hasCertificates = Certificate::getCertificateByUser($user_id);
  1355. $result['has_certificates'] = 0;
  1356. if (!empty($hasCertificates)) {
  1357. $result['has_certificates'] = 1;
  1358. }
  1359. $result['icon_status'] = '';
  1360. $result['icon_status_medium'] = '';
  1361. $result['is_admin'] = UserManager::is_admin($user_id);
  1362. // Getting user avatar.
  1363. if ($loadAvatars) {
  1364. $result['avatar'] = '';
  1365. $result['avatar_no_query'] = '';
  1366. $result['avatar_small'] = '';
  1367. $result['avatar_medium'] = '';
  1368. if (!isset($user['avatar'])) {
  1369. $originalFile = UserManager::getUserPicture(
  1370. $user_id,
  1371. USER_IMAGE_SIZE_ORIGINAL,
  1372. null,
  1373. $result
  1374. );
  1375. $result['avatar'] = $originalFile;
  1376. $avatarString = explode('?', $result['avatar']);
  1377. $result['avatar_no_query'] = reset($avatarString);
  1378. } else {
  1379. $result['avatar'] = $user['avatar'];
  1380. $avatarString = explode('?', $user['avatar']);
  1381. $result['avatar_no_query'] = reset($avatarString);
  1382. }
  1383. if (!isset($user['avatar_small'])) {
  1384. $smallFile = UserManager::getUserPicture(
  1385. $user_id,
  1386. USER_IMAGE_SIZE_SMALL,
  1387. null,
  1388. $result
  1389. );
  1390. $result['avatar_small'] = $smallFile;
  1391. } else {
  1392. $result['avatar_small'] = $user['avatar_small'];
  1393. }
  1394. if (!isset($user['avatar_medium'])) {
  1395. $mediumFile = UserManager::getUserPicture(
  1396. $user_id,
  1397. USER_IMAGE_SIZE_MEDIUM,
  1398. null,
  1399. $result
  1400. );
  1401. $result['avatar_medium'] = $mediumFile;
  1402. } else {
  1403. $result['avatar_medium'] = $user['avatar_medium'];
  1404. }
  1405. $urlImg = api_get_path(WEB_IMG_PATH);
  1406. $iconStatus = '';
  1407. $iconStatusMedium = '';
  1408. switch ($result['status']) {
  1409. case STUDENT:
  1410. if ($result['has_certificates']) {
  1411. $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
  1412. } else {
  1413. $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
  1414. }
  1415. break;
  1416. case COURSEMANAGER:
  1417. if ($result['is_admin']) {
  1418. $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
  1419. } else {
  1420. $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
  1421. }
  1422. break;
  1423. case STUDENT_BOSS:
  1424. $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
  1425. break;
  1426. }
  1427. if (!empty($iconStatus)) {
  1428. $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
  1429. $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
  1430. }
  1431. $result['icon_status'] = $iconStatus;
  1432. $result['icon_status_medium'] = $iconStatusMedium;
  1433. }
  1434. if (isset($user['user_is_online'])) {
  1435. $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
  1436. }
  1437. if (isset($user['user_is_online_in_chat'])) {
  1438. $result['user_is_online_in_chat'] = (int) $user['user_is_online_in_chat'];
  1439. }
  1440. if ($add_password) {
  1441. $result['password'] = $user['password'];
  1442. }
  1443. if (isset($result['profile_completed'])) {
  1444. $result['profile_completed'] = $user['profile_completed'];
  1445. }
  1446. $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
  1447. // Send message link
  1448. $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
  1449. $result['complete_name_with_message_link'] = Display::url(
  1450. $result['complete_name_with_username'],
  1451. $sendMessage,
  1452. ['class' => 'ajax']
  1453. );
  1454. if (isset($user['extra'])) {
  1455. $result['extra'] = $user['extra'];
  1456. }
  1457. return $result;
  1458. }
  1459. /**
  1460. * Finds all the information about a user.
  1461. * If no parameter is passed you find all the information about the current user.
  1462. *
  1463. * @param int $user_id
  1464. * @param bool $checkIfUserOnline
  1465. * @param bool $showPassword
  1466. * @param bool $loadExtraData
  1467. * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
  1468. * @param bool $loadAvatars turn off to improve performance and if avatars are not needed
  1469. * @param bool $updateCache update apc cache if exists
  1470. *
  1471. * @return mixed $user_info user_id, lastname, firstname, username, email, etc or false on error
  1472. *
  1473. * @author Patrick Cool <patrick.cool@UGent.be>
  1474. * @author Julio Montoya
  1475. *
  1476. * @version 21 September 2004
  1477. */
  1478. function api_get_user_info(
  1479. $user_id = 0,
  1480. $checkIfUserOnline = false,
  1481. $showPassword = false,
  1482. $loadExtraData = false,
  1483. $loadOnlyVisibleExtraData = false,
  1484. $loadAvatars = true,
  1485. $updateCache = false
  1486. ) {
  1487. $apcVar = null;
  1488. $user = false;
  1489. $cacheAvailable = api_get_configuration_value('apc');
  1490. if (empty($user_id)) {
  1491. $userFromSession = Session::read('_user');
  1492. if (isset($userFromSession)) {
  1493. if ($cacheAvailable === true &&
  1494. (
  1495. empty($userFromSession['is_anonymous']) &&
  1496. (isset($userFromSession['status']) && $userFromSession['status'] != ANONYMOUS)
  1497. )
  1498. ) {
  1499. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userFromSession['user_id'];
  1500. if (apcu_exists($apcVar)) {
  1501. if ($updateCache) {
  1502. apcu_store($apcVar, $userFromSession, 60);
  1503. }
  1504. $user = apcu_fetch($apcVar);
  1505. } else {
  1506. $user = _api_format_user(
  1507. $userFromSession,
  1508. $showPassword,
  1509. $loadAvatars
  1510. );
  1511. apcu_store($apcVar, $user, 60);
  1512. }
  1513. } else {
  1514. $user = _api_format_user(
  1515. $userFromSession,
  1516. $showPassword,
  1517. $loadAvatars
  1518. );
  1519. }
  1520. return $user;
  1521. }
  1522. return false;
  1523. }
  1524. // Make sure user_id is safe
  1525. $user_id = (int) $user_id;
  1526. // Re-use user information if not stale and already stored in APCu
  1527. if ($cacheAvailable === true) {
  1528. $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
  1529. if (apcu_exists($apcVar) && $updateCache == false && $checkIfUserOnline == false) {
  1530. $user = apcu_fetch($apcVar);
  1531. return $user;
  1532. }
  1533. }
  1534. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1535. WHERE id = $user_id";
  1536. $result = Database::query($sql);
  1537. if (Database::num_rows($result) > 0) {
  1538. $result_array = Database::fetch_array($result);
  1539. $result_array['user_is_online_in_chat'] = 0;
  1540. if ($checkIfUserOnline) {
  1541. $use_status_in_platform = user_is_online($user_id);
  1542. $result_array['user_is_online'] = $use_status_in_platform;
  1543. $user_online_in_chat = 0;
  1544. if ($use_status_in_platform) {
  1545. $user_status = UserManager::get_extra_user_data_by_field(
  1546. $user_id,
  1547. 'user_chat_status',
  1548. false,
  1549. true
  1550. );
  1551. if ((int) $user_status['user_chat_status'] == 1) {
  1552. $user_online_in_chat = 1;
  1553. }
  1554. }
  1555. $result_array['user_is_online_in_chat'] = $user_online_in_chat;
  1556. }
  1557. if ($loadExtraData) {
  1558. $fieldValue = new ExtraFieldValue('user');
  1559. $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
  1560. $user_id,
  1561. $loadOnlyVisibleExtraData
  1562. );
  1563. }
  1564. $user = _api_format_user($result_array, $showPassword, $loadAvatars);
  1565. }
  1566. if ($cacheAvailable === true) {
  1567. apcu_store($apcVar, $user, 60);
  1568. }
  1569. return $user;
  1570. }
  1571. /**
  1572. * @param int $userId
  1573. *
  1574. * @return User
  1575. */
  1576. function api_get_user_entity($userId)
  1577. {
  1578. $userId = (int) $userId;
  1579. $repo = UserManager::getRepository();
  1580. /** @var User $user */
  1581. $user = $repo->find($userId);
  1582. return $user;
  1583. }
  1584. /**
  1585. * Finds all the information about a user from username instead of user id.
  1586. *
  1587. * @param string $username
  1588. *
  1589. * @return mixed $user_info array user_id, lastname, firstname, username, email or false on error
  1590. *
  1591. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  1592. */
  1593. function api_get_user_info_from_username($username = '')
  1594. {
  1595. if (empty($username)) {
  1596. return false;
  1597. }
  1598. $username = trim($username);
  1599. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1600. WHERE username='".Database::escape_string($username)."'";
  1601. $result = Database::query($sql);
  1602. if (Database::num_rows($result) > 0) {
  1603. $resultArray = Database::fetch_array($result);
  1604. return _api_format_user($resultArray);
  1605. }
  1606. return false;
  1607. }
  1608. /**
  1609. * Get first user with an email.
  1610. *
  1611. * @param string $email
  1612. *
  1613. * @return array|bool
  1614. */
  1615. function api_get_user_info_from_email($email = '')
  1616. {
  1617. if (empty($email)) {
  1618. return false;
  1619. }
  1620. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  1621. WHERE email ='".Database::escape_string($email)."' LIMIT 1";
  1622. $result = Database::query($sql);
  1623. if (Database::num_rows($result) > 0) {
  1624. $resultArray = Database::fetch_array($result);
  1625. return _api_format_user($resultArray);
  1626. }
  1627. return false;
  1628. }
  1629. /**
  1630. * @return string
  1631. */
  1632. function api_get_course_id()
  1633. {
  1634. return Session::read('_cid', null);
  1635. }
  1636. /**
  1637. * Returns the current course id (integer).
  1638. *
  1639. * @param string $code Optional course code
  1640. *
  1641. * @return int
  1642. */
  1643. function api_get_course_int_id($code = null)
  1644. {
  1645. if (!empty($code)) {
  1646. $code = Database::escape_string($code);
  1647. $row = Database::select(
  1648. 'id',
  1649. Database::get_main_table(TABLE_MAIN_COURSE),
  1650. ['where' => ['code = ?' => [$code]]],
  1651. 'first'
  1652. );
  1653. if (is_array($row) && isset($row['id'])) {
  1654. return $row['id'];
  1655. } else {
  1656. return false;
  1657. }
  1658. }
  1659. return Session::read('_real_cid', 0);
  1660. }
  1661. /**
  1662. * Returns the current course directory.
  1663. *
  1664. * This function relies on api_get_course_info()
  1665. *
  1666. * @param string The course code - optional (takes it from session if not given)
  1667. *
  1668. * @return string The directory where the course is located inside the Chamilo "courses" directory
  1669. *
  1670. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  1671. */
  1672. function api_get_course_path($course_code = null)
  1673. {
  1674. $info = !empty($course_code) ? api_get_course_info($course_code) : api_get_course_info();
  1675. return $info['path'];
  1676. }
  1677. /**
  1678. * Gets a course setting from the current course_setting table. Try always using integer values.
  1679. *
  1680. * @param string $settingName The name of the setting we want from the table
  1681. * @param array $courseInfo
  1682. * @param bool $force force checking the value in the database
  1683. *
  1684. * @return mixed The value of that setting in that table. Return -1 if not found.
  1685. */
  1686. function api_get_course_setting($settingName, $courseInfo = [], $force = false)
  1687. {
  1688. if (empty($courseInfo)) {
  1689. $courseInfo = api_get_course_info();
  1690. }
  1691. if (empty($courseInfo) || empty($settingName)) {
  1692. return -1;
  1693. }
  1694. $courseId = isset($courseInfo['real_id']) && !empty($courseInfo['real_id']) ? $courseInfo['real_id'] : 0;
  1695. if (empty($courseId)) {
  1696. return -1;
  1697. }
  1698. static $courseSettingInfo = [];
  1699. if ($force) {
  1700. $courseSettingInfo = [];
  1701. }
  1702. if (!isset($courseSettingInfo[$courseId])) {
  1703. $table = Database::get_course_table(TABLE_COURSE_SETTING);
  1704. $settingName = Database::escape_string($settingName);
  1705. $sql = "SELECT variable, value FROM $table
  1706. WHERE c_id = $courseId ";
  1707. $res = Database::query($sql);
  1708. if (Database::num_rows($res) > 0) {
  1709. $result = Database::store_result($res, 'ASSOC');
  1710. $courseSettingInfo[$courseId] = array_column($result, 'value', 'variable');
  1711. if (isset($courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'])) {
  1712. $value = $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'];
  1713. if (!is_null($value)) {
  1714. $result = explode(',', $value);
  1715. $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'] = $result;
  1716. }
  1717. }
  1718. }
  1719. }
  1720. if (isset($courseSettingInfo[$courseId]) && isset($courseSettingInfo[$courseId][$settingName])) {
  1721. return $courseSettingInfo[$courseId][$settingName];
  1722. }
  1723. return -1;
  1724. }
  1725. /**
  1726. * Gets an anonymous user ID.
  1727. *
  1728. * For some tools that need tracking, like the learnpath tool, it is necessary
  1729. * to have a usable user-id to enable some kind of tracking, even if not
  1730. * perfect. An anonymous ID is taken from the users table by looking for a
  1731. * status of "6" (anonymous).
  1732. *
  1733. * @return int User ID of the anonymous user, or O if no anonymous user found
  1734. */
  1735. function api_get_anonymous_id()
  1736. {
  1737. // Find if another anon is connected now
  1738. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1739. $tableU = Database::get_main_table(TABLE_MAIN_USER);
  1740. $ip = Database::escape_string(api_get_real_ip());
  1741. $max = (int) api_get_configuration_value('max_anonymous_users');
  1742. if ($max >= 2) {
  1743. $sql = "SELECT * FROM $table as TEL
  1744. JOIN $tableU as U
  1745. ON U.user_id = TEL.login_user_id
  1746. WHERE TEL.user_ip = '$ip'
  1747. AND U.status = ".ANONYMOUS."
  1748. AND U.user_id != 2 ";
  1749. $result = Database::query($sql);
  1750. if (empty(Database::num_rows($result))) {
  1751. $login = uniqid('anon_');
  1752. $anonList = UserManager::get_user_list(['status' => ANONYMOUS], ['registration_date ASC']);
  1753. if (count($anonList) >= $max) {
  1754. foreach ($anonList as $userToDelete) {
  1755. UserManager::delete_user($userToDelete['user_id']);
  1756. break;
  1757. }
  1758. }
  1759. $userId = UserManager::create_user(
  1760. $login,
  1761. 'anon',
  1762. ANONYMOUS,
  1763. ' anonymous@localhost',
  1764. $login,
  1765. $login
  1766. );
  1767. return $userId;
  1768. } else {
  1769. $row = Database::fetch_array($result, 'ASSOC');
  1770. return $row['user_id'];
  1771. }
  1772. }
  1773. $table = Database::get_main_table(TABLE_MAIN_USER);
  1774. $sql = "SELECT user_id
  1775. FROM $table
  1776. WHERE status = ".ANONYMOUS." ";
  1777. $res = Database::query($sql);
  1778. if (Database::num_rows($res) > 0) {
  1779. $row = Database::fetch_array($res, 'ASSOC');
  1780. return $row['user_id'];
  1781. }
  1782. // No anonymous user was found.
  1783. return 0;
  1784. }
  1785. /**
  1786. * @param string $courseCode
  1787. * @param int $sessionId
  1788. * @param int $groupId
  1789. *
  1790. * @return string
  1791. */
  1792. function api_get_cidreq_params($courseCode, $sessionId = 0, $groupId = 0)
  1793. {
  1794. $courseCode = !empty($courseCode) ? htmlspecialchars($courseCode) : '';
  1795. $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
  1796. $groupId = !empty($groupId) ? (int) $groupId : 0;
  1797. $url = 'cidReq='.$courseCode;
  1798. $url .= '&id_session='.$sessionId;
  1799. $url .= '&gidReq='.$groupId;
  1800. return $url;
  1801. }
  1802. /**
  1803. * Returns the current course url part including session, group, and gradebook params.
  1804. *
  1805. * @param bool $addSessionId
  1806. * @param bool $addGroupId
  1807. * @param string $origin
  1808. *
  1809. * @return string Course & session references to add to a URL
  1810. */
  1811. function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
  1812. {
  1813. $courseCode = api_get_course_id();
  1814. $url = empty($courseCode) ? '' : 'cidReq='.htmlspecialchars($courseCode);
  1815. $origin = empty($origin) ? api_get_origin() : Security::remove_XSS($origin);
  1816. if ($addSessionId) {
  1817. if (!empty($url)) {
  1818. $url .= api_get_session_id() == 0 ? '&id_session=0' : '&id_session='.api_get_session_id();
  1819. }
  1820. }
  1821. if ($addGroupId) {
  1822. if (!empty($url)) {
  1823. $url .= api_get_group_id() == 0 ? '&gidReq=0' : '&gidReq='.api_get_group_id();
  1824. }
  1825. }
  1826. if (!empty($url)) {
  1827. $url .= '&gradebook='.intval(api_is_in_gradebook());
  1828. $url .= '&origin='.$origin;
  1829. }
  1830. return $url;
  1831. }
  1832. /**
  1833. * Get if we visited a gradebook page.
  1834. *
  1835. * @return bool
  1836. */
  1837. function api_is_in_gradebook()
  1838. {
  1839. return Session::read('in_gradebook', false);
  1840. }
  1841. /**
  1842. * Set that we are in a page inside a gradebook.
  1843. */
  1844. function api_set_in_gradebook()
  1845. {
  1846. Session::write('in_gradebook', true);
  1847. }
  1848. /**
  1849. * Remove gradebook session.
  1850. */
  1851. function api_remove_in_gradebook()
  1852. {
  1853. Session::erase('in_gradebook');
  1854. }
  1855. /**
  1856. * Returns the current course info array see api_format_course_array()
  1857. * If the course_code is given, the returned array gives info about that
  1858. * particular course, if none given it gets the course info from the session.
  1859. *
  1860. * @param string $course_code
  1861. *
  1862. * @return array
  1863. */
  1864. function api_get_course_info($course_code = null)
  1865. {
  1866. if (!empty($course_code)) {
  1867. $course_code = Database::escape_string($course_code);
  1868. $courseId = api_get_course_int_id($course_code);
  1869. if (empty($courseId)) {
  1870. return [];
  1871. }
  1872. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1873. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1874. $sql = "SELECT
  1875. course.*,
  1876. course_category.code faCode,
  1877. course_category.name faName
  1878. FROM $course_table
  1879. LEFT JOIN $course_cat_table
  1880. ON course.category_code = course_category.code
  1881. WHERE course.id = $courseId";
  1882. $result = Database::query($sql);
  1883. $courseInfo = [];
  1884. if (Database::num_rows($result) > 0) {
  1885. $data = Database::fetch_array($result);
  1886. $courseInfo = api_format_course_array($data);
  1887. }
  1888. return $courseInfo;
  1889. }
  1890. global $_course;
  1891. if ($_course == '-1') {
  1892. $_course = [];
  1893. }
  1894. return $_course;
  1895. }
  1896. /**
  1897. * @param int $courseId
  1898. *
  1899. * @return \Chamilo\CoreBundle\Entity\Course
  1900. */
  1901. function api_get_course_entity($courseId = 0)
  1902. {
  1903. if (empty($courseId)) {
  1904. $courseId = api_get_course_int_id();
  1905. }
  1906. return Database::getManager()->getRepository('ChamiloCoreBundle:Course')->find($courseId);
  1907. }
  1908. /**
  1909. * @param int $id
  1910. *
  1911. * @return \Chamilo\CoreBundle\Entity\Session
  1912. */
  1913. function api_get_session_entity($id = 0)
  1914. {
  1915. if (empty($id)) {
  1916. $id = api_get_session_id();
  1917. }
  1918. return Database::getManager()->getRepository('ChamiloCoreBundle:Session')->find($id);
  1919. }
  1920. /**
  1921. * Returns the current course info array.
  1922. * Now if the course_code is given, the returned array gives info about that
  1923. * particular course, not specially the current one.
  1924. *
  1925. * @param int $id Numeric ID of the course
  1926. *
  1927. * @return array The course info as an array formatted by api_format_course_array, including category.name
  1928. */
  1929. function api_get_course_info_by_id($id = null)
  1930. {
  1931. if (!empty($id)) {
  1932. $id = (int) $id;
  1933. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1934. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  1935. $sql = "SELECT
  1936. course.*,
  1937. course_category.code faCode,
  1938. course_category.name faName
  1939. FROM $course_table
  1940. LEFT JOIN $course_cat_table
  1941. ON course.category_code = course_category.code
  1942. WHERE course.id = $id";
  1943. $result = Database::query($sql);
  1944. $_course = [];
  1945. if (Database::num_rows($result) > 0) {
  1946. $row = Database::fetch_array($result);
  1947. $_course = api_format_course_array($row);
  1948. }
  1949. return $_course;
  1950. }
  1951. global $_course;
  1952. if ($_course == '-1') {
  1953. $_course = [];
  1954. }
  1955. return $_course;
  1956. }
  1957. /**
  1958. * Reformat the course array (output by api_get_course_info()) in order, mostly,
  1959. * to switch from 'code' to 'id' in the array. This is a legacy feature and is
  1960. * now possibly causing massive confusion as a new "id" field has been added to
  1961. * the course table in 1.9.0.
  1962. *
  1963. * @param $course_data
  1964. *
  1965. * @return array
  1966. *
  1967. * @todo eradicate the false "id"=code field of the $_course array and use the int id
  1968. */
  1969. function api_format_course_array($course_data)
  1970. {
  1971. if (empty($course_data)) {
  1972. return [];
  1973. }
  1974. $_course = [];
  1975. $_course['id'] = $course_data['code'];
  1976. $_course['real_id'] = $course_data['id'];
  1977. // Added
  1978. $_course['code'] = $course_data['code'];
  1979. $_course['name'] = $course_data['title'];
  1980. $_course['title'] = $course_data['title'];
  1981. $_course['official_code'] = $course_data['visual_code'];
  1982. $_course['visual_code'] = $course_data['visual_code'];
  1983. $_course['sysCode'] = $course_data['code'];
  1984. $_course['path'] = $course_data['directory']; // Use as key in path.
  1985. $_course['directory'] = $course_data['directory'];
  1986. $_course['creation_date'] = $course_data['creation_date'];
  1987. $_course['titular'] = $course_data['tutor_name'];
  1988. $_course['language'] = $course_data['course_language'];
  1989. $_course['extLink']['url'] = $course_data['department_url'];
  1990. $_course['extLink']['name'] = $course_data['department_name'];
  1991. $_course['categoryCode'] = $course_data['faCode'];
  1992. $_course['categoryName'] = $course_data['faName'];
  1993. $_course['visibility'] = $course_data['visibility'];
  1994. $_course['subscribe_allowed'] = $course_data['subscribe'];
  1995. $_course['subscribe'] = $course_data['subscribe'];
  1996. $_course['unsubscribe'] = $course_data['unsubscribe'];
  1997. $_course['course_language'] = $course_data['course_language'];
  1998. $_course['activate_legal'] = isset($course_data['activate_legal']) ? $course_data['activate_legal'] : false;
  1999. $_course['legal'] = $course_data['legal'];
  2000. $_course['show_score'] = $course_data['show_score']; //used in the work tool
  2001. $_course['department_name'] = $course_data['department_name'];
  2002. $_course['department_url'] = $course_data['department_url'];
  2003. $courseSys = api_get_path(SYS_COURSE_PATH).$course_data['directory'];
  2004. $webCourseHome = api_get_path(WEB_COURSE_PATH).$course_data['directory'];
  2005. // Course password
  2006. $_course['registration_code'] = !empty($course_data['registration_code']) ? sha1($course_data['registration_code']) : null;
  2007. $_course['disk_quota'] = $course_data['disk_quota'];
  2008. $_course['course_public_url'] = $webCourseHome.'/index.php';
  2009. $_course['course_sys_path'] = $courseSys.'/';
  2010. if (array_key_exists('add_teachers_to_sessions_courses', $course_data)) {
  2011. $_course['add_teachers_to_sessions_courses'] = $course_data['add_teachers_to_sessions_courses'];
  2012. }
  2013. // Course image
  2014. $_course['course_image_source'] = '';
  2015. if (file_exists($courseSys.'/course-pic85x85.png')) {
  2016. $url_image = $webCourseHome.'/course-pic85x85.png';
  2017. $_course['course_image_source'] = $courseSys.'/course-pic85x85.png';
  2018. } else {
  2019. $url_image = Display::return_icon(
  2020. 'course.png',
  2021. null,
  2022. null,
  2023. ICON_SIZE_BIG,
  2024. null,
  2025. true,
  2026. false
  2027. );
  2028. }
  2029. $_course['course_image'] = $url_image;
  2030. // Course large image
  2031. $_course['course_image_large_source'] = '';
  2032. if (file_exists($courseSys.'/course-pic.png')) {
  2033. $url_image = $webCourseHome.'/course-pic.png';
  2034. $_course['course_image_large_source'] = $courseSys.'/course-pic.png';
  2035. } else {
  2036. $url_image = Display::return_icon(
  2037. 'session_default.png',
  2038. null,
  2039. null,
  2040. null,
  2041. null,
  2042. true,
  2043. true
  2044. );
  2045. }
  2046. $_course['course_image_large'] = $url_image;
  2047. return $_course;
  2048. }
  2049. /**
  2050. * Returns a difficult to guess password.
  2051. *
  2052. * @param int $length the length of the password
  2053. *
  2054. * @return string the generated password
  2055. */
  2056. function api_generate_password($length = 8)
  2057. {
  2058. if ($length < 2) {
  2059. $length = 2;
  2060. }
  2061. $charactersLowerCase = 'abcdefghijkmnopqrstuvwxyz';
  2062. $charactersUpperCase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  2063. $minNumbers = 2;
  2064. $length = $length - $minNumbers;
  2065. $minLowerCase = round($length / 2);
  2066. $minUpperCase = $length - $minLowerCase;
  2067. $password = '';
  2068. $passwordRequirements = api_get_configuration_value('password_requirements');
  2069. $factory = new RandomLib\Factory();
  2070. $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
  2071. if (!empty($passwordRequirements)) {
  2072. $length = $passwordRequirements['min']['length'];
  2073. $minNumbers = $passwordRequirements['min']['numeric'];
  2074. $minLowerCase = $passwordRequirements['min']['lowercase'];
  2075. $minUpperCase = $passwordRequirements['min']['uppercase'];
  2076. $rest = $length - $minNumbers - $minLowerCase - $minUpperCase;
  2077. // Add the rest to fill the length requirement
  2078. if ($rest > 0) {
  2079. $password .= $generator->generateString($rest, $charactersLowerCase.$charactersUpperCase);
  2080. }
  2081. }
  2082. // Min digits default 2
  2083. for ($i = 0; $i < $minNumbers; $i++) {
  2084. $password .= $generator->generateInt(2, 9);
  2085. }
  2086. // Min lowercase
  2087. $password .= $generator->generateString($minLowerCase, $charactersLowerCase);
  2088. // Min uppercase
  2089. $password .= $generator->generateString($minUpperCase, $charactersUpperCase);
  2090. $password = str_shuffle($password);
  2091. return $password;
  2092. }
  2093. /**
  2094. * Checks a password to see wether it is OK to use.
  2095. *
  2096. * @param string $password
  2097. *
  2098. * @return bool if the password is acceptable, false otherwise
  2099. * Notes about what a password "OK to use" is:
  2100. * 1. The password should be at least 5 characters long.
  2101. * 2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
  2102. * 3. The password should contain at least 3 letters.
  2103. * 4. It should contain at least 2 digits.
  2104. * Settings will change if the configuration value is set: password_requirements
  2105. */
  2106. function api_check_password($password)
  2107. {
  2108. $passwordRequirements = Security::getPasswordRequirements();
  2109. $minLength = $passwordRequirements['min']['length'];
  2110. $minNumbers = $passwordRequirements['min']['numeric'];
  2111. // Optional
  2112. $minLowerCase = $passwordRequirements['min']['lowercase'];
  2113. $minUpperCase = $passwordRequirements['min']['uppercase'];
  2114. $minLetters = $minLowerCase + $minUpperCase;
  2115. $passwordLength = api_strlen($password);
  2116. $conditions = [
  2117. 'min_length' => $passwordLength >= $minLength,
  2118. ];
  2119. $digits = 0;
  2120. $lowerCase = 0;
  2121. $upperCase = 0;
  2122. for ($i = 0; $i < $passwordLength; $i++) {
  2123. $currentCharacterCode = api_ord(api_substr($password, $i, 1));
  2124. if ($currentCharacterCode >= 65 && $currentCharacterCode <= 90) {
  2125. $upperCase++;
  2126. }
  2127. if ($currentCharacterCode >= 97 && $currentCharacterCode <= 122) {
  2128. $lowerCase++;
  2129. }
  2130. if ($currentCharacterCode >= 48 && $currentCharacterCode <= 57) {
  2131. $digits++;
  2132. }
  2133. }
  2134. // Min number of digits
  2135. $conditions['min_numeric'] = $digits >= $minNumbers;
  2136. if (!empty($minUpperCase)) {
  2137. // Uppercase
  2138. $conditions['min_uppercase'] = $upperCase >= $minUpperCase;
  2139. }
  2140. if (!empty($minLowerCase)) {
  2141. // Lowercase
  2142. $conditions['min_lowercase'] = $upperCase >= $minLowerCase;
  2143. }
  2144. // Min letters
  2145. $letters = $upperCase + $lowerCase;
  2146. $conditions['min_letters'] = $letters >= $minLetters;
  2147. $isPasswordOk = true;
  2148. foreach ($conditions as $condition) {
  2149. if ($condition === false) {
  2150. $isPasswordOk = false;
  2151. break;
  2152. }
  2153. }
  2154. if ($isPasswordOk === false) {
  2155. $output = get_lang('NewPasswordRequirementsNotMatched').'<br />';
  2156. $output .= Security::getPasswordRequirementsToString($conditions);
  2157. Display::addFlash(Display::return_message($output, 'warning', false));
  2158. }
  2159. return $isPasswordOk;
  2160. }
  2161. /**
  2162. * Clears the user ID from the session if it was the anonymous user. Generally
  2163. * used on out-of-tools pages to remove a user ID that could otherwise be used
  2164. * in the wrong context.
  2165. * This function is to be used in conjunction with the api_set_anonymous()
  2166. * function to simulate the user existence in case of an anonymous visit.
  2167. *
  2168. * @param bool database check switch - passed to api_is_anonymous()
  2169. *
  2170. * @return bool true if succesfully unregistered, false if not anonymous
  2171. */
  2172. function api_clear_anonymous($db_check = false)
  2173. {
  2174. global $_user;
  2175. if (api_is_anonymous($_user['user_id'], $db_check)) {
  2176. unset($_user['user_id']);
  2177. Session::erase('_uid');
  2178. return true;
  2179. }
  2180. return false;
  2181. }
  2182. /**
  2183. * Returns the status string corresponding to the status code.
  2184. *
  2185. * @author Noel Dieschburg
  2186. *
  2187. * @param the int status code
  2188. *
  2189. * @return string
  2190. */
  2191. function get_status_from_code($status_code)
  2192. {
  2193. switch ($status_code) {
  2194. case STUDENT:
  2195. return get_lang('Student', '');
  2196. case COURSEMANAGER:
  2197. return get_lang('Teacher', '');
  2198. case SESSIONADMIN:
  2199. return get_lang('SessionsAdmin', '');
  2200. case DRH:
  2201. return get_lang('Drh', '');
  2202. }
  2203. }
  2204. /**
  2205. * Sets the current user as anonymous if it hasn't been identified yet. This
  2206. * function should be used inside a tool only. The function api_clear_anonymous()
  2207. * acts in the opposite direction by clearing the anonymous user's data every
  2208. * time we get on a course homepage or on a neutral page (index, admin, my space).
  2209. *
  2210. * @return bool true if set user as anonymous, false if user was already logged in or anonymous id could not be found
  2211. */
  2212. function api_set_anonymous()
  2213. {
  2214. global $_user;
  2215. if (!empty($_user['user_id'])) {
  2216. return false;
  2217. }
  2218. $user_id = api_get_anonymous_id();
  2219. if ($user_id == 0) {
  2220. return false;
  2221. }
  2222. if (isset($_user['is_anonymous'])) {
  2223. return false;
  2224. }
  2225. Session::erase('_user');
  2226. $_user['user_id'] = $user_id;
  2227. $_user['is_anonymous'] = true;
  2228. $GLOBALS['_user'] = $_user;
  2229. Session::write('_user', $_user);
  2230. return true;
  2231. }
  2232. /**
  2233. * Gets the current Chamilo (not PHP/cookie) session ID.
  2234. *
  2235. * @return int O if no active session, the session ID otherwise
  2236. */
  2237. function api_get_session_id()
  2238. {
  2239. return (int) Session::read('id_session', 0);
  2240. }
  2241. /**
  2242. * Gets the current Chamilo (not social network) group ID.
  2243. *
  2244. * @return int O if no active session, the session ID otherwise
  2245. */
  2246. function api_get_group_id()
  2247. {
  2248. return Session::read('_gid', 0);
  2249. }
  2250. /**
  2251. * Gets the current or given session name.
  2252. *
  2253. * @param int Session ID (optional)
  2254. *
  2255. * @return string The session name, or null if not found
  2256. */
  2257. function api_get_session_name($session_id = 0)
  2258. {
  2259. if (empty($session_id)) {
  2260. $session_id = api_get_session_id();
  2261. if (empty($session_id)) {
  2262. return null;
  2263. }
  2264. }
  2265. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  2266. $s = "SELECT name FROM $t WHERE id = ".(int) $session_id;
  2267. $r = Database::query($s);
  2268. $c = Database::num_rows($r);
  2269. if ($c > 0) {
  2270. //technically, there can be only one, but anyway we take the first
  2271. $rec = Database::fetch_array($r);
  2272. return $rec['name'];
  2273. }
  2274. return null;
  2275. }
  2276. /**
  2277. * Gets the session info by id.
  2278. *
  2279. * @param int $id Session ID
  2280. *
  2281. * @return array information of the session
  2282. */
  2283. function api_get_session_info($id)
  2284. {
  2285. return SessionManager::fetch($id);
  2286. }
  2287. /**
  2288. * Gets the session visibility by session id.
  2289. *
  2290. * @param int $session_id
  2291. * @param int $courseId
  2292. * @param bool $ignore_visibility_for_admins
  2293. *
  2294. * @return int
  2295. * 0 = session still available,
  2296. * SESSION_VISIBLE_READ_ONLY = 1,
  2297. * SESSION_VISIBLE = 2,
  2298. * SESSION_INVISIBLE = 3
  2299. */
  2300. function api_get_session_visibility(
  2301. $session_id,
  2302. $courseId = null,
  2303. $ignore_visibility_for_admins = true
  2304. ) {
  2305. if (api_is_platform_admin()) {
  2306. if ($ignore_visibility_for_admins) {
  2307. return SESSION_AVAILABLE;
  2308. }
  2309. }
  2310. $now = time();
  2311. if (empty($session_id)) {
  2312. return 0; // Means that the session is still available.
  2313. }
  2314. $session_id = (int) $session_id;
  2315. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2316. $result = Database::query("SELECT * FROM $tbl_session WHERE id = $session_id");
  2317. if (Database::num_rows($result) <= 0) {
  2318. return SESSION_INVISIBLE;
  2319. }
  2320. $row = Database::fetch_array($result, 'ASSOC');
  2321. $visibility = $original_visibility = $row['visibility'];
  2322. // I don't care the session visibility.
  2323. if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
  2324. // Session duration per student.
  2325. if (isset($row['duration']) && !empty($row['duration'])) {
  2326. $duration = $row['duration'] * 24 * 60 * 60;
  2327. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser($session_id, api_get_user_id());
  2328. // If there is a session duration but there is no previous
  2329. // access by the user, then the session is still available
  2330. if (count($courseAccess) == 0) {
  2331. return SESSION_AVAILABLE;
  2332. }
  2333. $currentTime = time();
  2334. $firstAccess = isset($courseAccess['login_course_date'])
  2335. ? api_strtotime($courseAccess['login_course_date'], 'UTC')
  2336. : 0;
  2337. $userDurationData = SessionManager::getUserSession(
  2338. api_get_user_id(),
  2339. $session_id
  2340. );
  2341. $userDuration = isset($userDurationData['duration'])
  2342. ? (intval($userDurationData['duration']) * 24 * 60 * 60)
  2343. : 0;
  2344. $totalDuration = $firstAccess + $duration + $userDuration;
  2345. return $totalDuration > $currentTime ? SESSION_AVAILABLE : SESSION_VISIBLE_READ_ONLY;
  2346. }
  2347. return SESSION_AVAILABLE;
  2348. }
  2349. // If start date was set.
  2350. if (!empty($row['access_start_date'])) {
  2351. $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : SESSION_INVISIBLE;
  2352. }
  2353. // If the end date was set.
  2354. if (!empty($row['access_end_date'])) {
  2355. // Only if date_start said that it was ok
  2356. if ($visibility === SESSION_AVAILABLE) {
  2357. $visibility = $now < api_strtotime($row['access_end_date'], 'UTC')
  2358. ? SESSION_AVAILABLE // Date still available
  2359. : $row['visibility']; // Session ends
  2360. }
  2361. }
  2362. // If I'm a coach the visibility can change in my favor depending in the coach dates.
  2363. $isCoach = api_is_coach($session_id, $courseId);
  2364. if ($isCoach) {
  2365. // Test start date.
  2366. if (!empty($row['coach_access_start_date'])) {
  2367. $start = api_strtotime($row['coach_access_start_date'], 'UTC');
  2368. $visibility = $start < $now ? SESSION_AVAILABLE : SESSION_INVISIBLE;
  2369. }
  2370. // Test end date.
  2371. if (!empty($row['coach_access_end_date'])) {
  2372. if ($visibility === SESSION_AVAILABLE) {
  2373. $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
  2374. $visibility = $endDateCoach >= $now ? SESSION_AVAILABLE : $row['visibility'];
  2375. }
  2376. }
  2377. }
  2378. return $visibility;
  2379. }
  2380. /**
  2381. * This function returns a (star) session icon if the session is not null and
  2382. * the user is not a student.
  2383. *
  2384. * @param int $sessionId
  2385. * @param int $statusId User status id - if 5 (student), will return empty
  2386. *
  2387. * @return string Session icon
  2388. */
  2389. function api_get_session_image($sessionId, $statusId)
  2390. {
  2391. $sessionId = (int) $sessionId;
  2392. $image = '';
  2393. if ($statusId != STUDENT) {
  2394. // Check whether is not a student
  2395. if ($sessionId > 0) {
  2396. $image = '&nbsp;&nbsp;'.Display::return_icon(
  2397. 'star.png',
  2398. get_lang('SessionSpecificResource'),
  2399. ['align' => 'absmiddle'],
  2400. ICON_SIZE_SMALL
  2401. );
  2402. }
  2403. }
  2404. return $image;
  2405. }
  2406. /**
  2407. * This function add an additional condition according to the session of the course.
  2408. *
  2409. * @param int $session_id session id
  2410. * @param bool $and optional, true if more than one condition false if the only condition in the query
  2411. * @param bool $with_base_content optional, true to accept content with session=0 as well,
  2412. * false for strict session condition
  2413. * @param string $session_field
  2414. *
  2415. * @return string condition of the session
  2416. */
  2417. function api_get_session_condition(
  2418. $session_id,
  2419. $and = true,
  2420. $with_base_content = false,
  2421. $session_field = 'session_id'
  2422. ) {
  2423. $session_id = (int) $session_id;
  2424. if (empty($session_field)) {
  2425. $session_field = 'session_id';
  2426. }
  2427. // Condition to show resources by session
  2428. $condition_add = $and ? ' AND ' : ' WHERE ';
  2429. if ($with_base_content) {
  2430. $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
  2431. } else {
  2432. if (empty($session_id)) {
  2433. $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
  2434. } else {
  2435. $condition_session = $condition_add." $session_field = $session_id ";
  2436. }
  2437. }
  2438. return $condition_session;
  2439. }
  2440. /**
  2441. * Returns the value of a setting from the web-adjustable admin config settings.
  2442. *
  2443. * WARNING true/false are stored as string, so when comparing you need to check e.g.
  2444. * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
  2445. * instead of
  2446. * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
  2447. *
  2448. * @param string $variable The variable name
  2449. * @param string $key The subkey (sub-variable) if any. Defaults to NULL
  2450. *
  2451. * @return string
  2452. *
  2453. * @author René Haentjens
  2454. * @author Bart Mollet
  2455. */
  2456. function api_get_setting($variable, $key = null)
  2457. {
  2458. global $_setting;
  2459. if ($variable == 'header_extra_content') {
  2460. $filename = api_get_home_path().'header_extra_content.txt';
  2461. if (file_exists($filename)) {
  2462. $value = file_get_contents($filename);
  2463. return $value;
  2464. } else {
  2465. return '';
  2466. }
  2467. }
  2468. if ($variable == 'footer_extra_content') {
  2469. $filename = api_get_home_path().'footer_extra_content.txt';
  2470. if (file_exists($filename)) {
  2471. $value = file_get_contents($filename);
  2472. return $value;
  2473. } else {
  2474. return '';
  2475. }
  2476. }
  2477. $value = null;
  2478. if (is_null($key)) {
  2479. $value = ((isset($_setting[$variable]) && $_setting[$variable] != '') ? $_setting[$variable] : null);
  2480. } else {
  2481. if (isset($_setting[$variable][$key])) {
  2482. $value = $_setting[$variable][$key];
  2483. }
  2484. }
  2485. return $value;
  2486. }
  2487. /**
  2488. * @param string $plugin
  2489. * @param string $variable
  2490. *
  2491. * @return string
  2492. */
  2493. function api_get_plugin_setting($plugin, $variable)
  2494. {
  2495. $variableName = $plugin.'_'.$variable;
  2496. $result = api_get_setting($variableName);
  2497. if (isset($result[$plugin])) {
  2498. $value = $result[$plugin];
  2499. $unserialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
  2500. if (false !== $unserialized) {
  2501. $value = $unserialized;
  2502. }
  2503. return $value;
  2504. }
  2505. return null;
  2506. }
  2507. /**
  2508. * Returns the value of a setting from the web-adjustable admin config settings.
  2509. */
  2510. function api_get_settings_params($params)
  2511. {
  2512. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2513. $result = Database::select('*', $table, ['where' => $params]);
  2514. return $result;
  2515. }
  2516. /**
  2517. * @param array $params example: [id = ? => '1']
  2518. *
  2519. * @return array
  2520. */
  2521. function api_get_settings_params_simple($params)
  2522. {
  2523. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2524. $result = Database::select('*', $table, ['where' => $params], 'one');
  2525. return $result;
  2526. }
  2527. /**
  2528. * Returns the value of a setting from the web-adjustable admin config settings.
  2529. */
  2530. function api_delete_settings_params($params)
  2531. {
  2532. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  2533. $result = Database::delete($table, $params);
  2534. return $result;
  2535. }
  2536. /**
  2537. * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection.
  2538. *
  2539. * @return string Escaped version of $_SERVER['PHP_SELF']
  2540. */
  2541. function api_get_self()
  2542. {
  2543. return htmlentities($_SERVER['PHP_SELF']);
  2544. }
  2545. /* USER PERMISSIONS */
  2546. /**
  2547. * Checks whether current user is a platform administrator.
  2548. *
  2549. * @param bool $allowSessionAdmins Whether session admins should be considered admins or not
  2550. * @param bool $allowDrh Whether HR directors should be considered admins or not
  2551. *
  2552. * @return bool true if the user has platform admin rights,
  2553. * false otherwise
  2554. *
  2555. * @see usermanager::is_admin(user_id) for a user-id specific function
  2556. */
  2557. function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
  2558. {
  2559. $isAdmin = Session::read('is_platformAdmin');
  2560. if ($isAdmin) {
  2561. return true;
  2562. }
  2563. $user = api_get_user_info();
  2564. return
  2565. isset($user['status']) &&
  2566. (
  2567. ($allowSessionAdmins && $user['status'] == SESSIONADMIN) ||
  2568. ($allowDrh && $user['status'] == DRH)
  2569. );
  2570. }
  2571. /**
  2572. * Checks whether the user given as user id is in the admin table.
  2573. *
  2574. * @param int $user_id If none provided, will use current user
  2575. * @param int $url URL ID. If provided, also check if the user is active on given URL
  2576. *
  2577. * @return bool True if the user is admin, false otherwise
  2578. */
  2579. function api_is_platform_admin_by_id($user_id = null, $url = null)
  2580. {
  2581. $user_id = (int) $user_id;
  2582. if (empty($user_id)) {
  2583. $user_id = api_get_user_id();
  2584. }
  2585. $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
  2586. $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
  2587. $res = Database::query($sql);
  2588. $is_admin = Database::num_rows($res) === 1;
  2589. if (!$is_admin || !isset($url)) {
  2590. return $is_admin;
  2591. }
  2592. // We get here only if $url is set
  2593. $url = (int) $url;
  2594. $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2595. $sql = "SELECT * FROM $url_user_table
  2596. WHERE access_url_id = $url AND user_id = $user_id";
  2597. $res = Database::query($sql);
  2598. $result = Database::num_rows($res) === 1;
  2599. return $result;
  2600. }
  2601. /**
  2602. * Returns the user's numeric status ID from the users table.
  2603. *
  2604. * @param int $user_id If none provided, will use current user
  2605. *
  2606. * @return int User's status (1 for teacher, 5 for student, etc)
  2607. */
  2608. function api_get_user_status($user_id = null)
  2609. {
  2610. $user_id = (int) $user_id;
  2611. if (empty($user_id)) {
  2612. $user_id = api_get_user_id();
  2613. }
  2614. $table = Database::get_main_table(TABLE_MAIN_USER);
  2615. $sql = "SELECT status FROM $table WHERE user_id = $user_id ";
  2616. $result = Database::query($sql);
  2617. $status = null;
  2618. if (Database::num_rows($result)) {
  2619. $row = Database::fetch_array($result);
  2620. $status = $row['status'];
  2621. }
  2622. return $status;
  2623. }
  2624. /**
  2625. * Checks whether current user is allowed to create courses.
  2626. *
  2627. * @return bool true if the user has course creation rights,
  2628. * false otherwise
  2629. */
  2630. function api_is_allowed_to_create_course()
  2631. {
  2632. if (api_is_platform_admin()) {
  2633. return true;
  2634. }
  2635. // Teachers can only create courses
  2636. if (api_is_teacher()) {
  2637. if (api_get_setting('allow_users_to_create_courses') === 'true') {
  2638. return true;
  2639. } else {
  2640. return false;
  2641. }
  2642. }
  2643. return Session::read('is_allowedCreateCourse');
  2644. }
  2645. /**
  2646. * Checks whether the current user is a course administrator.
  2647. *
  2648. * @return bool True if current user is a course administrator
  2649. */
  2650. function api_is_course_admin()
  2651. {
  2652. if (api_is_platform_admin()) {
  2653. return true;
  2654. }
  2655. return Session::read('is_courseAdmin');
  2656. }
  2657. /**
  2658. * Checks whether the current user is a course coach
  2659. * Based on the presence of user in session.id_coach (session general coach).
  2660. *
  2661. * @return bool True if current user is a course coach
  2662. */
  2663. function api_is_session_general_coach()
  2664. {
  2665. return Session::read('is_session_general_coach');
  2666. }
  2667. /**
  2668. * Checks whether the current user is a course tutor
  2669. * Based on the presence of user in session_rel_course_rel_user.user_id with status = 2.
  2670. *
  2671. * @return bool True if current user is a course tutor
  2672. */
  2673. function api_is_course_tutor()
  2674. {
  2675. return Session::read('is_courseTutor');
  2676. }
  2677. /**
  2678. * @param int $user_id
  2679. * @param int $courseId
  2680. * @param int $session_id
  2681. *
  2682. * @return bool
  2683. */
  2684. function api_is_course_session_coach($user_id, $courseId, $session_id)
  2685. {
  2686. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2687. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2688. $user_id = (int) $user_id;
  2689. $session_id = (int) $session_id;
  2690. $courseId = (int) $courseId;
  2691. $sql = "SELECT DISTINCT session.id
  2692. FROM $session_table
  2693. INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  2694. ON session.id = session_rc_ru.session_id
  2695. WHERE
  2696. session_rc_ru.user_id = '".$user_id."' AND
  2697. session_rc_ru.c_id = '$courseId' AND
  2698. session_rc_ru.status = 2 AND
  2699. session_rc_ru.session_id = '$session_id'";
  2700. $result = Database::query($sql);
  2701. return Database::num_rows($result) > 0;
  2702. }
  2703. /**
  2704. * Checks whether the current user is a course or session coach.
  2705. *
  2706. * @param int $session_id
  2707. * @param int $courseId
  2708. * @param bool Check whether we are in student view and, if we are, return false
  2709. *
  2710. * @return bool True if current user is a course or session coach
  2711. */
  2712. function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true)
  2713. {
  2714. $userId = api_get_user_id();
  2715. if (!empty($session_id)) {
  2716. $session_id = (int) $session_id;
  2717. } else {
  2718. $session_id = api_get_session_id();
  2719. }
  2720. // The student preview was on
  2721. if ($check_student_view && api_is_student_view_active()) {
  2722. return false;
  2723. }
  2724. if (!empty($courseId)) {
  2725. $courseId = (int) $courseId;
  2726. } else {
  2727. $courseId = api_get_course_int_id();
  2728. }
  2729. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  2730. $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2731. $sessionIsCoach = [];
  2732. if (!empty($courseId)) {
  2733. $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
  2734. FROM $session_table s
  2735. INNER JOIN $session_rel_course_rel_user_table session_rc_ru
  2736. ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
  2737. WHERE
  2738. session_rc_ru.c_id = '$courseId' AND
  2739. session_rc_ru.status = 2 AND
  2740. session_rc_ru.session_id = '$session_id'";
  2741. $result = Database::query($sql);
  2742. $sessionIsCoach = Database::store_result($result);
  2743. }
  2744. if (!empty($session_id)) {
  2745. $sql = "SELECT DISTINCT id, name, access_start_date, access_end_date
  2746. FROM $session_table
  2747. WHERE session.id_coach = $userId AND id = $session_id
  2748. ORDER BY access_start_date, access_end_date, name";
  2749. $result = Database::query($sql);
  2750. if (!empty($sessionIsCoach)) {
  2751. $sessionIsCoach = array_merge(
  2752. $sessionIsCoach,
  2753. Database::store_result($result)
  2754. );
  2755. } else {
  2756. $sessionIsCoach = Database::store_result($result);
  2757. }
  2758. }
  2759. return count($sessionIsCoach) > 0;
  2760. }
  2761. /**
  2762. * Checks whether the current user is a session administrator.
  2763. *
  2764. * @return bool True if current user is a course administrator
  2765. */
  2766. function api_is_session_admin()
  2767. {
  2768. $user = api_get_user_info();
  2769. return isset($user['status']) && $user['status'] == SESSIONADMIN;
  2770. }
  2771. /**
  2772. * Checks whether the current user is a human resources manager.
  2773. *
  2774. * @return bool True if current user is a human resources manager
  2775. */
  2776. function api_is_drh()
  2777. {
  2778. $user = api_get_user_info();
  2779. return isset($user['status']) && $user['status'] == DRH;
  2780. }
  2781. /**
  2782. * Checks whether the current user is a student.
  2783. *
  2784. * @return bool True if current user is a human resources manager
  2785. */
  2786. function api_is_student()
  2787. {
  2788. $user = api_get_user_info();
  2789. return isset($user['status']) && $user['status'] == STUDENT;
  2790. }
  2791. /**
  2792. * Checks whether the current user has the status 'teacher'.
  2793. *
  2794. * @return bool True if current user is a human resources manager
  2795. */
  2796. function api_is_teacher()
  2797. {
  2798. $user = api_get_user_info();
  2799. return isset($user['status']) && $user['status'] == COURSEMANAGER;
  2800. }
  2801. /**
  2802. * Checks whether the current user is a invited user.
  2803. *
  2804. * @return bool
  2805. */
  2806. function api_is_invitee()
  2807. {
  2808. $user = api_get_user_info();
  2809. return isset($user['status']) && $user['status'] == INVITEE;
  2810. }
  2811. /**
  2812. * This function checks whether a session is assigned into a category.
  2813. *
  2814. * @param int - session id
  2815. * @param string - category name
  2816. *
  2817. * @return bool - true if is found, otherwise false
  2818. */
  2819. function api_is_session_in_category($session_id, $category_name)
  2820. {
  2821. $session_id = (int) $session_id;
  2822. $category_name = Database::escape_string($category_name);
  2823. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2824. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  2825. $sql = "SELECT 1
  2826. FROM $tbl_session
  2827. WHERE $session_id IN (
  2828. SELECT s.id FROM $tbl_session s, $tbl_session_category sc
  2829. WHERE
  2830. s.session_category_id = sc.id AND
  2831. sc.name LIKE '%$category_name'
  2832. )";
  2833. $rs = Database::query($sql);
  2834. if (Database::num_rows($rs) > 0) {
  2835. return true;
  2836. } else {
  2837. return false;
  2838. }
  2839. }
  2840. /**
  2841. * Displays the title of a tool.
  2842. * Normal use: parameter is a string:
  2843. * api_display_tool_title("My Tool").
  2844. *
  2845. * Optionally, there can be a subtitle below
  2846. * the normal title, and / or a supra title above the normal title.
  2847. *
  2848. * e.g. supra title:
  2849. * group
  2850. * GROUP PROPERTIES
  2851. *
  2852. * e.g. subtitle:
  2853. * AGENDA
  2854. * calender & events tool
  2855. *
  2856. * @author Hugues Peeters <hugues.peeters@claroline.net>
  2857. *
  2858. * @param mixed $title_element - it could either be a string or an array
  2859. * containing 'supraTitle', 'mainTitle',
  2860. * 'subTitle'
  2861. */
  2862. function api_display_tool_title($title_element)
  2863. {
  2864. if (is_string($title_element)) {
  2865. $tit = $title_element;
  2866. unset($title_element);
  2867. $title_element['mainTitle'] = $tit;
  2868. }
  2869. echo '<h3>';
  2870. if (!empty($title_element['supraTitle'])) {
  2871. echo '<small>'.$title_element['supraTitle'].'</small><br />';
  2872. }
  2873. if (!empty($title_element['mainTitle'])) {
  2874. echo $title_element['mainTitle'];
  2875. }
  2876. if (!empty($title_element['subTitle'])) {
  2877. echo '<br /><small>'.$title_element['subTitle'].'</small>';
  2878. }
  2879. echo '</h3>';
  2880. }
  2881. /**
  2882. * Displays options for switching between student view and course manager view.
  2883. *
  2884. * Changes in version 1.2 (Patrick Cool)
  2885. * Student view switch now behaves as a real switch. It maintains its current state until the state
  2886. * is changed explicitly
  2887. *
  2888. * Changes in version 1.1 (Patrick Cool)
  2889. * student view now works correctly in subfolders of the document tool
  2890. * student view works correctly in the new links tool
  2891. *
  2892. * Example code for using this in your tools:
  2893. * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
  2894. * // display_tool_view_option($isStudentView);
  2895. * //}
  2896. * //and in later sections, use api_is_allowed_to_edit()
  2897. *
  2898. * @author Roan Embrechts
  2899. * @author Patrick Cool
  2900. * @author Julio Montoya, changes added in Chamilo
  2901. *
  2902. * @version 1.2
  2903. *
  2904. * @todo rewrite code so it is easier to understand
  2905. */
  2906. function api_display_tool_view_option()
  2907. {
  2908. if (api_get_setting('student_view_enabled') != 'true') {
  2909. return '';
  2910. }
  2911. $sourceurl = '';
  2912. $is_framed = false;
  2913. // Exceptions apply for all multi-frames pages
  2914. if (strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php') !== false) {
  2915. // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
  2916. return '';
  2917. }
  2918. // Uncomment to remove student view link from document view page
  2919. if (strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php') !== false) {
  2920. if (empty($_GET['lp_id'])) {
  2921. return '';
  2922. }
  2923. $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
  2924. $sourceurl = str_replace(
  2925. 'lp/lp_header.php',
  2926. 'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview'] == 'studentview' ? 'false' : 'true'),
  2927. $sourceurl
  2928. );
  2929. //showinframes doesn't handle student view anyway...
  2930. //return '';
  2931. $is_framed = true;
  2932. }
  2933. // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
  2934. if (!$is_framed) {
  2935. if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
  2936. $sourceurl = api_get_self().'?'.api_get_cidreq();
  2937. } else {
  2938. $sourceurl = $_SERVER['REQUEST_URI'];
  2939. }
  2940. }
  2941. $output_string = '';
  2942. if (!empty($_SESSION['studentview'])) {
  2943. if ($_SESSION['studentview'] == 'studentview') {
  2944. // We have to remove the isStudentView=true from the $sourceurl
  2945. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2946. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2947. $output_string .= '<a class="btn btn-primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.
  2948. Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToTeacherView').'</a>';
  2949. } elseif ($_SESSION['studentview'] == 'teacherview') {
  2950. // Switching to teacherview
  2951. $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
  2952. $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
  2953. $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
  2954. Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
  2955. }
  2956. } else {
  2957. $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
  2958. Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
  2959. }
  2960. $output_string = Security::remove_XSS($output_string);
  2961. $html = Display::tag('div', $output_string, ['class' => 'view-options']);
  2962. return $html;
  2963. }
  2964. // TODO: This is for the permission section.
  2965. /**
  2966. * Function that removes the need to directly use is_courseAdmin global in
  2967. * tool scripts. It returns true or false depending on the user's rights in
  2968. * this particular course.
  2969. * Optionally checking for tutor and coach roles here allows us to use the
  2970. * student_view feature altogether with these roles as well.
  2971. *
  2972. * @param bool Whether to check if the user has the tutor role
  2973. * @param bool Whether to check if the user has the coach role
  2974. * @param bool Whether to check if the user has the session coach role
  2975. * @param bool check the student view or not
  2976. *
  2977. * @author Roan Embrechts
  2978. * @author Patrick Cool
  2979. * @author Julio Montoya
  2980. *
  2981. * @version 1.1, February 2004
  2982. *
  2983. * @return bool true: the user has the rights to edit, false: he does not
  2984. */
  2985. function api_is_allowed_to_edit(
  2986. $tutor = false,
  2987. $coach = false,
  2988. $session_coach = false,
  2989. $check_student_view = true
  2990. ) {
  2991. $allowSessionAdminEdit = api_get_configuration_value('session_admins_edit_courses_content') === true;
  2992. // Admins can edit anything.
  2993. if (api_is_platform_admin($allowSessionAdminEdit)) {
  2994. //The student preview was on
  2995. if ($check_student_view && api_is_student_view_active()) {
  2996. return false;
  2997. } else {
  2998. return true;
  2999. }
  3000. }
  3001. $sessionId = api_get_session_id();
  3002. if ($sessionId && api_get_configuration_value('session_courses_read_only_mode')) {
  3003. $efv = new ExtraFieldValue('course');
  3004. $lockExrafieldField = $efv->get_values_by_handler_and_field_variable(
  3005. api_get_course_int_id(),
  3006. 'session_courses_read_only_mode'
  3007. );
  3008. if (!empty($lockExrafieldField['value'])) {
  3009. return false;
  3010. }
  3011. }
  3012. $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
  3013. $session_visibility = api_get_session_visibility($sessionId);
  3014. $is_courseAdmin = api_is_course_admin();
  3015. if (!$is_courseAdmin && $tutor) {
  3016. // If we also want to check if the user is a tutor...
  3017. $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
  3018. }
  3019. if (!$is_courseAdmin && $coach) {
  3020. // If we also want to check if the user is a coach...';
  3021. // Check if session visibility is read only for coaches.
  3022. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  3023. $is_allowed_coach_to_edit = false;
  3024. }
  3025. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
  3026. // Check if coach is allowed to edit a course.
  3027. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  3028. }
  3029. }
  3030. if (!$is_courseAdmin && $session_coach) {
  3031. $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
  3032. }
  3033. // Check if the student_view is enabled, and if so, if it is activated.
  3034. if (api_get_setting('student_view_enabled') == 'true') {
  3035. if (!empty($sessionId)) {
  3036. // Check if session visibility is read only for coaches.
  3037. if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
  3038. $is_allowed_coach_to_edit = false;
  3039. }
  3040. if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
  3041. // Check if coach is allowed to edit a course.
  3042. $is_allowed = $is_allowed_coach_to_edit;
  3043. } else {
  3044. $is_allowed = false;
  3045. }
  3046. if ($check_student_view) {
  3047. $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
  3048. }
  3049. } else {
  3050. if ($check_student_view) {
  3051. $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
  3052. } else {
  3053. $is_allowed = $is_courseAdmin;
  3054. }
  3055. }
  3056. return $is_allowed;
  3057. } else {
  3058. return $is_courseAdmin;
  3059. }
  3060. }
  3061. /**
  3062. * Returns true if user is a course coach of at least one course in session.
  3063. *
  3064. * @param int $sessionId
  3065. *
  3066. * @return bool
  3067. */
  3068. function api_is_coach_of_course_in_session($sessionId)
  3069. {
  3070. if (api_is_platform_admin()) {
  3071. return true;
  3072. }
  3073. $userId = api_get_user_id();
  3074. $courseList = UserManager::get_courses_list_by_session(
  3075. $userId,
  3076. $sessionId
  3077. );
  3078. // Session visibility.
  3079. $visibility = api_get_session_visibility(
  3080. $sessionId,
  3081. null,
  3082. false
  3083. );
  3084. if ($visibility != SESSION_VISIBLE && !empty($courseList)) {
  3085. // Course Coach session visibility.
  3086. $blockedCourseCount = 0;
  3087. $closedVisibilityList = [
  3088. COURSE_VISIBILITY_CLOSED,
  3089. COURSE_VISIBILITY_HIDDEN,
  3090. ];
  3091. foreach ($courseList as $course) {
  3092. // Checking session visibility
  3093. $sessionCourseVisibility = api_get_session_visibility(
  3094. $sessionId,
  3095. $course['real_id']
  3096. );
  3097. $courseIsVisible = !in_array(
  3098. $course['visibility'],
  3099. $closedVisibilityList
  3100. );
  3101. if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
  3102. $blockedCourseCount++;
  3103. }
  3104. }
  3105. // If all courses are blocked then no show in the list.
  3106. if ($blockedCourseCount === count($courseList)) {
  3107. $visibility = SESSION_INVISIBLE;
  3108. } else {
  3109. $visibility = SESSION_VISIBLE;
  3110. }
  3111. }
  3112. switch ($visibility) {
  3113. case SESSION_VISIBLE_READ_ONLY:
  3114. case SESSION_VISIBLE:
  3115. case SESSION_AVAILABLE:
  3116. return true;
  3117. break;
  3118. case SESSION_INVISIBLE:
  3119. return false;
  3120. }
  3121. return false;
  3122. }
  3123. /**
  3124. * Checks if a student can edit contents in a session depending
  3125. * on the session visibility.
  3126. *
  3127. * @param bool $tutor Whether to check if the user has the tutor role
  3128. * @param bool $coach Whether to check if the user has the coach role
  3129. *
  3130. * @return bool true: the user has the rights to edit, false: he does not
  3131. */
  3132. function api_is_allowed_to_session_edit($tutor = false, $coach = false)
  3133. {
  3134. if (api_is_allowed_to_edit($tutor, $coach)) {
  3135. // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
  3136. return true;
  3137. } else {
  3138. $sessionId = api_get_session_id();
  3139. if ($sessionId == 0) {
  3140. // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
  3141. return true;
  3142. } else {
  3143. // I'm in a session and I'm a student
  3144. // Get the session visibility
  3145. $session_visibility = api_get_session_visibility($sessionId);
  3146. // if 5 the session is still available
  3147. switch ($session_visibility) {
  3148. case SESSION_VISIBLE_READ_ONLY: // 1
  3149. return false;
  3150. case SESSION_VISIBLE: // 2
  3151. return true;
  3152. case SESSION_INVISIBLE: // 3
  3153. return false;
  3154. case SESSION_AVAILABLE: //5
  3155. return true;
  3156. }
  3157. }
  3158. }
  3159. }
  3160. /**
  3161. * Checks whether the user is allowed in a specific tool for a specific action.
  3162. *
  3163. * @param string $tool the tool we are checking if the user has a certain permission
  3164. * @param string $action the action we are checking (add, edit, delete, move, visibility)
  3165. *
  3166. * @return bool
  3167. *
  3168. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3169. * @author Julio Montoya
  3170. *
  3171. * @version 1.0
  3172. */
  3173. function api_is_allowed($tool, $action, $task_id = 0)
  3174. {
  3175. $_user = api_get_user_info();
  3176. $_course = api_get_course_info();
  3177. if (api_is_course_admin()) {
  3178. return true;
  3179. }
  3180. if (is_array($_course) and count($_course) > 0) {
  3181. require_once api_get_path(SYS_CODE_PATH).'permissions/permissions_functions.inc.php';
  3182. // Getting the permissions of this user.
  3183. if ($task_id == 0) {
  3184. $user_permissions = get_permissions('user', $_user['user_id']);
  3185. $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
  3186. }
  3187. // Getting the permissions of the task.
  3188. if ($task_id != 0) {
  3189. $task_permissions = get_permissions('task', $task_id);
  3190. /* !!! */$_SESSION['total_permissions'][$_course['code']] = $task_permissions;
  3191. }
  3192. //print_r($_SESSION['total_permissions']);
  3193. // Getting the permissions of the groups of the user
  3194. //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
  3195. //foreach($groups_of_user as $group)
  3196. // $this_group_permissions = get_permissions('group', $group);
  3197. // Getting the permissions of the courseroles of the user
  3198. $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
  3199. // Getting the permissions of the platformroles of the user
  3200. //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
  3201. // Getting the permissions of the roles of the groups of the user
  3202. //foreach($groups_of_user as $group)
  3203. // $this_group_courserole_permissions = get_roles_permissions('group', $group);
  3204. // Getting the permissions of the platformroles of the groups of the user
  3205. //foreach($groups_of_user as $group)
  3206. // $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
  3207. }
  3208. // If the permissions are limited, we have to map the extended ones to the limited ones.
  3209. if (api_get_setting('permissions') == 'limited') {
  3210. if ($action == 'Visibility') {
  3211. $action = 'Edit';
  3212. }
  3213. if ($action == 'Move') {
  3214. $action = 'Edit';
  3215. }
  3216. }
  3217. // The session that contains all the permissions already exists for this course
  3218. // so there is no need to requery everything.
  3219. //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
  3220. if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) {
  3221. if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) {
  3222. return true;
  3223. } else {
  3224. return false;
  3225. }
  3226. }
  3227. }
  3228. /**
  3229. * Tells whether this user is an anonymous user.
  3230. *
  3231. * @param int $user_id User ID (optional, will take session ID if not provided)
  3232. * @param bool $db_check Whether to check in the database (true) or simply in
  3233. * the session (false) to see if the current user is the anonymous user
  3234. *
  3235. * @return bool true if this user is anonymous, false otherwise
  3236. */
  3237. function api_is_anonymous($user_id = null, $db_check = false)
  3238. {
  3239. if (!isset($user_id)) {
  3240. $user_id = api_get_user_id();
  3241. }
  3242. if ($db_check) {
  3243. $info = api_get_user_info($user_id);
  3244. if ($info['status'] == ANONYMOUS) {
  3245. return true;
  3246. }
  3247. }
  3248. $_user = api_get_user_info();
  3249. if (isset($_user['status']) && $_user['status'] == ANONYMOUS) {
  3250. //if ($_user['user_id'] == 0) {
  3251. // In some cases, api_set_anonymous doesn't seem to be triggered in local.inc.php. Make sure it is.
  3252. // Occurs in agenda for admin links - YW
  3253. global $use_anonymous;
  3254. if (isset($use_anonymous) && $use_anonymous) {
  3255. api_set_anonymous();
  3256. }
  3257. return true;
  3258. }
  3259. return (isset($_user['is_anonymous']) && $_user['is_anonymous'] === true) || $_user === false;
  3260. }
  3261. /**
  3262. * Displays message "You are not allowed here..." and exits the entire script.
  3263. *
  3264. * @param bool $print_headers Whether or not to print headers (default = false -> does not print them)
  3265. * @param string $message
  3266. * @param int $responseCode
  3267. */
  3268. function api_not_allowed(
  3269. $print_headers = false,
  3270. $message = null,
  3271. $responseCode = 0
  3272. ) {
  3273. if (api_get_setting('sso_authentication') === 'true') {
  3274. global $osso;
  3275. if ($osso) {
  3276. $osso->logout();
  3277. }
  3278. }
  3279. $home_url = api_get_path(WEB_PATH);
  3280. $user_id = api_get_user_id();
  3281. $course = api_get_course_id();
  3282. global $this_section;
  3283. if (CustomPages::enabled() && !isset($user_id)) {
  3284. if (empty($user_id)) {
  3285. // Why the CustomPages::enabled() need to be to set the request_uri
  3286. $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
  3287. }
  3288. CustomPages::display(CustomPages::INDEX_UNLOGGED);
  3289. }
  3290. $origin = api_get_origin();
  3291. $msg = null;
  3292. if (isset($message)) {
  3293. $msg = $message;
  3294. } else {
  3295. $msg = Display::return_message(
  3296. get_lang('NotAllowedClickBack').'
  3297. <script>function goBack(){window.history.back();}</script>',
  3298. 'error',
  3299. false
  3300. );
  3301. $msg .= '<p class="text-center">
  3302. <a onclick="goBack();" class="btn btn-default" href="'.$home_url.'">'.get_lang('GoBack').'</a>
  3303. </p>';
  3304. }
  3305. $msg = Display::div($msg, ['align' => 'center']);
  3306. $show_headers = 0;
  3307. if ($print_headers && $origin != 'learnpath') {
  3308. $show_headers = 1;
  3309. }
  3310. $tpl = new Template(null, $show_headers, $show_headers, false, true, false, true, $responseCode);
  3311. $tpl->assign('hide_login_link', 1);
  3312. $tpl->assign('content', $msg);
  3313. if (($user_id != 0 && !api_is_anonymous()) &&
  3314. (!isset($course) || $course == -1) &&
  3315. empty($_GET['cidReq'])
  3316. ) {
  3317. // if the access is not authorized and there is some login information
  3318. // but the cidReq is not found, assume we are missing course data and send the user
  3319. // to the user_portal
  3320. $tpl->display_one_col_template();
  3321. exit;
  3322. }
  3323. if (!empty($_SERVER['REQUEST_URI']) &&
  3324. (
  3325. !empty($_GET['cidReq']) ||
  3326. $this_section == SECTION_MYPROFILE ||
  3327. $this_section == SECTION_PLATFORM_ADMIN
  3328. )
  3329. ) {
  3330. $courseCode = api_get_course_id();
  3331. // Only display form and return to the previous URL if there was a course ID included
  3332. if ($user_id != 0 && !api_is_anonymous()) {
  3333. //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
  3334. $tpl->assign('content', $msg);
  3335. $tpl->display_one_col_template();
  3336. exit;
  3337. }
  3338. if (!is_null($courseCode)) {
  3339. api_set_firstpage_parameter($courseCode);
  3340. }
  3341. // If the user has no user ID, then his session has expired
  3342. $form = api_get_not_allowed_login_form();
  3343. // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (above)
  3344. $content = Display::return_message(get_lang('NotAllowed'), 'error', false);
  3345. if (!empty($courseCode)) {
  3346. $content .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
  3347. }
  3348. if (api_is_cas_activated()) {
  3349. $content .= Display::return_message(sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")), '', false);
  3350. $content .= Display::div(
  3351. "<br/><a href='".get_cas_direct_URL(api_get_course_id())."'>".sprintf(get_lang('LoginWithYourAccount'), api_get_setting("Institution"))."</a><br/><br/>",
  3352. ['align' => 'center']
  3353. );
  3354. $content .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
  3355. $content .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
  3356. $content .= "<div style='display:none;'>";
  3357. }
  3358. $content .= '<div class="well">';
  3359. $content .= $form->returnForm();
  3360. $content .= '</div>';
  3361. if (api_is_cas_activated()) {
  3362. $content .= "</div>";
  3363. }
  3364. if (!empty($courseCode)) {
  3365. $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
  3366. get_lang('ReturnToCourseHomepage').'</a></p>';
  3367. } else {
  3368. $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
  3369. get_lang('BackHome').'</a></p>';
  3370. }
  3371. $tpl->setLoginBodyClass();
  3372. $tpl->assign('content', $content);
  3373. $tpl->display_one_col_template();
  3374. exit;
  3375. }
  3376. if ($user_id != 0 && !api_is_anonymous()) {
  3377. $tpl->display_one_col_template();
  3378. exit;
  3379. }
  3380. $msg = null;
  3381. // The session is over and we were not in a course,
  3382. // or we try to get directly to a private course without being logged
  3383. $courseId = api_get_course_int_id();
  3384. if (!empty($courseId)) {
  3385. api_set_firstpage_parameter(api_get_course_id());
  3386. $tpl->setLoginBodyClass();
  3387. // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (bellow)
  3388. $msg = Display::return_message(get_lang('NotAllowed'), 'error', false);
  3389. $msg .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
  3390. $casEnabled = api_is_cas_activated();
  3391. if ($casEnabled) {
  3392. $msg .= Display::return_message(
  3393. sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")),
  3394. '',
  3395. false
  3396. );
  3397. $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/>", ['align' => 'center']);
  3398. $msg .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
  3399. $msg .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
  3400. $msg .= "<div style='display:none;'>";
  3401. }
  3402. $form = api_get_not_allowed_login_form();
  3403. $msg .= '<div class="well">';
  3404. $msg .= $form->returnForm();
  3405. $msg .= '</div>';
  3406. if ($casEnabled) {
  3407. $msg .= "</div>";
  3408. }
  3409. } else {
  3410. // we were not in a course, return to home page
  3411. $msg = Display::return_message(
  3412. get_lang('NotAllowed'),
  3413. 'error',
  3414. false
  3415. );
  3416. $msg .= '<p class="text-center">
  3417. <a class="btn btn-default" href="'.$home_url.'">'.get_lang('BackHome').'</a>
  3418. </p>';
  3419. if (!empty($message)) {
  3420. $msg = $message;
  3421. }
  3422. if (api_is_anonymous()) {
  3423. $form = api_get_not_allowed_login_form();
  3424. $msg .= '<div class="well">';
  3425. $msg .= $form->returnForm();
  3426. $msg .= '</div>';
  3427. }
  3428. }
  3429. $tpl->assign('content', $msg);
  3430. $tpl->display_one_col_template();
  3431. exit;
  3432. }
  3433. /**
  3434. * @return FormValidator
  3435. */
  3436. function api_get_not_allowed_login_form()
  3437. {
  3438. $action = api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
  3439. $action = str_replace('&amp;', '&', $action);
  3440. Session::write('redirect_after_not_allow_page', $action);
  3441. $action .= '&redirect_after_not_allow_page=1';
  3442. $form = new FormValidator(
  3443. 'formLogin',
  3444. 'post',
  3445. $action,
  3446. null,
  3447. ['class' => 'form-stacked']
  3448. );
  3449. $params = [
  3450. 'placeholder' => get_lang('UserName'),
  3451. 'class' => 'col-md-3',
  3452. ];
  3453. if (api_browser_support('autocapitalize')) {
  3454. $params['autocapitalize'] = 'none';
  3455. }
  3456. $form->addElement(
  3457. 'text',
  3458. 'login',
  3459. null,
  3460. $params
  3461. );
  3462. $form->addElement(
  3463. 'password',
  3464. 'password',
  3465. null,
  3466. ['placeholder' => get_lang('Password'), 'class' => 'col-md-3']
  3467. ); //new
  3468. $form->addButtonNext(get_lang('LoginEnter'), 'submitAuth');
  3469. return $form;
  3470. }
  3471. /**
  3472. * Gets a UNIX timestamp from a database (MySQL) datetime format string.
  3473. *
  3474. * @param $last_post_datetime standard output date in a sql query
  3475. *
  3476. * @return int timestamp
  3477. *
  3478. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>
  3479. *
  3480. * @version October 2003
  3481. * @desc convert sql date to unix timestamp
  3482. */
  3483. function convert_sql_date($last_post_datetime)
  3484. {
  3485. list($last_post_date, $last_post_time) = explode(' ', $last_post_datetime);
  3486. list($year, $month, $day) = explode('-', $last_post_date);
  3487. list($hour, $min, $sec) = explode(':', $last_post_time);
  3488. return mktime((int) $hour, (int) $min, (int) $sec, (int) $month, (int) $day, (int) $year);
  3489. }
  3490. /**
  3491. * Gets item visibility from the item_property table.
  3492. *
  3493. * Getting the visibility is done by getting the last updated visibility entry,
  3494. * using the largest session ID found if session 0 and another was found (meaning
  3495. * the only one that is actually from the session, in case there are results from
  3496. * session 0 *AND* session n).
  3497. *
  3498. * @param array $_course Course properties array (result of api_get_course_info())
  3499. * @param string $tool Tool (learnpath, document, etc)
  3500. * @param int $id The item ID in the given tool
  3501. * @param int $session The session ID (optional)
  3502. * @param int $user_id
  3503. * @param string $type
  3504. * @param string $group_id
  3505. *
  3506. * @return int -1 on error, 0 if invisible, 1 if visible
  3507. */
  3508. function api_get_item_visibility(
  3509. $_course,
  3510. $tool,
  3511. $id,
  3512. $session = 0,
  3513. $user_id = null,
  3514. $type = null,
  3515. $group_id = null
  3516. ) {
  3517. if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) {
  3518. return -1;
  3519. }
  3520. $tool = Database::escape_string($tool);
  3521. $id = (int) $id;
  3522. $session = (int) $session;
  3523. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3524. $course_id = (int) $_course['real_id'];
  3525. $userCondition = '';
  3526. if (!empty($user_id)) {
  3527. $user_id = (int) $user_id;
  3528. $userCondition = " AND to_user_id = $user_id ";
  3529. }
  3530. $typeCondition = '';
  3531. if (!empty($type)) {
  3532. $type = Database::escape_string($type);
  3533. $typeCondition = " AND lastedit_type = '$type' ";
  3534. }
  3535. $groupCondition = '';
  3536. if (!empty($group_id)) {
  3537. $group_id = (int) $group_id;
  3538. $groupCondition = " AND to_group_id = '$group_id' ";
  3539. }
  3540. $sql = "SELECT visibility
  3541. FROM $TABLE_ITEMPROPERTY
  3542. WHERE
  3543. c_id = $course_id AND
  3544. tool = '$tool' AND
  3545. ref = $id AND
  3546. (session_id = $session OR session_id = 0 OR session_id IS NULL)
  3547. $userCondition $typeCondition $groupCondition
  3548. ORDER BY session_id DESC, lastedit_date DESC
  3549. LIMIT 1";
  3550. $res = Database::query($sql);
  3551. if ($res === false || Database::num_rows($res) == 0) {
  3552. return -1;
  3553. }
  3554. $row = Database::fetch_array($res);
  3555. return (int) $row['visibility'];
  3556. }
  3557. /**
  3558. * Delete a row in the c_item_property table.
  3559. *
  3560. * @param array $courseInfo
  3561. * @param string $tool
  3562. * @param int $itemId
  3563. * @param int $userId
  3564. * @param int $groupId group.iid
  3565. * @param int $sessionId
  3566. *
  3567. * @return false|null
  3568. */
  3569. function api_item_property_delete(
  3570. $courseInfo,
  3571. $tool,
  3572. $itemId,
  3573. $userId,
  3574. $groupId = 0,
  3575. $sessionId = 0
  3576. ) {
  3577. if (empty($courseInfo)) {
  3578. return false;
  3579. }
  3580. $courseId = (int) $courseInfo['real_id'];
  3581. if (empty($courseId) || empty($tool) || empty($itemId)) {
  3582. return false;
  3583. }
  3584. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3585. $tool = Database::escape_string($tool);
  3586. $itemId = intval($itemId);
  3587. $userId = intval($userId);
  3588. $groupId = intval($groupId);
  3589. $sessionId = intval($sessionId);
  3590. $groupCondition = " AND to_group_id = $groupId ";
  3591. if (empty($groupId)) {
  3592. $groupCondition = " AND (to_group_id is NULL OR to_group_id = 0) ";
  3593. }
  3594. $userCondition = " AND to_user_id = $userId ";
  3595. if (empty($userId)) {
  3596. $userCondition = " AND (to_user_id is NULL OR to_user_id = 0) ";
  3597. }
  3598. $sessionCondition = api_get_session_condition($sessionId, true, false, 'session_id');
  3599. $sql = "DELETE FROM $table
  3600. WHERE
  3601. c_id = $courseId AND
  3602. tool = '$tool' AND
  3603. ref = $itemId
  3604. $sessionCondition
  3605. $userCondition
  3606. $groupCondition
  3607. ";
  3608. Database::query($sql);
  3609. }
  3610. /**
  3611. * Updates or adds item properties to the Item_propetry table
  3612. * Tool and lastedit_type are language independant strings (langvars->get_lang!).
  3613. *
  3614. * @param array $_course array with course properties
  3615. * @param string $tool tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3616. * @param int $item_id id of the item itself, linked to key of every tool ('id', ...)
  3617. * @param string $last_edit_type add or update action
  3618. * (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
  3619. * (2) "delete"
  3620. * (3) "visible"
  3621. * (4) "invisible"
  3622. * @param int $user_id id of the editing/adding user
  3623. * @param array $groupInfo must include group.iid/group.od
  3624. * @param int $to_user_id id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
  3625. * @param string $start_visible 0000-00-00 00:00:00 format
  3626. * @param string $end_visible 0000-00-00 00:00:00 format
  3627. * @param int $session_id The session ID, if any, otherwise will default to 0
  3628. *
  3629. * @return bool false if update fails
  3630. *
  3631. * @author Toon Van Hoecke <Toon.VanHoecke@UGent.be>, Ghent University
  3632. *
  3633. * @version January 2005
  3634. * @desc update the item_properties table (if entry not exists, insert) of the course
  3635. */
  3636. function api_item_property_update(
  3637. $_course,
  3638. $tool,
  3639. $item_id,
  3640. $last_edit_type,
  3641. $user_id,
  3642. $groupInfo = [],
  3643. $to_user_id = null,
  3644. $start_visible = '',
  3645. $end_visible = '',
  3646. $session_id = 0
  3647. ) {
  3648. if (empty($_course)) {
  3649. return false;
  3650. }
  3651. $course_id = $_course['real_id'];
  3652. if (empty($course_id)) {
  3653. return false;
  3654. }
  3655. $to_group_id = 0;
  3656. if (!empty($groupInfo) && isset($groupInfo['iid'])) {
  3657. $to_group_id = (int) $groupInfo['iid'];
  3658. }
  3659. $em = Database::getManager();
  3660. // Definition of variables.
  3661. $tool = Database::escape_string($tool);
  3662. $item_id = (int) $item_id;
  3663. $lastEditTypeNoFilter = $last_edit_type;
  3664. $last_edit_type = Database::escape_string($last_edit_type);
  3665. $user_id = (int) $user_id;
  3666. $startVisible = "NULL";
  3667. if (!empty($start_visible)) {
  3668. $start_visible = Database::escape_string($start_visible);
  3669. $startVisible = "'$start_visible'";
  3670. }
  3671. $endVisible = "NULL";
  3672. if (!empty($end_visible)) {
  3673. $end_visible = Database::escape_string($end_visible);
  3674. $endVisible = "'$end_visible'";
  3675. }
  3676. $to_filter = '';
  3677. $time = api_get_utc_datetime();
  3678. if (!empty($session_id)) {
  3679. $session_id = (int) $session_id;
  3680. } else {
  3681. $session_id = api_get_session_id();
  3682. }
  3683. // Definition of tables.
  3684. $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3685. if ($to_user_id <= 0) {
  3686. $to_user_id = null; // No to_user_id set
  3687. }
  3688. if (!is_null($to_user_id)) {
  3689. // $to_user_id has more priority than $to_group_id
  3690. $to_user_id = (int) $to_user_id;
  3691. $to_field = 'to_user_id';
  3692. $to_value = $to_user_id;
  3693. } else {
  3694. // $to_user_id is not set.
  3695. $to_field = 'to_group_id';
  3696. $to_value = $to_group_id;
  3697. }
  3698. $toValueCondition = empty($to_value) ? 'NULL' : "'$to_value'";
  3699. // Set filters for $to_user_id and $to_group_id, with priority for $to_user_id
  3700. $condition_session = " AND session_id = $session_id ";
  3701. if (empty($session_id)) {
  3702. $condition_session = ' AND (session_id = 0 OR session_id IS NULL) ';
  3703. }
  3704. $filter = " c_id = $course_id AND tool = '$tool' AND ref = $item_id $condition_session ";
  3705. // Check whether $to_user_id and $to_group_id are passed in the function call.
  3706. // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
  3707. if (is_null($to_user_id) && is_null($to_group_id)) {
  3708. $to_group_id = 0;
  3709. }
  3710. if (!is_null($to_user_id)) {
  3711. // Set filter to intended user.
  3712. $to_filter = " AND to_user_id = $to_user_id $condition_session";
  3713. } else {
  3714. // Set filter to intended group.
  3715. if (($to_group_id != 0) && $to_group_id == strval(intval($to_group_id))) {
  3716. $to_filter = " AND to_group_id = $to_group_id $condition_session";
  3717. }
  3718. }
  3719. // Adding filter if set.
  3720. $filter .= $to_filter;
  3721. // Update if possible
  3722. $set_type = '';
  3723. switch ($lastEditTypeNoFilter) {
  3724. case 'delete':
  3725. // delete = make item only visible for the platform admin.
  3726. $visibility = '2';
  3727. if (!empty($session_id)) {
  3728. // Check whether session id already exist into item_properties for updating visibility or add it.
  3729. $sql = "SELECT session_id FROM $tableItemProperty
  3730. WHERE
  3731. c_id = $course_id AND
  3732. tool = '$tool' AND
  3733. ref = $item_id AND
  3734. session_id = $session_id";
  3735. $rs = Database::query($sql);
  3736. if (Database::num_rows($rs) > 0) {
  3737. $sql = "UPDATE $tableItemProperty
  3738. SET lastedit_type = '".str_replace('_', '', ucwords($tool))."Deleted',
  3739. lastedit_date = '$time',
  3740. lastedit_user_id = $user_id,
  3741. visibility = $visibility,
  3742. session_id = $session_id $set_type
  3743. WHERE $filter";
  3744. $result = Database::query($sql);
  3745. } else {
  3746. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
  3747. VALUES ($course_id, '$tool',$item_id, '$time', $user_id, '$time', '$last_edit_type',$user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3748. $result = Database::query($sql);
  3749. $id = Database::insert_id();
  3750. if ($id) {
  3751. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3752. Database::query($sql);
  3753. }
  3754. }
  3755. } else {
  3756. $sql = "UPDATE $tableItemProperty
  3757. SET
  3758. lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted',
  3759. lastedit_date='$time',
  3760. lastedit_user_id = $user_id,
  3761. visibility = $visibility $set_type
  3762. WHERE $filter";
  3763. $result = Database::query($sql);
  3764. }
  3765. break;
  3766. case 'visible': // Change item to visible.
  3767. $visibility = '1';
  3768. if (!empty($session_id)) {
  3769. // Check whether session id already exist into item_properties for updating visibility or add it.
  3770. $sql = "SELECT session_id FROM $tableItemProperty
  3771. WHERE
  3772. c_id = $course_id AND
  3773. tool = '$tool' AND
  3774. ref = $item_id AND
  3775. session_id = $session_id";
  3776. $rs = Database::query($sql);
  3777. if (Database::num_rows($rs) > 0) {
  3778. $sql = "UPDATE $tableItemProperty
  3779. SET
  3780. lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
  3781. lastedit_date='$time',
  3782. lastedit_user_id = $user_id,
  3783. visibility = $visibility,
  3784. session_id = $session_id $set_type
  3785. WHERE $filter";
  3786. $result = Database::query($sql);
  3787. } else {
  3788. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
  3789. VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3790. $result = Database::query($sql);
  3791. $id = Database::insert_id();
  3792. if ($id) {
  3793. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3794. Database::query($sql);
  3795. }
  3796. }
  3797. } else {
  3798. $sql = "UPDATE $tableItemProperty
  3799. SET
  3800. lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
  3801. lastedit_date='$time',
  3802. lastedit_user_id = $user_id,
  3803. visibility = $visibility $set_type
  3804. WHERE $filter";
  3805. $result = Database::query($sql);
  3806. }
  3807. break;
  3808. case 'invisible': // Change item to invisible.
  3809. $visibility = '0';
  3810. if (!empty($session_id)) {
  3811. // Check whether session id already exist into item_properties for updating visibility or add it
  3812. $sql = "SELECT session_id FROM $tableItemProperty
  3813. WHERE
  3814. c_id = $course_id AND
  3815. tool = '$tool' AND
  3816. ref = $item_id AND
  3817. session_id = $session_id";
  3818. $rs = Database::query($sql);
  3819. if (Database::num_rows($rs) > 0) {
  3820. $sql = "UPDATE $tableItemProperty
  3821. SET
  3822. lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
  3823. lastedit_date = '$time',
  3824. lastedit_user_id = $user_id,
  3825. visibility = $visibility,
  3826. session_id = $session_id $set_type
  3827. WHERE $filter";
  3828. $result = Database::query($sql);
  3829. } else {
  3830. $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id)
  3831. VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
  3832. $result = Database::query($sql);
  3833. $id = Database::insert_id();
  3834. if ($id) {
  3835. $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
  3836. Database::query($sql);
  3837. }
  3838. }
  3839. } else {
  3840. $sql = "UPDATE $tableItemProperty
  3841. SET
  3842. lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
  3843. lastedit_date = '$time',
  3844. lastedit_user_id = $user_id,
  3845. visibility = $visibility $set_type
  3846. WHERE $filter";
  3847. $result = Database::query($sql);
  3848. }
  3849. break;
  3850. default: // The item will be added or updated.
  3851. $set_type = ", lastedit_type = '$last_edit_type' ";
  3852. $visibility = '1';
  3853. //$filter .= $to_filter; already added
  3854. $sql = "UPDATE $tableItemProperty
  3855. SET
  3856. lastedit_date = '$time',
  3857. lastedit_user_id = $user_id $set_type
  3858. WHERE $filter";
  3859. $result = Database::query($sql);
  3860. }
  3861. // Insert if no entries are found (can only happen in case of $last_edit_type switch is 'default').
  3862. if ($result == false || Database::affected_rows($result) == 0) {
  3863. $objCourse = $em->find('ChamiloCoreBundle:Course', intval($course_id));
  3864. $objTime = new DateTime('now', new DateTimeZone('UTC'));
  3865. $objUser = api_get_user_entity($user_id);
  3866. if (empty($objUser)) {
  3867. // Use anonymous
  3868. $user_id = api_get_anonymous_id();
  3869. $objUser = api_get_user_entity($user_id);
  3870. }
  3871. $objGroup = null;
  3872. if (!empty($to_group_id)) {
  3873. $objGroup = $em->find('ChamiloCourseBundle:CGroupInfo', $to_group_id);
  3874. }
  3875. $objToUser = api_get_user_entity($to_user_id);
  3876. $objSession = $em->find('ChamiloCoreBundle:Session', intval($session_id));
  3877. $startVisibleDate = !empty($start_visible) ? new DateTime($start_visible, new DateTimeZone('UTC')) : null;
  3878. $endVisibleDate = !empty($endVisibleDate) ? new DateTime($endVisibleDate, new DateTimeZone('UTC')) : null;
  3879. $cItemProperty = new CItemProperty($objCourse);
  3880. $cItemProperty
  3881. ->setTool($tool)
  3882. ->setRef($item_id)
  3883. ->setInsertDate($objTime)
  3884. ->setInsertUser($objUser)
  3885. ->setLasteditDate($objTime)
  3886. ->setLasteditType($last_edit_type)
  3887. ->setGroup($objGroup)
  3888. ->setToUser($objToUser)
  3889. ->setVisibility($visibility)
  3890. ->setStartVisible($startVisibleDate)
  3891. ->setEndVisible($endVisibleDate)
  3892. ->setSession($objSession);
  3893. $em->persist($cItemProperty);
  3894. $em->flush();
  3895. $id = $cItemProperty->getIid();
  3896. if ($id) {
  3897. $cItemProperty->setId($id);
  3898. $em->merge($cItemProperty);
  3899. $em->flush();
  3900. return false;
  3901. }
  3902. }
  3903. return true;
  3904. }
  3905. /**
  3906. * Gets item property by tool.
  3907. *
  3908. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3909. * @param string $course_code
  3910. * @param int $session_id
  3911. *
  3912. * @return array All fields from c_item_property (all rows found) or empty array
  3913. */
  3914. function api_get_item_property_by_tool($tool, $course_code, $session_id = null)
  3915. {
  3916. $course_info = api_get_course_info($course_code);
  3917. $tool = Database::escape_string($tool);
  3918. // Definition of tables.
  3919. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3920. $session_id = (int) $session_id;
  3921. $session_condition = ' AND session_id = '.$session_id;
  3922. if (empty($session_id)) {
  3923. $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
  3924. }
  3925. $course_id = $course_info['real_id'];
  3926. $sql = "SELECT * FROM $item_property_table
  3927. WHERE
  3928. c_id = $course_id AND
  3929. tool = '$tool'
  3930. $session_condition ";
  3931. $rs = Database::query($sql);
  3932. $list = [];
  3933. if (Database::num_rows($rs) > 0) {
  3934. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3935. $list[] = $row;
  3936. }
  3937. }
  3938. return $list;
  3939. }
  3940. /**
  3941. * Gets item property by tool and user.
  3942. *
  3943. * @param int $userId
  3944. * @param int $tool
  3945. * @param int $courseId
  3946. * @param int $session_id
  3947. *
  3948. * @return array
  3949. */
  3950. function api_get_item_property_list_by_tool_by_user(
  3951. $userId,
  3952. $tool,
  3953. $courseId,
  3954. $session_id = 0
  3955. ) {
  3956. $userId = intval($userId);
  3957. $tool = Database::escape_string($tool);
  3958. $session_id = intval($session_id);
  3959. $courseId = intval($courseId);
  3960. // Definition of tables.
  3961. $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3962. $session_condition = ' AND session_id = '.$session_id;
  3963. if (empty($session_id)) {
  3964. $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
  3965. }
  3966. $sql = "SELECT * FROM $item_property_table
  3967. WHERE
  3968. insert_user_id = $userId AND
  3969. c_id = $courseId AND
  3970. tool = '$tool'
  3971. $session_condition ";
  3972. $rs = Database::query($sql);
  3973. $list = [];
  3974. if (Database::num_rows($rs) > 0) {
  3975. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  3976. $list[] = $row;
  3977. }
  3978. }
  3979. return $list;
  3980. }
  3981. /**
  3982. * Gets item property id from tool of a course.
  3983. *
  3984. * @param string $course_code course code
  3985. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  3986. * @param int $ref id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  3987. * @param int $sessionId Session ID (optional)
  3988. *
  3989. * @return int
  3990. */
  3991. function api_get_item_property_id($course_code, $tool, $ref, $sessionId = 0)
  3992. {
  3993. $course_info = api_get_course_info($course_code);
  3994. $tool = Database::escape_string($tool);
  3995. $ref = (int) $ref;
  3996. // Definition of tables.
  3997. $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3998. $course_id = $course_info['real_id'];
  3999. $sessionId = (int) $sessionId;
  4000. $sessionCondition = " AND session_id = $sessionId ";
  4001. if (empty($sessionId)) {
  4002. $sessionCondition = ' AND (session_id = 0 OR session_id IS NULL) ';
  4003. }
  4004. $sql = "SELECT id FROM $tableItemProperty
  4005. WHERE
  4006. c_id = $course_id AND
  4007. tool = '$tool' AND
  4008. ref = $ref
  4009. $sessionCondition";
  4010. $rs = Database::query($sql);
  4011. $item_property_id = '';
  4012. if (Database::num_rows($rs) > 0) {
  4013. $row = Database::fetch_array($rs);
  4014. $item_property_id = $row['id'];
  4015. }
  4016. return $item_property_id;
  4017. }
  4018. /**
  4019. * Inserts a record in the track_e_item_property table (No update).
  4020. *
  4021. * @param string $tool
  4022. * @param int $ref
  4023. * @param string $title
  4024. * @param string $content
  4025. * @param int $progress
  4026. *
  4027. * @return bool|int
  4028. */
  4029. function api_track_item_property_update($tool, $ref, $title, $content, $progress)
  4030. {
  4031. $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  4032. $course_id = api_get_course_int_id(); //numeric
  4033. $course_code = api_get_course_id(); //alphanumeric
  4034. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  4035. if (!empty($item_property_id)) {
  4036. $sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
  4037. course_id = '$course_id',
  4038. item_property_id = '$item_property_id',
  4039. title = '".Database::escape_string($title)."',
  4040. content = '".Database::escape_string($content)."',
  4041. progress = '".intval($progress)."',
  4042. lastedit_date = '".api_get_utc_datetime()."',
  4043. lastedit_user_id = '".api_get_user_id()."',
  4044. session_id = '".api_get_session_id()."'";
  4045. $result = Database::query($sql);
  4046. $affected_rows = Database::affected_rows($result);
  4047. return $affected_rows;
  4048. }
  4049. return false;
  4050. }
  4051. /**
  4052. * @param string $tool
  4053. * @param int $ref
  4054. *
  4055. * @return array|resource
  4056. */
  4057. function api_get_track_item_property_history($tool, $ref)
  4058. {
  4059. $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
  4060. $course_id = api_get_course_int_id(); //numeric
  4061. $course_code = api_get_course_id(); //alphanumeric
  4062. $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
  4063. $sql = "SELECT * FROM $tbl_stats_item_property
  4064. WHERE item_property_id = $item_property_id AND course_id = $course_id
  4065. ORDER BY lastedit_date DESC";
  4066. $result = Database::query($sql);
  4067. if ($result === false or $result === null) {
  4068. $result = [];
  4069. } else {
  4070. $result = Database::store_result($result, 'ASSOC');
  4071. }
  4072. return $result;
  4073. }
  4074. /**
  4075. * Gets item property data from tool of a course id.
  4076. *
  4077. * @param int $course_id
  4078. * @param string $tool tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
  4079. * @param int $ref id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
  4080. * @param int $session_id
  4081. * @param int $groupId
  4082. *
  4083. * @return array with all fields from c_item_property, empty array if not found or false if course could not be found
  4084. */
  4085. function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0, $groupId = 0)
  4086. {
  4087. $courseInfo = api_get_course_info_by_id($course_id);
  4088. if (empty($courseInfo)) {
  4089. return false;
  4090. }
  4091. $tool = Database::escape_string($tool);
  4092. $course_id = $courseInfo['real_id'];
  4093. $ref = (int) $ref;
  4094. $session_id = (int) $session_id;
  4095. $sessionCondition = " session_id = $session_id";
  4096. if (empty($session_id)) {
  4097. $sessionCondition = ' (session_id = 0 OR session_id IS NULL) ';
  4098. }
  4099. // Definition of tables.
  4100. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  4101. $sql = "SELECT * FROM $table
  4102. WHERE
  4103. c_id = $course_id AND
  4104. tool = '$tool' AND
  4105. ref = $ref AND
  4106. $sessionCondition ";
  4107. if (!empty($groupId)) {
  4108. $groupId = (int) $groupId;
  4109. $sql .= " AND to_group_id = $groupId ";
  4110. }
  4111. $rs = Database::query($sql);
  4112. $row = [];
  4113. if (Database::num_rows($rs) > 0) {
  4114. $row = Database::fetch_array($rs, 'ASSOC');
  4115. }
  4116. return $row;
  4117. }
  4118. /**
  4119. * Displays a combo box so the user can select his/her preferred language.
  4120. *
  4121. * @param string The desired name= value for the select
  4122. * @param bool Whether we use the JQuery Chozen library or not
  4123. * (in some cases, like the indexing language picker, it can alter the presentation)
  4124. *
  4125. * @return string
  4126. */
  4127. function api_get_languages_combo($name = 'language')
  4128. {
  4129. $ret = '';
  4130. $platformLanguage = api_get_setting('platformLanguage');
  4131. // Retrieve a complete list of all the languages.
  4132. $language_list = api_get_languages();
  4133. if (count($language_list['name']) < 2) {
  4134. return $ret;
  4135. }
  4136. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  4137. if (isset($_SESSION['user_language_choice'])) {
  4138. $default = $_SESSION['user_language_choice'];
  4139. } else {
  4140. $default = $platformLanguage;
  4141. }
  4142. $languages = $language_list['name'];
  4143. $folder = $language_list['folder'];
  4144. $ret .= '<select name="'.$name.'" id="language_chosen" class="selectpicker form-control">';
  4145. foreach ($languages as $key => $value) {
  4146. if ($folder[$key] == $default) {
  4147. $selected = ' selected="selected"';
  4148. } else {
  4149. $selected = '';
  4150. }
  4151. $ret .= sprintf('<option value=%s" %s>%s</option>', $folder[$key], $selected, $value);
  4152. }
  4153. $ret .= '</select>';
  4154. return $ret;
  4155. }
  4156. /**
  4157. * Displays a form (drop down menu) so the user can select his/her preferred language.
  4158. * The form works with or without javascript.
  4159. *
  4160. * @param bool Hide form if only one language available (defaults to false = show the box anyway)
  4161. * @param bool $showAsButton
  4162. *
  4163. * @return string|null Display the box directly
  4164. */
  4165. function api_display_language_form($hide_if_no_choice = false, $showAsButton = false)
  4166. {
  4167. // Retrieve a complete list of all the languages.
  4168. $language_list = api_get_languages();
  4169. if (count($language_list['name']) <= 1 && $hide_if_no_choice) {
  4170. return; //don't show any form
  4171. }
  4172. // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
  4173. if (isset($_SESSION['user_language_choice'])) {
  4174. $user_selected_language = $_SESSION['user_language_choice'];
  4175. }
  4176. if (empty($user_selected_language)) {
  4177. $user_selected_language = api_get_setting('platformLanguage');
  4178. }
  4179. $currentLanguageId = api_get_language_id($user_selected_language);
  4180. $currentLanguageInfo = api_get_language_info($currentLanguageId);
  4181. $countryCode = languageToCountryIsoCode($currentLanguageInfo['isocode']);
  4182. $url = api_get_self();
  4183. if ($showAsButton) {
  4184. $html = '<div class="btn-group">
  4185. <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
  4186. <span class="flag-icon flag-icon-'.$countryCode.'"></span>
  4187. '.$currentLanguageInfo['original_name'].'
  4188. <span class="caret">
  4189. </span>
  4190. </button>';
  4191. } else {
  4192. $html = '
  4193. <a href="'.$url.'" class="dropdown-toggle" data-toggle="dropdown" role="button">
  4194. <span class="flag-icon flag-icon-'.$countryCode.'"></span>
  4195. '.$currentLanguageInfo['original_name'].'
  4196. <span class="caret"></span>
  4197. </a>
  4198. ';
  4199. }
  4200. $html .= '<ul class="dropdown-menu" role="menu">';
  4201. foreach ($language_list['all'] as $key => $data) {
  4202. $urlLink = $url.'?language='.$data['english_name'];
  4203. $html .= '<li><a href="'.$urlLink.'"><span class="flag-icon flag-icon-'.languageToCountryIsoCode($data['isocode']).'"></span> '.$data['original_name'].'</a></li>';
  4204. }
  4205. $html .= '</ul>';
  4206. if ($showAsButton) {
  4207. $html .= '</div>';
  4208. }
  4209. return $html;
  4210. }
  4211. /**
  4212. * @param string $languageIsoCode
  4213. *
  4214. * @return string
  4215. */
  4216. function languageToCountryIsoCode($languageIsoCode)
  4217. {
  4218. $allow = api_get_configuration_value('language_flags_by_country');
  4219. // @todo save in DB
  4220. switch ($languageIsoCode) {
  4221. case 'ko':
  4222. $country = 'kr';
  4223. break;
  4224. case 'ja':
  4225. $country = 'jp';
  4226. break;
  4227. case 'ca':
  4228. $country = 'es';
  4229. if ($allow) {
  4230. $country = 'catalan';
  4231. }
  4232. break;
  4233. case 'gl': // galego
  4234. $country = 'es';
  4235. if ($allow) {
  4236. $country = 'galician';
  4237. }
  4238. break;
  4239. case 'ka':
  4240. $country = 'ge';
  4241. break;
  4242. case 'sl':
  4243. $country = 'si';
  4244. break;
  4245. case 'eu': // Euskera
  4246. $country = 'es';
  4247. if ($allow) {
  4248. $country = 'basque';
  4249. }
  4250. break;
  4251. case 'cs':
  4252. $country = 'cz';
  4253. break;
  4254. case 'el':
  4255. $country = 'ae';
  4256. break;
  4257. case 'ar':
  4258. $country = 'ae';
  4259. break;
  4260. case 'en':
  4261. $country = 'gb';
  4262. break;
  4263. case 'he':
  4264. $country = 'il';
  4265. break;
  4266. case 'uk': // Ukraine
  4267. $country = 'ua';
  4268. break;
  4269. case 'da':
  4270. $country = 'dk';
  4271. break;
  4272. case 'pt-BR':
  4273. $country = 'br';
  4274. break;
  4275. case 'qu':
  4276. $country = 'pe';
  4277. break;
  4278. case 'sv':
  4279. $country = 'se';
  4280. break;
  4281. case 'zh-TW':
  4282. case 'zh':
  4283. $country = 'cn';
  4284. break;
  4285. default:
  4286. $country = $languageIsoCode;
  4287. break;
  4288. }
  4289. $country = strtolower($country);
  4290. return $country;
  4291. }
  4292. /**
  4293. * Returns a list of all the languages that are made available by the admin.
  4294. *
  4295. * @return array An array with all languages. Structure of the array is
  4296. * array['name'] = An array with the name of every language
  4297. * array['folder'] = An array with the corresponding names of the language-folders in the filesystem
  4298. */
  4299. function api_get_languages()
  4300. {
  4301. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  4302. $sql = "SELECT * FROM $tbl_language WHERE available='1'
  4303. ORDER BY original_name ASC";
  4304. $result = Database::query($sql);
  4305. $language_list = [];
  4306. while ($row = Database::fetch_array($result)) {
  4307. $language_list['name'][] = $row['original_name'];
  4308. $language_list['folder'][] = $row['dokeos_folder'];
  4309. $language_list['all'][] = $row;
  4310. }
  4311. return $language_list;
  4312. }
  4313. /**
  4314. * Returns a list of all the languages that are made available by the admin.
  4315. *
  4316. * @return array
  4317. */
  4318. function api_get_languages_to_array()
  4319. {
  4320. $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  4321. $sql = "SELECT * FROM $tbl_language WHERE available='1' ORDER BY original_name ASC";
  4322. $result = Database::query($sql);
  4323. $languages = [];
  4324. while ($row = Database::fetch_array($result)) {
  4325. $languages[$row['dokeos_folder']] = $row['original_name'];
  4326. }
  4327. return $languages;
  4328. }
  4329. /**
  4330. * Returns the id (the database id) of a language.
  4331. *
  4332. * @param string language name (the corresponding name of the language-folder in the filesystem)
  4333. *
  4334. * @return int id of the language
  4335. */
  4336. function api_get_language_id($language)
  4337. {
  4338. if (empty($language)) {
  4339. return null;
  4340. }
  4341. static $staticResult;
  4342. if (isset($staticResult[$language])) {
  4343. return $staticResult[$language];
  4344. } else {
  4345. $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  4346. $language = Database::escape_string($language);
  4347. $sql = "SELECT id FROM $table
  4348. WHERE dokeos_folder = '$language' LIMIT 1";
  4349. $result = Database::query($sql);
  4350. $row = Database::fetch_array($result);
  4351. $staticResult[$language] = $row['id'];
  4352. return $row['id'];
  4353. }
  4354. }
  4355. /**
  4356. * Gets language of the requested type for the current user. Types are :
  4357. * user_profil_lang : profile language of current user
  4358. * user_select_lang : language selected by user at login
  4359. * course_lang : language of the current course
  4360. * platform_lang : default platform language.
  4361. *
  4362. * @param string $lang_type
  4363. *
  4364. * @return string
  4365. */
  4366. function api_get_language_from_type($lang_type)
  4367. {
  4368. $return = false;
  4369. switch ($lang_type) {
  4370. case 'platform_lang':
  4371. $temp_lang = api_get_setting('platformLanguage');
  4372. if (!empty($temp_lang)) {
  4373. $return = $temp_lang;
  4374. }
  4375. break;
  4376. case 'user_profil_lang':
  4377. $_user = api_get_user_info();
  4378. if (isset($_user['language']) && !empty($_user['language'])) {
  4379. $return = $_user['language'];
  4380. }
  4381. break;
  4382. case 'user_selected_lang':
  4383. if (isset($_SESSION['user_language_choice']) && !empty($_SESSION['user_language_choice'])) {
  4384. $return = $_SESSION['user_language_choice'];
  4385. }
  4386. break;
  4387. case 'course_lang':
  4388. global $_course;
  4389. $cidReq = null;
  4390. if (empty($_course)) {
  4391. // Code modified because the local.inc.php file it's declarated after this work
  4392. // causing the function api_get_course_info() returns a null value
  4393. $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : null;
  4394. $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
  4395. if (empty($cidReq) && !empty($cDir)) {
  4396. $c = CourseManager::getCourseCodeFromDirectory($cDir);
  4397. if ($c) {
  4398. $cidReq = $c;
  4399. }
  4400. }
  4401. }
  4402. $_course = api_get_course_info($cidReq);
  4403. if (isset($_course['language']) && !empty($_course['language'])) {
  4404. $return = $_course['language'];
  4405. $showCourseInUserLanguage = api_get_course_setting('show_course_in_user_language');
  4406. if ($showCourseInUserLanguage == 1) {
  4407. $userInfo = api_get_user_info();
  4408. if (isset($userInfo['language'])) {
  4409. $return = $userInfo['language'];
  4410. }
  4411. }
  4412. }
  4413. break;
  4414. default:
  4415. $return = false;
  4416. break;
  4417. }
  4418. return $return;
  4419. }
  4420. /**
  4421. * Get the language information by its id.
  4422. *
  4423. * @param int $languageId
  4424. *
  4425. * @throws Exception
  4426. *
  4427. * @return array
  4428. */
  4429. function api_get_language_info($languageId)
  4430. {
  4431. if (empty($languageId)) {
  4432. return [];
  4433. }
  4434. $language = Database::getManager()
  4435. ->find('ChamiloCoreBundle:Language', $languageId);
  4436. if (!$language) {
  4437. return [];
  4438. }
  4439. return [
  4440. 'id' => $language->getId(),
  4441. 'original_name' => $language->getOriginalName(),
  4442. 'english_name' => $language->getEnglishName(),
  4443. 'isocode' => $language->getIsocode(),
  4444. 'dokeos_folder' => $language->getDokeosFolder(),
  4445. 'available' => $language->getAvailable(),
  4446. 'parent_id' => $language->getParent() ? $language->getParent()->getId() : null,
  4447. ];
  4448. }
  4449. /**
  4450. * Returns the name of the visual (CSS) theme to be applied on the current page.
  4451. * The returned name depends on the platform, course or user -wide settings.
  4452. *
  4453. * @return string The visual theme's name, it is the name of a folder inside web/css/themes
  4454. */
  4455. function api_get_visual_theme()
  4456. {
  4457. static $visual_theme;
  4458. if (!isset($visual_theme)) {
  4459. // Get style directly from DB
  4460. $styleFromDatabase = api_get_settings_params_simple(
  4461. [
  4462. 'variable = ? AND access_url = ?' => [
  4463. 'stylesheets',
  4464. api_get_current_access_url_id(),
  4465. ],
  4466. ]
  4467. );
  4468. if ($styleFromDatabase) {
  4469. $platform_theme = $styleFromDatabase['selected_value'];
  4470. } else {
  4471. $platform_theme = api_get_setting('stylesheets');
  4472. }
  4473. // Platform's theme.
  4474. $visual_theme = $platform_theme;
  4475. if (api_get_setting('user_selected_theme') == 'true') {
  4476. $user_info = api_get_user_info();
  4477. if (isset($user_info['theme'])) {
  4478. $user_theme = $user_info['theme'];
  4479. if (!empty($user_theme)) {
  4480. $visual_theme = $user_theme;
  4481. // User's theme.
  4482. }
  4483. }
  4484. }
  4485. $course_id = api_get_course_id();
  4486. if (!empty($course_id)) {
  4487. if (api_get_setting('allow_course_theme') == 'true') {
  4488. $course_theme = api_get_course_setting('course_theme', api_get_course_info());
  4489. if (!empty($course_theme) && $course_theme != -1) {
  4490. if (!empty($course_theme)) {
  4491. // Course's theme.
  4492. $visual_theme = $course_theme;
  4493. }
  4494. }
  4495. $allow_lp_theme = api_get_course_setting('allow_learning_path_theme');
  4496. if ($allow_lp_theme == 1) {
  4497. global $lp_theme_css, $lp_theme_config;
  4498. // These variables come from the file lp_controller.php.
  4499. if (!$lp_theme_config) {
  4500. if (!empty($lp_theme_css)) {
  4501. // LP's theme.
  4502. $visual_theme = $lp_theme_css;
  4503. }
  4504. }
  4505. }
  4506. }
  4507. }
  4508. if (empty($visual_theme)) {
  4509. $visual_theme = 'chamilo';
  4510. }
  4511. global $lp_theme_log;
  4512. if ($lp_theme_log) {
  4513. $visual_theme = $platform_theme;
  4514. }
  4515. }
  4516. return $visual_theme;
  4517. }
  4518. /**
  4519. * Returns a list of CSS themes currently available in the CSS folder
  4520. * The folder must have a default.css file.
  4521. *
  4522. * @param bool $getOnlyThemeFromVirtualInstance Used by the vchamilo plugin
  4523. *
  4524. * @return array list of themes directories from the css folder
  4525. * Note: Directory names (names of themes) in the file system should contain ASCII-characters only
  4526. */
  4527. function api_get_themes($getOnlyThemeFromVirtualInstance = false)
  4528. {
  4529. // This configuration value is set by the vchamilo plugin
  4530. $virtualTheme = api_get_configuration_value('virtual_css_theme_folder');
  4531. $readCssFolder = function ($dir) use ($virtualTheme) {
  4532. $finder = new Finder();
  4533. $themes = $finder->directories()->in($dir)->depth(0)->sortByName();
  4534. $list = [];
  4535. /** @var Symfony\Component\Finder\SplFileInfo $theme */
  4536. foreach ($themes as $theme) {
  4537. $folder = $theme->getFilename();
  4538. // A theme folder is consider if there's a default.css file
  4539. if (!file_exists($theme->getPathname().'/default.css')) {
  4540. continue;
  4541. }
  4542. $name = ucwords(str_replace('_', ' ', $folder));
  4543. if ($folder == $virtualTheme) {
  4544. continue;
  4545. }
  4546. $list[$folder] = $name;
  4547. }
  4548. return $list;
  4549. };
  4550. $dir = api_get_path(SYS_CSS_PATH).'themes/';
  4551. $list = $readCssFolder($dir);
  4552. if (!empty($virtualTheme)) {
  4553. $newList = $readCssFolder($dir.'/'.$virtualTheme);
  4554. if ($getOnlyThemeFromVirtualInstance) {
  4555. return $newList;
  4556. }
  4557. $list = $list + $newList;
  4558. asort($list);
  4559. }
  4560. return $list;
  4561. }
  4562. /**
  4563. * Find the largest sort value in a given user_course_category
  4564. * This function is used when we are moving a course to a different category
  4565. * and also when a user subscribes to courses (the new course is added at the end of the main category.
  4566. *
  4567. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  4568. *
  4569. * @param int $user_course_category the id of the user_course_category
  4570. * @param int $user_id
  4571. *
  4572. * @return int the value of the highest sort of the user_course_category
  4573. */
  4574. function api_max_sort_value($user_course_category, $user_id)
  4575. {
  4576. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4577. $sql = "SELECT max(sort) as max_sort FROM $tbl_course_user
  4578. WHERE
  4579. user_id='".intval($user_id)."' AND
  4580. relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
  4581. user_course_cat='".intval($user_course_category)."'";
  4582. $result_max = Database::query($sql);
  4583. if (Database::num_rows($result_max) == 1) {
  4584. $row_max = Database::fetch_array($result_max);
  4585. return $row_max['max_sort'];
  4586. }
  4587. return 0;
  4588. }
  4589. /**
  4590. * Transforms a number of seconds in hh:mm:ss format.
  4591. *
  4592. * @author Julian Prud'homme
  4593. *
  4594. * @param int $seconds number of seconds
  4595. * @param string $space
  4596. * @param bool $showSeconds
  4597. * @param bool $roundMinutes
  4598. *
  4599. * @return string the formatted time
  4600. */
  4601. function api_time_to_hms($seconds, $space = ':', $showSeconds = true, $roundMinutes = false)
  4602. {
  4603. // $seconds = -1 means that we have wrong data in the db.
  4604. if ($seconds == -1) {
  4605. return
  4606. get_lang('Unknown').
  4607. Display::return_icon(
  4608. 'info2.gif',
  4609. get_lang('WrongDatasForTimeSpentOnThePlatform'),
  4610. ['align' => 'absmiddle', 'hspace' => '3px']
  4611. );
  4612. }
  4613. // How many hours ?
  4614. $hours = floor($seconds / 3600);
  4615. // How many minutes ?
  4616. $min = floor(($seconds - ($hours * 3600)) / 60);
  4617. if ($roundMinutes) {
  4618. if ($min >= 45) {
  4619. $min = 45;
  4620. }
  4621. if ($min >= 30 && $min <= 44) {
  4622. $min = 30;
  4623. }
  4624. if ($min >= 15 && $min <= 29) {
  4625. $min = 15;
  4626. }
  4627. if ($min >= 0 && $min <= 14) {
  4628. $min = 0;
  4629. }
  4630. }
  4631. // How many seconds
  4632. $sec = floor($seconds - ($hours * 3600) - ($min * 60));
  4633. if ($hours < 10) {
  4634. $hours = "0$hours";
  4635. }
  4636. if ($sec < 10) {
  4637. $sec = "0$sec";
  4638. }
  4639. if ($min < 10) {
  4640. $min = "0$min";
  4641. }
  4642. $seconds = '';
  4643. if ($showSeconds) {
  4644. $seconds = $space.$sec;
  4645. }
  4646. return $hours.$space.$min.$seconds;
  4647. }
  4648. /* FILE SYSTEM RELATED FUNCTIONS */
  4649. /**
  4650. * Returns the permissions to be assigned to every newly created directory by the web-server.
  4651. * The return value is based on the platform administrator's setting
  4652. * "Administration > Configuration settings > Security > Permissions for new directories".
  4653. *
  4654. * @return int returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value
  4655. */
  4656. function api_get_permissions_for_new_directories()
  4657. {
  4658. static $permissions;
  4659. if (!isset($permissions)) {
  4660. $permissions = trim(api_get_setting('permissions_for_new_directories'));
  4661. // The default value 0777 is according to that in the platform administration panel after fresh system installation.
  4662. $permissions = octdec(!empty($permissions) ? $permissions : '0777');
  4663. }
  4664. return $permissions;
  4665. }
  4666. /**
  4667. * Returns the permissions to be assigned to every newly created directory by the web-server.
  4668. * The return value is based on the platform administrator's setting
  4669. * "Administration > Configuration settings > Security > Permissions for new files".
  4670. *
  4671. * @return int returns the permissions in the format
  4672. * "Owner-Group-Others, Read-Write-Execute", as an integer value
  4673. */
  4674. function api_get_permissions_for_new_files()
  4675. {
  4676. static $permissions;
  4677. if (!isset($permissions)) {
  4678. $permissions = trim(api_get_setting('permissions_for_new_files'));
  4679. // The default value 0666 is according to that in the platform
  4680. // administration panel after fresh system installation.
  4681. $permissions = octdec(!empty($permissions) ? $permissions : '0666');
  4682. }
  4683. return $permissions;
  4684. }
  4685. /**
  4686. * Deletes a file, or a folder and its contents.
  4687. *
  4688. * @author Aidan Lister <aidan@php.net>
  4689. *
  4690. * @version 1.0.3
  4691. *
  4692. * @param string $dirname Directory to delete
  4693. * @param bool Deletes only the content or not
  4694. * @param bool $strict if one folder/file fails stop the loop
  4695. *
  4696. * @return bool Returns TRUE on success, FALSE on failure
  4697. *
  4698. * @see http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
  4699. *
  4700. * @author Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
  4701. * @author Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
  4702. */
  4703. function rmdirr($dirname, $delete_only_content_in_folder = false, $strict = false)
  4704. {
  4705. $res = true;
  4706. // A sanity check.
  4707. if (!file_exists($dirname)) {
  4708. return false;
  4709. }
  4710. $php_errormsg = '';
  4711. // Simple delete for a file.
  4712. if (is_file($dirname) || is_link($dirname)) {
  4713. $res = unlink($dirname);
  4714. if ($res === false) {
  4715. 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);
  4716. }
  4717. return $res;
  4718. }
  4719. // Loop through the folder.
  4720. $dir = dir($dirname);
  4721. // A sanity check.
  4722. $is_object_dir = is_object($dir);
  4723. if ($is_object_dir) {
  4724. while (false !== $entry = $dir->read()) {
  4725. // Skip pointers.
  4726. if ($entry == '.' || $entry == '..') {
  4727. continue;
  4728. }
  4729. // Recurse.
  4730. if ($strict) {
  4731. $result = rmdirr("$dirname/$entry");
  4732. if ($result == false) {
  4733. $res = false;
  4734. break;
  4735. }
  4736. } else {
  4737. rmdirr("$dirname/$entry");
  4738. }
  4739. }
  4740. }
  4741. // Clean up.
  4742. if ($is_object_dir) {
  4743. $dir->close();
  4744. }
  4745. if ($delete_only_content_in_folder == false) {
  4746. $res = rmdir($dirname);
  4747. if ($res === false) {
  4748. 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);
  4749. }
  4750. }
  4751. return $res;
  4752. }
  4753. // TODO: This function is to be simplified. File access modes to be implemented.
  4754. /**
  4755. * function adapted from a php.net comment
  4756. * copy recursively a folder.
  4757. *
  4758. * @param the source folder
  4759. * @param the dest folder
  4760. * @param an array of excluded file_name (without extension)
  4761. * @param copied_files the returned array of copied files
  4762. * @param string $source
  4763. * @param string $dest
  4764. */
  4765. function copyr($source, $dest, $exclude = [], $copied_files = [])
  4766. {
  4767. if (empty($dest)) {
  4768. return false;
  4769. }
  4770. // Simple copy for a file
  4771. if (is_file($source)) {
  4772. $path_info = pathinfo($source);
  4773. if (!in_array($path_info['filename'], $exclude)) {
  4774. copy($source, $dest);
  4775. }
  4776. return true;
  4777. } elseif (!is_dir($source)) {
  4778. //then source is not a dir nor a file, return
  4779. return false;
  4780. }
  4781. // Make destination directory.
  4782. if (!is_dir($dest)) {
  4783. mkdir($dest, api_get_permissions_for_new_directories());
  4784. }
  4785. // Loop through the folder.
  4786. $dir = dir($source);
  4787. while (false !== $entry = $dir->read()) {
  4788. // Skip pointers
  4789. if ($entry == '.' || $entry == '..') {
  4790. continue;
  4791. }
  4792. // Deep copy directories.
  4793. if ($dest !== "$source/$entry") {
  4794. $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
  4795. }
  4796. }
  4797. // Clean up.
  4798. $dir->close();
  4799. return true;
  4800. }
  4801. /**
  4802. * @todo: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach.
  4803. * Documentation header to be added here.
  4804. *
  4805. * @param string $pathname
  4806. * @param string $base_path_document
  4807. * @param int $session_id
  4808. *
  4809. * @return mixed True if directory already exists, false if a file already exists at
  4810. * the destination and null if everything goes according to plan
  4811. */
  4812. function copy_folder_course_session(
  4813. $pathname,
  4814. $base_path_document,
  4815. $session_id,
  4816. $course_info,
  4817. $document,
  4818. $source_course_id
  4819. ) {
  4820. $table = Database::get_course_table(TABLE_DOCUMENT);
  4821. $session_id = intval($session_id);
  4822. $source_course_id = intval($source_course_id);
  4823. // Check whether directory already exists.
  4824. if (is_dir($pathname) || empty($pathname)) {
  4825. return true;
  4826. }
  4827. // Ensure that a file with the same name does not already exist.
  4828. if (is_file($pathname)) {
  4829. trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
  4830. return false;
  4831. }
  4832. $course_id = $course_info['real_id'];
  4833. $folders = explode(DIRECTORY_SEPARATOR, str_replace($base_path_document.DIRECTORY_SEPARATOR, '', $pathname));
  4834. $new_pathname = $base_path_document;
  4835. $path = '';
  4836. foreach ($folders as $folder) {
  4837. $new_pathname .= DIRECTORY_SEPARATOR.$folder;
  4838. $path .= DIRECTORY_SEPARATOR.$folder;
  4839. if (!file_exists($new_pathname)) {
  4840. $path = Database::escape_string($path);
  4841. $sql = "SELECT * FROM $table
  4842. WHERE
  4843. c_id = $source_course_id AND
  4844. path = '$path' AND
  4845. filetype = 'folder' AND
  4846. session_id = '$session_id'";
  4847. $rs1 = Database::query($sql);
  4848. $num_rows = Database::num_rows($rs1);
  4849. if ($num_rows == 0) {
  4850. mkdir($new_pathname, api_get_permissions_for_new_directories());
  4851. // Insert new folder with destination session_id.
  4852. $params = [
  4853. 'c_id' => $course_id,
  4854. 'path' => $path,
  4855. 'comment' => $document->comment,
  4856. 'title' => basename($new_pathname),
  4857. 'filetype' => 'folder',
  4858. 'size' => '0',
  4859. 'session_id' => $session_id,
  4860. ];
  4861. $document_id = Database::insert($table, $params);
  4862. if ($document_id) {
  4863. $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
  4864. Database::query($sql);
  4865. api_item_property_update(
  4866. $course_info,
  4867. TOOL_DOCUMENT,
  4868. $document_id,
  4869. 'FolderCreated',
  4870. api_get_user_id(),
  4871. 0,
  4872. 0,
  4873. null,
  4874. null,
  4875. $session_id
  4876. );
  4877. }
  4878. }
  4879. }
  4880. } // en foreach
  4881. }
  4882. // TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
  4883. /**
  4884. * @param string $path
  4885. */
  4886. function api_chmod_R($path, $filemode)
  4887. {
  4888. if (!is_dir($path)) {
  4889. return chmod($path, $filemode);
  4890. }
  4891. $handler = opendir($path);
  4892. while ($file = readdir($handler)) {
  4893. if ($file != '.' && $file != '..') {
  4894. $fullpath = "$path/$file";
  4895. if (!is_dir($fullpath)) {
  4896. if (!chmod($fullpath, $filemode)) {
  4897. return false;
  4898. }
  4899. } else {
  4900. if (!api_chmod_R($fullpath, $filemode)) {
  4901. return false;
  4902. }
  4903. }
  4904. }
  4905. }
  4906. closedir($handler);
  4907. return chmod($path, $filemode);
  4908. }
  4909. // TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
  4910. /**
  4911. * Parse info file format. (e.g: file.info).
  4912. *
  4913. * Files should use an ini-like format to specify values.
  4914. * White-space generally doesn't matter, except inside values.
  4915. * e.g.
  4916. *
  4917. * @verbatim
  4918. * key = value
  4919. * key = "value"
  4920. * key = 'value'
  4921. * key = "multi-line
  4922. *
  4923. * value"
  4924. * key = 'multi-line
  4925. *
  4926. * value'
  4927. * key
  4928. * =
  4929. * 'value'
  4930. * @endverbatim
  4931. *
  4932. * Arrays are created using a GET-like syntax:
  4933. *
  4934. * @verbatim
  4935. * key[] = "numeric array"
  4936. * key[index] = "associative array"
  4937. * key[index][] = "nested numeric array"
  4938. * key[index][index] = "nested associative array"
  4939. * @endverbatim
  4940. *
  4941. * PHP constants are substituted in, but only when used as the entire value:
  4942. *
  4943. * Comments should start with a semi-colon at the beginning of a line.
  4944. *
  4945. * This function is NOT for placing arbitrary module-specific settings. Use
  4946. * variable_get() and variable_set() for that.
  4947. *
  4948. * Information stored in the module.info file:
  4949. * - name: The real name of the module for display purposes.
  4950. * - description: A brief description of the module.
  4951. * - dependencies: An array of shortnames of other modules this module depends on.
  4952. * - package: The name of the package of modules this module belongs to.
  4953. *
  4954. * Example of .info file:
  4955. * <code>
  4956. * @verbatim
  4957. * name = Forum
  4958. * description = Enables threaded discussions about general topics.
  4959. * dependencies[] = taxonomy
  4960. * dependencies[] = comment
  4961. * package = Core - optional
  4962. * version = VERSION
  4963. * @endverbatim
  4964. * </code>
  4965. *
  4966. * @param string $filename
  4967. * The file we are parsing. Accepts file with relative or absolute path.
  4968. *
  4969. * @return
  4970. * The info array
  4971. */
  4972. function api_parse_info_file($filename)
  4973. {
  4974. $info = [];
  4975. if (!file_exists($filename)) {
  4976. return $info;
  4977. }
  4978. $data = file_get_contents($filename);
  4979. if (preg_match_all('
  4980. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  4981. ((?:
  4982. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  4983. \[[^\[\]]*\] # unless they are balanced and not nested
  4984. )+?)
  4985. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  4986. (?:
  4987. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  4988. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  4989. ([^\r\n]*?) # Non-quoted string
  4990. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  4991. @msx', $data, $matches, PREG_SET_ORDER)) {
  4992. $key = $value1 = $value2 = $value3 = '';
  4993. foreach ($matches as $match) {
  4994. // Fetch the key and value string.
  4995. $i = 0;
  4996. foreach (['key', 'value1', 'value2', 'value3'] as $var) {
  4997. $$var = isset($match[++$i]) ? $match[$i] : '';
  4998. }
  4999. $value = stripslashes(substr($value1, 1, -1)).stripslashes(substr($value2, 1, -1)).$value3;
  5000. // Parse array syntax.
  5001. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  5002. $last = array_pop($keys);
  5003. $parent = &$info;
  5004. // Create nested arrays.
  5005. foreach ($keys as $key) {
  5006. if ($key == '') {
  5007. $key = count($parent);
  5008. }
  5009. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  5010. $parent[$key] = [];
  5011. }
  5012. $parent = &$parent[$key];
  5013. }
  5014. // Handle PHP constants.
  5015. if (defined($value)) {
  5016. $value = constant($value);
  5017. }
  5018. // Insert actual value.
  5019. if ($last == '') {
  5020. $last = count($parent);
  5021. }
  5022. $parent[$last] = $value;
  5023. }
  5024. }
  5025. return $info;
  5026. }
  5027. /**
  5028. * Gets Chamilo version from the configuration files.
  5029. *
  5030. * @return string A string of type "1.8.4", or an empty string if the version could not be found
  5031. */
  5032. function api_get_version()
  5033. {
  5034. return (string) api_get_configuration_value('system_version');
  5035. }
  5036. /**
  5037. * Gets the software name (the name/brand of the Chamilo-based customized system).
  5038. *
  5039. * @return string
  5040. */
  5041. function api_get_software_name()
  5042. {
  5043. $name = api_get_configuration_value('software_name');
  5044. if (!empty($name)) {
  5045. return $name;
  5046. } else {
  5047. return 'Chamilo';
  5048. }
  5049. }
  5050. /**
  5051. * Checks whether status given in parameter exists in the platform.
  5052. *
  5053. * @param mixed the status (can be either int either string)
  5054. *
  5055. * @return bool if the status exists, else returns false
  5056. */
  5057. function api_status_exists($status_asked)
  5058. {
  5059. global $_status_list;
  5060. return in_array($status_asked, $_status_list) ? true : isset($_status_list[$status_asked]);
  5061. }
  5062. /**
  5063. * Checks whether status given in parameter exists in the platform. The function
  5064. * returns the status ID or false if it does not exist, but given the fact there
  5065. * is no "0" status, the return value can be checked against
  5066. * if(api_status_key()) to know if it exists.
  5067. *
  5068. * @param mixed The status (can be either int or string)
  5069. *
  5070. * @return mixed Status ID if exists, false otherwise
  5071. */
  5072. function api_status_key($status)
  5073. {
  5074. global $_status_list;
  5075. return isset($_status_list[$status]) ? $status : array_search($status, $_status_list);
  5076. }
  5077. /**
  5078. * Gets the status langvars list.
  5079. *
  5080. * @return string[] the list of status with their translations
  5081. */
  5082. function api_get_status_langvars()
  5083. {
  5084. return [
  5085. COURSEMANAGER => get_lang('Teacher', ''),
  5086. SESSIONADMIN => get_lang('SessionsAdmin', ''),
  5087. DRH => get_lang('Drh', ''),
  5088. STUDENT => get_lang('Student', ''),
  5089. ANONYMOUS => get_lang('Anonymous', ''),
  5090. STUDENT_BOSS => get_lang('RoleStudentBoss', ''),
  5091. INVITEE => get_lang('Invited'),
  5092. ];
  5093. }
  5094. /**
  5095. * The function that retrieves all the possible settings for a certain config setting.
  5096. *
  5097. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  5098. */
  5099. function api_get_settings_options($var)
  5100. {
  5101. $table_settings_options = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  5102. $var = Database::escape_string($var);
  5103. $sql = "SELECT * FROM $table_settings_options
  5104. WHERE variable = '$var'
  5105. ORDER BY id";
  5106. $result = Database::query($sql);
  5107. $settings_options_array = [];
  5108. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5109. $settings_options_array[] = $row;
  5110. }
  5111. return $settings_options_array;
  5112. }
  5113. /**
  5114. * @param array $params
  5115. */
  5116. function api_set_setting_option($params)
  5117. {
  5118. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  5119. if (empty($params['id'])) {
  5120. Database::insert($table, $params);
  5121. } else {
  5122. Database::update($table, $params, ['id = ? ' => $params['id']]);
  5123. }
  5124. }
  5125. /**
  5126. * @param array $params
  5127. */
  5128. function api_set_setting_simple($params)
  5129. {
  5130. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5131. $url_id = api_get_current_access_url_id();
  5132. if (empty($params['id'])) {
  5133. $params['access_url'] = $url_id;
  5134. Database::insert($table, $params);
  5135. } else {
  5136. Database::update($table, $params, ['id = ? ' => [$params['id']]]);
  5137. }
  5138. }
  5139. /**
  5140. * @param int $id
  5141. */
  5142. function api_delete_setting_option($id)
  5143. {
  5144. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  5145. if (!empty($id)) {
  5146. Database::delete($table, ['id = ? ' => $id]);
  5147. }
  5148. }
  5149. /**
  5150. * Sets a platform configuration setting to a given value.
  5151. *
  5152. * @param string The variable we want to update
  5153. * @param string The value we want to record
  5154. * @param string The sub-variable if any (in most cases, this will remain null)
  5155. * @param string The category if any (in most cases, this will remain null)
  5156. * @param int The access_url for which this parameter is valid
  5157. * @param string $cat
  5158. *
  5159. * @return bool|null
  5160. */
  5161. function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1)
  5162. {
  5163. if (empty($var)) {
  5164. return false;
  5165. }
  5166. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5167. $var = Database::escape_string($var);
  5168. $value = Database::escape_string($value);
  5169. $access_url = (int) $access_url;
  5170. if (empty($access_url)) {
  5171. $access_url = 1;
  5172. }
  5173. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  5174. if (!empty($subvar)) {
  5175. $subvar = Database::escape_string($subvar);
  5176. $select .= " AND subkey = '$subvar'";
  5177. }
  5178. if (!empty($cat)) {
  5179. $cat = Database::escape_string($cat);
  5180. $select .= " AND category = '$cat'";
  5181. }
  5182. if ($access_url > 1) {
  5183. $select .= " AND access_url = $access_url";
  5184. } else {
  5185. $select .= " AND access_url = 1 ";
  5186. }
  5187. $res = Database::query($select);
  5188. if (Database::num_rows($res) > 0) {
  5189. // Found item for this access_url.
  5190. $row = Database::fetch_array($res);
  5191. $sql = "UPDATE $t_settings SET selected_value = '$value'
  5192. WHERE id = ".$row['id'];
  5193. Database::query($sql);
  5194. } else {
  5195. // Item not found for this access_url, we have to check if it exist with access_url = 1
  5196. $select = "SELECT * FROM $t_settings
  5197. WHERE variable = '$var' AND access_url = 1 ";
  5198. // Just in case
  5199. if ($access_url == 1) {
  5200. if (!empty($subvar)) {
  5201. $select .= " AND subkey = '$subvar'";
  5202. }
  5203. if (!empty($cat)) {
  5204. $select .= " AND category = '$cat'";
  5205. }
  5206. $res = Database::query($select);
  5207. if (Database::num_rows($res) > 0) {
  5208. // We have a setting for access_url 1, but none for the current one, so create one.
  5209. $row = Database::fetch_array($res);
  5210. $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url)
  5211. VALUES
  5212. ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
  5213. "'".$row['type']."','".$row['category']."',".
  5214. "'$value','".$row['title']."',".
  5215. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
  5216. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url)";
  5217. Database::query($insert);
  5218. } else {
  5219. // Such a setting does not exist.
  5220. //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
  5221. }
  5222. } else {
  5223. // Other access url.
  5224. if (!empty($subvar)) {
  5225. $select .= " AND subkey = '$subvar'";
  5226. }
  5227. if (!empty($cat)) {
  5228. $select .= " AND category = '$cat'";
  5229. }
  5230. $res = Database::query($select);
  5231. if (Database::num_rows($res) > 0) {
  5232. // We have a setting for access_url 1, but none for the current one, so create one.
  5233. $row = Database::fetch_array($res);
  5234. if ($row['access_url_changeable'] == 1) {
  5235. $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES
  5236. ('".$row['variable']."',".
  5237. (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
  5238. "'".$row['type']."','".$row['category']."',".
  5239. "'$value','".$row['title']."',".
  5240. "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
  5241. (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
  5242. "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
  5243. Database::query($insert);
  5244. }
  5245. } else { // Such a setting does not exist.
  5246. //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
  5247. }
  5248. }
  5249. }
  5250. }
  5251. /**
  5252. * Sets a whole category of settings to one specific value.
  5253. *
  5254. * @param string Category
  5255. * @param string Value
  5256. * @param int Access URL. Optional. Defaults to 1
  5257. * @param array Optional array of filters on field type
  5258. * @param string $category
  5259. * @param string $value
  5260. *
  5261. * @return bool
  5262. */
  5263. function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = [])
  5264. {
  5265. if (empty($category)) {
  5266. return false;
  5267. }
  5268. $category = Database::escape_string($category);
  5269. $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5270. $access_url = (int) $access_url;
  5271. if (empty($access_url)) {
  5272. $access_url = 1;
  5273. }
  5274. if (isset($value)) {
  5275. $value = Database::escape_string($value);
  5276. $sql = "UPDATE $t_s SET selected_value = '$value'
  5277. WHERE category = '$category' AND access_url = $access_url";
  5278. if (is_array($fieldtype) && count($fieldtype) > 0) {
  5279. $sql .= " AND ( ";
  5280. $i = 0;
  5281. foreach ($fieldtype as $type) {
  5282. if ($i > 0) {
  5283. $sql .= ' OR ';
  5284. }
  5285. $type = Database::escape_string($type);
  5286. $sql .= " type='".$type."' ";
  5287. $i++;
  5288. }
  5289. $sql .= ")";
  5290. }
  5291. $res = Database::query($sql);
  5292. return $res !== false;
  5293. } else {
  5294. $sql = "UPDATE $t_s SET selected_value = NULL
  5295. WHERE category = '$category' AND access_url = $access_url";
  5296. if (is_array($fieldtype) && count($fieldtype) > 0) {
  5297. $sql .= " AND ( ";
  5298. $i = 0;
  5299. foreach ($fieldtype as $type) {
  5300. if ($i > 0) {
  5301. $sql .= ' OR ';
  5302. }
  5303. $type = Database::escape_string($type);
  5304. $sql .= " type='".$type."' ";
  5305. $i++;
  5306. }
  5307. $sql .= ")";
  5308. }
  5309. $res = Database::query($sql);
  5310. return $res !== false;
  5311. }
  5312. }
  5313. /**
  5314. * Gets all available access urls in an array (as in the database).
  5315. *
  5316. * @return array An array of database records
  5317. */
  5318. function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC')
  5319. {
  5320. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5321. $from = (int) $from;
  5322. $to = (int) $to;
  5323. $order = Database::escape_string($order, null, false);
  5324. $direction = Database::escape_string($direction, null, false);
  5325. $sql = "SELECT id, url, description, active, created_by, tms
  5326. FROM $table
  5327. ORDER BY $order $direction
  5328. LIMIT $to OFFSET $from";
  5329. $res = Database::query($sql);
  5330. return Database::store_result($res);
  5331. }
  5332. /**
  5333. * Gets the access url info in an array.
  5334. *
  5335. * @param int $id Id of the access url
  5336. * @param bool $returnDefault Set to false if you want the real URL if URL 1 is still 'http://localhost/'
  5337. *
  5338. * @return array All the info (url, description, active, created_by, tms)
  5339. * from the access_url table
  5340. *
  5341. * @author Julio Montoya
  5342. */
  5343. function api_get_access_url($id, $returnDefault = true)
  5344. {
  5345. static $staticResult;
  5346. $id = (int) $id;
  5347. if (isset($staticResult[$id])) {
  5348. $result = $staticResult[$id];
  5349. } else {
  5350. // Calling the Database:: library dont work this is handmade.
  5351. $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5352. $sql = "SELECT url, description, active, created_by, tms
  5353. FROM $table_access_url WHERE id = '$id' ";
  5354. $res = Database::query($sql);
  5355. $result = @Database::fetch_array($res);
  5356. $staticResult[$id] = $result;
  5357. }
  5358. // If the result url is 'http://localhost/' (the default) and the root_web
  5359. // (=current url) is different, and the $id is = 1 (which might mean
  5360. // api_get_current_access_url_id() returned 1 by default), then return the
  5361. // root_web setting instead of the current URL
  5362. // This is provided as an option to avoid breaking the storage of URL-specific
  5363. // homepages in home/localhost/
  5364. if ($id === 1 && $returnDefault === false) {
  5365. $currentUrl = api_get_current_access_url_id();
  5366. // only do this if we are on the main URL (=1), otherwise we could get
  5367. // information on another URL instead of the one asked as parameter
  5368. if ($currentUrl === 1) {
  5369. $rootWeb = api_get_path(WEB_PATH);
  5370. $default = 'http://localhost/';
  5371. if ($result['url'] === $default && $rootWeb != $default) {
  5372. $result['url'] = $rootWeb;
  5373. }
  5374. }
  5375. }
  5376. return $result;
  5377. }
  5378. /**
  5379. * Gets all the current settings for a specific access url.
  5380. *
  5381. * @param string The category, if any, that we want to get
  5382. * @param string Whether we want a simple list (display a category) or
  5383. * a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
  5384. * @param int Access URL's ID. Optional. Uses 1 by default, which is the unique URL
  5385. *
  5386. * @return array Array of database results for the current settings of the current access URL
  5387. */
  5388. function &api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0)
  5389. {
  5390. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  5391. $access_url = (int) $access_url;
  5392. $where_condition = '';
  5393. if ($url_changeable == 1) {
  5394. $where_condition = " AND access_url_changeable= '1' ";
  5395. }
  5396. if (empty($access_url) || $access_url == -1) {
  5397. $access_url = 1;
  5398. }
  5399. $sql = "SELECT * FROM $table
  5400. WHERE access_url = $access_url $where_condition ";
  5401. if (!empty($cat)) {
  5402. $cat = Database::escape_string($cat);
  5403. $sql .= " AND category='$cat' ";
  5404. }
  5405. if ($ordering == 'group') {
  5406. $sql .= " ORDER BY id ASC";
  5407. } else {
  5408. $sql .= " ORDER BY 1,2 ASC";
  5409. }
  5410. $result = Database::query($sql);
  5411. if ($result === null) {
  5412. return [];
  5413. }
  5414. $result = Database::store_result($result, 'ASSOC');
  5415. return $result;
  5416. }
  5417. /**
  5418. * @param string $value The value we want to record
  5419. * @param string $variable The variable name we want to insert
  5420. * @param string $subKey The subkey for the variable we want to insert
  5421. * @param string $type The type for the variable we want to insert
  5422. * @param string $category The category for the variable we want to insert
  5423. * @param string $title The title
  5424. * @param string $comment The comment
  5425. * @param string $scope The scope
  5426. * @param string $subKeyText The subkey text
  5427. * @param int $accessUrlId The access_url for which this parameter is valid
  5428. * @param int $visibility The changeability of this setting for non-master urls
  5429. *
  5430. * @return int The setting ID
  5431. */
  5432. function api_add_setting(
  5433. $value,
  5434. $variable,
  5435. $subKey = '',
  5436. $type = 'textfield',
  5437. $category = '',
  5438. $title = '',
  5439. $comment = '',
  5440. $scope = '',
  5441. $subKeyText = '',
  5442. $accessUrlId = 1,
  5443. $visibility = 0
  5444. ) {
  5445. $em = Database::getManager();
  5446. $settingRepo = $em->getRepository('ChamiloCoreBundle:SettingsCurrent');
  5447. $accessUrlId = (int) $accessUrlId ?: 1;
  5448. if (is_array($value)) {
  5449. $value = serialize($value);
  5450. } else {
  5451. $value = trim($value);
  5452. }
  5453. $criteria = ['variable' => $variable, 'accessUrl' => $accessUrlId];
  5454. if (!empty($subKey)) {
  5455. $criteria['subkey'] = $subKey;
  5456. }
  5457. // Check if this variable doesn't exist already
  5458. /** @var SettingsCurrent $setting */
  5459. $setting = $settingRepo->findOneBy($criteria);
  5460. if ($setting) {
  5461. $setting->setSelectedValue($value);
  5462. $em->persist($setting);
  5463. $em->flush();
  5464. return $setting->getId();
  5465. }
  5466. // Item not found for this access_url, we have to check if the whole thing is missing
  5467. // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
  5468. $setting = new SettingsCurrent();
  5469. $setting
  5470. ->setVariable($variable)
  5471. ->setSelectedValue($value)
  5472. ->setType($type)
  5473. ->setCategory($category)
  5474. ->setSubkey($subKey)
  5475. ->setTitle($title)
  5476. ->setComment($comment)
  5477. ->setScope($scope)
  5478. ->setSubkeytext($subKeyText)
  5479. ->setAccessUrl($accessUrlId)
  5480. ->setAccessUrlChangeable($visibility);
  5481. $em->persist($setting);
  5482. $em->flush();
  5483. return $setting->getId();
  5484. }
  5485. /**
  5486. * Checks wether a user can or can't view the contents of a course.
  5487. *
  5488. * @deprecated use CourseManager::is_user_subscribed_in_course
  5489. *
  5490. * @param int $userid User id or NULL to get it from $_SESSION
  5491. * @param int $cid course id to check whether the user is allowed
  5492. *
  5493. * @return bool
  5494. */
  5495. function api_is_course_visible_for_user($userid = null, $cid = null)
  5496. {
  5497. if ($userid === null) {
  5498. $userid = api_get_user_id();
  5499. }
  5500. if (empty($userid) || strval(intval($userid)) != $userid) {
  5501. if (api_is_anonymous()) {
  5502. $userid = api_get_anonymous_id();
  5503. } else {
  5504. return false;
  5505. }
  5506. }
  5507. $cid = Database::escape_string($cid);
  5508. $courseInfo = api_get_course_info($cid);
  5509. $courseId = $courseInfo['real_id'];
  5510. $is_platformAdmin = api_is_platform_admin();
  5511. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  5512. $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
  5513. $sql = "SELECT
  5514. $course_table.category_code,
  5515. $course_table.visibility,
  5516. $course_table.code,
  5517. $course_cat_table.code
  5518. FROM $course_table
  5519. LEFT JOIN $course_cat_table
  5520. ON $course_table.category_code = $course_cat_table.code
  5521. WHERE
  5522. $course_table.code = '$cid'
  5523. LIMIT 1";
  5524. $result = Database::query($sql);
  5525. if (Database::num_rows($result) > 0) {
  5526. $visibility = Database::fetch_array($result);
  5527. $visibility = $visibility['visibility'];
  5528. } else {
  5529. $visibility = 0;
  5530. }
  5531. // Shortcut permissions in case the visibility is "open to the world".
  5532. if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
  5533. return true;
  5534. }
  5535. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5536. $sql = "SELECT
  5537. is_tutor, status
  5538. FROM $tbl_course_user
  5539. WHERE
  5540. user_id = '$userid' AND
  5541. relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND
  5542. c_id = $courseId
  5543. LIMIT 1";
  5544. $result = Database::query($sql);
  5545. if (Database::num_rows($result) > 0) {
  5546. // This user has got a recorded state for this course.
  5547. $cuData = Database::fetch_array($result);
  5548. $is_courseMember = true;
  5549. $is_courseAdmin = ($cuData['status'] == 1);
  5550. }
  5551. if (!$is_courseAdmin) {
  5552. // This user has no status related to this course.
  5553. // Is it the session coach or the session admin?
  5554. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  5555. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  5556. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  5557. $sql = "SELECT
  5558. session.id_coach, session_admin_id, session.id
  5559. FROM
  5560. $tbl_session as session
  5561. INNER JOIN $tbl_session_course
  5562. ON session_rel_course.session_id = session.id
  5563. AND session_rel_course.c_id = '$courseId'
  5564. LIMIT 1";
  5565. $result = Database::query($sql);
  5566. $row = Database::store_result($result);
  5567. if ($row[0]['id_coach'] == $userid) {
  5568. $is_courseMember = true;
  5569. $is_courseAdmin = false;
  5570. } elseif ($row[0]['session_admin_id'] == $userid) {
  5571. $is_courseMember = false;
  5572. $is_courseAdmin = false;
  5573. } else {
  5574. // Check if the current user is the course coach.
  5575. $sql = "SELECT 1
  5576. FROM $tbl_session_course
  5577. WHERE session_rel_course.c_id = '$courseId'
  5578. AND session_rel_course.id_coach = '$userid'
  5579. LIMIT 1";
  5580. $result = Database::query($sql);
  5581. //if ($row = Database::fetch_array($result)) {
  5582. if (Database::num_rows($result) > 0) {
  5583. $is_courseMember = true;
  5584. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5585. $sql = "SELECT status FROM $tbl_user
  5586. WHERE user_id = $userid
  5587. LIMIT 1";
  5588. $result = Database::query($sql);
  5589. if (Database::result($result, 0, 0) == 1) {
  5590. $is_courseAdmin = true;
  5591. } else {
  5592. $is_courseAdmin = false;
  5593. }
  5594. } else {
  5595. // Check if the user is a student is this session.
  5596. $sql = "SELECT id
  5597. FROM $tbl_session_course_user
  5598. WHERE
  5599. user_id = '$userid' AND
  5600. c_id = '$courseId'
  5601. LIMIT 1";
  5602. if (Database::num_rows($result) > 0) {
  5603. // This user haa got a recorded state for this course.
  5604. while ($row = Database::fetch_array($result)) {
  5605. $is_courseMember = true;
  5606. $is_courseAdmin = false;
  5607. }
  5608. }
  5609. }
  5610. }
  5611. }
  5612. switch ($visibility) {
  5613. case COURSE_VISIBILITY_OPEN_WORLD:
  5614. return true;
  5615. case COURSE_VISIBILITY_OPEN_PLATFORM:
  5616. return isset($userid);
  5617. case COURSE_VISIBILITY_REGISTERED:
  5618. case COURSE_VISIBILITY_CLOSED:
  5619. return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
  5620. case COURSE_VISIBILITY_HIDDEN:
  5621. return $is_platformAdmin;
  5622. }
  5623. return false;
  5624. }
  5625. /**
  5626. * Returns whether an element (forum, message, survey ...) belongs to a session or not.
  5627. *
  5628. * @param string the tool of the element
  5629. * @param int the element id in database
  5630. * @param int the session_id to compare with element session id
  5631. *
  5632. * @return bool true if the element is in the session, false else
  5633. */
  5634. function api_is_element_in_the_session($tool, $element_id, $session_id = null)
  5635. {
  5636. if (is_null($session_id)) {
  5637. $session_id = api_get_session_id();
  5638. }
  5639. $element_id = (int) $element_id;
  5640. if (empty($element_id)) {
  5641. return false;
  5642. }
  5643. // Get information to build query depending of the tool.
  5644. switch ($tool) {
  5645. case TOOL_SURVEY:
  5646. $table_tool = Database::get_course_table(TABLE_SURVEY);
  5647. $key_field = 'survey_id';
  5648. break;
  5649. case TOOL_ANNOUNCEMENT:
  5650. $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
  5651. $key_field = 'id';
  5652. break;
  5653. case TOOL_AGENDA:
  5654. $table_tool = Database::get_course_table(TABLE_AGENDA);
  5655. $key_field = 'id';
  5656. break;
  5657. case TOOL_GROUP:
  5658. $table_tool = Database::get_course_table(TABLE_GROUP);
  5659. $key_field = 'id';
  5660. break;
  5661. default:
  5662. return false;
  5663. }
  5664. $course_id = api_get_course_int_id();
  5665. $sql = "SELECT session_id FROM $table_tool
  5666. WHERE c_id = $course_id AND $key_field = ".$element_id;
  5667. $rs = Database::query($sql);
  5668. if ($element_session_id = Database::result($rs, 0, 0)) {
  5669. if ($element_session_id == intval($session_id)) {
  5670. // The element belongs to the session.
  5671. return true;
  5672. }
  5673. }
  5674. return false;
  5675. }
  5676. /**
  5677. * Replaces "forbidden" characters in a filename string.
  5678. *
  5679. * @param string $filename
  5680. * @param bool $treat_spaces_as_hyphens
  5681. *
  5682. * @return string
  5683. */
  5684. function api_replace_dangerous_char($filename, $treat_spaces_as_hyphens = true)
  5685. {
  5686. // Some non-properly encoded file names can cause the whole file to be
  5687. // skipped when uploaded. Avoid this by detecting the encoding and
  5688. // converting to UTF-8, setting the source as ASCII (a reasonably
  5689. // limited characters set) if nothing could be found (BT#
  5690. $encoding = api_detect_encoding($filename);
  5691. if (empty($encoding)) {
  5692. $encoding = 'ASCII';
  5693. if (!api_is_valid_ascii($filename)) {
  5694. // try iconv and try non standard ASCII a.k.a CP437
  5695. // see BT#15022
  5696. if (function_exists('iconv')) {
  5697. $result = iconv('CP437', 'UTF-8', $filename);
  5698. if (api_is_valid_utf8($result)) {
  5699. $filename = $result;
  5700. $encoding = 'UTF-8';
  5701. }
  5702. }
  5703. }
  5704. }
  5705. $filename = api_to_system_encoding($filename, $encoding);
  5706. $url = URLify::filter(
  5707. $filename,
  5708. 250,
  5709. '',
  5710. true,
  5711. true,
  5712. false,
  5713. false,
  5714. $treat_spaces_as_hyphens
  5715. );
  5716. return $url;
  5717. }
  5718. /**
  5719. * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
  5720. *
  5721. * @author Ivan Tcholakov, 28-JUN-2006.
  5722. */
  5723. function api_request_uri()
  5724. {
  5725. if (!empty($_SERVER['REQUEST_URI'])) {
  5726. return $_SERVER['REQUEST_URI'];
  5727. }
  5728. $uri = $_SERVER['SCRIPT_NAME'];
  5729. if (!empty($_SERVER['QUERY_STRING'])) {
  5730. $uri .= '?'.$_SERVER['QUERY_STRING'];
  5731. }
  5732. $_SERVER['REQUEST_URI'] = $uri;
  5733. return $uri;
  5734. }
  5735. /** Gets the current access_url id of the Chamilo Platform
  5736. * @author Julio Montoya <gugli100@gmail.com>
  5737. *
  5738. * @return int access_url_id of the current Chamilo Installation
  5739. */
  5740. function api_get_current_access_url_id()
  5741. {
  5742. static $id;
  5743. if (!empty($id)) {
  5744. return $id;
  5745. }
  5746. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5747. $path = Database::escape_string(api_get_path(WEB_PATH));
  5748. $sql = "SELECT id FROM $table WHERE url = '".$path."'";
  5749. $result = Database::query($sql);
  5750. if (Database::num_rows($result) > 0) {
  5751. $id = Database::result($result, 0, 0);
  5752. if ($id === false) {
  5753. return -1;
  5754. }
  5755. return (int) $id;
  5756. }
  5757. $id = 1;
  5758. //if the url in WEB_PATH was not found, it can only mean that there is
  5759. // either a configuration problem or the first URL has not been defined yet
  5760. // (by default it is http://localhost/). Thus the more sensible thing we can
  5761. // do is return 1 (the main URL) as the user cannot hack this value anyway
  5762. return 1;
  5763. }
  5764. /**
  5765. * Gets the registered urls from a given user id.
  5766. *
  5767. * @author Julio Montoya <gugli100@gmail.com>
  5768. *
  5769. * @return int user id
  5770. */
  5771. function api_get_access_url_from_user($user_id)
  5772. {
  5773. $user_id = (int) $user_id;
  5774. $table_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  5775. $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
  5776. $sql = "SELECT access_url_id
  5777. FROM $table_url_rel_user url_rel_user
  5778. INNER JOIN $table_url u
  5779. ON (url_rel_user.access_url_id = u.id)
  5780. WHERE user_id = ".intval($user_id);
  5781. $result = Database::query($sql);
  5782. $list = [];
  5783. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5784. $list[] = $row['access_url_id'];
  5785. }
  5786. return $list;
  5787. }
  5788. /**
  5789. * Gets the status of a user in a course.
  5790. *
  5791. * @param int $user_id
  5792. * @param int $courseId
  5793. *
  5794. * @return int user status
  5795. */
  5796. function api_get_status_of_user_in_course($user_id, $courseId)
  5797. {
  5798. $tbl_rel_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5799. if (!empty($user_id) && !empty($courseId)) {
  5800. $user_id = intval($user_id);
  5801. $courseId = intval($courseId);
  5802. $sql = 'SELECT status
  5803. FROM '.$tbl_rel_course_user.'
  5804. WHERE user_id='.$user_id.' AND c_id = '.$courseId;
  5805. $result = Database::query($sql);
  5806. $row_status = Database::fetch_array($result, 'ASSOC');
  5807. return $row_status['status'];
  5808. } else {
  5809. return 0;
  5810. }
  5811. }
  5812. /**
  5813. * Checks whether the curent user is in a group or not.
  5814. *
  5815. * @param string The group id - optional (takes it from session if not given)
  5816. * @param string The course code - optional (no additional check by course if course code is not given)
  5817. *
  5818. * @return bool
  5819. *
  5820. * @author Ivan Tcholakov
  5821. */
  5822. function api_is_in_group($groupIdParam = null, $courseCodeParam = null)
  5823. {
  5824. if (!empty($courseCodeParam)) {
  5825. $courseCode = api_get_course_id();
  5826. if (!empty($courseCode)) {
  5827. if ($courseCodeParam != $courseCode) {
  5828. return false;
  5829. }
  5830. } else {
  5831. return false;
  5832. }
  5833. }
  5834. $groupId = api_get_group_id();
  5835. if (isset($groupId) && $groupId != '') {
  5836. if (!empty($groupIdParam)) {
  5837. return $groupIdParam == $groupId;
  5838. } else {
  5839. return true;
  5840. }
  5841. }
  5842. return false;
  5843. }
  5844. /**
  5845. * Checks whether a secret key is valid.
  5846. *
  5847. * @param string $original_key_secret - secret key from (webservice) client
  5848. * @param string $security_key - security key from Chamilo
  5849. *
  5850. * @return bool - true if secret key is valid, false otherwise
  5851. */
  5852. function api_is_valid_secret_key($original_key_secret, $security_key)
  5853. {
  5854. return $original_key_secret == sha1($security_key);
  5855. }
  5856. /**
  5857. * Checks whether a user is into course.
  5858. *
  5859. * @param int $course_id - the course id
  5860. * @param int $user_id - the user id
  5861. *
  5862. * @return bool
  5863. */
  5864. function api_is_user_of_course($course_id, $user_id)
  5865. {
  5866. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  5867. $sql = 'SELECT user_id FROM '.$tbl_course_rel_user.'
  5868. WHERE
  5869. c_id ="'.intval($course_id).'" AND
  5870. user_id = "'.intval($user_id).'" AND
  5871. relation_type <> '.COURSE_RELATION_TYPE_RRHH.' ';
  5872. $result = Database::query($sql);
  5873. return Database::num_rows($result) == 1;
  5874. }
  5875. /**
  5876. * Checks whether the server's operating system is Windows (TM).
  5877. *
  5878. * @return bool - true if the operating system is Windows, false otherwise
  5879. */
  5880. function api_is_windows_os()
  5881. {
  5882. if (function_exists('php_uname')) {
  5883. // php_uname() exists as of PHP 4.0.2, according to the documentation.
  5884. // We expect that this function will always work for Chamilo 1.8.x.
  5885. $os = php_uname();
  5886. }
  5887. // The following methods are not needed, but let them stay, just in case.
  5888. elseif (isset($_ENV['OS'])) {
  5889. // Sometimes $_ENV['OS'] may not be present (bugs?)
  5890. $os = $_ENV['OS'];
  5891. } elseif (defined('PHP_OS')) {
  5892. // PHP_OS means on which OS PHP was compiled, this is why
  5893. // using PHP_OS is the last choice for detection.
  5894. $os = PHP_OS;
  5895. } else {
  5896. return false;
  5897. }
  5898. return strtolower(substr((string) $os, 0, 3)) == 'win';
  5899. }
  5900. /**
  5901. * This function informs whether the sent request is XMLHttpRequest.
  5902. */
  5903. function api_is_xml_http_request()
  5904. {
  5905. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  5906. }
  5907. /**
  5908. * This wrapper function has been implemented for avoiding some known problems about the function getimagesize().
  5909. *
  5910. * @see http://php.net/manual/en/function.getimagesize.php
  5911. * @see http://www.dokeos.com/forum/viewtopic.php?t=12345
  5912. * @see http://www.dokeos.com/forum/viewtopic.php?t=16355
  5913. *
  5914. * @return int
  5915. */
  5916. function api_getimagesize($path)
  5917. {
  5918. $image = new Image($path);
  5919. return $image->get_image_size();
  5920. }
  5921. /**
  5922. * This function resizes an image, with preserving its proportions (or aspect ratio).
  5923. *
  5924. * @author Ivan Tcholakov, MAY-2009.
  5925. *
  5926. * @param int $image System path or URL of the image
  5927. * @param int $target_width Targeted width
  5928. * @param int $target_height Targeted height
  5929. *
  5930. * @return array Calculated new width and height
  5931. */
  5932. function api_resize_image($image, $target_width, $target_height)
  5933. {
  5934. $image_properties = api_getimagesize($image);
  5935. return api_calculate_image_size(
  5936. $image_properties['width'],
  5937. $image_properties['height'],
  5938. $target_width,
  5939. $target_height
  5940. );
  5941. }
  5942. /**
  5943. * This function calculates new image size, with preserving image's proportions (or aspect ratio).
  5944. *
  5945. * @author Ivan Tcholakov, MAY-2009.
  5946. * @author The initial idea has been taken from code by Patrick Cool, MAY-2004.
  5947. *
  5948. * @param int $image_width Initial width
  5949. * @param int $image_height Initial height
  5950. * @param int $target_width Targeted width
  5951. * @param int $target_height Targeted height
  5952. *
  5953. * @return array Calculated new width and height
  5954. */
  5955. function api_calculate_image_size(
  5956. $image_width,
  5957. $image_height,
  5958. $target_width,
  5959. $target_height
  5960. ) {
  5961. // Only maths is here.
  5962. $result = ['width' => $image_width, 'height' => $image_height];
  5963. if ($image_width <= 0 || $image_height <= 0) {
  5964. return $result;
  5965. }
  5966. $resize_factor_width = $target_width / $image_width;
  5967. $resize_factor_height = $target_height / $image_height;
  5968. $delta_width = $target_width - $image_width * $resize_factor_height;
  5969. $delta_height = $target_height - $image_height * $resize_factor_width;
  5970. if ($delta_width > $delta_height) {
  5971. $result['width'] = ceil($image_width * $resize_factor_height);
  5972. $result['height'] = ceil($image_height * $resize_factor_height);
  5973. } elseif ($delta_width < $delta_height) {
  5974. $result['width'] = ceil($image_width * $resize_factor_width);
  5975. $result['height'] = ceil($image_height * $resize_factor_width);
  5976. } else {
  5977. $result['width'] = ceil($target_width);
  5978. $result['height'] = ceil($target_height);
  5979. }
  5980. return $result;
  5981. }
  5982. /**
  5983. * Returns a list of Chamilo's tools or
  5984. * checks whether a given identificator is a valid Chamilo's tool.
  5985. *
  5986. * @author Isaac flores paz
  5987. *
  5988. * @param string The tool name to filter
  5989. *
  5990. * @return mixed Filtered string or array
  5991. */
  5992. function api_get_tools_lists($my_tool = null)
  5993. {
  5994. $tools_list = [
  5995. TOOL_DOCUMENT,
  5996. TOOL_THUMBNAIL,
  5997. TOOL_HOTPOTATOES,
  5998. TOOL_CALENDAR_EVENT,
  5999. TOOL_LINK,
  6000. TOOL_COURSE_DESCRIPTION,
  6001. TOOL_SEARCH,
  6002. TOOL_LEARNPATH,
  6003. TOOL_ANNOUNCEMENT,
  6004. TOOL_FORUM,
  6005. TOOL_THREAD,
  6006. TOOL_POST,
  6007. TOOL_DROPBOX,
  6008. TOOL_QUIZ,
  6009. TOOL_USER,
  6010. TOOL_GROUP,
  6011. TOOL_BLOGS,
  6012. TOOL_CHAT,
  6013. TOOL_STUDENTPUBLICATION,
  6014. TOOL_TRACKING,
  6015. TOOL_HOMEPAGE_LINK,
  6016. TOOL_COURSE_SETTING,
  6017. TOOL_BACKUP,
  6018. TOOL_COPY_COURSE_CONTENT,
  6019. TOOL_RECYCLE_COURSE,
  6020. TOOL_COURSE_HOMEPAGE,
  6021. TOOL_COURSE_RIGHTS_OVERVIEW,
  6022. TOOL_UPLOAD,
  6023. TOOL_COURSE_MAINTENANCE,
  6024. TOOL_SURVEY,
  6025. TOOL_WIKI,
  6026. TOOL_GLOSSARY,
  6027. TOOL_GRADEBOOK,
  6028. TOOL_NOTEBOOK,
  6029. TOOL_ATTENDANCE,
  6030. TOOL_COURSE_PROGRESS,
  6031. ];
  6032. if (empty($my_tool)) {
  6033. return $tools_list;
  6034. }
  6035. return in_array($my_tool, $tools_list) ? $my_tool : '';
  6036. }
  6037. /**
  6038. * Checks whether we already approved the last version term and condition.
  6039. *
  6040. * @param int user id
  6041. *
  6042. * @return bool true if we pass false otherwise
  6043. */
  6044. function api_check_term_condition($userId)
  6045. {
  6046. if (api_get_setting('allow_terms_conditions') === 'true') {
  6047. // Check if exists terms and conditions
  6048. if (LegalManager::count() == 0) {
  6049. return true;
  6050. }
  6051. $extraFieldValue = new ExtraFieldValue('user');
  6052. $data = $extraFieldValue->get_values_by_handler_and_field_variable(
  6053. $userId,
  6054. 'legal_accept'
  6055. );
  6056. if (!empty($data) && isset($data['value']) && !empty($data['value'])) {
  6057. $result = $data['value'];
  6058. $user_conditions = explode(':', $result);
  6059. $version = $user_conditions[0];
  6060. $langId = $user_conditions[1];
  6061. $realVersion = LegalManager::get_last_version($langId);
  6062. return $version >= $realVersion;
  6063. }
  6064. return false;
  6065. }
  6066. return false;
  6067. }
  6068. /**
  6069. * Gets all information of a tool into course.
  6070. *
  6071. * @param int The tool id
  6072. *
  6073. * @return array
  6074. */
  6075. function api_get_tool_information_by_name($name)
  6076. {
  6077. $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
  6078. $course_id = api_get_course_int_id();
  6079. $sql = "SELECT * FROM $t_tool
  6080. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  6081. $rs = Database::query($sql);
  6082. return Database::fetch_array($rs, 'ASSOC');
  6083. }
  6084. /**
  6085. * Function used to protect a "global" admin script.
  6086. * The function blocks access when the user has no global platform admin rights.
  6087. * Global admins are the admins that are registered in the main.admin table
  6088. * AND the users who have access to the "principal" portal.
  6089. * That means that there is a record in the main.access_url_rel_user table
  6090. * with his user id and the access_url_id=1.
  6091. *
  6092. * @author Julio Montoya
  6093. *
  6094. * @param int $user_id
  6095. *
  6096. * @return bool
  6097. */
  6098. function api_is_global_platform_admin($user_id = null)
  6099. {
  6100. $user_id = (int) $user_id;
  6101. if (empty($user_id)) {
  6102. $user_id = api_get_user_id();
  6103. }
  6104. if (api_is_platform_admin_by_id($user_id)) {
  6105. $urlList = api_get_access_url_from_user($user_id);
  6106. // The admin is registered in the first "main" site with access_url_id = 1
  6107. if (in_array(1, $urlList)) {
  6108. return true;
  6109. } else {
  6110. return false;
  6111. }
  6112. }
  6113. return false;
  6114. }
  6115. /**
  6116. * @param int $admin_id_to_check
  6117. * @param int $my_user_id
  6118. * @param bool $allow_session_admin
  6119. *
  6120. * @return bool
  6121. */
  6122. function api_global_admin_can_edit_admin(
  6123. $admin_id_to_check,
  6124. $my_user_id = null,
  6125. $allow_session_admin = false
  6126. ) {
  6127. if (empty($my_user_id)) {
  6128. $my_user_id = api_get_user_id();
  6129. }
  6130. $iam_a_global_admin = api_is_global_platform_admin($my_user_id);
  6131. $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
  6132. if ($iam_a_global_admin) {
  6133. // Global admin can edit everything
  6134. return true;
  6135. } else {
  6136. // If i'm a simple admin
  6137. $is_platform_admin = api_is_platform_admin_by_id($my_user_id);
  6138. if ($allow_session_admin) {
  6139. $is_platform_admin = api_is_platform_admin_by_id($my_user_id) || (api_get_user_status($my_user_id) == SESSIONADMIN);
  6140. }
  6141. if ($is_platform_admin) {
  6142. if ($user_is_global_admin) {
  6143. return false;
  6144. } else {
  6145. return true;
  6146. }
  6147. } else {
  6148. return false;
  6149. }
  6150. }
  6151. }
  6152. /**
  6153. * @param int $admin_id_to_check
  6154. * @param int $my_user_id
  6155. * @param bool $allow_session_admin
  6156. *
  6157. * @return bool|null
  6158. */
  6159. function api_protect_super_admin($admin_id_to_check, $my_user_id = null, $allow_session_admin = false)
  6160. {
  6161. if (api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id, $allow_session_admin)) {
  6162. return true;
  6163. } else {
  6164. api_not_allowed();
  6165. }
  6166. }
  6167. /**
  6168. * Function used to protect a global admin script.
  6169. * The function blocks access when the user has no global platform admin rights.
  6170. * See also the api_is_global_platform_admin() function wich defines who's a "global" admin.
  6171. *
  6172. * @author Julio Montoya
  6173. */
  6174. function api_protect_global_admin_script()
  6175. {
  6176. if (!api_is_global_platform_admin()) {
  6177. api_not_allowed();
  6178. return false;
  6179. }
  6180. return true;
  6181. }
  6182. /**
  6183. * Get active template.
  6184. *
  6185. * @param string theme type (optional: default)
  6186. * @param string path absolute(abs) or relative(rel) (optional:rel)
  6187. *
  6188. * @return string actived template path
  6189. */
  6190. function api_get_template($path_type = 'rel')
  6191. {
  6192. $path_types = ['rel', 'abs'];
  6193. $template_path = '';
  6194. if (in_array($path_type, $path_types)) {
  6195. if ($path_type == 'rel') {
  6196. $template_path = api_get_path(SYS_TEMPLATE_PATH);
  6197. } else {
  6198. $template_path = api_get_path(WEB_TEMPLATE_PATH);
  6199. }
  6200. }
  6201. $actived_theme = 'default';
  6202. if (api_get_setting('active_template')) {
  6203. $actived_theme = api_get_setting('active_template');
  6204. }
  6205. $actived_theme_path = $template_path.$actived_theme.DIRECTORY_SEPARATOR;
  6206. return $actived_theme_path;
  6207. }
  6208. /**
  6209. * Check browser support for specific file types or features
  6210. * This function checks if the user's browser supports a file format or given
  6211. * feature, or returns the current browser and major version when
  6212. * $format=check_browser. Only a limited number of formats and features are
  6213. * checked by this method. Make sure you check its definition first.
  6214. *
  6215. * @param string $format Can be a file format (extension like svg, webm, ...) or a feature (like autocapitalize, ...)
  6216. *
  6217. * @return bool or return text array if $format=check_browser
  6218. *
  6219. * @author Juan Carlos Raña Trabado
  6220. */
  6221. function api_browser_support($format = '')
  6222. {
  6223. $browser = new Browser();
  6224. $current_browser = $browser->getBrowser();
  6225. $a_versiontemp = explode('.', $browser->getVersion());
  6226. $current_majorver = $a_versiontemp[0];
  6227. static $result;
  6228. if (isset($result[$format])) {
  6229. return $result[$format];
  6230. }
  6231. // Native svg support
  6232. if ($format == 'svg') {
  6233. if (($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6234. ($current_browser == 'Firefox' && $current_majorver > 1) ||
  6235. ($current_browser == 'Safari' && $current_majorver >= 4) ||
  6236. ($current_browser == 'Chrome' && $current_majorver >= 1) ||
  6237. ($current_browser == 'Opera' && $current_majorver >= 9)
  6238. ) {
  6239. $result[$format] = true;
  6240. return true;
  6241. } else {
  6242. $result[$format] = false;
  6243. return false;
  6244. }
  6245. } elseif ($format == 'pdf') {
  6246. // native pdf support
  6247. if ($current_browser == 'Chrome' && $current_majorver >= 6) {
  6248. $result[$format] = true;
  6249. return true;
  6250. } else {
  6251. $result[$format] = false;
  6252. return false;
  6253. }
  6254. } elseif ($format == 'tif' || $format == 'tiff') {
  6255. //native tif support
  6256. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  6257. $result[$format] = true;
  6258. return true;
  6259. } else {
  6260. $result[$format] = false;
  6261. return false;
  6262. }
  6263. } elseif ($format == 'ogg' || $format == 'ogx' || $format == 'ogv' || $format == 'oga') {
  6264. //native ogg, ogv,oga support
  6265. if (($current_browser == 'Firefox' && $current_majorver >= 3) ||
  6266. ($current_browser == 'Chrome' && $current_majorver >= 3) ||
  6267. ($current_browser == 'Opera' && $current_majorver >= 9)) {
  6268. $result[$format] = true;
  6269. return true;
  6270. } else {
  6271. $result[$format] = false;
  6272. return false;
  6273. }
  6274. } elseif ($format == 'mpg' || $format == 'mpeg') {
  6275. //native mpg support
  6276. if (($current_browser == 'Safari' && $current_majorver >= 5)) {
  6277. $result[$format] = true;
  6278. return true;
  6279. } else {
  6280. $result[$format] = false;
  6281. return false;
  6282. }
  6283. } elseif ($format == 'mp4') {
  6284. //native mp4 support (TODO: Android, iPhone)
  6285. if ($current_browser == 'Android' || $current_browser == 'iPhone') {
  6286. $result[$format] = true;
  6287. return true;
  6288. } else {
  6289. $result[$format] = false;
  6290. return false;
  6291. }
  6292. } elseif ($format == 'mov') {
  6293. //native mov support( TODO:check iPhone)
  6294. if ($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone') {
  6295. $result[$format] = true;
  6296. return true;
  6297. } else {
  6298. $result[$format] = false;
  6299. return false;
  6300. }
  6301. } elseif ($format == 'avi') {
  6302. //native avi support
  6303. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  6304. $result[$format] = true;
  6305. return true;
  6306. } else {
  6307. $result[$format] = false;
  6308. return false;
  6309. }
  6310. } elseif ($format == 'wmv') {
  6311. //native wmv support
  6312. if ($current_browser == 'Firefox' && $current_majorver >= 4) {
  6313. $result[$format] = true;
  6314. return true;
  6315. } else {
  6316. $result[$format] = false;
  6317. return false;
  6318. }
  6319. } elseif ($format == 'webm') {
  6320. //native webm support (TODO:check IE9, Chrome9, Android)
  6321. if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
  6322. ($current_browser == 'Opera' && $current_majorver >= 9) ||
  6323. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6324. ($current_browser == 'Chrome' && $current_majorver >= 9) ||
  6325. $current_browser == 'Android'
  6326. ) {
  6327. $result[$format] = true;
  6328. return true;
  6329. } else {
  6330. $result[$format] = false;
  6331. return false;
  6332. }
  6333. } elseif ($format == 'wav') {
  6334. //native wav support (only some codecs !)
  6335. if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
  6336. ($current_browser == 'Safari' && $current_majorver >= 5) ||
  6337. ($current_browser == 'Opera' && $current_majorver >= 9) ||
  6338. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6339. ($current_browser == 'Chrome' && $current_majorver > 9) ||
  6340. $current_browser == 'Android' ||
  6341. $current_browser == 'iPhone'
  6342. ) {
  6343. $result[$format] = true;
  6344. return true;
  6345. } else {
  6346. $result[$format] = false;
  6347. return false;
  6348. }
  6349. } elseif ($format == 'mid' || $format == 'kar') {
  6350. //native midi support (TODO:check Android)
  6351. if ($current_browser == 'Opera' && $current_majorver >= 9 || $current_browser == 'Android') {
  6352. $result[$format] = true;
  6353. return true;
  6354. } else {
  6355. $result[$format] = false;
  6356. return false;
  6357. }
  6358. } elseif ($format == 'wma') {
  6359. //native wma support
  6360. if ($current_browser == 'Firefox' && $current_majorver >= 4) {
  6361. $result[$format] = true;
  6362. return true;
  6363. } else {
  6364. $result[$format] = false;
  6365. return false;
  6366. }
  6367. } elseif ($format == 'au') {
  6368. //native au support
  6369. if ($current_browser == 'Safari' && $current_majorver >= 5) {
  6370. $result[$format] = true;
  6371. return true;
  6372. } else {
  6373. $result[$format] = false;
  6374. return false;
  6375. }
  6376. } elseif ($format == 'mp3') {
  6377. //native mp3 support (TODO:check Android, iPhone)
  6378. if (($current_browser == 'Safari' && $current_majorver >= 5) ||
  6379. ($current_browser == 'Chrome' && $current_majorver >= 6) ||
  6380. ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
  6381. $current_browser == 'Android' ||
  6382. $current_browser == 'iPhone' ||
  6383. $current_browser == 'Firefox'
  6384. ) {
  6385. $result[$format] = true;
  6386. return true;
  6387. } else {
  6388. $result[$format] = false;
  6389. return false;
  6390. }
  6391. } elseif ($format == 'autocapitalize') {
  6392. // Help avoiding showing the autocapitalize option if the browser doesn't
  6393. // support it: this attribute is against the HTML5 standard
  6394. if ($current_browser == 'Safari' || $current_browser == 'iPhone') {
  6395. return true;
  6396. } else {
  6397. return false;
  6398. }
  6399. } elseif ($format == "check_browser") {
  6400. $array_check_browser = [$current_browser, $current_majorver];
  6401. return $array_check_browser;
  6402. } else {
  6403. $result[$format] = false;
  6404. return false;
  6405. }
  6406. }
  6407. /**
  6408. * This function checks if exist path and file browscap.ini
  6409. * In order for this to work, your browscap configuration setting in php.ini
  6410. * must point to the correct location of the browscap.ini file on your system
  6411. * http://php.net/manual/en/function.get-browser.php.
  6412. *
  6413. * @return bool
  6414. *
  6415. * @author Juan Carlos Raña Trabado
  6416. */
  6417. function api_check_browscap()
  6418. {
  6419. $setting = ini_get('browscap');
  6420. if ($setting) {
  6421. $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
  6422. if (strpos($setting, 'browscap.ini') && !empty($browser)) {
  6423. return true;
  6424. }
  6425. }
  6426. return false;
  6427. }
  6428. /**
  6429. * Returns the <script> HTML tag.
  6430. */
  6431. function api_get_js($file)
  6432. {
  6433. return '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
  6434. }
  6435. /**
  6436. * Returns the <script> HTML tag.
  6437. *
  6438. * @return string
  6439. */
  6440. function api_get_asset($file)
  6441. {
  6442. return '<script type="text/javascript" src="'.api_get_path(WEB_PUBLIC_PATH).'assets/'.$file.'"></script>'."\n";
  6443. }
  6444. /**
  6445. * Returns the <script> HTML tag.
  6446. *
  6447. * @param string $file
  6448. * @param string $media
  6449. *
  6450. * @return string
  6451. */
  6452. function api_get_css_asset($file, $media = 'screen')
  6453. {
  6454. return '<link href="'.api_get_path(WEB_PUBLIC_PATH).'assets/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
  6455. }
  6456. /**
  6457. * Returns the <link> HTML tag.
  6458. *
  6459. * @param string $file
  6460. * @param string $media
  6461. */
  6462. function api_get_css($file, $media = 'screen')
  6463. {
  6464. return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
  6465. }
  6466. /**
  6467. * Returns the js header to include the jquery library.
  6468. */
  6469. function api_get_jquery_js()
  6470. {
  6471. return api_get_asset('jquery/dist/jquery.min.js');
  6472. }
  6473. /**
  6474. * Returns the jquery path.
  6475. *
  6476. * @return string
  6477. */
  6478. function api_get_jquery_web_path()
  6479. {
  6480. return api_get_path(WEB_PUBLIC_PATH).'assets/jquery/dist/jquery.min.js';
  6481. }
  6482. /**
  6483. * @return string
  6484. */
  6485. function api_get_jquery_ui_js_web_path()
  6486. {
  6487. return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/jquery-ui.min.js';
  6488. }
  6489. /**
  6490. * @return string
  6491. */
  6492. function api_get_jquery_ui_css_web_path()
  6493. {
  6494. return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
  6495. }
  6496. /**
  6497. * Returns the jquery-ui library js headers.
  6498. *
  6499. * @param bool add the jqgrid library
  6500. *
  6501. * @return string html tags
  6502. */
  6503. function api_get_jquery_ui_js($include_jqgrid = false)
  6504. {
  6505. $libraries = [];
  6506. if ($include_jqgrid) {
  6507. $libraries[] = 'jqgrid';
  6508. }
  6509. return api_get_jquery_libraries_js($libraries);
  6510. }
  6511. function api_get_jqgrid_js()
  6512. {
  6513. return api_get_jquery_libraries_js(['jqgrid']);
  6514. }
  6515. /**
  6516. * Returns the jquery library js and css headers.
  6517. *
  6518. * @param array list of jquery libraries supported jquery-ui, jqgrid
  6519. * @param bool add the jquery library
  6520. *
  6521. * @return string html tags
  6522. */
  6523. function api_get_jquery_libraries_js($libraries)
  6524. {
  6525. $js = '';
  6526. $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
  6527. //jqgrid js and css
  6528. if (in_array('jqgrid', $libraries)) {
  6529. $languaje = 'en';
  6530. $platform_isocode = strtolower(api_get_language_isocode());
  6531. //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  6532. $jqgrid_langs = [
  6533. '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',
  6534. ];
  6535. if (in_array($platform_isocode, $jqgrid_langs)) {
  6536. $languaje = $platform_isocode;
  6537. }
  6538. //$js .= '<link rel="stylesheet" href="'.$js_path.'jqgrid/css/ui.jqgrid.css" type="text/css">';
  6539. $js .= api_get_css($js_path.'jqgrid/css/ui.jqgrid.css');
  6540. $js .= api_get_js('jqgrid/js/i18n/grid.locale-'.$languaje.'.js');
  6541. $js .= api_get_js('jqgrid/js/jquery.jqGrid.min.js');
  6542. }
  6543. //Document multiple upload funcionality
  6544. if (in_array('jquery-upload', $libraries)) {
  6545. $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
  6546. $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
  6547. $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
  6548. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
  6549. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
  6550. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
  6551. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
  6552. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
  6553. $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
  6554. $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload.css');
  6555. $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload-ui.css');
  6556. }
  6557. // jquery datepicker
  6558. if (in_array('datepicker', $libraries)) {
  6559. $languaje = 'en-GB';
  6560. $platform_isocode = strtolower(api_get_language_isocode());
  6561. // languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  6562. $datapicker_langs = [
  6563. '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',
  6564. ];
  6565. if (in_array($platform_isocode, $datapicker_langs)) {
  6566. $languaje = $platform_isocode;
  6567. }
  6568. $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
  6569. $script = '<script>
  6570. $(function(){
  6571. $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
  6572. $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
  6573. });
  6574. </script>
  6575. ';
  6576. $js .= $script;
  6577. }
  6578. return $js;
  6579. }
  6580. /**
  6581. * Returns the URL to the course or session, removing the complexity of the URL
  6582. * building piece by piece.
  6583. *
  6584. * This function relies on api_get_course_info()
  6585. *
  6586. * @param string $courseCode The course code - optional (takes it from context if not given)
  6587. * @param int $sessionId The session ID - optional (takes it from context if not given)
  6588. * @param int $groupId The group ID - optional (takes it from context if not given)
  6589. *
  6590. * @return string The URL to a course, a session, or empty string if nothing works e.g. https://localhost/courses/ABC/index.php?session_id=3&gidReq=1
  6591. *
  6592. * @author Julio Montoya <gugli100@gmail.com>
  6593. */
  6594. function api_get_course_url($courseCode = null, $sessionId = null, $groupId = null)
  6595. {
  6596. $courseDirectory = '';
  6597. $url = '';
  6598. // If courseCode not set, get context or []
  6599. if (empty($courseCode)) {
  6600. $courseInfo = api_get_course_info();
  6601. } else {
  6602. $courseInfo = api_get_course_info($courseCode);
  6603. }
  6604. // If course defined, get directory, otherwise keep empty string
  6605. if (!empty($courseInfo['directory'])) {
  6606. $courseDirectory = $courseInfo['directory'];
  6607. }
  6608. // If sessionId not set, get context or 0
  6609. if (empty($sessionId)) {
  6610. $sessionId = api_get_session_id();
  6611. }
  6612. // If groupId not set, get context or 0
  6613. if (empty($groupId)) {
  6614. $groupId = api_get_group_id();
  6615. }
  6616. // Build the URL
  6617. if (!empty($courseDirectory)) {
  6618. // directory not empty, so we do have a course
  6619. $url = api_get_path(WEB_COURSE_PATH).$courseDirectory.'/index.php?id_session='.$sessionId.'&gidReq='.$groupId;
  6620. } elseif (!empty($sessionId) && api_get_configuration_value('remove_session_url') !== true) {
  6621. // if the course was unset and the session was set, send directly to the session
  6622. $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
  6623. }
  6624. // if not valid combination was found, return an empty string
  6625. return $url;
  6626. }
  6627. /**
  6628. * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on.
  6629. *
  6630. * @return bool true if multi site is enabled
  6631. */
  6632. function api_get_multiple_access_url()
  6633. {
  6634. global $_configuration;
  6635. if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
  6636. return true;
  6637. }
  6638. return false;
  6639. }
  6640. /**
  6641. * @return bool
  6642. */
  6643. function api_is_multiple_url_enabled()
  6644. {
  6645. return api_get_multiple_access_url();
  6646. }
  6647. /**
  6648. * Returns a md5 unique id.
  6649. *
  6650. * @todo add more parameters
  6651. */
  6652. function api_get_unique_id()
  6653. {
  6654. $id = md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
  6655. return $id;
  6656. }
  6657. /**
  6658. * Get home path.
  6659. *
  6660. * @return string
  6661. */
  6662. function api_get_home_path()
  6663. {
  6664. // FIX : Start the routing determination from central path definition
  6665. $home = api_get_path(SYS_HOME_PATH);
  6666. if (api_get_multiple_access_url()) {
  6667. $access_url_id = api_get_current_access_url_id();
  6668. $url_info = api_get_access_url($access_url_id);
  6669. $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
  6670. $clean_url = api_replace_dangerous_char($url);
  6671. $clean_url = str_replace('/', '-', $clean_url);
  6672. $clean_url .= '/';
  6673. if ($clean_url != 'localhost/') {
  6674. // means that the multiple URL was not well configured we don't rename the $home variable
  6675. return "{$home}{$clean_url}";
  6676. }
  6677. }
  6678. return $home;
  6679. }
  6680. /**
  6681. * @param int Course id
  6682. * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
  6683. * @param int the item id (tool id, exercise id, lp id)
  6684. *
  6685. * @return bool
  6686. */
  6687. function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null)
  6688. {
  6689. if (api_is_platform_admin()) {
  6690. return false;
  6691. }
  6692. if (api_get_setting('gradebook_locking_enabled') == 'true') {
  6693. if (empty($course_code)) {
  6694. $course_code = api_get_course_id();
  6695. }
  6696. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
  6697. $item_id = intval($item_id);
  6698. $link_type = intval($link_type);
  6699. $course_code = Database::escape_string($course_code);
  6700. $sql = "SELECT locked FROM $table
  6701. WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
  6702. $result = Database::query($sql);
  6703. if (Database::num_rows($result)) {
  6704. return true;
  6705. }
  6706. }
  6707. return false;
  6708. }
  6709. /**
  6710. * Blocks a page if the item was added in a gradebook.
  6711. *
  6712. * @param int exercise id, work id, thread id,
  6713. * @param int LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
  6714. * see gradebook/lib/be/linkfactory
  6715. * @param string course code
  6716. *
  6717. * @return false|null
  6718. */
  6719. function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null)
  6720. {
  6721. if (api_is_platform_admin()) {
  6722. return false;
  6723. }
  6724. if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
  6725. $message = Display::return_message(get_lang('ResourceLockedByGradebook'), 'warning');
  6726. api_not_allowed(true, $message);
  6727. }
  6728. }
  6729. /**
  6730. * Checks the PHP version installed is enough to run Chamilo.
  6731. *
  6732. * @param string Include path (used to load the error page)
  6733. */
  6734. function api_check_php_version($my_inc_path = null)
  6735. {
  6736. if (!function_exists('version_compare') || version_compare(phpversion(), REQUIRED_PHP_VERSION, '<')) {
  6737. $global_error_code = 1;
  6738. // Incorrect PHP version
  6739. $global_page = $my_inc_path.'global_error_message.inc.php';
  6740. if (file_exists($global_page)) {
  6741. require $global_page;
  6742. }
  6743. exit;
  6744. }
  6745. }
  6746. /**
  6747. * Checks whether the Archive directory is present and writeable. If not,
  6748. * prints a warning message.
  6749. */
  6750. function api_check_archive_dir()
  6751. {
  6752. if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
  6753. $message = Display::return_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'), 'warning');
  6754. api_not_allowed(true, $message);
  6755. }
  6756. }
  6757. /**
  6758. * Returns an array of global configuration settings which should be ignored
  6759. * when printing the configuration settings screens.
  6760. *
  6761. * @return array Array of strings, each identifying one of the excluded settings
  6762. */
  6763. function api_get_locked_settings()
  6764. {
  6765. return [
  6766. 'server_type',
  6767. 'permanently_remove_deleted_files',
  6768. 'account_valid_duration',
  6769. 'service_ppt2lp',
  6770. 'wcag_anysurfer_public_pages',
  6771. 'upload_extensions_list_type',
  6772. 'upload_extensions_blacklist',
  6773. 'upload_extensions_whitelist',
  6774. 'upload_extensions_skip',
  6775. 'upload_extensions_replace_by',
  6776. 'hide_dltt_markup',
  6777. 'split_users_upload_directory',
  6778. 'permissions_for_new_directories',
  6779. 'permissions_for_new_files',
  6780. 'platform_charset',
  6781. 'ldap_description',
  6782. 'cas_activate',
  6783. 'cas_server',
  6784. 'cas_server_uri',
  6785. 'cas_port',
  6786. 'cas_protocol',
  6787. 'cas_add_user_activate',
  6788. 'update_user_info_cas_with_ldap',
  6789. 'languagePriority1',
  6790. 'languagePriority2',
  6791. 'languagePriority3',
  6792. 'languagePriority4',
  6793. 'login_is_email',
  6794. 'chamilo_database_version',
  6795. ];
  6796. }
  6797. /**
  6798. * Checks if the user is corrently logged in. Returns the user ID if he is, or
  6799. * false if he isn't. If the user ID is given and is an integer, then the same
  6800. * ID is simply returned.
  6801. *
  6802. * @param int User ID
  6803. *
  6804. * @return bool Integer User ID is logged in, or false otherwise
  6805. */
  6806. function api_user_is_login($user_id = null)
  6807. {
  6808. $user_id = empty($user_id) ? api_get_user_id() : (int) $user_id;
  6809. return $user_id && !api_is_anonymous();
  6810. }
  6811. /**
  6812. * Guess the real ip for register in the database, even in reverse proxy cases.
  6813. * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
  6814. * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
  6815. * Note: the result of this function is not SQL-safe. Please escape it before
  6816. * inserting in a database.
  6817. *
  6818. * @return string the user's real ip (unsafe - escape it before inserting to db)
  6819. *
  6820. * @author Jorge Frisancho Jibaja <jrfdeft@gmail.com>, USIL - Some changes to allow the use of real IP using reverse proxy
  6821. *
  6822. * @version CEV CHANGE 24APR2012
  6823. */
  6824. function api_get_real_ip()
  6825. {
  6826. $ip = trim($_SERVER['REMOTE_ADDR']);
  6827. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  6828. if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  6829. @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  6830. } else {
  6831. $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
  6832. }
  6833. $ip = trim($ip1);
  6834. }
  6835. return $ip;
  6836. }
  6837. /**
  6838. * Checks whether an IP is included inside an IP range.
  6839. *
  6840. * @param string IP address
  6841. * @param string IP range
  6842. * @param string $ip
  6843. *
  6844. * @return bool True if IP is in the range, false otherwise
  6845. *
  6846. * @author claudiu at cnixs dot com on http://www.php.net/manual/fr/ref.network.php#55230
  6847. * @author Yannick Warnier for improvements and managment of multiple ranges
  6848. *
  6849. * @todo check for IPv6 support
  6850. */
  6851. function api_check_ip_in_range($ip, $range)
  6852. {
  6853. if (empty($ip) or empty($range)) {
  6854. return false;
  6855. }
  6856. $ip_ip = ip2long($ip);
  6857. // divide range param into array of elements
  6858. if (strpos($range, ',') !== false) {
  6859. $ranges = explode(',', $range);
  6860. } else {
  6861. $ranges = [$range];
  6862. }
  6863. foreach ($ranges as $range) {
  6864. $range = trim($range);
  6865. if (empty($range)) {
  6866. continue;
  6867. }
  6868. if (strpos($range, '/') === false) {
  6869. if (strcmp($ip, $range) === 0) {
  6870. return true; // there is a direct IP match, return OK
  6871. }
  6872. continue; //otherwise, get to the next range
  6873. }
  6874. // the range contains a "/", so analyse completely
  6875. list($net, $mask) = explode("/", $range);
  6876. $ip_net = ip2long($net);
  6877. // mask binary magic
  6878. $ip_mask = ~((1 << (32 - $mask)) - 1);
  6879. $ip_ip_net = $ip_ip & $ip_mask;
  6880. if ($ip_ip_net == $ip_net) {
  6881. return true;
  6882. }
  6883. }
  6884. return false;
  6885. }
  6886. function api_check_user_access_to_legal($course_visibility)
  6887. {
  6888. $course_visibility_list = [COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM];
  6889. return in_array($course_visibility, $course_visibility_list) || api_is_drh();
  6890. }
  6891. /**
  6892. * Checks if the global chat is enabled or not.
  6893. *
  6894. * @return bool
  6895. */
  6896. function api_is_global_chat_enabled()
  6897. {
  6898. return
  6899. !api_is_anonymous() &&
  6900. api_get_setting('allow_global_chat') === 'true' &&
  6901. api_get_setting('allow_social_tool') === 'true';
  6902. }
  6903. /**
  6904. * @todo Fix tool_visible_by_default_at_creation labels
  6905. *
  6906. * @param int $item_id
  6907. * @param int $tool_id
  6908. * @param int $group_id id
  6909. * @param array $courseInfo
  6910. * @param int $sessionId
  6911. * @param int $userId
  6912. */
  6913. function api_set_default_visibility(
  6914. $item_id,
  6915. $tool_id,
  6916. $group_id = 0,
  6917. $courseInfo = [],
  6918. $sessionId = 0,
  6919. $userId = 0
  6920. ) {
  6921. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  6922. $courseId = $courseInfo['real_id'];
  6923. $courseCode = $courseInfo['code'];
  6924. $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
  6925. $userId = empty($userId) ? api_get_user_id() : $userId;
  6926. // if group is null force group_id = 0, this force is needed to create a LP folder with group = 0
  6927. if (is_null($group_id)) {
  6928. $group_id = 0;
  6929. } else {
  6930. $group_id = empty($group_id) ? api_get_group_id() : $group_id;
  6931. }
  6932. $groupInfo = [];
  6933. if (!empty($group_id)) {
  6934. $groupInfo = GroupManager::get_group_properties($group_id);
  6935. }
  6936. $original_tool_id = $tool_id;
  6937. switch ($tool_id) {
  6938. case TOOL_LINK:
  6939. case TOOL_LINK_CATEGORY:
  6940. $tool_id = 'links';
  6941. break;
  6942. case TOOL_DOCUMENT:
  6943. $tool_id = 'documents';
  6944. break;
  6945. case TOOL_LEARNPATH:
  6946. $tool_id = 'learning';
  6947. break;
  6948. case TOOL_ANNOUNCEMENT:
  6949. $tool_id = 'announcements';
  6950. break;
  6951. case TOOL_FORUM:
  6952. case TOOL_FORUM_CATEGORY:
  6953. case TOOL_FORUM_THREAD:
  6954. $tool_id = 'forums';
  6955. break;
  6956. case TOOL_QUIZ:
  6957. $tool_id = 'quiz';
  6958. break;
  6959. }
  6960. $setting = api_get_setting('tool_visible_by_default_at_creation');
  6961. if (isset($setting[$tool_id])) {
  6962. $visibility = 'invisible';
  6963. if ($setting[$tool_id] == 'true') {
  6964. $visibility = 'visible';
  6965. }
  6966. // Read the portal and course default visibility
  6967. if ($tool_id === 'documents') {
  6968. $visibility = DocumentManager::getDocumentDefaultVisibility($courseInfo);
  6969. }
  6970. api_item_property_update(
  6971. $courseInfo,
  6972. $original_tool_id,
  6973. $item_id,
  6974. $visibility,
  6975. $userId,
  6976. $groupInfo,
  6977. null,
  6978. null,
  6979. null,
  6980. $sessionId
  6981. );
  6982. // Fixes default visibility for tests
  6983. switch ($original_tool_id) {
  6984. case TOOL_QUIZ:
  6985. if (empty($sessionId)) {
  6986. $objExerciseTmp = new Exercise($courseId);
  6987. $objExerciseTmp->read($item_id);
  6988. if ($visibility == 'visible') {
  6989. $objExerciseTmp->enable();
  6990. $objExerciseTmp->save();
  6991. } else {
  6992. $objExerciseTmp->disable();
  6993. $objExerciseTmp->save();
  6994. }
  6995. }
  6996. break;
  6997. }
  6998. }
  6999. }
  7000. /**
  7001. * @return string
  7002. */
  7003. function api_get_security_key()
  7004. {
  7005. return api_get_configuration_value('security_key');
  7006. }
  7007. /**
  7008. * @param int $user_id
  7009. * @param int $courseId
  7010. * @param int $session_id
  7011. *
  7012. * @return array
  7013. */
  7014. function api_detect_user_roles($user_id, $courseId, $session_id = 0)
  7015. {
  7016. $user_roles = [];
  7017. $courseInfo = api_get_course_info_by_id($courseId);
  7018. $course_code = $courseInfo['code'];
  7019. $url_id = api_get_current_access_url_id();
  7020. if (api_is_platform_admin_by_id($user_id, $url_id)) {
  7021. $user_roles[] = PLATFORM_ADMIN;
  7022. }
  7023. /*if (api_is_drh()) {
  7024. $user_roles[] = DRH;
  7025. }*/
  7026. if (!empty($session_id)) {
  7027. if (SessionManager::user_is_general_coach($user_id, $session_id)) {
  7028. $user_roles[] = SESSION_GENERAL_COACH;
  7029. }
  7030. }
  7031. if (!empty($course_code)) {
  7032. if (empty($session_id)) {
  7033. if (CourseManager::is_course_teacher($user_id, $course_code)) {
  7034. $user_roles[] = COURSEMANAGER;
  7035. }
  7036. if (CourseManager::get_tutor_in_course_status($user_id, $courseInfo['real_id'])) {
  7037. $user_roles[] = COURSE_TUTOR;
  7038. }
  7039. if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) {
  7040. $user_roles[] = COURSE_STUDENT;
  7041. }
  7042. } else {
  7043. $user_status_in_session = SessionManager::get_user_status_in_course_session(
  7044. $user_id,
  7045. $courseId,
  7046. $session_id
  7047. );
  7048. if (!empty($user_status_in_session)) {
  7049. if ($user_status_in_session == 0) {
  7050. $user_roles[] = SESSION_STUDENT;
  7051. }
  7052. if ($user_status_in_session == 2) {
  7053. $user_roles[] = SESSION_COURSE_COACH;
  7054. }
  7055. }
  7056. /*if (api_is_course_session_coach($user_id, $course_code, $session_id)) {
  7057. $user_roles[] = SESSION_COURSE_COACH;
  7058. }*/
  7059. }
  7060. }
  7061. return $user_roles;
  7062. }
  7063. /**
  7064. * @param int $courseId
  7065. * @param int $session_id
  7066. *
  7067. * @return bool
  7068. */
  7069. function api_coach_can_edit_view_results($courseId = null, $session_id = null)
  7070. {
  7071. if (api_is_platform_admin()) {
  7072. return true;
  7073. }
  7074. $user_id = api_get_user_id();
  7075. if (empty($courseId)) {
  7076. $courseId = api_get_course_int_id();
  7077. }
  7078. if (empty($session_id)) {
  7079. $session_id = api_get_session_id();
  7080. }
  7081. $roles = api_detect_user_roles($user_id, $courseId, $session_id);
  7082. if (in_array(SESSION_COURSE_COACH, $roles)) {
  7083. //return api_get_setting('session_tutor_reports_visibility') == 'true';
  7084. return true;
  7085. } else {
  7086. if (in_array(COURSEMANAGER, $roles)) {
  7087. return true;
  7088. }
  7089. return false;
  7090. }
  7091. }
  7092. /**
  7093. * @param string $file
  7094. *
  7095. * @return string
  7096. */
  7097. function api_get_js_simple($file)
  7098. {
  7099. return '<script type="text/javascript" src="'.$file.'"></script>'."\n";
  7100. }
  7101. function api_set_settings_and_plugins()
  7102. {
  7103. global $_configuration;
  7104. $_setting = [];
  7105. $_plugins = [];
  7106. // access_url == 1 is the default chamilo location
  7107. $settings_by_access_list = [];
  7108. $access_url_id = api_get_current_access_url_id();
  7109. if ($access_url_id != 1) {
  7110. $url_info = api_get_access_url($_configuration['access_url']);
  7111. if ($url_info['active'] == 1) {
  7112. $settings_by_access = &api_get_settings(null, 'list', $_configuration['access_url'], 1);
  7113. foreach ($settings_by_access as &$row) {
  7114. if (empty($row['variable'])) {
  7115. $row['variable'] = 0;
  7116. }
  7117. if (empty($row['subkey'])) {
  7118. $row['subkey'] = 0;
  7119. }
  7120. if (empty($row['category'])) {
  7121. $row['category'] = 0;
  7122. }
  7123. $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
  7124. }
  7125. }
  7126. }
  7127. $result = api_get_settings(null, 'list', 1);
  7128. foreach ($result as &$row) {
  7129. if ($access_url_id != 1) {
  7130. if ($url_info['active'] == 1) {
  7131. $var = empty($row['variable']) ? 0 : $row['variable'];
  7132. $subkey = empty($row['subkey']) ? 0 : $row['subkey'];
  7133. $category = empty($row['category']) ? 0 : $row['category'];
  7134. }
  7135. if ($row['access_url_changeable'] == 1 && $url_info['active'] == 1) {
  7136. if (isset($settings_by_access_list[$var]) &&
  7137. $settings_by_access_list[$var][$subkey][$category]['selected_value'] != '') {
  7138. if ($row['subkey'] == null) {
  7139. $_setting[$row['variable']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
  7140. } else {
  7141. $_setting[$row['variable']][$row['subkey']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
  7142. }
  7143. } else {
  7144. if ($row['subkey'] == null) {
  7145. $_setting[$row['variable']] = $row['selected_value'];
  7146. } else {
  7147. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  7148. }
  7149. }
  7150. } else {
  7151. if ($row['subkey'] == null) {
  7152. $_setting[$row['variable']] = $row['selected_value'];
  7153. } else {
  7154. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  7155. }
  7156. }
  7157. } else {
  7158. if ($row['subkey'] == null) {
  7159. $_setting[$row['variable']] = $row['selected_value'];
  7160. } else {
  7161. $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
  7162. }
  7163. }
  7164. }
  7165. $result = api_get_settings('Plugins', 'list', $access_url_id);
  7166. $_plugins = [];
  7167. foreach ($result as &$row) {
  7168. $key = &$row['variable'];
  7169. if (is_string($_setting[$key])) {
  7170. $_setting[$key] = [];
  7171. }
  7172. $_setting[$key][] = $row['selected_value'];
  7173. $_plugins[$key][] = $row['selected_value'];
  7174. }
  7175. $_SESSION['_setting'] = $_setting;
  7176. $_SESSION['_plugins'] = $_plugins;
  7177. }
  7178. /**
  7179. * Modify default memory_limit and max_execution_time limits
  7180. * Needed when processing long tasks.
  7181. */
  7182. function api_set_more_memory_and_time_limits()
  7183. {
  7184. if (function_exists('ini_set')) {
  7185. api_set_memory_limit('256M');
  7186. ini_set('max_execution_time', 1800);
  7187. }
  7188. }
  7189. /**
  7190. * Tries to set memory limit, if authorized and new limit is higher than current.
  7191. *
  7192. * @param string $mem New memory limit
  7193. *
  7194. * @return bool True on success, false on failure or current is higher than suggested
  7195. * @assert (null) === false
  7196. * @assert (-1) === false
  7197. * @assert (0) === true
  7198. * @assert ('1G') === true
  7199. */
  7200. function api_set_memory_limit($mem)
  7201. {
  7202. //if ini_set() not available, this function is useless
  7203. if (!function_exists('ini_set') || is_null($mem) || $mem == -1) {
  7204. return false;
  7205. }
  7206. $memory_limit = ini_get('memory_limit');
  7207. if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)) {
  7208. ini_set('memory_limit', $mem);
  7209. return true;
  7210. }
  7211. return false;
  7212. }
  7213. /**
  7214. * Gets memory limit in bytes.
  7215. *
  7216. * @param string The memory size (128M, 1G, 1000K, etc)
  7217. *
  7218. * @return int
  7219. * @assert (null) === false
  7220. * @assert ('1t') === 1099511627776
  7221. * @assert ('1g') === 1073741824
  7222. * @assert ('1m') === 1048576
  7223. * @assert ('100k') === 102400
  7224. */
  7225. function api_get_bytes_memory_limit($mem)
  7226. {
  7227. $size = strtolower(substr($mem, -1));
  7228. switch ($size) {
  7229. case 't':
  7230. $mem = intval(substr($mem, -1)) * 1024 * 1024 * 1024 * 1024;
  7231. break;
  7232. case 'g':
  7233. $mem = intval(substr($mem, 0, -1)) * 1024 * 1024 * 1024;
  7234. break;
  7235. case 'm':
  7236. $mem = intval(substr($mem, 0, -1)) * 1024 * 1024;
  7237. break;
  7238. case 'k':
  7239. $mem = intval(substr($mem, 0, -1)) * 1024;
  7240. break;
  7241. default:
  7242. // we assume it's integer only
  7243. $mem = intval($mem);
  7244. break;
  7245. }
  7246. return $mem;
  7247. }
  7248. /**
  7249. * Finds all the information about a user from username instead of user id.
  7250. *
  7251. * @param string $officialCode
  7252. *
  7253. * @return array $user_info user_id, lastname, firstname, username, email, ...
  7254. *
  7255. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  7256. */
  7257. function api_get_user_info_from_official_code($officialCode)
  7258. {
  7259. if (empty($officialCode)) {
  7260. return false;
  7261. }
  7262. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
  7263. WHERE official_code ='".Database::escape_string($officialCode)."'";
  7264. $result = Database::query($sql);
  7265. if (Database::num_rows($result) > 0) {
  7266. $result_array = Database::fetch_array($result);
  7267. return _api_format_user($result_array);
  7268. }
  7269. return false;
  7270. }
  7271. /**
  7272. * @param string $usernameInputId
  7273. * @param string $passwordInputId
  7274. *
  7275. * @return string|null
  7276. */
  7277. function api_get_password_checker_js($usernameInputId, $passwordInputId)
  7278. {
  7279. $checkPass = api_get_setting('allow_strength_pass_checker');
  7280. $useStrengthPassChecker = $checkPass === 'true';
  7281. if ($useStrengthPassChecker === false) {
  7282. return null;
  7283. }
  7284. $translations = [
  7285. 'wordLength' => get_lang('PasswordIsTooShort'),
  7286. 'wordNotEmail' => get_lang('YourPasswordCannotBeTheSameAsYourEmail'),
  7287. 'wordSimilarToUsername' => get_lang('YourPasswordCannotContainYourUsername'),
  7288. 'wordTwoCharacterClasses' => get_lang('WordTwoCharacterClasses'),
  7289. 'wordRepetitions' => get_lang('TooManyRepetitions'),
  7290. 'wordSequences' => get_lang('YourPasswordContainsSequences'),
  7291. 'errorList' => get_lang('ErrorsFound'),
  7292. 'veryWeak' => get_lang('PasswordVeryWeak'),
  7293. 'weak' => get_lang('PasswordWeak'),
  7294. 'normal' => get_lang('PasswordNormal'),
  7295. 'medium' => get_lang('PasswordMedium'),
  7296. 'strong' => get_lang('PasswordStrong'),
  7297. 'veryStrong' => get_lang('PasswordVeryStrong'),
  7298. ];
  7299. $js = api_get_asset('pwstrength-bootstrap/dist/pwstrength-bootstrap.min.js');
  7300. $js .= "<script>
  7301. var errorMessages = {
  7302. password_to_short : \"".get_lang('PasswordIsTooShort')."\",
  7303. same_as_username : \"".get_lang('YourPasswordCannotBeTheSameAsYourUsername')."\"
  7304. };
  7305. $(function() {
  7306. var lang = ".json_encode($translations).";
  7307. var options = {
  7308. onLoad : function () {
  7309. //$('#messages').text('Start typing password');
  7310. },
  7311. onKeyUp: function (evt) {
  7312. $(evt.target).pwstrength('outputErrorList');
  7313. },
  7314. errorMessages : errorMessages,
  7315. viewports: {
  7316. progress: '#password_progress',
  7317. verdict: '#password-verdict',
  7318. errors: '#password-errors'
  7319. },
  7320. usernameField: '$usernameInputId'
  7321. };
  7322. options.i18n = {
  7323. t: function (key) {
  7324. var result = lang[key];
  7325. return result === key ? '' : result; // This assumes you return the
  7326. }
  7327. };
  7328. $('".$passwordInputId."').pwstrength(options);
  7329. });
  7330. </script>";
  7331. return $js;
  7332. }
  7333. /**
  7334. * create an user extra field called 'captcha_blocked_until_date'.
  7335. *
  7336. * @param string $username
  7337. *
  7338. * @return bool
  7339. */
  7340. function api_block_account_captcha($username)
  7341. {
  7342. $userInfo = api_get_user_info_from_username($username);
  7343. if (empty($userInfo)) {
  7344. return false;
  7345. }
  7346. $minutesToBlock = api_get_setting('captcha_time_to_block');
  7347. $time = time() + $minutesToBlock * 60;
  7348. UserManager::update_extra_field_value(
  7349. $userInfo['user_id'],
  7350. 'captcha_blocked_until_date',
  7351. api_get_utc_datetime($time)
  7352. );
  7353. return true;
  7354. }
  7355. /**
  7356. * @param string $username
  7357. *
  7358. * @return bool
  7359. */
  7360. function api_clean_account_captcha($username)
  7361. {
  7362. $userInfo = api_get_user_info_from_username($username);
  7363. if (empty($userInfo)) {
  7364. return false;
  7365. }
  7366. Session::erase('loginFailedCount');
  7367. UserManager::update_extra_field_value(
  7368. $userInfo['user_id'],
  7369. 'captcha_blocked_until_date',
  7370. null
  7371. );
  7372. return true;
  7373. }
  7374. /**
  7375. * @param string $username
  7376. *
  7377. * @return bool
  7378. */
  7379. function api_get_user_blocked_by_captcha($username)
  7380. {
  7381. $userInfo = api_get_user_info_from_username($username);
  7382. if (empty($userInfo)) {
  7383. return false;
  7384. }
  7385. $data = UserManager::get_extra_user_data_by_field(
  7386. $userInfo['user_id'],
  7387. 'captcha_blocked_until_date'
  7388. );
  7389. if (isset($data) && isset($data['captcha_blocked_until_date'])) {
  7390. return $data['captcha_blocked_until_date'];
  7391. }
  7392. return false;
  7393. }
  7394. /**
  7395. * Remove tags from HTML anf return the $in_number_char first non-HTML char
  7396. * Postfix the text with "..." if it has been truncated.
  7397. *
  7398. * @param string $text
  7399. * @param int $number
  7400. *
  7401. * @return string
  7402. *
  7403. * @author hubert borderiou
  7404. */
  7405. function api_get_short_text_from_html($text, $number)
  7406. {
  7407. // Delete script and style tags
  7408. $text = preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "$1$3", $text);
  7409. $text = api_html_entity_decode($text);
  7410. $out_res = api_remove_tags_with_space($text, false);
  7411. $postfix = "...";
  7412. if (strlen($out_res) > $number) {
  7413. $out_res = substr($out_res, 0, $number).$postfix;
  7414. }
  7415. return $out_res;
  7416. }
  7417. /**
  7418. * Replace tags with a space in a text.
  7419. * If $in_double_quote_replace, replace " with '' (for HTML attribute purpose, for exemple).
  7420. *
  7421. * @return string
  7422. *
  7423. * @author hubert borderiou
  7424. */
  7425. function api_remove_tags_with_space($in_html, $in_double_quote_replace = true)
  7426. {
  7427. $out_res = $in_html;
  7428. if ($in_double_quote_replace) {
  7429. $out_res = str_replace('"', "''", $out_res);
  7430. }
  7431. // avoid text stuck together when tags are removed, adding a space after >
  7432. $out_res = str_replace(">", "> ", $out_res);
  7433. $out_res = strip_tags($out_res);
  7434. return $out_res;
  7435. }
  7436. /**
  7437. * If true, the drh can access all content (courses, users) inside a session.
  7438. *
  7439. * @return bool
  7440. */
  7441. function api_drh_can_access_all_session_content()
  7442. {
  7443. $value = api_get_setting('drh_can_access_all_session_content');
  7444. return $value === 'true';
  7445. }
  7446. /**
  7447. * @param string $tool
  7448. * @param string $setting
  7449. * @param int $defaultValue
  7450. *
  7451. * @return string
  7452. */
  7453. function api_get_default_tool_setting($tool, $setting, $defaultValue)
  7454. {
  7455. global $_configuration;
  7456. if (isset($_configuration[$tool]) &&
  7457. isset($_configuration[$tool]['default_settings']) &&
  7458. isset($_configuration[$tool]['default_settings'][$setting])
  7459. ) {
  7460. return $_configuration[$tool]['default_settings'][$setting];
  7461. }
  7462. return $defaultValue;
  7463. }
  7464. /**
  7465. * Checks if user can login as another user.
  7466. *
  7467. * @param int $loginAsUserId the user id to log in
  7468. * @param int $userId my user id
  7469. *
  7470. * @return bool
  7471. */
  7472. function api_can_login_as($loginAsUserId, $userId = null)
  7473. {
  7474. if (empty($userId)) {
  7475. $userId = api_get_user_id();
  7476. }
  7477. if ($loginAsUserId == $userId) {
  7478. return false;
  7479. }
  7480. if (empty($loginAsUserId)) {
  7481. return false;
  7482. }
  7483. if ($loginAsUserId != strval(intval($loginAsUserId))) {
  7484. return false;
  7485. }
  7486. // Check if the user to login is an admin
  7487. if (api_is_platform_admin_by_id($loginAsUserId)) {
  7488. // Only super admins can login to admin accounts
  7489. if (!api_global_admin_can_edit_admin($loginAsUserId)) {
  7490. return false;
  7491. }
  7492. }
  7493. $userInfo = api_get_user_info($loginAsUserId);
  7494. $isDrh = function () use ($loginAsUserId) {
  7495. if (api_is_drh()) {
  7496. if (api_drh_can_access_all_session_content()) {
  7497. $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
  7498. 'drh_all',
  7499. api_get_user_id()
  7500. );
  7501. $userList = [];
  7502. if (is_array($users)) {
  7503. foreach ($users as $user) {
  7504. $userList[] = $user['user_id'];
  7505. }
  7506. }
  7507. if (in_array($loginAsUserId, $userList)) {
  7508. return true;
  7509. }
  7510. } else {
  7511. if (api_is_drh() &&
  7512. UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())
  7513. ) {
  7514. return true;
  7515. }
  7516. }
  7517. }
  7518. return false;
  7519. };
  7520. $loginAsStatusForSessionAdmins = [STUDENT];
  7521. if (api_get_configuration_value('allow_session_admin_login_as_teacher')) {
  7522. $loginAsStatusForSessionAdmins[] = COURSEMANAGER;
  7523. }
  7524. return api_is_platform_admin() ||
  7525. (api_is_session_admin() && in_array($userInfo['status'], $loginAsStatusForSessionAdmins)) ||
  7526. $isDrh();
  7527. }
  7528. /**
  7529. * @return bool
  7530. */
  7531. function api_is_allowed_in_course()
  7532. {
  7533. if (api_is_platform_admin()) {
  7534. return true;
  7535. }
  7536. return Session::read('is_allowed_in_course');
  7537. }
  7538. /**
  7539. * Set the cookie to go directly to the course code $in_firstpage
  7540. * after login.
  7541. *
  7542. * @param string $value is the course code of the course to go
  7543. */
  7544. function api_set_firstpage_parameter($value)
  7545. {
  7546. setcookie('GotoCourse', $value);
  7547. }
  7548. /**
  7549. * Delete the cookie to go directly to the course code $in_firstpage
  7550. * after login.
  7551. */
  7552. function api_delete_firstpage_parameter()
  7553. {
  7554. setcookie('GotoCourse', '', time() - 3600);
  7555. }
  7556. /**
  7557. * @return bool if course_code for direct course access after login is set
  7558. */
  7559. function exist_firstpage_parameter()
  7560. {
  7561. return isset($_COOKIE['GotoCourse']) && $_COOKIE['GotoCourse'] != '';
  7562. }
  7563. /**
  7564. * @return return the course_code of the course where user login
  7565. */
  7566. function api_get_firstpage_parameter()
  7567. {
  7568. return $_COOKIE['GotoCourse'];
  7569. }
  7570. /**
  7571. * Return true on https install.
  7572. *
  7573. * @return bool
  7574. */
  7575. function api_is_https()
  7576. {
  7577. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  7578. $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_configuration['force_https_forwarded_proto'])
  7579. ) {
  7580. $isSecured = true;
  7581. } else {
  7582. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  7583. $isSecured = true;
  7584. } else {
  7585. $isSecured = false;
  7586. // last chance
  7587. if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
  7588. $isSecured = true;
  7589. }
  7590. }
  7591. }
  7592. return $isSecured;
  7593. }
  7594. /**
  7595. * Return protocol (http or https).
  7596. *
  7597. * @return string
  7598. */
  7599. function api_get_protocol()
  7600. {
  7601. return api_is_https() ? 'https' : 'http';
  7602. }
  7603. /**
  7604. * Return a string where " are replaced with 2 '
  7605. * It is useful when you pass a PHP variable in a Javascript browser dialog
  7606. * e.g. : alert("<?php get_lang('Message') ?>");
  7607. * and message contains character ".
  7608. *
  7609. * @param string $in_text
  7610. *
  7611. * @return string
  7612. */
  7613. function convert_double_quote_to_single($in_text)
  7614. {
  7615. return api_preg_replace('/"/', "''", $in_text);
  7616. }
  7617. /**
  7618. * Get origin.
  7619. *
  7620. * @param string
  7621. *
  7622. * @return string
  7623. */
  7624. function api_get_origin()
  7625. {
  7626. $origin = isset($_REQUEST['origin']) ? Security::remove_XSS($_REQUEST['origin']) : '';
  7627. return $origin;
  7628. }
  7629. /**
  7630. * Warns an user that the portal reach certain limit.
  7631. *
  7632. * @param string $limitName
  7633. */
  7634. function api_warn_hosting_contact($limitName)
  7635. {
  7636. $hostingParams = api_get_configuration_value(1);
  7637. $email = null;
  7638. if (!empty($hostingParams)) {
  7639. if (isset($hostingParams['hosting_contact_mail'])) {
  7640. $email = $hostingParams['hosting_contact_mail'];
  7641. }
  7642. }
  7643. if (!empty($email)) {
  7644. $subject = get_lang('HostingWarningReached');
  7645. $body = get_lang('PortalName').': '.api_get_path(WEB_PATH)." \n ";
  7646. $body .= get_lang('PortalLimitType').': '.$limitName." \n ";
  7647. if (isset($hostingParams[$limitName])) {
  7648. $body .= get_lang('Value').': '.$hostingParams[$limitName];
  7649. }
  7650. api_mail_html(null, $email, $subject, $body);
  7651. }
  7652. }
  7653. /**
  7654. * Gets value of a variable from app/config/configuration.php
  7655. * Variables that are not set in the configuration.php file but set elsewhere:
  7656. * - virtual_css_theme_folder (vchamilo plugin)
  7657. * - access_url (global.inc.php)
  7658. * - apc/apc_prefix (global.inc.php).
  7659. *
  7660. * @param string $variable
  7661. *
  7662. * @return bool|mixed
  7663. */
  7664. function api_get_configuration_value($variable)
  7665. {
  7666. global $_configuration;
  7667. // Check the current url id, id = 1 by default
  7668. $urlId = isset($_configuration['access_url']) ? (int) $_configuration['access_url'] : 1;
  7669. $variable = trim($variable);
  7670. // Check if variable exists
  7671. if (isset($_configuration[$variable])) {
  7672. if (is_array($_configuration[$variable])) {
  7673. // Check if it exists for the sub portal
  7674. if (array_key_exists($urlId, $_configuration[$variable])) {
  7675. return $_configuration[$variable][$urlId];
  7676. } else {
  7677. // Try to found element with id = 1 (master portal)
  7678. if (array_key_exists(1, $_configuration[$variable])) {
  7679. return $_configuration[$variable][1];
  7680. }
  7681. }
  7682. }
  7683. return $_configuration[$variable];
  7684. }
  7685. return false;
  7686. }
  7687. /**
  7688. * Returns supported image extensions in the portal.
  7689. *
  7690. * @param bool $supportVectors Whether vector images should also be accepted or not
  7691. *
  7692. * @return array Supported image extensions in the portal
  7693. */
  7694. function api_get_supported_image_extensions($supportVectors = true)
  7695. {
  7696. // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
  7697. $supportedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif'];
  7698. if ($supportVectors) {
  7699. array_push($supportedImageExtensions, 'svg');
  7700. }
  7701. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  7702. array_push($supportedImageExtensions, 'webp');
  7703. }
  7704. return $supportedImageExtensions;
  7705. }
  7706. /**
  7707. * This setting changes the registration status for the campus.
  7708. *
  7709. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  7710. *
  7711. * @version August 2006
  7712. *
  7713. * @param bool $listCampus Whether we authorize
  7714. *
  7715. * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
  7716. */
  7717. function api_register_campus($listCampus = true)
  7718. {
  7719. $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  7720. $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
  7721. Database::query($sql);
  7722. if (!$listCampus) {
  7723. $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
  7724. Database::query($sql);
  7725. }
  7726. }
  7727. /**
  7728. * Checks whether current user is a student boss.
  7729. *
  7730. * @global array $_user
  7731. *
  7732. * @return bool
  7733. */
  7734. function api_is_student_boss()
  7735. {
  7736. $_user = api_get_user_info();
  7737. return isset($_user['status']) && $_user['status'] == STUDENT_BOSS;
  7738. }
  7739. /**
  7740. * Check whether the user type should be exclude.
  7741. * Such as invited or anonymous users.
  7742. *
  7743. * @param bool $checkDB Optional. Whether check the user status
  7744. * @param int $userId Options. The user id
  7745. *
  7746. * @return bool
  7747. */
  7748. function api_is_excluded_user_type($checkDB = false, $userId = 0)
  7749. {
  7750. if ($checkDB) {
  7751. $userId = empty($userId) ? api_get_user_id() : (int) $userId;
  7752. if ($userId == 0) {
  7753. return true;
  7754. }
  7755. $userInfo = api_get_user_info($userId);
  7756. switch ($userInfo['status']) {
  7757. case INVITEE:
  7758. case ANONYMOUS:
  7759. return true;
  7760. default:
  7761. return false;
  7762. }
  7763. }
  7764. $isInvited = api_is_invitee();
  7765. $isAnonymous = api_is_anonymous();
  7766. if ($isInvited || $isAnonymous) {
  7767. return true;
  7768. }
  7769. return false;
  7770. }
  7771. /**
  7772. * Get the user status to ignore in reports.
  7773. *
  7774. * @param string $format Optional. The result type (array or string)
  7775. *
  7776. * @return array|string
  7777. */
  7778. function api_get_users_status_ignored_in_reports($format = 'array')
  7779. {
  7780. $excludedTypes = [
  7781. INVITEE,
  7782. ANONYMOUS,
  7783. ];
  7784. if ($format == 'string') {
  7785. return implode(', ', $excludedTypes);
  7786. }
  7787. return $excludedTypes;
  7788. }
  7789. /**
  7790. * Set the Site Use Cookie Warning for 1 year.
  7791. */
  7792. function api_set_site_use_cookie_warning_cookie()
  7793. {
  7794. setcookie('ChamiloUsesCookies', 'ok', time() + 31556926);
  7795. }
  7796. /**
  7797. * Return true if the Site Use Cookie Warning Cookie warning exists.
  7798. *
  7799. * @return bool
  7800. */
  7801. function api_site_use_cookie_warning_cookie_exist()
  7802. {
  7803. return isset($_COOKIE['ChamiloUsesCookies']);
  7804. }
  7805. /**
  7806. * Given a number of seconds, format the time to show hours, minutes and seconds.
  7807. *
  7808. * @param int $time The time in seconds
  7809. * @param string $originFormat Optional. PHP o JS
  7810. *
  7811. * @return string (00h00'00")
  7812. */
  7813. function api_format_time($time, $originFormat = 'php')
  7814. {
  7815. $h = get_lang('h');
  7816. $hours = $time / 3600;
  7817. $mins = ($time % 3600) / 60;
  7818. $secs = ($time % 60);
  7819. if ($time < 0) {
  7820. $hours = 0;
  7821. $mins = 0;
  7822. $secs = 0;
  7823. }
  7824. if ($originFormat == 'js') {
  7825. $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
  7826. } else {
  7827. $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
  7828. }
  7829. return $formattedTime;
  7830. }
  7831. /**
  7832. * Create a new empty directory with index.html file.
  7833. *
  7834. * @param string $name The new directory name
  7835. * @param string $parentDirectory Directory parent directory name
  7836. *
  7837. * @return bool Return true if the directory was create. Otherwise return false
  7838. */
  7839. function api_create_protected_dir($name, $parentDirectory)
  7840. {
  7841. $isCreated = false;
  7842. if (!is_writable($parentDirectory)) {
  7843. return false;
  7844. }
  7845. $fullPath = $parentDirectory.api_replace_dangerous_char($name);
  7846. if (mkdir($fullPath, api_get_permissions_for_new_directories(), true)) {
  7847. $fp = fopen($fullPath.'/index.html', 'w');
  7848. if ($fp) {
  7849. if (fwrite($fp, '<html><head></head><body></body></html>')) {
  7850. $isCreated = true;
  7851. }
  7852. }
  7853. fclose($fp);
  7854. }
  7855. return $isCreated;
  7856. }
  7857. /**
  7858. * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
  7859. * Sender name and email can be specified, if not specified
  7860. * name and email of the platform admin are used.
  7861. *
  7862. * @author Bert Vanderkimpen ICT&O UGent
  7863. * @author Yannick Warnier <yannick.warnier@beeznest.com>
  7864. *
  7865. * @param string name of recipient
  7866. * @param string email of recipient
  7867. * @param string email subject
  7868. * @param string email body
  7869. * @param string sender name
  7870. * @param string sender e-mail
  7871. * @param array $extra_headers in form $headers = array($name => $value) to allow parsing
  7872. * @param array $data_file (path and filename)
  7873. * @param bool $embedded_image True for attaching a embedded file inside content html (optional)
  7874. * @param array $additionalParameters
  7875. * @param string $sendErrorTo If there's an error while sending the email, $sendErrorTo will receive a notification
  7876. *
  7877. * @return int true if mail was sent
  7878. *
  7879. * @see class.phpmailer.php
  7880. */
  7881. function api_mail_html(
  7882. $recipient_name,
  7883. $recipient_email,
  7884. $subject,
  7885. $message,
  7886. $senderName = '',
  7887. $senderEmail = '',
  7888. $extra_headers = [],
  7889. $data_file = [],
  7890. $embedded_image = false,
  7891. $additionalParameters = [],
  7892. $sendErrorTo = ''
  7893. ) {
  7894. global $platform_email;
  7895. $mail = new PHPMailer();
  7896. $mail->Mailer = $platform_email['SMTP_MAILER'];
  7897. $mail->Host = $platform_email['SMTP_HOST'];
  7898. $mail->Port = $platform_email['SMTP_PORT'];
  7899. $mail->CharSet = isset($platform_email['SMTP_CHARSET']) ? $platform_email['SMTP_CHARSET'] : 'UTF-8';
  7900. // Stay far below SMTP protocol 980 chars limit.
  7901. $mail->WordWrap = 200;
  7902. if ($platform_email['SMTP_AUTH']) {
  7903. $mail->SMTPAuth = 1;
  7904. $mail->Username = $platform_email['SMTP_USER'];
  7905. $mail->Password = $platform_email['SMTP_PASS'];
  7906. if (isset($platform_email['SMTP_SECURE'])) {
  7907. $mail->SMTPSecure = $platform_email['SMTP_SECURE'];
  7908. }
  7909. }
  7910. $mail->SMTPDebug = isset($platform_email['SMTP_DEBUG']) ? $platform_email['SMTP_DEBUG'] : 0;
  7911. // 5 = low, 1 = high
  7912. $mail->Priority = 3;
  7913. $mail->SMTPKeepAlive = true;
  7914. api_set_noreply_and_from_address_to_mailer(
  7915. $mail,
  7916. ['name' => $senderName, 'email' => $senderEmail],
  7917. !empty($extra_headers['reply_to']) ? $extra_headers['reply_to'] : []
  7918. );
  7919. if (!empty($sendErrorTo) && PHPMailer::ValidateAddress($sendErrorTo)) {
  7920. $mail->AddCustomHeader('Errors-To: '.$sendErrorTo);
  7921. }
  7922. unset($extra_headers['reply_to']);
  7923. $mail->Subject = $subject;
  7924. $mail->AltBody = strip_tags(
  7925. str_replace('<br />', "\n", api_html_entity_decode($message))
  7926. );
  7927. $list = api_get_configuration_value('send_all_emails_to');
  7928. if (!empty($list) && isset($list['emails'])) {
  7929. foreach ($list['emails'] as $email) {
  7930. $mail->AddAddress($email);
  7931. }
  7932. }
  7933. // Send embedded image.
  7934. if ($embedded_image) {
  7935. // Get all images html inside content.
  7936. preg_match_all("/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i", $message, $m);
  7937. // Prepare new tag images.
  7938. $new_images_html = [];
  7939. $i = 1;
  7940. if (!empty($m[1])) {
  7941. foreach ($m[1] as $image_path) {
  7942. $real_path = realpath($image_path);
  7943. $filename = basename($image_path);
  7944. $image_cid = $filename.'_'.$i;
  7945. $encoding = 'base64';
  7946. $image_type = mime_content_type($real_path);
  7947. $mail->AddEmbeddedImage(
  7948. $real_path,
  7949. $image_cid,
  7950. $filename,
  7951. $encoding,
  7952. $image_type
  7953. );
  7954. $new_images_html[] = '<img src="cid:'.$image_cid.'" />';
  7955. $i++;
  7956. }
  7957. }
  7958. // Replace origin image for new embedded image html.
  7959. $x = 0;
  7960. if (!empty($m[0])) {
  7961. foreach ($m[0] as $orig_img) {
  7962. $message = str_replace($orig_img, $new_images_html[$x], $message);
  7963. $x++;
  7964. }
  7965. }
  7966. }
  7967. $mailView = new Template(null, false, false, false, false, false, false);
  7968. $noReply = api_get_setting('noreply_email_address');
  7969. if (!empty($noReply)) {
  7970. $message .= '<br />'.get_lang('ThisIsAutomaticEmailNoReply');
  7971. }
  7972. $mailView->assign('content', $message);
  7973. if (isset($additionalParameters['link'])) {
  7974. $mailView->assign('link', $additionalParameters['link']);
  7975. }
  7976. $mailView->assign('mail_header_style', api_get_configuration_value('mail_header_style'));
  7977. $mailView->assign('mail_content_style', api_get_configuration_value('mail_content_style'));
  7978. $layout = $mailView->get_template('mail/mail.tpl');
  7979. $mail->Body = $mailView->fetch($layout);
  7980. // Attachment.
  7981. if (!empty($data_file)) {
  7982. foreach ($data_file as $file_attach) {
  7983. if (!empty($file_attach['path']) && !empty($file_attach['filename'])) {
  7984. $mail->AddAttachment($file_attach['path'], $file_attach['filename']);
  7985. }
  7986. }
  7987. }
  7988. // Only valid addresses are accepted.
  7989. if (is_array($recipient_email)) {
  7990. foreach ($recipient_email as $dest) {
  7991. if (api_valid_email($dest)) {
  7992. $mail->AddAddress($dest, $recipient_name);
  7993. }
  7994. }
  7995. } else {
  7996. if (api_valid_email($recipient_email)) {
  7997. $mail->AddAddress($recipient_email, $recipient_name);
  7998. } else {
  7999. return 0;
  8000. }
  8001. }
  8002. if (is_array($extra_headers) && count($extra_headers) > 0) {
  8003. foreach ($extra_headers as $key => $value) {
  8004. switch (strtolower($key)) {
  8005. case 'encoding':
  8006. case 'content-transfer-encoding':
  8007. $mail->Encoding = $value;
  8008. break;
  8009. case 'charset':
  8010. $mail->Charset = $value;
  8011. break;
  8012. case 'contenttype':
  8013. case 'content-type':
  8014. $mail->ContentType = $value;
  8015. break;
  8016. default:
  8017. $mail->AddCustomHeader($key.':'.$value);
  8018. break;
  8019. }
  8020. }
  8021. } else {
  8022. if (!empty($extra_headers)) {
  8023. $mail->AddCustomHeader($extra_headers);
  8024. }
  8025. }
  8026. // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
  8027. $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
  8028. // Send the mail message.
  8029. if (!$mail->Send()) {
  8030. error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'<br />');
  8031. if ($mail->SMTPDebug) {
  8032. error_log(
  8033. "Connection details :: ".
  8034. "Protocol: ".$mail->Mailer.' :: '.
  8035. "Host/Port: ".$mail->Host.':'.$mail->Port.' :: '.
  8036. "Authent/Open: ".($mail->SMTPAuth ? 'Authent' : 'Open').' :: '.
  8037. ($mail->SMTPAuth ? " User/Pass: ".$mail->Username.':'.$mail->Password : '').' :: '.
  8038. "Sender: ".$mail->Sender
  8039. );
  8040. }
  8041. return 0;
  8042. }
  8043. if (!empty($additionalParameters)) {
  8044. $plugin = new AppPlugin();
  8045. $smsPlugin = $plugin->getSMSPluginLibrary();
  8046. if ($smsPlugin) {
  8047. $smsPlugin->send($additionalParameters);
  8048. }
  8049. }
  8050. // Clear all the addresses.
  8051. $mail->ClearAddresses();
  8052. // Clear all attachments
  8053. $mail->ClearAttachments();
  8054. return 1;
  8055. }
  8056. /**
  8057. * @param string $tool Possible values: GroupManager::GROUP_TOOL_*
  8058. * @param bool $showHeader
  8059. */
  8060. function api_protect_course_group($tool, $showHeader = true)
  8061. {
  8062. $groupId = api_get_group_id();
  8063. if (!empty($groupId)) {
  8064. if (api_is_platform_admin()) {
  8065. return true;
  8066. }
  8067. if (api_is_allowed_to_edit(false, true, true)) {
  8068. return true;
  8069. }
  8070. $userId = api_get_user_id();
  8071. $sessionId = api_get_session_id();
  8072. if (!empty($sessionId)) {
  8073. if (api_is_coach($sessionId, api_get_course_int_id())) {
  8074. return true;
  8075. }
  8076. if (api_is_drh()) {
  8077. if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
  8078. return true;
  8079. }
  8080. }
  8081. }
  8082. $groupInfo = GroupManager::get_group_properties($groupId);
  8083. // Group doesn't exists
  8084. if (empty($groupInfo)) {
  8085. api_not_allowed($showHeader);
  8086. }
  8087. // Check group access
  8088. $allow = GroupManager::user_has_access(
  8089. $userId,
  8090. $groupInfo['iid'],
  8091. $tool
  8092. );
  8093. if (!$allow) {
  8094. api_not_allowed($showHeader);
  8095. }
  8096. }
  8097. }
  8098. /**
  8099. * Check if a date is in a date range.
  8100. *
  8101. * @param datetime $startDate
  8102. * @param datetime $endDate
  8103. * @param datetime $currentDate
  8104. *
  8105. * @return bool true if date is in rage, false otherwise
  8106. */
  8107. function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
  8108. {
  8109. $startDate = strtotime(api_get_local_time($startDate));
  8110. $endDate = strtotime(api_get_local_time($endDate));
  8111. $currentDate = strtotime(api_get_local_time($currentDate));
  8112. if ($currentDate >= $startDate && $currentDate <= $endDate) {
  8113. return true;
  8114. }
  8115. return false;
  8116. }
  8117. /**
  8118. * Eliminate the duplicates of a multidimensional array by sending the key.
  8119. *
  8120. * @param array $array multidimensional array
  8121. * @param int $key key to find to compare
  8122. *
  8123. * @return array
  8124. */
  8125. function api_unique_multidim_array($array, $key)
  8126. {
  8127. $temp_array = [];
  8128. $i = 0;
  8129. $key_array = [];
  8130. foreach ($array as $val) {
  8131. if (!in_array($val[$key], $key_array)) {
  8132. $key_array[$i] = $val[$key];
  8133. $temp_array[$i] = $val;
  8134. }
  8135. $i++;
  8136. }
  8137. return $temp_array;
  8138. }
  8139. /**
  8140. * Limit the access to Session Admins when the limit_session_admin_role
  8141. * configuration variable is set to true.
  8142. */
  8143. function api_protect_limit_for_session_admin()
  8144. {
  8145. $limitAdmin = api_get_setting('limit_session_admin_role');
  8146. if (api_is_session_admin() && $limitAdmin === 'true') {
  8147. api_not_allowed(true);
  8148. }
  8149. }
  8150. /**
  8151. * Limits that a session admin has access to list users.
  8152. * When limit_session_admin_list_users configuration variable is set to true.
  8153. */
  8154. function api_protect_session_admin_list_users()
  8155. {
  8156. $limitAdmin = api_get_configuration_value('limit_session_admin_list_users');
  8157. if (api_is_session_admin() && true === $limitAdmin) {
  8158. api_not_allowed(true);
  8159. }
  8160. }
  8161. /**
  8162. * @return bool
  8163. */
  8164. function api_is_student_view_active()
  8165. {
  8166. $studentView = Session::read('studentview');
  8167. return $studentView == 'studentview';
  8168. }
  8169. /**
  8170. * Adds a file inside the upload/$type/id.
  8171. *
  8172. * @param string $type
  8173. * @param array $file
  8174. * @param int $itemId
  8175. * @param string $cropParameters
  8176. *
  8177. * @return array|bool
  8178. */
  8179. function api_upload_file($type, $file, $itemId, $cropParameters = '')
  8180. {
  8181. $upload = process_uploaded_file($file);
  8182. if ($upload) {
  8183. $name = api_replace_dangerous_char($file['name']);
  8184. // No "dangerous" files
  8185. $name = disable_dangerous_file($name);
  8186. $pathId = '/'.substr((string) $itemId, 0, 1).'/'.$itemId.'/';
  8187. $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
  8188. if (!is_dir($path)) {
  8189. mkdir($path, api_get_permissions_for_new_directories(), true);
  8190. }
  8191. $pathToSave = $path.$name;
  8192. $result = moveUploadedFile($file, $pathToSave);
  8193. if ($result) {
  8194. if (!empty($cropParameters)) {
  8195. $image = new Image($pathToSave);
  8196. $image->crop($cropParameters);
  8197. }
  8198. return ['path_to_save' => $pathId.$name];
  8199. }
  8200. return false;
  8201. }
  8202. }
  8203. /**
  8204. * @param string $type
  8205. * @param int $itemId
  8206. * @param string $file
  8207. *
  8208. * @return bool
  8209. */
  8210. function api_get_uploaded_web_url($type, $itemId, $file)
  8211. {
  8212. return api_get_uploaded_file($type, $itemId, $file, true);
  8213. }
  8214. /**
  8215. * @param string $type
  8216. * @param int $itemId
  8217. * @param string $file
  8218. * @param bool $getUrl
  8219. *
  8220. * @return bool
  8221. */
  8222. function api_get_uploaded_file($type, $itemId, $file, $getUrl = false)
  8223. {
  8224. $itemId = (int) $itemId;
  8225. $pathId = '/'.substr((string) $itemId, 0, 1).'/'.$itemId.'/';
  8226. $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
  8227. $file = basename($file);
  8228. $file = $path.'/'.$file;
  8229. if (Security::check_abs_path($file, $path) && is_file($file) && file_exists($file)) {
  8230. if ($getUrl) {
  8231. return str_replace(api_get_path(SYS_UPLOAD_PATH), api_get_path(WEB_UPLOAD_PATH), $file);
  8232. }
  8233. return $file;
  8234. }
  8235. return false;
  8236. }
  8237. /**
  8238. * @param string $type
  8239. * @param int $itemId
  8240. * @param string $file
  8241. * @param string $title
  8242. */
  8243. function api_download_uploaded_file($type, $itemId, $file, $title = '')
  8244. {
  8245. $file = api_get_uploaded_file($type, $itemId, $file);
  8246. if ($file) {
  8247. if (Security::check_abs_path($file, api_get_path(SYS_UPLOAD_PATH).$type)) {
  8248. DocumentManager::file_send_for_download($file, true, $title);
  8249. exit;
  8250. }
  8251. }
  8252. api_not_allowed(true);
  8253. }
  8254. /**
  8255. * @param string $type
  8256. * @param string $file
  8257. */
  8258. function api_remove_uploaded_file($type, $file)
  8259. {
  8260. $typePath = api_get_path(SYS_UPLOAD_PATH).$type;
  8261. $path = $typePath.'/'.$file;
  8262. if (Security::check_abs_path($path, $typePath) && file_exists($path) && is_file($path)) {
  8263. unlink($path);
  8264. }
  8265. }
  8266. /**
  8267. * @param string $type
  8268. * @param int $itemId
  8269. * @param string $file
  8270. *
  8271. * @return bool
  8272. */
  8273. function api_remove_uploaded_file_by_id($type, $itemId, $file)
  8274. {
  8275. $file = api_get_uploaded_file($type, $itemId, $file, false);
  8276. $typePath = api_get_path(SYS_UPLOAD_PATH).$type;
  8277. if (Security::check_abs_path($file, $typePath) && file_exists($file) && is_file($file)) {
  8278. unlink($file);
  8279. return true;
  8280. }
  8281. return false;
  8282. }
  8283. /**
  8284. * Converts string value to float value.
  8285. *
  8286. * 3.141516 => 3.141516
  8287. * 3,141516 => 3.141516
  8288. *
  8289. * @todo WIP
  8290. *
  8291. * @param string $number
  8292. *
  8293. * @return float
  8294. */
  8295. function api_float_val($number)
  8296. {
  8297. $number = (float) str_replace(',', '.', trim($number));
  8298. return $number;
  8299. }
  8300. /**
  8301. * Converts float values
  8302. * Example if $decimals = 2.
  8303. *
  8304. * 3.141516 => 3.14
  8305. * 3,141516 => 3,14
  8306. *
  8307. * @param string $number number in iso code
  8308. * @param int $decimals
  8309. * @param string $decimalSeparator
  8310. * @param string $thousandSeparator
  8311. *
  8312. * @return bool|string
  8313. */
  8314. function api_number_format($number, $decimals = 0, $decimalSeparator = '.', $thousandSeparator = ',')
  8315. {
  8316. $number = api_float_val($number);
  8317. return number_format($number, $decimals, $decimalSeparator, $thousandSeparator);
  8318. }
  8319. /**
  8320. * Set location url with a exit break by default.
  8321. *
  8322. * @param $url
  8323. * @param bool $exit
  8324. */
  8325. function location($url, $exit = true)
  8326. {
  8327. header('Location: '.$url);
  8328. if ($exit) {
  8329. exit;
  8330. }
  8331. }
  8332. /**
  8333. * @return string
  8334. */
  8335. function api_get_web_url()
  8336. {
  8337. if (api_get_setting('server_type') === 'test') {
  8338. return api_get_path(WEB_PATH).'web/app_dev.php/';
  8339. } else {
  8340. return api_get_path(WEB_PATH).'web/';
  8341. }
  8342. }
  8343. /**
  8344. * @param string $from
  8345. * @param string $to
  8346. *
  8347. * @return string
  8348. */
  8349. function api_get_relative_path($from, $to)
  8350. {
  8351. // some compatibility fixes for Windows paths
  8352. $from = is_dir($from) ? rtrim($from, '\/').'/' : $from;
  8353. $to = is_dir($to) ? rtrim($to, '\/').'/' : $to;
  8354. $from = str_replace('\\', '/', $from);
  8355. $to = str_replace('\\', '/', $to);
  8356. $from = explode('/', $from);
  8357. $to = explode('/', $to);
  8358. $relPath = $to;
  8359. foreach ($from as $depth => $dir) {
  8360. // find first non-matching dir
  8361. if ($dir === $to[$depth]) {
  8362. // ignore this directory
  8363. array_shift($relPath);
  8364. } else {
  8365. // get number of remaining dirs to $from
  8366. $remaining = count($from) - $depth;
  8367. if ($remaining > 1) {
  8368. // add traversals up to first matching dir
  8369. $padLength = (count($relPath) + $remaining - 1) * -1;
  8370. $relPath = array_pad($relPath, $padLength, '..');
  8371. break;
  8372. } else {
  8373. $relPath[0] = './'.$relPath[0];
  8374. }
  8375. }
  8376. }
  8377. return implode('/', $relPath);
  8378. }
  8379. /**
  8380. * Unserialize content using Brummann\Polyfill\Unserialize.
  8381. *
  8382. * @param string $type
  8383. * @param string $serialized
  8384. * @param bool $ignoreErrors. Optional.
  8385. *
  8386. * @return mixed
  8387. */
  8388. function api_unserialize_content($type, $serialized, $ignoreErrors = false)
  8389. {
  8390. switch ($type) {
  8391. case 'career':
  8392. case 'sequence_graph':
  8393. $allowedClasses = [Graph::class, VerticesMap::class, Vertices::class, Edges::class];
  8394. break;
  8395. case 'lp':
  8396. $allowedClasses = [
  8397. learnpath::class,
  8398. learnpathItem::class,
  8399. aicc::class,
  8400. aiccBlock::class,
  8401. aiccItem::class,
  8402. aiccObjective::class,
  8403. aiccResource::class,
  8404. scorm::class,
  8405. scormItem::class,
  8406. scormMetadata::class,
  8407. scormOrganization::class,
  8408. scormResource::class,
  8409. Link::class,
  8410. LpItem::class,
  8411. ];
  8412. break;
  8413. case 'course':
  8414. $allowedClasses = [
  8415. Course::class,
  8416. Announcement::class,
  8417. Attendance::class,
  8418. CalendarEvent::class,
  8419. CourseCopyLearnpath::class,
  8420. CourseCopyTestCategory::class,
  8421. CourseDescription::class,
  8422. CourseSession::class,
  8423. Document::class,
  8424. Forum::class,
  8425. ForumCategory::class,
  8426. ForumPost::class,
  8427. ForumTopic::class,
  8428. Glossary::class,
  8429. GradeBookBackup::class,
  8430. Link::class,
  8431. LinkCategory::class,
  8432. Quiz::class,
  8433. QuizQuestion::class,
  8434. QuizQuestionOption::class,
  8435. ScormDocument::class,
  8436. Survey::class,
  8437. SurveyInvitation::class,
  8438. SurveyQuestion::class,
  8439. Thematic::class,
  8440. ToolIntro::class,
  8441. Wiki::class,
  8442. Work::class,
  8443. stdClass::class,
  8444. ];
  8445. break;
  8446. case 'not_allowed_classes':
  8447. default:
  8448. $allowedClasses = false;
  8449. }
  8450. if ($ignoreErrors) {
  8451. return @Unserialize::unserialize(
  8452. $serialized,
  8453. ['allowed_classes' => $allowedClasses]
  8454. );
  8455. }
  8456. return Unserialize::unserialize(
  8457. $serialized,
  8458. ['allowed_classes' => $allowedClasses]
  8459. );
  8460. }
  8461. /**
  8462. * Set the From and ReplyTo properties to PHPMailer instance.
  8463. *
  8464. * @param PHPMailer $mailer
  8465. * @param array $sender
  8466. * @param array $replyToAddress
  8467. *
  8468. * @throws phpmailerException
  8469. */
  8470. function api_set_noreply_and_from_address_to_mailer(PHPMailer $mailer, array $sender, array $replyToAddress = [])
  8471. {
  8472. $platformEmail = $GLOBALS['platform_email'];
  8473. $noReplyAddress = api_get_setting('noreply_email_address');
  8474. $avoidReplyToAddress = false;
  8475. if (!empty($noReplyAddress)) {
  8476. $avoidReplyToAddress = api_get_configuration_value('mail_no_reply_avoid_reply_to');
  8477. }
  8478. $notification = new Notification();
  8479. // If the parameter is set don't use the admin.
  8480. $senderName = !empty($sender['name']) ? $sender['name'] : $notification->getDefaultPlatformSenderName();
  8481. $senderEmail = !empty($sender['email']) ? $sender['email'] : $notification->getDefaultPlatformSenderEmail();
  8482. // Send errors to the platform admin
  8483. $adminEmail = api_get_setting('emailAdministrator');
  8484. if (PHPMailer::ValidateAddress($adminEmail)) {
  8485. $mailer->AddCustomHeader('Errors-To: '.$adminEmail);
  8486. }
  8487. // Reply to first
  8488. if (!$avoidReplyToAddress) {
  8489. if (
  8490. !empty($replyToAddress) &&
  8491. isset($platformEmail['SMTP_UNIQUE_REPLY_TO']) && $platformEmail['SMTP_UNIQUE_REPLY_TO'] &&
  8492. PHPMailer::ValidateAddress($replyToAddress['mail'])
  8493. ) {
  8494. $mailer->AddReplyTo($replyToAddress['email'], $replyToAddress['name']);
  8495. $mailer->Sender = $replyToAddress['mail'];
  8496. }
  8497. }
  8498. //If the SMTP configuration only accept one sender
  8499. if (
  8500. isset($platformEmail['SMTP_UNIQUE_SENDER']) &&
  8501. $platformEmail['SMTP_UNIQUE_SENDER']
  8502. ) {
  8503. $senderName = $platformEmail['SMTP_FROM_NAME'];
  8504. $senderEmail = $platformEmail['SMTP_FROM_EMAIL'];
  8505. if (PHPMailer::ValidateAddress($senderEmail)) {
  8506. //force-set Sender to $senderEmail, otherwise SetFrom only does it if it is currently empty
  8507. $mailer->Sender = $senderEmail;
  8508. }
  8509. }
  8510. $mailer->SetFrom($senderEmail, $senderName, !$avoidReplyToAddress);
  8511. }
  8512. /**
  8513. * @param string $template
  8514. *
  8515. * @return string
  8516. */
  8517. function api_find_template($template)
  8518. {
  8519. return Template::findTemplateFilePath($template);
  8520. }
  8521. /**
  8522. * @return array
  8523. */
  8524. function api_get_language_list_for_flag()
  8525. {
  8526. $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
  8527. $sql = "SELECT english_name, isocode FROM $table
  8528. ORDER BY original_name ASC";
  8529. static $languages = [];
  8530. if (empty($languages)) {
  8531. $result = Database::query($sql);
  8532. while ($row = Database::fetch_array($result)) {
  8533. $languages[$row['english_name']] = $row['isocode'];
  8534. }
  8535. $languages['english'] = 'gb';
  8536. }
  8537. return $languages;
  8538. }
  8539. /**
  8540. * @return string
  8541. */
  8542. function api_get_language_translate_html()
  8543. {
  8544. $translate = api_get_configuration_value('translate_html');
  8545. if (!$translate) {
  8546. return '';
  8547. }
  8548. $languageList = api_get_languages();
  8549. $hideAll = '';
  8550. foreach ($languageList['all'] as $language) {
  8551. $hideAll .= '
  8552. $("span:lang('.$language['isocode'].')").filter(
  8553. function(e, val) {
  8554. // Only find the spans if they have set the lang
  8555. if ($(this).attr("lang") == null) {
  8556. return false;
  8557. }
  8558. // Ignore ckeditor classes
  8559. return !this.className.match(/cke(.*)/);
  8560. }).hide();'."\n";
  8561. }
  8562. $userInfo = api_get_user_info();
  8563. $languageId = api_get_language_id($userInfo['language']);
  8564. $languageInfo = api_get_language_info($languageId);
  8565. $isoCode = 'en';
  8566. if (!empty($languageInfo)) {
  8567. $isoCode = $languageInfo['isocode'];
  8568. }
  8569. return '
  8570. $(function() {
  8571. '.$hideAll.'
  8572. var defaultLanguageFromUser = "'.$isoCode.'";
  8573. $("span:lang('.$isoCode.')").filter(
  8574. function() {
  8575. // Ignore ckeditor classes
  8576. return !this.className.match(/cke(.*)/);
  8577. }).show();
  8578. var defaultLanguage = "";
  8579. var langFromUserFound = false;
  8580. $(this).find("span").filter(
  8581. function() {
  8582. // Ignore ckeditor classes
  8583. return !this.className.match(/cke(.*)/);
  8584. }).each(function() {
  8585. defaultLanguage = $(this).attr("lang");
  8586. if (defaultLanguage) {
  8587. $(this).before().next("br").remove();
  8588. if (defaultLanguageFromUser == defaultLanguage) {
  8589. langFromUserFound = true;
  8590. }
  8591. }
  8592. });
  8593. // Show default language
  8594. if (langFromUserFound == false && defaultLanguage) {
  8595. $("span:lang("+defaultLanguage+")").filter(
  8596. function() {
  8597. // Ignore ckeditor classes
  8598. return !this.className.match(/cke(.*)/);
  8599. }).show();
  8600. }
  8601. });
  8602. ';
  8603. }