api.lib.php 294 KB

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