organizr.class.php 255 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934
  1. <?php
  2. use Dibi\Connection;
  3. class Organizr
  4. {
  5. // Use Custom Functions From Traits;
  6. use TwoFAFunctions;
  7. use ApiFunctions;
  8. use AuthFunctions;
  9. use BackupFunctions;
  10. use ConfigFunctions;
  11. use DemoFunctions;
  12. use HomepageConnectFunctions;
  13. use HomepageFunctions;
  14. use LogFunctions;
  15. use NetDataFunctions;
  16. use NormalFunctions;
  17. use OAuthFunctions;
  18. use OptionsFunction;
  19. use OrganizrFunctions;
  20. use PluginFunctions;
  21. use StaticFunctions;
  22. use SSOFunctions;
  23. use TokenFunctions;
  24. use UpdateFunctions;
  25. use UpgradeFunctions;
  26. // Use homepage item functions
  27. use BookmarksHomepageItem;
  28. use CalendarHomepageItem;
  29. use CouchPotatoHomepageItem;
  30. use DelugeHomepageItem;
  31. use DonateHomepageItem;
  32. use EmbyHomepageItem;
  33. use HealthChecksHomepageItem;
  34. use HTMLHomepageItem;
  35. use ICalHomepageItem;
  36. use JackettHomepageItem;
  37. use ProwlarrHomepageItem;
  38. use JDownloaderHomepageItem;
  39. use JellyfinHomepageItem;
  40. use LidarrHomepageItem;
  41. use MiscHomepageItem;
  42. use MonitorrHomepageItem;
  43. use NetDataHomepageItem;
  44. use NZBGetHomepageItem;
  45. use OctoPrintHomepageItem;
  46. use OmbiHomepageItem;
  47. use OverseerrHomepageItem;
  48. use PiHoleHomepageItem;
  49. use AdGuardHomepageItem;
  50. use PlexHomepageItem;
  51. use QBitTorrentHomepageItem;
  52. use RadarrHomepageItem;
  53. use RTorrentHomepageItem;
  54. use SabNZBdHomepageItem;
  55. use SickRageHomepageItem;
  56. use SonarrHomepageItem;
  57. use SpeedTestHomepageItem;
  58. use TautulliHomepageItem;
  59. use TraktHomepageItem;
  60. use TransmissionHomepageItem;
  61. use UnifiHomepageItem;
  62. use WeatherHomepageItem;
  63. use uTorrentHomepageItem;
  64. use UptimeKumaHomepageItem;
  65. use PromPageHomepageItem;
  66. // ===================================
  67. // Organizr Version
  68. public $version = '2.1.2490';
  69. // ===================================
  70. // Quick php Version check
  71. public $minimumPHP = '7.4';
  72. // ===================================
  73. protected $db;
  74. protected $otherDb;
  75. public $config;
  76. public $user;
  77. public $userConfigPath;
  78. public $defaultConfigPath;
  79. public $currentTime;
  80. public $docker;
  81. public $dev;
  82. public $demo;
  83. public $commit;
  84. public $fileHash;
  85. public $cookieName;
  86. public $logFile;
  87. public $timeExecution;
  88. public $root;
  89. public $paths;
  90. public $checkForUpdates;
  91. public $groupOptions;
  92. public $warnings;
  93. public $errors;
  94. public bool $loggerSetup = false;
  95. public \Nekonomokochan\PhpJsonLogger\Logger $logger;
  96. public function __construct($checkForUpdates = false)
  97. {
  98. // Constructed from Updater?
  99. $this->checkForUpdates = $checkForUpdates;
  100. // Set Project Root directory and paths
  101. $this->root = dirname(__DIR__, 2);
  102. $this->paths = [
  103. 'Root Folder' => $this->root . DIRECTORY_SEPARATOR,
  104. 'Cache Folder' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR,
  105. 'Tab Folder' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR,
  106. 'API Folder' => dirname(__DIR__, 1) . DIRECTORY_SEPARATOR
  107. ];
  108. // Temp Set Errors
  109. $this->errors = E_ERROR;//E_ALL & ~E_NOTICE
  110. // Set current time
  111. $this->currentTime = gmdate('Y-m-d\TH:i:s\Z');
  112. // Set variable if install is for official docker
  113. $this->docker = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Docker.txt'));
  114. // Set variable if install is for develop and set php Error levels
  115. $this->dev = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Dev.txt'));
  116. // Set variable if install is for demo
  117. $this->demo = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Demo.txt'));
  118. // Set variable if install has commit hash and variable to be used as hash for files
  119. $this->commit = ($this->docker && !$this->dev) ? file_get_contents(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Github.txt') : null;
  120. $this->fileHash = ($this->commit) ?? $this->version;
  121. $this->fileHash = trim($this->fileHash);
  122. // Set location path to user config path
  123. $this->chooseConfigFile();
  124. // Set location path to default config path
  125. $this->defaultConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'default.php';
  126. // Load Config file
  127. $this->config = $this->config();
  128. // Set cookie name for Organizr Instance
  129. $this->cookieName = ($this->hasConfig()) ? $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp' : 'organizr_token_temp';
  130. // Set custom Error handler
  131. set_error_handler([$this, 'setAPIErrorResponse'], $this->errors);
  132. // Next Check PHP Version
  133. $this->checkPHP();
  134. // Check Disk Space
  135. $this->checkDiskSpace();
  136. // Set UUID for device
  137. $this->setDeviceUUID();
  138. // Add Plugin prefix to plugin global
  139. $this->setPluginListNameFromConfigPrefix();
  140. // Add database path to paths
  141. $this->addDatabaseToPaths();
  142. // Set Start Execution Time
  143. $this->timeExecution = $this->timeExecution();
  144. $this->phpErrors();
  145. // Set organizr Logs and logger
  146. $this->logFile = $this->setOrganizrLog();
  147. $this->setLoggerChannel();
  148. // Connect to DB
  149. $this->connectDB();
  150. // Check DB Writable
  151. $this->checkWritableDB();
  152. // Get token form cookie and validate
  153. $this->setCurrentUser();
  154. // might just run this at index
  155. $this->upgradeCheck();
  156. // Is Page load Organizr OAuth?
  157. $this->checkForOrganizrOAuth();
  158. // Is user Blacklisted?
  159. $this->checkIfUserIsBlacklisted();
  160. }
  161. public function __destruct()
  162. {
  163. $this->disconnectDB();
  164. }
  165. public function addDatabaseToPaths()
  166. {
  167. if ($this->hasConfig()) {
  168. $this->paths = array_merge($this->paths, ['DB Folder' => $this->config['dbLocation']]);
  169. }
  170. }
  171. public function chooseConfigFile()
  172. {
  173. $oldUserConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
  174. $userConfigPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
  175. if (file_exists($userConfigPath) && file_exists($oldUserConfigPath)) {
  176. $this->userConfigPath = $userConfigPath;
  177. } elseif (file_exists($oldUserConfigPath)) {
  178. $this->makeDir(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR);
  179. if ($this->rcopy($oldUserConfigPath, $userConfigPath)) {
  180. $this->userConfigPath = $userConfigPath;
  181. @unlink($oldUserConfigPath);
  182. } else {
  183. $this->userConfigPath = $oldUserConfigPath;
  184. }
  185. } else {
  186. $this->userConfigPath = $userConfigPath;
  187. }
  188. }
  189. public function hasConfig()
  190. {
  191. return (file_exists($this->userConfigPath)) ?? false;
  192. }
  193. public function hasDatabase($file = null)
  194. {
  195. $databaseType = $this->config['driver'];
  196. if (!$this->hasConfig()) {
  197. return false;
  198. }
  199. switch (strtolower($databaseType)) {
  200. case 'sqlite3':
  201. $file = $file ? $this->config['dbLocation'] . $file : $this->config['dbLocation'] . $this->config['dbName'];
  202. return [
  203. 'driver' => 'sqlite3',
  204. 'database' => $file
  205. ];
  206. case 'mysql':
  207. case 'mysqli':
  208. $db = $file ? 'tempMigration' : $this->config['dbName'];
  209. return [
  210. 'driver' => 'mysqli',
  211. 'host' => $this->config['dbHost'],
  212. 'username' => $this->config['dbUsername'],
  213. 'password' => $this->decrypt($this->config['dbPassword']),
  214. 'database' => $db,
  215. 'options' => [
  216. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  217. ],
  218. 'flags' => MYSQLI_CLIENT_COMPRESS,
  219. ];
  220. case 'postgre':
  221. $config = [
  222. 'driver' => 'postgre',
  223. 'username' => $this->config['dbUsername'],
  224. 'password' => $this->decrypt($this->config['dbPassword']),
  225. 'persistent' => true,
  226. ];
  227. $host = $this->qualifyURL($this->config['dbHost'], true);
  228. if ($host['port']) {
  229. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  230. }
  231. if ($host['host']) {
  232. $config = array_merge($config, ['host' => $host['host']]);
  233. }
  234. if (!$host['host'] && $host['path']) {
  235. $config = array_merge($config, ['host' => $host['path']]);
  236. }
  237. return $config;
  238. default:
  239. return false;
  240. }
  241. }
  242. protected function connectDB()
  243. {
  244. $databaseConnection = $this->hasDatabase();
  245. //$this->prettyPrint($databaseConnection);
  246. if ($databaseConnection) {
  247. try {
  248. $this->db = new Connection($databaseConnection);
  249. } catch (Dibi\Exception $e) {
  250. $this->db = null;
  251. }
  252. } else {
  253. $this->db = null;
  254. }
  255. }
  256. public function disconnectDB()
  257. {
  258. if ($this->db) {
  259. $this->db->disconnect();
  260. $this->db = null;
  261. unset($this->db);
  262. }
  263. }
  264. public function connectOtherDB($file = null)
  265. {
  266. $databaseConnection = $this->hasDatabase('tempMigration.db');
  267. if ($databaseConnection) {
  268. try {
  269. $this->otherDb = new Connection($databaseConnection);
  270. } catch (Dibi\Exception $e) {
  271. $this->prettyPrint($e->getMessage());
  272. $this->otherDb = null;
  273. }
  274. } else {
  275. $this->otherDb = null;
  276. }
  277. }
  278. public function setDeviceUUID()
  279. {
  280. if (!isset($_COOKIE['organizr_user_uuid'])) {
  281. $this->coookie('set', 'organizr_user_uuid', $this->gen_uuid(), 7);
  282. }
  283. }
  284. public function refreshDeviceUUID()
  285. {
  286. if (isset($_COOKIE['organizr_user_uuid'])) {
  287. $this->coookie('delete', 'organizr_user_uuid');
  288. }
  289. $this->coookie('set', 'organizr_user_uuid', $this->gen_uuid(), 7);
  290. }
  291. public function setCurrentUser($validate = true)
  292. {
  293. $user = false;
  294. if ($this->hasDatabase()) {
  295. if ($this->hasCookie()) {
  296. $user = $this->getUserFromToken($_COOKIE[$this->cookieName]);
  297. }
  298. }
  299. $this->user = ($user) ?: $this->guestUser();
  300. $this->setLoggerChannel(null, $this->user['username']);
  301. if ($validate) {
  302. $this->checkUserTokenForValidation();
  303. }
  304. }
  305. public function checkUserTokenForValidation()
  306. {
  307. if ($this->hasDB()) {
  308. if ($this->hasCookie()) {
  309. $this->validateToken($_COOKIE[$this->cookieName]);
  310. }
  311. }
  312. }
  313. public function phpErrors()
  314. {
  315. $errorTypes = $this->dev ? E_ERROR | E_WARNING | E_PARSE | E_NOTICE : 0;
  316. // Temp overwrite for now
  317. $displayErrors = $this->dev ? 1 : 0;
  318. error_reporting($this->errors);
  319. ini_set('display_errors', $displayErrors);
  320. }
  321. public function checkForOrganizrOAuth()
  322. {
  323. // Oauth?
  324. if ($this->hasDB() && $this->user) {
  325. if ($this->user['groupID'] == '999') {
  326. $this->setLoggerChannel('OAuth')->debug('Starting OAuth login check');
  327. $data = [
  328. 'enabled' => $this->config['authProxyEnabled'],
  329. 'header_name' => $this->config['authProxyHeaderName'],
  330. 'header_name_email' => $this->config['authProxyHeaderNameEmail'],
  331. 'whitelist' => $this->config['authProxyWhitelist'],
  332. ];
  333. if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
  334. if (isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])]) || isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])])) {
  335. $this->coookieSeconds('set', 'organizrOAuth', 'true', 20000, false);
  336. $this->setLoggerChannel('OAuth')->info('OAuth pre-check passed - adding organizrOAuth cookie', $data);
  337. } else {
  338. $data = array_merge($data, ['headers' => $this->getallheadersi()]);
  339. $this->setLoggerChannel('OAuth')->debug('Headers not set', $data);
  340. }
  341. } else {
  342. $this->setLoggerChannel('OAuth')->debug('OAuth not triggered', $data);
  343. }
  344. }
  345. }
  346. }
  347. public function checkIfUserIsBlacklisted()
  348. {
  349. if ($this->hasConfig()) {
  350. $currentIP = $this->userIP();
  351. if ($this->config['blacklisted'] !== '') {
  352. if (in_array($currentIP, $this->arrayIP($this->config['blacklisted']))) {
  353. $this->setLoggerChannel('Authentication');
  354. $this->logger->debug('User was sent to black hole', ['blacklist' => $this->config['blacklisted']]);
  355. die($this->showHTML('Blacklisted', $this->config['blacklistedMessage']));
  356. }
  357. }
  358. }
  359. }
  360. public function checkDiskSpace($directory = './')
  361. {
  362. $readable = @is_readable($directory);
  363. if ($readable) {
  364. $disk = $this->checkDisk($directory);
  365. $diskLevels = [
  366. 'warn' => 1000000000,
  367. 'warn_human_readable' => $this->human_filesize(1000000000, 0),
  368. 'error' => 100000000,
  369. 'error_human_readable' => $this->human_filesize(100000000, 0),
  370. ];
  371. if ($disk['free']['raw'] <= $diskLevels['error']) {
  372. die($this->showHTML('Low Disk Space', 'You are dangerously low on disk space.<br/>There is only ' . $disk['free']['human_readable'] . ' remaining.<br/><b>Percent Used = ' . $disk['used']['percent_used'] . '%</b>'));
  373. } elseif ($disk['free']['raw'] <= $diskLevels['warn']) {
  374. $this->warnings[] = 'You are low on disk space. There is only ' . $disk['free']['human_readable'] . ' remaining. This warning shows up because you are past the warning threshold of ' . $diskLevels['warn_human_readable'];
  375. }
  376. }
  377. return true;
  378. }
  379. public function getFreeSpace($directory = './')
  380. {
  381. $disk = disk_free_space($directory);
  382. return [
  383. 'raw' => $disk,
  384. 'human_readable' => $this->human_filesize($disk, 0)
  385. ];
  386. }
  387. public function getDiskSpace($directory = './')
  388. {
  389. $disk = disk_total_space($directory);
  390. return [
  391. 'raw' => $disk,
  392. 'human_readable' => $this->human_filesize($disk, 0)
  393. ];
  394. }
  395. public function getUsedSpace($directory = './')
  396. {
  397. $diskFree = $this->getFreeSpace($directory);
  398. $diskTotal = $this->getDiskSpace($directory);
  399. $diskUsed = $diskTotal['raw'] - $diskFree['raw'];
  400. $percentUsed = ($diskUsed / $diskTotal['raw']) * 100;
  401. $percentFree = 100 - $percentUsed;
  402. return [
  403. 'raw' => $diskUsed,
  404. 'human_readable' => $this->human_filesize($diskUsed, 0),
  405. 'percent_used' => round($percentUsed),
  406. 'percent_free' => round($percentFree)
  407. ];
  408. }
  409. public function checkDisk($directory = './')
  410. {
  411. $readable = @is_readable($directory);
  412. if ($readable) {
  413. return [
  414. 'free' => $this->getFreeSpace($directory),
  415. 'used' => $this->getUsedSpace($directory),
  416. 'total' => $this->getDiskSpace($directory),
  417. ];
  418. } else {
  419. return [
  420. 'free' => 'error accessing path',
  421. 'used' => 'error accessing path',
  422. 'total' => 'error accessing path',
  423. ];
  424. }
  425. }
  426. public function errorCodes($error = 000)
  427. {
  428. $errorCodes = [
  429. 400 => [
  430. 'type' => 'Bad Request',
  431. 'description' => 'The request was incorrect'
  432. ],
  433. 401 => [
  434. 'type' => 'Unauthorized ',
  435. 'description' => 'You are not authorized to view this page'
  436. ],
  437. 402 => [
  438. 'type' => 'Payment Required',
  439. 'description' => 'Payment required before you can view this page'
  440. ],
  441. 403 => [
  442. 'type' => 'Forbidden',
  443. 'description' => 'You are forbidden to view this page'
  444. ],
  445. 404 => [
  446. 'type' => 'Not Found',
  447. 'description' => 'The requested resource was not found'
  448. ],
  449. 405 => [
  450. 'type' => 'Method Not Allowed',
  451. 'description' => 'The requested method is not allowed'
  452. ],
  453. 406 => [
  454. 'type' => 'Not Acceptable',
  455. 'description' => 'There was an issue with the requests Headers'
  456. ],
  457. 407 => [
  458. 'type' => 'Proxy Authentication Required',
  459. 'description' => 'Authentication is required and was not passed'
  460. ],
  461. 408 => [
  462. 'type' => 'Request Time-out',
  463. 'description' => 'The request has timed out'
  464. ],
  465. 409 => [
  466. 'type' => 'Conflict',
  467. 'description' => 'An error has occurred'
  468. ],
  469. 410 => [
  470. 'type' => 'Gone',
  471. 'description' => 'The requested resource is no longer available and has been permanently removed'
  472. ],
  473. 411 => [
  474. 'type' => 'Length Required',
  475. 'description' => 'The request can not be processed without a "Content-Length" header field'
  476. ],
  477. 412 => [
  478. 'type' => 'Precondition Failed',
  479. 'description' => ' A header needed was not found'
  480. ],
  481. 413 => [
  482. 'type' => 'Request Entity Too Large',
  483. 'description' => 'The query was too large to be processed by the server'
  484. ],
  485. 414 => [
  486. 'type' => 'Request-URI Too Long',
  487. 'description' => 'The URI of the request was too long'
  488. ],
  489. 415 => [
  490. 'type' => 'Unsupported Media Type',
  491. 'description' => 'The contents of the request has been submitted with invalid or out of defined media type'
  492. ],
  493. 416 => [
  494. 'type' => 'Requested range not satisfiable',
  495. 'description' => 'The requested resource was part of an invalid or is not on the server'
  496. ],
  497. 417 => [
  498. 'type' => 'Expectation Failed',
  499. 'description' => 'Expected Header was not found'
  500. ],
  501. 444 => [
  502. 'type' => 'No Response',
  503. 'description' => 'Nothing was returned from server'
  504. ],
  505. 500 => [
  506. 'type' => 'Internal Server Error',
  507. 'description' => 'An unexpected server error'
  508. ],
  509. 501 => [
  510. 'type' => 'Not Implemented',
  511. 'description' => 'The functionality to process the request is not available from this server'
  512. ],
  513. 502 => [
  514. 'type' => 'Bad Gateway',
  515. 'description' => 'The server could not fulfill its function as a gateway or proxy'
  516. ],
  517. 503 => [
  518. 'type' => 'Service Unavailable',
  519. 'description' => 'The server is temporarily unavailable, due to overloading or maintenance'
  520. ],
  521. 504 => [
  522. 'type' => 'Gateway Time-out',
  523. 'description' => 'The server could not fulfill its function as a gateway or proxy'
  524. ],
  525. 505 => [
  526. 'type' => 'HTTP version not supported',
  527. 'description' => 'The used version of HTTP is not supported by the server or rejected'
  528. ],
  529. 507 => [
  530. 'type' => 'Insufficient Storage',
  531. 'description' => 'The request could not be processed because the server disk space it currently is not sufficient'
  532. ],
  533. 509 => [
  534. 'type' => 'Bandwidth Limit Exceeded',
  535. 'description' => 'The request was rejected, because otherwise the bandwidth would be exceeded'
  536. ],
  537. 510 => [
  538. 'type' => 'Not Extended',
  539. 'description' => 'The request does not contain all information that is waiting for the requested server extension imperative'
  540. ],
  541. 000 => [
  542. 'type' => 'Unexpected Error',
  543. 'description' => 'An unexpected error occurred'
  544. ],
  545. ];
  546. return (isset($errorCodes[$error])) ? $errorCodes[$error] : $errorCodes[000];
  547. }
  548. public function showTopBarHamburger()
  549. {
  550. if ($this->config['allowCollapsableSideMenu']) {
  551. if ($this->config['sideMenuCollapsed']) {
  552. return '<a class="toggle-side-menu" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
  553. } else {
  554. return '<a class="toggle-side-menu hidden" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
  555. }
  556. }
  557. return '';
  558. }
  559. public function showSideBarHamburger()
  560. {
  561. if ($this->config['allowCollapsableSideMenu']) {
  562. if (!$this->config['sideMenuCollapsed']) {
  563. return '<i class="hidden-xs ti-shift-left mouse"></i>';
  564. }
  565. }
  566. return '<i class="ti-menu hidden-xs"></i>';
  567. }
  568. public function showSideBarText()
  569. {
  570. if ($this->config['allowCollapsableSideMenu']) {
  571. if (!$this->config['sideMenuCollapsed']) {
  572. return '<span class="hide-menu hidden-xs" lang="en">Hide Menu</span>';
  573. }
  574. }
  575. return '<span class="hide-menu hidden-xs" lang="en">Navigation</span>';
  576. }
  577. public function auth()
  578. {
  579. if ($this->hasDB()) {
  580. $this->setLoggerChannel('Auth');
  581. if (isset($_GET['type'])) {
  582. switch (strtolower($_GET['type'])) {
  583. case 'whitelist':
  584. case 'white':
  585. case 'w':
  586. case 'wl':
  587. case 'allow':
  588. $_GET['whitelist'] = $_GET['ips'] ?? false;
  589. break;
  590. case 'blacklist':
  591. case 'black':
  592. case 'b':
  593. case 'bl':
  594. case 'deny':
  595. $_GET['blacklist'] = $_GET['ips'] ?? false;
  596. break;
  597. default:
  598. $this->setAPIResponse('error', $_GET['type'] . ' is not a valid type', 401);
  599. return true;
  600. }
  601. }
  602. $whitelist = $_GET['whitelist'] ?? false;
  603. $blacklist = $_GET['blacklist'] ?? false;
  604. $group = 0;
  605. $groupParam = ($_GET['group']) ?? 0;
  606. $redirect = false;
  607. if (isset($groupParam)) {
  608. if (is_numeric($groupParam)) {
  609. $group = (int)$groupParam;
  610. } else {
  611. $group = $this->getTabGroupByTabName($groupParam);
  612. }
  613. }
  614. $currentIP = $this->userIP();
  615. $unlocked = !($this->user['locked'] == '1');
  616. if (isset($this->user)) {
  617. $currentUser = $this->user['username'];
  618. $currentGroup = $this->user['groupID'];
  619. $currentEmail = $this->user['email'];
  620. } else {
  621. $currentUser = 'Guest';
  622. $currentGroup = $this->getUserLevel();
  623. $currentEmail = 'guest@guest.com';
  624. }
  625. $userInfo = [
  626. "user" => $currentUser,
  627. "group" => $currentGroup,
  628. "email" => $currentEmail,
  629. "user_ip" => $currentIP,
  630. "requested_group" => $group,
  631. "uuid" => $_COOKIE['organizr_user_uuid'] ?? 'n/a'
  632. ];
  633. $this->logger->debug('Starting check', $userInfo);
  634. $responseMessage = 'User is not Authorized or User is locked';
  635. if ($whitelist) {
  636. if (in_array($currentIP, $this->arrayIP($whitelist))) {
  637. $responseMessage = 'User is whitelisted';
  638. $this->setAPIResponse('success', $responseMessage, 200, $userInfo);
  639. $this->logger->debug($responseMessage, $userInfo);
  640. return true;
  641. }
  642. }
  643. if ($blacklist) {
  644. if (in_array($currentIP, $this->arrayIP($blacklist))) {
  645. $responseMessage = 'User is blacklisted';
  646. $this->setAPIResponse('error', $responseMessage, 401, $userInfo);
  647. $this->logger->debug($responseMessage, $userInfo);
  648. return true;
  649. }
  650. }
  651. if ($group !== null) {
  652. if ((isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER'] == 'traefik') || $this->config['traefikAuthEnable']) {
  653. $return = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && isset($_SERVER['HTTP_X_FORWARDED_URI']) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) ? '?return=' . $_SERVER['HTTP_X_FORWARDED_PROTO'] . '://' . $_SERVER['HTTP_X_FORWARDED_HOST'] . $_SERVER['HTTP_X_FORWARDED_URI'] : '';
  654. $redirectDomain = ($this->config['traefikDomainOverride'] !== '') ? $this->config['traefikDomainOverride'] : $this->getServerPath();
  655. $redirect = 'Location: ' . $redirectDomain . $return;
  656. }
  657. if ($this->qualifyRequest($group) && $unlocked) {
  658. header("X-Organizr-User: $currentUser");
  659. header("X-Organizr-Email: $currentEmail");
  660. header("X-Organizr-Group: $currentGroup");
  661. $responseMessage = 'User is authorized';
  662. $this->setAPIResponse('success', $responseMessage, 200, $userInfo);
  663. $this->logger->debug($responseMessage, $userInfo);
  664. } else {
  665. if (!$redirect) {
  666. $this->setAPIResponse('error', $responseMessage, 401, $userInfo);
  667. $this->logger->debug($responseMessage, $userInfo);
  668. } else {
  669. exit(http_response_code(401) . header($redirect));
  670. }
  671. }
  672. } else {
  673. $this->setAPIResponse('error', 'Missing info', 401);
  674. $this->logger->debug('Missing info', $userInfo);
  675. }
  676. return true;
  677. } else {
  678. $this->setAPIResponse('error', 'Organizr is not setup or an error occurred', 401);
  679. return false;
  680. }
  681. }
  682. public function getIpInfo($ip = null)
  683. {
  684. if (!$ip) {
  685. $this->setResponse(422, 'No IP Address supplied');
  686. return false;
  687. }
  688. try {
  689. $options = array('verify' => false);
  690. $response = Requests::get('https://ipinfo.io/' . $ip . '/?token=ddd0c072ad5021', array(), $options);
  691. if ($response->success) {
  692. $api = json_decode($response->body, true);
  693. $this->setResponse(200, null, $api);
  694. return true;
  695. } else {
  696. $this->setResponse(500, 'An error occurred', null);
  697. }
  698. } catch (Requests_Exception $e) {
  699. $this->setResponse(500, 'An error occurred', $e->getMessage());
  700. }
  701. return false;
  702. }
  703. public function setAPIResponse($result = null, $message = null, $responseCode = null, $data = null)
  704. {
  705. if ($result) {
  706. $GLOBALS['api']['response']['result'] = $result;
  707. }
  708. if ($message) {
  709. $GLOBALS['api']['response']['message'] = $message;
  710. }
  711. if ($responseCode) {
  712. $GLOBALS['responseCode'] = $responseCode;
  713. }
  714. if ($data) {
  715. $GLOBALS['api']['response']['data'] = $data;
  716. }
  717. }
  718. public function setResponse(int $responseCode = 200, string $message = null, $data = null)
  719. {
  720. switch ($responseCode) {
  721. case 200:
  722. case 201:
  723. case 204:
  724. $result = 'success';
  725. break;
  726. default:
  727. $result = 'error';
  728. break;
  729. }
  730. $GLOBALS['api']['response']['result'] = $result;
  731. if ($message) {
  732. $GLOBALS['api']['response']['message'] = $message;
  733. }
  734. if ($responseCode) {
  735. $GLOBALS['responseCode'] = $responseCode;
  736. }
  737. if ($data) {
  738. $GLOBALS['api']['response']['data'] = $data;
  739. }
  740. }
  741. public function printWarningsAndErrors()
  742. {
  743. if (isset($GLOBALS['api']['response']['exceptions'])) {
  744. $this->prettyPrint($GLOBALS['api']['response']['exceptions'], true);
  745. } else {
  746. $this->prettyPrint('No Errors');
  747. }
  748. }
  749. public function setAPIErrorResponse($number, $message, $file, $line)
  750. {
  751. if (!(error_reporting() & $number)) {
  752. return;
  753. }
  754. $exceptions = [
  755. E_ERROR => 'E_ERROR',
  756. E_WARNING => 'E_WARNING',
  757. E_PARSE => 'E_PARSE',
  758. E_NOTICE => 'E_NOTICE',
  759. E_CORE_ERROR => 'E_CORE_ERROR',
  760. E_CORE_WARNING => 'E_CORE_WARNING',
  761. E_COMPILE_ERROR => 'E_COMPILE_ERROR',
  762. E_COMPILE_WARNING => 'E_COMPILE_WARNING',
  763. E_USER_ERROR => 'E_USER_ERROR',
  764. E_USER_WARNING => 'E_USER_WARNING',
  765. E_USER_NOTICE => 'E_USER_NOTICE',
  766. E_STRICT => 'E_STRICT',
  767. E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
  768. E_DEPRECATED => 'E_DEPRECATED',
  769. E_USER_DEPRECATED => 'E_USER_DEPRECATED',
  770. E_ALL => 'E_ALL'
  771. ];
  772. switch ($number) {
  773. case E_USER_ERROR:
  774. case E_ERROR:
  775. case E_CORE_ERROR:
  776. case E_COMPILE_ERROR:
  777. case E_RECOVERABLE_ERROR:
  778. $type = 'errors';
  779. break;
  780. case E_USER_WARNING:
  781. case E_WARNING:
  782. case E_CORE_WARNING:
  783. case E_COMPILE_WARNING:
  784. $type = 'warnings';
  785. break;
  786. case E_USER_NOTICE:
  787. case E_PARSE:
  788. case E_DEPRECATED:
  789. case E_USER_DEPRECATED:
  790. case E_NOTICE:
  791. $type = 'notice';
  792. break;
  793. default:
  794. $type = 'other';
  795. break;
  796. }
  797. if ($this->qualifyRequest(1)) {
  798. $count = isset($GLOBALS['api']['response']['exceptions'][$type]) ? count($GLOBALS['api']['response']['exceptions'][$type]) : 0;
  799. if ($count <= 10) {
  800. $GLOBALS['api']['response']['exceptions'][$type][] = [
  801. 'error' => $exceptions[$number],
  802. 'message' => $message,
  803. 'file' => $file,
  804. 'line' => $line
  805. ];
  806. }
  807. }
  808. $this->handleError($exceptions[$number], $message, $file, $line, $type);
  809. }
  810. public function setErrorResponse($number, $message, $file, $line)
  811. {
  812. $error = [
  813. 'error' => $number,
  814. 'message' => $message,
  815. 'file' => $file,
  816. 'line' => $line
  817. ];
  818. $this->handleError($number, $message, $file, $line);
  819. //$this->prettyPrint($error, true);
  820. }
  821. public function handleError($number, $message, $file, $line, $type)
  822. {
  823. $log = false;
  824. $error = sprintf('Organizr %s: %s in %s on line %d', $number, $message, $file, $line);
  825. error_log($error);
  826. if ($this->dev) {
  827. $log = true;
  828. } else {
  829. if ($type == 'errors') {
  830. $log = true;
  831. }
  832. }
  833. if ($log && $this->hasDB()) {
  834. $this->setLoggerChannel('Server Error')->warning('PHP Error', $error);
  835. }
  836. }
  837. public function checkRoute($request)
  838. {
  839. $route = '/api/v2/' . explode('api/v2/', $request->getUri()->getPath())[1];
  840. $method = $request->getMethod();
  841. $data = $this->apiData($request);
  842. if (!in_array($route, $GLOBALS['bypass'])) {
  843. if ($this->isApprovedRequest($method, $data) === false) {
  844. $this->setAPIResponse('error', 'Not authorized for current Route: ' . $route, 401);
  845. $this->setLoggerChannel('API Security');
  846. $this->logger->notice('Killed Attack From [' . ($_SERVER['HTTP_REFERER'] ?? 'No Referer') . ']');
  847. return false;
  848. }
  849. }
  850. return true;
  851. }
  852. public function apiData($request, $decode = true)
  853. {
  854. switch ($request->getMethod()) {
  855. case 'POST':
  856. if (stripos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
  857. return $decode ? json_decode(file_get_contents('php://input', 'r'), true) : file_get_contents('php://input', 'r');
  858. } else {
  859. return $request->getParsedBody();
  860. }
  861. default:
  862. if (stripos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
  863. return $decode ? json_decode(file_get_contents('php://input', 'r'), true) : file_get_contents('php://input', 'r');
  864. } else {
  865. return null;
  866. }
  867. }
  868. }
  869. public function getPlugins($returnType = 'all')
  870. {
  871. if ($this->hasDB()) {
  872. switch ($returnType) {
  873. case 'enabled':
  874. $returnType = 'enabled';
  875. break;
  876. case 'disabled':
  877. $returnType = 'disabled';
  878. break;
  879. default:
  880. $returnType = 'all';
  881. }
  882. $pluginList = [];
  883. foreach ($GLOBALS['plugins'] as $key => $value) {
  884. if (strpos($value['license'], $this->config['license']) !== false) {
  885. $GLOBALS['plugins'][$key]['enabled'] = $this->config[$value['configPrefix'] . '-enabled'] ?? false;
  886. if ($returnType == 'all') {
  887. $pluginList[$key] = $GLOBALS['plugins'][$key];
  888. } elseif ($returnType == 'enabled' && $GLOBALS['plugins'][$key]['enabled'] == true) {
  889. $pluginList[$key] = $GLOBALS['plugins'][$key];
  890. } elseif ($returnType == 'disabled' && $GLOBALS['plugins'][$key]['enabled'] == false) {
  891. $pluginList[$key] = $GLOBALS['plugins'][$key];
  892. }
  893. }
  894. }
  895. asort($pluginList);
  896. return $pluginList;
  897. }
  898. return false;
  899. }
  900. public function refreshCookieName()
  901. {
  902. $this->cookieName = $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp';
  903. }
  904. public function favIcons($rootPath = '')
  905. {
  906. $favicon = '
  907. <link rel="apple-touch-icon" sizes="180x180" href="' . $rootPath . 'plugins/images/favicon/apple-touch-icon.png">
  908. <link rel="icon" type="image/png" sizes="32x32" href="' . $rootPath . 'plugins/images/favicon/favicon-32x32.png">
  909. <link rel="icon" type="image/png" sizes="16x16" href="' . $rootPath . 'plugins/images/favicon/favicon-16x16.png">
  910. <link rel="manifest" href="' . $rootPath . 'plugins/images/favicon/site.webmanifest" crossorigin="use-credentials">
  911. <link rel="mask-icon" href="' . $rootPath . 'plugins/images/favicon/safari-pinned-tab.svg" color="#5bbad5">
  912. <link rel="shortcut icon" href="' . $rootPath . 'plugins/images/favicon/favicon.ico">
  913. <meta name="msapplication-TileColor" content="#da532c">
  914. <meta name="msapplication-TileImage" content="' . $rootPath . 'plugins/images/favicon/mstile-144x144.png">
  915. <meta name="msapplication-config" content="' . $rootPath . 'plugins/images/favicon/browserconfig.xml">
  916. <meta name="theme-color" content="#ffffff">
  917. ';
  918. if ($this->config['favIcon'] !== '' && $rootPath !== '') {
  919. $this->config['favIcon'] = str_replace('data/favicon', $rootPath . 'data/favicon', $this->config['favIcon']);
  920. }
  921. return ($this->config['favIcon'] == '') ? $favicon : $this->config['favIcon'];
  922. }
  923. public function pluginGlobalList()
  924. {
  925. $pluginSearch = '-enabled';
  926. $pluginInclude = '-include';
  927. $plugins = array_filter($this->config, function ($k) use ($pluginSearch) {
  928. return stripos($k, $pluginSearch) !== false;
  929. }, ARRAY_FILTER_USE_KEY);
  930. $plugins['includes'] = array_filter($this->config, function ($k) use ($pluginInclude) {
  931. return stripos($k, $pluginInclude) !== false;
  932. }, ARRAY_FILTER_USE_KEY);
  933. return $plugins;
  934. }
  935. public function googleTracking()
  936. {
  937. if ($this->config['gaTrackingID'] !== '') {
  938. return '
  939. <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
  940. <script async src="https://www.googletagmanager.com/gtag/js?id=' . $this->config['gaTrackingID'] . '"></script>
  941. <script>
  942. window.dataLayer = window.dataLayer || [];
  943. function gtag(){dataLayer.push(arguments);}
  944. gtag("js", new Date());
  945. gtag("config","' . $this->config['gaTrackingID'] . '");
  946. </script>
  947. ';
  948. }
  949. return null;
  950. }
  951. public function matchBrackets($text, $brackets = 's')
  952. {
  953. switch ($brackets) {
  954. case 's':
  955. case 'square':
  956. $pattern = '#\[(.*?)\]#';
  957. break;
  958. case 'c':
  959. case 'curly':
  960. $pattern = '#\((.*?)\)#';
  961. break;
  962. default:
  963. return null;
  964. }
  965. preg_match($pattern, $text, $match);
  966. return $match[1];
  967. }
  968. public function languagePacks($encode = false)
  969. {
  970. $files = array();
  971. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'langpack' . DIRECTORY_SEPARATOR . "*.json") as $filename) {
  972. if (strpos(basename($filename), '[') !== false) {
  973. $explode = explode('[', basename($filename));
  974. $files[] = array(
  975. 'filename' => basename($filename),
  976. 'code' => $explode[0],
  977. 'language' => $this->matchBrackets(basename($filename))
  978. );
  979. }
  980. }
  981. usort($files, function ($a, $b) {
  982. return $a['language'] <=> $b['language'];
  983. });
  984. return ($encode) ? json_encode($files) : $files;
  985. }
  986. public function getRootPath()
  987. {
  988. $count = (count(explode('/', $_SERVER['REQUEST_URI']))) - 2;
  989. $rootPath = '';
  990. $rootPath .= str_repeat('../', $count);
  991. return $rootPath;
  992. }
  993. public function setTheme($theme = null, $rootPath = '')
  994. {
  995. $theme = $theme ?? $this->config['theme'];
  996. $themeInformation = $this->validateTheme($theme);
  997. if (!$themeInformation) {
  998. $themeInformation = $this->defaultThemeInformation()['information']['Organizr'];
  999. }
  1000. return '<link id="theme" href="' . $rootPath . $themeInformation['path'] . '/' . $themeInformation['name'] . '.css?v=' . $this->fileHash . '" rel="stylesheet">';
  1001. }
  1002. public function validateTheme($theme = null)
  1003. {
  1004. $theme = $theme ?? $this->config['theme'];
  1005. $information = $this->getAllThemesInformation();
  1006. if (isset($information[$theme])) {
  1007. return $information[$theme];
  1008. } else {
  1009. return null;
  1010. }
  1011. }
  1012. public function getAllThemesInformation()
  1013. {
  1014. $organizrThemes = $this->defaultThemeInformation();
  1015. $userThemes = $this->userThemeInformation();
  1016. if ($userThemes) {
  1017. return array_merge($organizrThemes['information'], $userThemes);
  1018. }
  1019. return $organizrThemes['information'];
  1020. }
  1021. public function userThemeInformation()
  1022. {
  1023. $themes = $this->config['installedThemes'];
  1024. if (is_array($themes)) {
  1025. return $themes;
  1026. } else {
  1027. return [];
  1028. }
  1029. }
  1030. public function defaultThemeInformation()
  1031. {
  1032. return [
  1033. 'files' => ['Blue', 'Organizr'],
  1034. 'information' => [
  1035. 'Blue' => [
  1036. 'name' => 'Blue',
  1037. 'repo' => null,
  1038. 'version' => '1.0.0',
  1039. 'path' => 'css/themes'
  1040. ],
  1041. 'Organizr' => [
  1042. 'name' => 'Organizr',
  1043. 'repo' => null,
  1044. 'version' => '1.0.0',
  1045. 'path' => 'css/themes'
  1046. ]
  1047. ]
  1048. ];
  1049. }
  1050. public function getAllThemes()
  1051. {
  1052. $organizrThemes = $this->getOrganizrThemes();
  1053. $userThemes = $this->getUserThemes();
  1054. if ($userThemes) {
  1055. return array_merge($organizrThemes, $userThemes);
  1056. }
  1057. return $organizrThemes;
  1058. }
  1059. public function getOrganizrThemes()
  1060. {
  1061. $themes = [];
  1062. $themeFolder = $this->root . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'themes';
  1063. $originalThemes = $this->defaultThemeInformation();
  1064. foreach (glob($themeFolder . DIRECTORY_SEPARATOR . '*.css') as $filename) {
  1065. $file = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename));
  1066. if (in_array($file, $originalThemes['files'])) {
  1067. $themes[] = array(
  1068. 'name' => $file,
  1069. 'value' => $file,
  1070. );
  1071. }
  1072. }
  1073. return $themes;
  1074. }
  1075. public function getUserThemes()
  1076. {
  1077. $themes = [];
  1078. $themeFolder = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes';
  1079. $userThemesInformation = $this->userThemeInformation();
  1080. if (file_exists($themeFolder)) {
  1081. $directoryIterator = new RecursiveDirectoryIterator($themeFolder, FilesystemIterator::SKIP_DOTS);
  1082. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1083. foreach ($iteratorIterator as $info) {
  1084. if (stripos($info->getFilename(), '.css') !== false) {
  1085. $file = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($info->getFilename()));
  1086. if (key_exists($file, $userThemesInformation)) {
  1087. $themes[] = [
  1088. 'name' => ucwords(str_replace('_', ' ', $file)),
  1089. 'value' => $file,
  1090. ];
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return $themes;
  1096. }
  1097. public function setPluginListNameFromConfigPrefix()
  1098. {
  1099. foreach ($GLOBALS['plugins'] as $pluginName => $pluginInfo) {
  1100. $GLOBALS['pluginInfo'][strtolower($pluginInfo['configPrefix'])] = $pluginInfo;
  1101. $GLOBALS['pluginInfo'][strtolower($pluginName)] = $pluginInfo;
  1102. }
  1103. }
  1104. public function pluginFilesFromDirectory($directory, $webDirectory, $type, $settings = false, $rootPath = '')
  1105. {
  1106. $files = '';
  1107. if (file_exists($directory)) {
  1108. $directoryIterator = new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS);
  1109. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1110. switch ($type) {
  1111. case 'js':
  1112. foreach ($iteratorIterator as $info) {
  1113. if (pathinfo($info->getPathname(), PATHINFO_EXTENSION) == 'js') {
  1114. $pluginEnabled = false;
  1115. $keyOriginal = strtoupper(basename(dirname($info->getPathname())));
  1116. $key = str_replace('-SETTINGS', '', $keyOriginal);
  1117. $continue = false;
  1118. if ($settings) {
  1119. if ($info->getFilename() == 'settings.js') {
  1120. $continue = true;
  1121. }
  1122. } else {
  1123. if ($info->getFilename() !== 'settings.js') {
  1124. $continue = true;
  1125. }
  1126. }
  1127. switch ($key) {
  1128. case 'PHP-MAILER':
  1129. $key = 'PHPMAILER';
  1130. break;
  1131. case 'NGXC':
  1132. $key = 'ngxc';
  1133. break;
  1134. default:
  1135. $key = $key;
  1136. }
  1137. if (isset($this->config[$key . '-enabled'])) {
  1138. if ($this->config[$key . '-enabled']) {
  1139. $pluginEnabled = true;
  1140. }
  1141. }
  1142. if ($pluginEnabled || $settings) {
  1143. if ($continue) {
  1144. $version = $GLOBALS['pluginInfo'][strtolower($key)]['version'] ?? $this->fileHash;
  1145. $files .= '<script src="' . $rootPath . $webDirectory . basename(dirname($info->getPathname())) . '/' . basename($info->getFilename()) . '?v=' . $version . '" defer="true"></script>';
  1146. }
  1147. }
  1148. }
  1149. }
  1150. break;
  1151. case 'css':
  1152. foreach ($iteratorIterator as $info) {
  1153. if (pathinfo($info->getPathname(), PATHINFO_EXTENSION) == 'css') {
  1154. $key = basename(dirname($info->getPathname()));
  1155. $version = $GLOBALS['pluginInfo'][strtolower($key)]['version'] ?? $this->fileHash;
  1156. $files .= '<link href="' . $rootPath . $webDirectory . basename(dirname($info->getPathname())) . '/' . basename($info->getFilename()) . '?v=' . $version . '" rel="stylesheet">';
  1157. }
  1158. }
  1159. break;
  1160. default:
  1161. break;
  1162. }
  1163. }
  1164. return $files;
  1165. }
  1166. public function pluginFiles($type, $settings = false, $rootPath = '')
  1167. {
  1168. $files = '';
  1169. $organizrPlugins = $this->root . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'plugins';
  1170. $files .= $this->pluginFilesFromDirectory($organizrPlugins, 'api/plugins/', $type, $settings);
  1171. $userPlugins = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins';
  1172. $files .= $this->pluginFilesFromDirectory($userPlugins, 'data/plugins/', $type, $settings);
  1173. return $files;
  1174. }
  1175. public function formKey($script = true)
  1176. {
  1177. if (isset($this->config['organizrHash'])) {
  1178. if ($this->config['organizrHash'] !== '') {
  1179. $hash = password_hash(substr($this->config['organizrHash'], 2, 10), PASSWORD_BCRYPT);
  1180. return ($script) ? '<script>local("s","formKey","' . $hash . '");</script>' : $hash;
  1181. }
  1182. }
  1183. }
  1184. private function checkPHP()
  1185. {
  1186. if (!(version_compare(PHP_VERSION, $this->minimumPHP) >= 0)) {
  1187. die($this->showHTML('PHP Version', 'Organizr needs PHP Version: ' . $this->minimumPHP . '<br/> You have PHP Version: ' . PHP_VERSION));
  1188. }
  1189. }
  1190. private function checkWritableDB()
  1191. {
  1192. if ($this->hasDB()) {
  1193. if (isset($this->config['dbLocation']) && isset($this->config['dbName'])) {
  1194. $db = is_writable($this->config['dbLocation'] . $this->config['dbName']);
  1195. if (!$db) {
  1196. //die($this->showHTML('Organizr DB is not writable!', 'Please check permissions and/or disk space'));
  1197. }
  1198. } else {
  1199. die($this->showHTML('Config File Malformed', 'dbLocation and/or dbName is not listed in config.php'));
  1200. }
  1201. }
  1202. }
  1203. // Create config file in the return syntax
  1204. public function createConfig($array, $path = null, $nest = 0)
  1205. {
  1206. $path = ($path) ? $path : $this->userConfigPath;
  1207. // Define Initial Value
  1208. $output = array();
  1209. // Sort Items
  1210. ksort($array);
  1211. // Update the current config version
  1212. if (!$nest) {
  1213. // Inject Current Version
  1214. $output[] = "\t'configVersion' => '" . (isset($array['apply_CONFIG_VERSION']) ? $array['apply_CONFIG_VERSION'] : $this->version) . "'";
  1215. }
  1216. unset($array['configVersion']);
  1217. unset($array['apply_CONFIG_VERSION']);
  1218. // Process Settings
  1219. foreach ($array as $k => $v) {
  1220. $allowCommit = true;
  1221. $item = '';
  1222. switch (gettype($v)) {
  1223. case 'boolean':
  1224. $item = ($v ? 'true' : 'false');
  1225. break;
  1226. case 'integer':
  1227. case 'double':
  1228. case 'NULL':
  1229. $item = $v;
  1230. break;
  1231. case 'string':
  1232. $item = "'" . str_replace(array('\\', "'"), array('\\\\', "\'"), $v) . "'";
  1233. break;
  1234. case 'array':
  1235. $item = $this->createConfig($v, false, $nest + 1);
  1236. break;
  1237. default:
  1238. $allowCommit = false;
  1239. }
  1240. if ($allowCommit) {
  1241. $output[] = str_repeat("\t", $nest + 1) . "'$k' => $item";
  1242. }
  1243. }
  1244. // Build output
  1245. $output = (!$nest ? "<?php\nreturn " : '') . "[\n" . implode(",\n", $output) . "\n" . str_repeat("\t", $nest) . ']' . (!$nest ? ';' : '');
  1246. if (!$nest && $path) {
  1247. $pathDigest = pathinfo($path);
  1248. @mkdir($pathDigest['dirname'], 0770, true);
  1249. if (file_exists($path)) {
  1250. rename($path, $pathDigest['dirname'] . '/' . $pathDigest['filename'] . '.bak.php');
  1251. }
  1252. $file = fopen($path, 'w');
  1253. fwrite($file, $output);
  1254. fclose($file);
  1255. if (file_exists($path)) {
  1256. return true;
  1257. }
  1258. return false;
  1259. } else {
  1260. return $output;
  1261. }
  1262. }
  1263. // Commit new values to the configuration
  1264. public function updateConfig($new, $current = false)
  1265. {
  1266. // Get config if not supplied
  1267. if ($current === false) {
  1268. //$current = $this->loadConfig();
  1269. $current = $this->config;
  1270. } elseif (is_string($current) && is_file($current)) {
  1271. $current = $this->loadConfig($current);
  1272. }
  1273. // Inject Parts
  1274. foreach ($new as $k => $v) {
  1275. $current[$k] = $v;
  1276. $this->config[$k] = $v;
  1277. }
  1278. // Return Create
  1279. return $this->createConfig($current);
  1280. }
  1281. public function removeConfigItem($new, $current = false)
  1282. {
  1283. // Get config if not supplied
  1284. if ($current === false) {
  1285. $current = $this->config;
  1286. } elseif (is_string($current) && is_file($current)) {
  1287. $current = $this->loadConfig($current);
  1288. }
  1289. // Inject Parts
  1290. foreach ($new as $k) {
  1291. if (isset($current[$k])) {
  1292. $current['deletedConfigItems'][$k] = $current[$k];
  1293. $this->config['deletedConfigItems'][$k] = $current[$k];
  1294. }
  1295. unset($current[$k]);
  1296. unset($this->config[$k]);
  1297. }
  1298. // Return Create
  1299. return $this->createConfig($current);
  1300. }
  1301. public function loadConfig($path = null)
  1302. {
  1303. $path = ($path) ? $path : $this->userConfigPath;
  1304. if (!is_file($path)) {
  1305. return null;
  1306. } else {
  1307. return (array)call_user_func(function () use ($path) {
  1308. return include($path);
  1309. });
  1310. }
  1311. }
  1312. public function fillDefaultConfig($array)
  1313. {
  1314. $path = $this->defaultConfigPath;
  1315. if (is_string($path)) {
  1316. $loadedDefaults = $this->loadConfig($path);
  1317. } else {
  1318. $loadedDefaults = $path;
  1319. }
  1320. // Include all plugin config files
  1321. $folder = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'plugins';
  1322. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  1323. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1324. foreach ($iteratorIterator as $info) {
  1325. if ($info->getFilename() == 'config.php') {
  1326. $loadedDefaults = array_merge($loadedDefaults, $this->loadConfig($info->getPathname()));
  1327. }
  1328. }
  1329. /*
  1330. * Include all custom Plugin routes
  1331. */
  1332. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins')) {
  1333. $folder = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins';
  1334. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  1335. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1336. foreach ($iteratorIterator as $info) {
  1337. if ($info->getFilename() == 'config.php') {
  1338. $loadedDefaults = array_merge($loadedDefaults, $this->loadConfig($info->getPathname()));
  1339. }
  1340. }
  1341. }
  1342. return (is_array($loadedDefaults) ? $this->fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  1343. }
  1344. public function fillDefaultConfig_recurse($current, $defaults)
  1345. {
  1346. foreach ($defaults as $k => $v) {
  1347. if (!isset($current[$k])) {
  1348. $current[$k] = $v;
  1349. } elseif (is_array($current[$k]) && is_array($v)) {
  1350. $current[$k] = $this->fillDefaultConfig_recurse($current[$k], $v);
  1351. }
  1352. }
  1353. return $current;
  1354. }
  1355. public function config($tries = 1)
  1356. {
  1357. // Load config or default
  1358. if (file_exists($this->userConfigPath)) {
  1359. $config = $this->fillDefaultConfig($this->loadConfig($this->userConfigPath));
  1360. } else {
  1361. $config = $this->fillDefaultConfig($this->loadConfig($this->defaultConfigPath));
  1362. }
  1363. if ((!is_array($config) || !file_exists($this->userConfigPath)) && $tries < 5) {
  1364. $tries++;
  1365. return $this->config($tries);
  1366. }
  1367. return $config;
  1368. }
  1369. public function combineConfig($array)
  1370. {
  1371. $this->config = array_merge($this->config, $array);
  1372. return $this->config;
  1373. }
  1374. public function status($action = false)
  1375. {
  1376. $status = [];
  1377. $dependenciesActive = [];
  1378. $dependenciesInactive = [];
  1379. $extensions = ['PDO_SQLITE', 'PDO', 'SQLITE3', 'zip', 'cURL', 'openssl', 'simplexml', 'json', 'session', 'filter', 'fileinfo', 'mbstring'];
  1380. $functions = ['hash', 'fopen', 'fsockopen', 'fwrite', 'fclose', 'readfile'];
  1381. foreach ($extensions as $check) {
  1382. if (extension_loaded($check)) {
  1383. array_push($dependenciesActive, $check);
  1384. } else {
  1385. array_push($dependenciesInactive, $check);
  1386. }
  1387. }
  1388. foreach ($functions as $check) {
  1389. if (function_exists($check)) {
  1390. array_push($dependenciesActive, $check);
  1391. } else {
  1392. array_push($dependenciesInactive, $check);
  1393. }
  1394. }
  1395. $status['writable'] = is_writable(dirname(__DIR__, 2));
  1396. $status['minVersion'] = (version_compare(PHP_VERSION, $this->minimumPHP) >= 0);
  1397. $status['os'] = $this->getOS();
  1398. $status['php'] = phpversion();
  1399. $status['userConfigPathExists'] = file_exists($this->userConfigPath);
  1400. if (!($status['minVersion'])) {
  1401. $status['action'] = 'php';
  1402. if ($action) {
  1403. header($this->getServerPath() . 'api/v2/organizr/error');
  1404. exit;
  1405. }
  1406. } elseif (count($dependenciesInactive) > 0) {
  1407. $status['action'] = 'dependencies';
  1408. } elseif (!$status['writable']) {
  1409. $status['action'] = 'permission';
  1410. } elseif (!$status['userConfigPathExists']) {
  1411. $status['action'] = 'wizard';
  1412. } else {
  1413. $status['action'] = 'launch';
  1414. if ($action) {
  1415. echo '<script type="text/javascript"> window.location.href="' . $this->getServerPath() . 'api/v2/organizr/error/409' . '";</script>';
  1416. exit;
  1417. }
  1418. }
  1419. return $status;
  1420. }
  1421. public function launch()
  1422. {
  1423. $status = array();
  1424. $dependenciesActive = array();
  1425. $dependenciesInactive = array();
  1426. $extensions = array('PDO_SQLITE', 'PDO', 'SQLITE3', 'zip', 'cURL', 'openssl', 'simplexml', 'json', 'session', 'filter', 'fileinfo', 'mbstring');
  1427. $functions = array('hash', 'fopen', 'fsockopen', 'fwrite', 'fclose', 'readfile');
  1428. foreach ($extensions as $check) {
  1429. if (extension_loaded($check)) {
  1430. array_push($dependenciesActive, $check);
  1431. } else {
  1432. array_push($dependenciesInactive, $check);
  1433. }
  1434. }
  1435. foreach ($functions as $check) {
  1436. if (function_exists($check)) {
  1437. array_push($dependenciesActive, $check);
  1438. } else {
  1439. array_push($dependenciesInactive, $check);
  1440. }
  1441. }
  1442. if (!file_exists($this->userConfigPath)) {
  1443. $status['status'] = 'wizard';//wizard - ok for test
  1444. }
  1445. if (count($dependenciesInactive) > 0 || !is_writable(dirname(__DIR__, 2)) || !(version_compare(PHP_VERSION, $this->minimumPHP) >= 0)) {
  1446. $status['status'] = 'dependencies';
  1447. }
  1448. $status['status'] = ($status['status']) ?? 'ok';
  1449. $status['writable'] = is_writable(dirname(__DIR__, 2)) ? 'yes' : 'no';
  1450. $status['minVersion'] = (version_compare(PHP_VERSION, $this->minimumPHP) >= 0) ? 'yes' : 'no';
  1451. $status['dependenciesActive'] = $dependenciesActive;
  1452. $status['dependenciesInactive'] = $dependenciesInactive;
  1453. $status['version'] = $this->version;
  1454. $status['os'] = $this->getOS();
  1455. $status['php'] = phpversion();
  1456. $status['php_user'] = get_current_user();
  1457. $status['userConfigPath'] = $this->userConfigPath;
  1458. return $status;
  1459. }
  1460. public function hasDB()
  1461. {
  1462. return (file_exists($this->userConfigPath)) ?? false;
  1463. }
  1464. public function hasCookie()
  1465. {
  1466. return ($_COOKIE[$this->cookieName]) ?? false;
  1467. }
  1468. public function getGuest()
  1469. {
  1470. $guest = array(
  1471. 'group' => 'Guest',
  1472. 'group_id' => 999,
  1473. 'image' => 'plugins/images/groups/guest.png'
  1474. );
  1475. $response = [
  1476. array(
  1477. 'function' => 'fetch',
  1478. 'query' => 'SELECT * FROM groups WHERE `group_id` = 999'
  1479. ),
  1480. ];
  1481. return $this->hasDB() ? $this->processQueries($response) : $guest;
  1482. }
  1483. public function getSchema()
  1484. {
  1485. if ($this->config['driver'] == 'sqlite3') {
  1486. $response = [
  1487. array(
  1488. 'function' => 'fetchAll',
  1489. 'query' => 'SELECT name, sql FROM sqlite_master WHERE type=\'table\' ORDER BY name'
  1490. ),
  1491. ];
  1492. return $this->hasDB() ? $this->processQueries($response) : 'Database not setup yet';
  1493. } else {
  1494. return false;
  1495. }
  1496. }
  1497. public function guestUser()
  1498. {
  1499. if ($this->hasDB()) {
  1500. if ($this->getUserLevel() !== 999) {
  1501. $guest = array(
  1502. "token" => null,
  1503. "tokenDate" => null,
  1504. "tokenExpire" => null,
  1505. "username" => "Organizr API",
  1506. "uid" => $this->guestHash(0, 5),
  1507. "group" => 'Admin',
  1508. "groupID" => 0,
  1509. "email" => null,
  1510. //"groupImage"=>getGuest()['image'],
  1511. "image" => $this->getGuest()['image'],
  1512. "userID" => null,
  1513. "loggedin" => false,
  1514. "locked" => false,
  1515. "tokenList" => null,
  1516. "authService" => null
  1517. );
  1518. }
  1519. }
  1520. $guest = $guest ?? array(
  1521. "token" => null,
  1522. "tokenDate" => null,
  1523. "tokenExpire" => null,
  1524. "username" => "Guest",
  1525. "uid" => $this->guestHash(0, 5),
  1526. "group" => $this->getGuest()['group'],
  1527. "groupID" => $this->getGuest()['group_id'],
  1528. "email" => null,
  1529. //"groupImage"=>getGuest()['image'],
  1530. "image" => $this->getGuest()['image'],
  1531. "userID" => null,
  1532. "loggedin" => false,
  1533. "locked" => false,
  1534. "tokenList" => null,
  1535. "authService" => null
  1536. );
  1537. return $guest;
  1538. }
  1539. public function getAllUserTokens($id, $includeAllFields = true)
  1540. {
  1541. $select = $includeAllFields ? '*' : 'token, ip, id, expires, created';
  1542. $response = [
  1543. array(
  1544. 'function' => 'fetchAll',
  1545. 'query' => array(
  1546. 'SELECT ' . $select . ' FROM `tokens` WHERE user_id = ? AND expires > ?',
  1547. [$id],
  1548. [$this->currentTime]
  1549. )
  1550. ),
  1551. ];
  1552. return $this->processQueries($response);
  1553. }
  1554. public function getUserById($id)
  1555. {
  1556. $response = [
  1557. array(
  1558. 'function' => 'fetch',
  1559. 'query' => array(
  1560. 'SELECT * FROM users WHERE id = ?',
  1561. $id
  1562. )
  1563. )
  1564. ];
  1565. return $this->processQueries($response);
  1566. }
  1567. public function getUserByEmail($email)
  1568. {
  1569. $response = [
  1570. array(
  1571. 'function' => 'fetch',
  1572. 'query' => array(
  1573. 'SELECT * FROM users WHERE email = ? COLLATE NOCASE',
  1574. $email
  1575. )
  1576. )
  1577. ];
  1578. return $this->processQueries($response);
  1579. }
  1580. protected function invalidToken($token)
  1581. {
  1582. if (isset($_COOKIE[$this->cookieName])) {
  1583. if ($token == $_COOKIE[$this->cookieName]) {
  1584. $this->setLoggerChannel('Authentication');
  1585. $this->logger->debug('Token was invalid - deleting cookie and user session');
  1586. $this->coookie('delete', $this->cookieName);
  1587. $this->user = null;
  1588. }
  1589. }
  1590. }
  1591. public function validateToken($token, $api = false)
  1592. {
  1593. // Validate script
  1594. $userInfo = $this->jwtParse($token);
  1595. $validated = (bool)$userInfo;
  1596. if ($validated == true) {
  1597. $allTokens = $this->getAllUserTokens($userInfo['userID']);
  1598. $user = $this->getUserById($userInfo['userID']);
  1599. $tokenKey = $this->searchArray($allTokens, 'token', $token);
  1600. $tokenCheck = ($tokenKey !== false);
  1601. if (!$tokenCheck) {
  1602. $this->setLoggerChannel('Authentication');
  1603. $this->logger->debug('Token failed check against all token listings', $allTokens);
  1604. $this->invalidToken($token);
  1605. if ($api) {
  1606. $this->setResponse(403, 'Token was not in approved list');
  1607. }
  1608. return false;
  1609. } else {
  1610. // Check if user is on same browser as token
  1611. if ($allTokens[$tokenKey]['browser'] !== $_SERVER ['HTTP_USER_AGENT']) {
  1612. if ($this->config['matchUserAgents']) {
  1613. $this->setLoggerChannel('Authentication')->warning('Mismatch of useragent', ['token' => $allTokens[$tokenKey]['browser'], 'browser' => $_SERVER ['HTTP_USER_AGENT']]);
  1614. $this->invalidToken($token);
  1615. return false;
  1616. }
  1617. }
  1618. if (($allTokens[$tokenKey]['ip'] !== $this->userIP()) && (!$this->isLocalOrServer())) {
  1619. if ($this->config['matchUserIP']) {
  1620. $this->setLoggerChannel('Authentication')->warning('Mismatch of user IP', ['token' => $allTokens[$tokenKey]['ip'], 'user' => $this->userIP()]);
  1621. $this->invalidToken($token);
  1622. return false;
  1623. }
  1624. }
  1625. if ($api) {
  1626. $this->setResponse(200, 'Token is valid');
  1627. }
  1628. return array(
  1629. 'token' => $token,
  1630. 'tokenDate' => $userInfo['tokenDate'],
  1631. 'tokenExpire' => $userInfo['tokenExpire'],
  1632. 'username' => $user['username'] ?? $userInfo['username'],
  1633. 'uid' => $this->guestHash(0, 5),
  1634. 'group' => $user['group'] ?? $userInfo['group'],
  1635. 'groupID' => $user['group_id'] ?? $userInfo['groupID'],
  1636. 'email' => $user['email'] ?? $userInfo['email'],
  1637. 'image' => $user['image'] ?? $userInfo['image'],
  1638. 'userID' => $user['id'] ?? $userInfo['userID'],
  1639. 'loggedin' => true,
  1640. 'locked' => $user['locked'] ?? 0,
  1641. 'tokenList' => $allTokens,
  1642. 'authService' => (isset($user['auth_service'])) ? explode('::', $user['auth_service'])[0] : 'internal'
  1643. );
  1644. }
  1645. } else {
  1646. if ($api) {
  1647. $this->setResponse(403, 'Token was invalid');
  1648. }
  1649. $this->setLoggerChannel('Authentication');
  1650. $this->logger->debug('User token was invalid', ['token' => $token]);
  1651. $this->invalidToken($token);
  1652. }
  1653. if ($api) {
  1654. $this->setResponse(403, 'Token was invalid');
  1655. }
  1656. return false;
  1657. }
  1658. public function getUserFromToken($token)
  1659. {
  1660. // Validate script
  1661. $userInfo = $this->jwtParse($token);
  1662. $validated = (bool)$userInfo;
  1663. if ($validated == true) {
  1664. $user = $this->getUserById($userInfo['userID']);
  1665. $allTokens = $this->getAllUserTokens($userInfo['userID'], false);
  1666. return array(
  1667. 'token' => $token,
  1668. 'tokenDate' => $userInfo['tokenDate'],
  1669. 'tokenExpire' => $userInfo['tokenExpire'],
  1670. 'username' => $user['username'] ?? $userInfo['username'],
  1671. 'uid' => $this->guestHash(0, 5),
  1672. 'group' => $user['group'] ?? $userInfo['group'],
  1673. 'groupID' => $user['group_id'] ?? $userInfo['groupID'],
  1674. 'email' => $user['email'] ?? $userInfo['email'],
  1675. 'image' => $user['image'] ?? $userInfo['image'],
  1676. 'userID' => $user['id'] ?? $userInfo['userID'],
  1677. 'loggedin' => true,
  1678. 'locked' => $user['locked'] ?? 0,
  1679. 'tokenList' => $allTokens,
  1680. 'authService' => (isset($user['auth_service'])) ? explode('::', $user['auth_service'])[0] : 'internal'
  1681. );
  1682. }
  1683. return false;
  1684. }
  1685. public function defaultUserGroup()
  1686. {
  1687. $response = [
  1688. array(
  1689. 'function' => 'fetch',
  1690. 'query' => 'SELECT * FROM groups WHERE `default` = 1'
  1691. )
  1692. ];
  1693. return $this->processQueries($response);
  1694. }
  1695. public function getAllTabs()
  1696. {
  1697. $response = [
  1698. array(
  1699. 'function' => 'fetchAll',
  1700. 'query' => 'SELECT * FROM tabs ORDER BY `order` ASC',
  1701. 'key' => 'tabs'
  1702. ),
  1703. array(
  1704. 'function' => 'fetchAll',
  1705. 'query' => 'SELECT * FROM categories ORDER BY `order` ASC',
  1706. 'key' => 'categories'
  1707. ),
  1708. array(
  1709. 'function' => 'fetchAll',
  1710. 'query' => 'SELECT * FROM groups ORDER BY `group_id` ASC',
  1711. 'key' => 'groups'
  1712. ),
  1713. ];
  1714. $query = $this->processQueries($response);
  1715. $this->applyTabVariables($query['tabs']);
  1716. return $query;
  1717. }
  1718. public function applyTabVariables($tabs)
  1719. {
  1720. $variables = [
  1721. '{domain}' => $this->getServer(),
  1722. '{username}' => $this->user['username'],
  1723. '{username_lower}' => $this->user['username'],
  1724. '{email}' => $this->user['email'],
  1725. '{group}' => $this->user['group'],
  1726. '{group_id}' => $this->user['groupID'],
  1727. '{komga}' => $_COOKIE['komga_token'] ?? ''
  1728. ];
  1729. if (empty($tabs)) {
  1730. return $tabs;
  1731. }
  1732. foreach ($tabs as $id => $tab) {
  1733. $tabs[$id]['url'] = $this->userDefinedIdReplacementLink($tab['url'], $variables);
  1734. $tabs[$id]['url_local'] = $this->userDefinedIdReplacementLink($tab['url_local'], $variables);
  1735. }
  1736. return $tabs;
  1737. }
  1738. public function getUsers()
  1739. {
  1740. $response = [
  1741. array(
  1742. 'function' => 'fetchAll',
  1743. 'query' => 'SELECT * FROM users'
  1744. ),
  1745. array(
  1746. 'function' => 'fetchAll',
  1747. 'query' => 'SELECT * FROM groups ORDER BY group_id ASC'
  1748. ),
  1749. ];
  1750. return $this->processQueries($response);
  1751. }
  1752. public function usernameTaken($username, $email, $id = null)
  1753. {
  1754. if ($id) {
  1755. $response = [
  1756. array(
  1757. 'function' => 'fetch',
  1758. 'query' => array(
  1759. 'SELECT * FROM users WHERE `id` != ? AND (username = ? COLLATE NOCASE or email = ? COLLATE NOCASE)',
  1760. $id,
  1761. $username,
  1762. $email
  1763. )
  1764. ),
  1765. ];
  1766. } else {
  1767. $response = [
  1768. array(
  1769. 'function' => 'fetch',
  1770. 'query' => array(
  1771. 'SELECT * FROM users WHERE username = ? COLLATE NOCASE or email = ? COLLATE NOCASE',
  1772. [$username],
  1773. [$email]
  1774. )
  1775. ),
  1776. ];
  1777. }
  1778. return $this->processQueries($response);
  1779. }
  1780. public function cleanPageName($page)
  1781. {
  1782. return ($page) ? strtolower(str_replace(array('%20', ' ', '-', '_'), '_', $page)) : '';
  1783. }
  1784. public function cleanClassName($name, $char = '-')
  1785. {
  1786. return ($name) ? (str_replace(array('%20', ' ', '-', '_'), $char, strtolower($name))) : '';
  1787. }
  1788. public function reverseCleanClassName($name)
  1789. {
  1790. return ($name) ? (str_replace(array('%20', '-', '_'), ' ', strtolower($name))) : '';
  1791. }
  1792. public function getPageList()
  1793. {
  1794. return $GLOBALS['organizrPages'];
  1795. }
  1796. public function getPage($page)
  1797. {
  1798. if (!$page) {
  1799. $this->setAPIResponse('error', 'Page not setup', 409);
  1800. return null;
  1801. }
  1802. $pageFunction = 'get_page_' . $this->cleanPageName($page);
  1803. if (function_exists($pageFunction)) {
  1804. return $pageFunction($this);
  1805. } else {
  1806. $this->setAPIResponse('error', 'Page not setup', 409);
  1807. return null;
  1808. }
  1809. }
  1810. public function getUserLevel()
  1811. {
  1812. // Grab token
  1813. $requesterToken = $this->getallheadersi()['token'] ?? ($_GET['apikey'] ?? false);
  1814. $apiKey = ($this->config['organizrAPI']) ?? null;
  1815. // Check token or API key
  1816. // If API key, return 0 for admin
  1817. if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
  1818. //DO API CHECK
  1819. return 0;
  1820. } elseif (isset($this->user)) {
  1821. return $this->user['groupID'];
  1822. }
  1823. // All else fails? return guest id
  1824. return 999;
  1825. }
  1826. public function qualifyRequest($accessLevelNeeded, $api = false)
  1827. {
  1828. if ($this->getUserLevel() <= $accessLevelNeeded && $this->getUserLevel() !== null) {
  1829. return true;
  1830. } else {
  1831. if ($api) {
  1832. $this->setAPIResponse('error', 'Not Authorized', 401);
  1833. }
  1834. return false;
  1835. }
  1836. }
  1837. public function qualifyLength($string, $length = 100, $api = false)
  1838. {
  1839. if (strlen($string) <= $length) {
  1840. return true;
  1841. } else {
  1842. if ($api) {
  1843. $this->setResponse(409, 'String is over limit of: ' . $length);
  1844. }
  1845. return false;
  1846. }
  1847. }
  1848. public function getImages()
  1849. {
  1850. $allIconsPrep = array();
  1851. $allIcons = array();
  1852. $ignore = array(".", "..", "._.DS_Store", ".DS_Store", ".pydio_id", "index.html");
  1853. $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'tabs' . DIRECTORY_SEPARATOR;
  1854. $path = 'plugins/images/tabs/';
  1855. $images = scandir($dirname);
  1856. foreach ($images as $image) {
  1857. if (!in_array($image, $ignore)) {
  1858. $allIconsPrep[$image] = array(
  1859. 'path' => $path,
  1860. 'name' => $image
  1861. );
  1862. }
  1863. }
  1864. $dirname = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1865. $path = 'data/userTabs/';
  1866. if (file_exists($dirname)) {
  1867. $images = scandir($dirname);
  1868. foreach ($images as $image) {
  1869. if (!in_array($image, $ignore)) {
  1870. $allIconsPrep[$image] = array(
  1871. 'path' => $path,
  1872. 'name' => $image
  1873. );
  1874. }
  1875. }
  1876. }
  1877. uksort($allIconsPrep, 'strcasecmp');
  1878. foreach ($allIconsPrep as $item) {
  1879. $allIcons[] = $item['path'] . $item['name'];
  1880. }
  1881. return $allIcons;
  1882. }
  1883. public function getImagesSelect()
  1884. {
  1885. $term = $_GET['search'] ?? null;
  1886. $page = $_GET['page'] ?? 1;
  1887. $limit = $_GET['limit'] ?? 20;
  1888. $offset = ($page * $limit) - $limit;
  1889. $goodIcons['results'] = [];
  1890. $goodIcons['limit'] = $limit;
  1891. $goodIcons['page'] = $page;
  1892. $goodIcons['term'] = $term;
  1893. $imageListing = $this->getImages();
  1894. $newImageListing = [];
  1895. foreach ($imageListing as $image) {
  1896. $newImageListing[] = [
  1897. 'id' => $image,
  1898. 'text' => basename($image)
  1899. ];
  1900. }
  1901. foreach ($newImageListing as $k => $v) {
  1902. if ($term) {
  1903. if (stripos($v['text'], $term) !== false) {
  1904. $goodIcons['results'][] = $v;
  1905. }
  1906. } else {
  1907. $goodIcons['results'][] = $v;
  1908. }
  1909. }
  1910. $total = count($goodIcons['results']);
  1911. $goodIcons['total'] = $total;
  1912. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  1913. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  1914. return $goodIcons;
  1915. }
  1916. public function removeImage($image = null)
  1917. {
  1918. if (!$image) {
  1919. $this->setAPIResponse('error', 'No image supplied', 422);
  1920. return false;
  1921. }
  1922. $approvedPath = 'data/userTabs/';
  1923. $removeImage = $approvedPath . pathinfo($image, PATHINFO_BASENAME);
  1924. if ($this->approvedFileExtension($removeImage, 'image')) {
  1925. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage)) {
  1926. $this->setLoggerChannel('Image Manager');
  1927. $this->logger->info('Image Manager Function - Deleted Image [' . pathinfo($image, PATHINFO_BASENAME) . ']');
  1928. $this->setAPIResponse(null, pathinfo($image, PATHINFO_BASENAME) . ' has been deleted', null);
  1929. return (unlink(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage));
  1930. } else {
  1931. $this->setAPIResponse('error', $removeImage . ' does not exist', 404);
  1932. return false;
  1933. }
  1934. } else {
  1935. $this->setAPIResponse('error', $removeImage . ' is not approved to be deleted', 409);
  1936. return false;
  1937. }
  1938. }
  1939. public function uploadImage()
  1940. {
  1941. $filesCheck = array_filter($_FILES);
  1942. if (empty($filesCheck)) {
  1943. $this->setResponse(500, 'No File was uploaded');
  1944. return false;
  1945. }
  1946. if ($_FILES['file']['tmp_name'] == '') {
  1947. $this->setResponse(500, 'File upload error');
  1948. return false;
  1949. }
  1950. if (strpos($_FILES['file']['type'], 'image/') === false) {
  1951. $this->setResponse(403, 'File Type not image', $_FILES['file']['type']);
  1952. return false;
  1953. }
  1954. if (!$this->approvedFileType($_FILES['file']['tmp_name'])) {
  1955. $this->setResponse(403, 'File Type not approved', $_FILES['file']['tmp_name']);
  1956. return false;
  1957. }
  1958. if (!$this->approvedFileExtension($_FILES['file']['name'])) {
  1959. $this->setResponse(403, 'File Extension not approved');
  1960. return false;
  1961. }
  1962. ini_set('upload_max_filesize', '10M');
  1963. ini_set('post_max_size', '10M');
  1964. $tempFile = $_FILES['file']['tmp_name'];
  1965. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1966. $this->makeDir($targetPath);
  1967. $targetFile = $targetPath . $this->sanitizeUserString($_FILES['file']['name']);
  1968. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  1969. return move_uploaded_file($tempFile, $targetFile);
  1970. }
  1971. public function formatPingHost($host)
  1972. {
  1973. $host = $this->qualifyURL($host, true);
  1974. if ($host['port'] !== '') {
  1975. $host['port'] = str_replace(':', '', $host['port']);
  1976. }
  1977. if ($host['host'] == '' && $host['path'] !== '') {
  1978. $host['host'] = $host['path'];
  1979. $host['path'] = '';
  1980. if (strpos($host['host'], '/') !== false) {
  1981. $host['host'] = explode('/', $host['host'])[0];
  1982. }
  1983. }
  1984. return $host;
  1985. }
  1986. public function ping($pings)
  1987. {
  1988. if ($this->qualifyRequest($this->config['pingAuth'], true)) {
  1989. if (!$pings['list']) {
  1990. $this->setAPIResponse('error', 'No ping hostname/IP\'s entered', 409);
  1991. return null;
  1992. }
  1993. $pings = $pings['list'];
  1994. $type = gettype($pings);
  1995. $ping = new Ping("");
  1996. $ping->setTtl(128);
  1997. $ping->setTimeout(2);
  1998. switch ($type) {
  1999. case "array":
  2000. $results = [];
  2001. foreach ($pings as $k => $v) {
  2002. $pingFormatted = $this->formatPingHost($v);
  2003. $ping->setHost($pingFormatted['host']);
  2004. if ($pingFormatted['port'] !== '') {
  2005. $ping->setPort($pingFormatted['port']);
  2006. $latency = $ping->ping('fsockopen');
  2007. } else {
  2008. $latency = $ping->ping();
  2009. }
  2010. if ($latency || $latency === 0) {
  2011. $results[$v] = $latency;
  2012. } else {
  2013. $results[$v] = false;
  2014. }
  2015. }
  2016. break;
  2017. case "string":
  2018. $pingFormatted = $this->formatPingHost($pings);
  2019. $ping->setHost($pingFormatted['host']);
  2020. if ($pingFormatted['port'] !== '') {
  2021. $ping->setPort($pingFormatted['port']);
  2022. $latency = $ping->ping('fsockopen');
  2023. } else {
  2024. $latency = $ping->ping();
  2025. }
  2026. if ($latency || $latency === 0) {
  2027. $results = $latency;
  2028. } else {
  2029. $results = null;
  2030. }
  2031. break;
  2032. }
  2033. return ($results) ?? null;
  2034. }
  2035. return null;
  2036. }
  2037. public function getPluginSettings()
  2038. {
  2039. return [
  2040. 'Marketplace' => [
  2041. $this->settingsOption('notice', null, ['notice' => 'danger', 'body' => '3rd Party Repositories are not affiliated with Organizr and therefore the code on these repositories are not inspected. Use at your own risk.']),
  2042. $this->settingsOption('multiple-url', 'externalPluginMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  2043. $this->settingsOption('token', 'githubAccessToken', ['label' => 'Github Person Access Token', 'help' => 'The Github Person Access Token will help with API rate limiting as well as let you access your own Private Repos']),
  2044. $this->settingsOption('switch', 'checkForPluginUpdate', ['label' => 'Check for Plugin Updates', ['help' => 'Check for updates on page load']])
  2045. ]
  2046. ];
  2047. }
  2048. public function getThemeSettings()
  2049. {
  2050. return [
  2051. 'Marketplace' => [
  2052. $this->settingsOption('notice', null, ['notice' => 'danger', 'body' => '3rd Party Repositories are not affiliated with Organizr and therefore the themes on these repositories are not inspected. Use at your own risk.']),
  2053. $this->settingsOption('multiple-url', 'externalThemeMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  2054. $this->settingsOption('token', 'githubAccessToken', ['label' => 'Github Person Access Token', 'help' => 'The Github Person Access Token will help with API rate limiting as well as let you access your own Private Repos']),
  2055. $this->settingsOption('switch', 'checkForThemeUpdate', ['label' => 'Check for Theme Updates', ['help' => 'Check for updates on page load']])
  2056. ]
  2057. ];
  2058. }
  2059. public function getCustomizeAppearance()
  2060. {
  2061. return [
  2062. 'Top Bar' => [
  2063. $this->settingsOption('input', 'logo', ['label' => 'Logo URL']),
  2064. $this->settingsOption('input', 'title', ['label' => 'Organizr Title']),
  2065. $this->settingsOption('switch', 'useLogo', ['label' => 'Use Logo instead of Title', 'help' => 'Also sets the title of your site']),
  2066. $this->settingsOption('input', 'description', ['label' => 'Meta Description', 'help' => 'Used to set the description for SEO meta tags']),
  2067. ],
  2068. 'Side Menu' => [
  2069. $this->settingsOption('switch', 'allowCollapsableSideMenu', ['label' => 'Allow Side Menu to be Collapsable']),
  2070. $this->settingsOption('switch', 'sideMenuCollapsed', ['label' => 'Side Menu Collapsed at Launch']),
  2071. $this->settingsOption('switch', 'collapseSideMenuOnClick', ['label' => 'Collapse Side Menu after clicking Tab']),
  2072. $this->settingsOption('switch', 'githubMenuLink', ['label' => 'Show GitHub Repo Link']),
  2073. $this->settingsOption('switch', 'organizrFeatureRequestLink', ['label' => 'Show Organizr Feature Request Link']),
  2074. $this->settingsOption('switch', 'organizrSupportMenuLink', ['label' => 'Show Organizr Support Link']),
  2075. $this->settingsOption('switch', 'organizrDocsMenuLink', ['label' => 'Show Organizr Docs Link']),
  2076. $this->settingsOption('switch', 'organizrSignoutMenuLink', ['label' => 'Show Organizr Sign out & in Button on Sidebar']),
  2077. $this->settingsOption('switch', 'expandCategoriesByDefault', ['label' => 'Expand All Categories']),
  2078. $this->settingsOption('switch', 'autoCollapseCategories', ['label' => 'Auto-Collapse Categories']),
  2079. $this->settingsOption('switch', 'autoExpandNavBar', ['label' => 'Auto-Expand Nav Bar']),
  2080. $this->settingsOption('select', 'unsortedTabs', ['label' => 'Unsorted Tab Placement', 'options' => [['name' => 'Top', 'value' => 'top'], ['name' => 'Bottom', 'value' => 'bottom']]]),
  2081. ],
  2082. 'Login Page' => [
  2083. $this->settingsOption('input', 'loginLogo', ['label' => 'Login Logo URL']),
  2084. $this->settingsOption('multiple-url', 'loginWallpaper', ['label' => 'Login Wallpaper URL', 'help' => 'You may enter multiple URL\'s']),
  2085. $this->settingsOption('switch', 'useLogoLogin', ['label' => 'Use Logo instead of Title on Login Page']),
  2086. $this->settingsOption('switch', 'minimalLoginScreen', ['label' => 'Minimal Login Screen']),
  2087. $this->settingsOption('switch', 'useRandomMediaImage', ['label' => 'Use Random Media Wallpaper From Media Server']),
  2088. ],
  2089. 'Options' => [
  2090. $this->settingsOption('switch', 'alternateHomepageHeaders', ['label' => 'Alternate Homepage Titles']),
  2091. $this->settingsOption('switch', 'disableHomepageModals', ['label' => 'Disable Homepage Saved Modal', 'help' => 'Disable the modal when saving homepage config settings']),
  2092. $this->settingsOption('switch', 'debugErrors', ['label' => 'Show Debug Errors']),
  2093. $this->settingsOption('switch', 'easterEggs', ['label' => 'Show Easter Eggs']),
  2094. $this->settingsOption('input', 'gaTrackingID', ['label' => 'Google Analytics Tracking ID', 'placeholder' => 'e.g. UA-XXXXXXXXX-X']),
  2095. ],
  2096. 'Colors & Themes' => [
  2097. $this->settingsOption('notice', null, ['notice' => 'info', 'title' => 'Attention', 'bodyHTML' => '<span lang="en">The value of #987654 is just a placeholder, you can change to any value you like.</span><span lang="en">To revert back to default, save with no value defined in the relevant field.</span>']),
  2098. $this->settingsOption('blank'),
  2099. $this->settingsOption('button', '', ['label' => 'Reset Colors', 'icon' => 'fa fa-ticket', 'text' => 'Reset', 'attr' => 'onclick="resetCustomColors()"']),
  2100. $this->settingsOption('blank'),
  2101. $this->settingsOption('color', 'headerColor', ['label' => 'Nav Bar Color']),
  2102. $this->settingsOption('color', 'headerTextColor', ['label' => 'Nav Bar Text Color']),
  2103. $this->settingsOption('color', 'sidebarColor', ['label' => 'Side Bar Color']),
  2104. $this->settingsOption('color', 'sidebarTextColor', ['label' => 'Side Bar Text Color']),
  2105. $this->settingsOption('color', 'accentColor', ['label' => 'Accent Color']),
  2106. $this->settingsOption('color', 'accentTextColor', ['label' => 'Accent Text Color']),
  2107. $this->settingsOption('color', 'buttonColor', ['label' => 'Button Color']),
  2108. $this->settingsOption('color', 'buttonTextColor', ['label' => 'Button Text Color']),
  2109. $this->settingsOption('select', 'theme', ['label' => 'Theme', 'class' => 'themeChanger', 'options' => $this->getAllThemes()]),
  2110. $this->settingsOption('select', 'style', ['label' => 'Style', 'class' => 'styleChanger', 'options' => [['name' => 'Light', 'value' => 'light'], ['name' => 'Dark', 'value' => 'dark'], ['name' => 'Horizontal', 'value' => 'horizontal']]]),
  2111. ],
  2112. 'Notifications' => [
  2113. $this->settingsOption('select', 'notificationBackbone', ['label' => 'Type', 'class' => 'notifyChanger', 'options' => $this->notificationTypesOptions()]),
  2114. $this->settingsOption('select', 'notificationPosition', ['label' => 'Position', 'class' => 'notifyPositionChanger', 'options' => $this->notificationPositionsOptions()]),
  2115. $this->settingsOption('html', null, ['label' => 'Test Message', 'html' => '
  2116. <div class="btn-group m-r-10 dropup">
  2117. <button aria-expanded="false" data-toggle="dropdown" class="btn btn-info btn-outline dropdown-toggle waves-effect waves-light" type="button">
  2118. <i class="fa fa-comment m-r-5"></i>
  2119. <span>Test </span>
  2120. </button>
  2121. <ul role="menu" class="dropdown-menu">
  2122. <li><a onclick="message(\'Test Message\',\'This is a success Message\',activeInfo.settings.notifications.position,\'#FFF\',\'success\',\'5000\');">Success</a></li>
  2123. <li><a onclick="message(\'Test Message\',\'This is a info Message\',activeInfo.settings.notifications.position,\'#FFF\',\'info\',\'5000\');">Info</a></li>
  2124. <li><a onclick="message(\'Test Message\',\'This is a warning Message\',activeInfo.settings.notifications.position,\'#FFF\',\'warning\',\'5000\');">Warning</a></li>
  2125. <li><a onclick="message(\'Test Message\',\'This is a error Message\',activeInfo.settings.notifications.position,\'#FFF\',\'error\',\'5000\');">Error</a></li>
  2126. </ul>
  2127. </div>
  2128. ']
  2129. ),
  2130. ],
  2131. 'FavIcon' => [
  2132. $this->settingsOption('html', null, ['label' => 'Instructions', 'override' => 12, 'html' => '
  2133. <div class="panel panel-default">
  2134. <div class="panel-heading">
  2135. <a href="https://realfavicongenerator.net/" target="_blank"><span class="label label-info m-l-5">Visit FavIcon Site</span></a>
  2136. </div>
  2137. <div class="panel-wrapper collapse in">
  2138. <div class="panel-body">
  2139. <ul class="list-icons">
  2140. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Select your Favicon picture]</li>
  2141. <li lang="en"><i class="fa fa-caret-right text-info"></i> Choose your image to use</li>
  2142. <li lang="en"><i class="fa fa-caret-right text-info"></i> Edit settings to your liking</li>
  2143. <li lang="en"><i class="fa fa-caret-right text-info"></i> At bottom of page on [Favicon Generator Options] under [Path] choose [I cannot or I do not want to place favicon files at the root of my web site.]</li>
  2144. <li lang="en"><i class="fa fa-caret-right text-info"></i> Enter this path <code>data/favicon</code></li>
  2145. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Generate your Favicons and HTML code]</li>
  2146. <li lang="en"><i class="fa fa-caret-right text-info"></i> Download and unzip file and place in <code>data/favicon</code></li>
  2147. <li lang="en"><i class="fa fa-caret-right text-info"></i> Copy code and paste inside left box</li>
  2148. </ul>
  2149. </div>
  2150. </div>
  2151. </div>
  2152. ']
  2153. ),
  2154. $this->settingsOption('code-editor', 'favIcon', ['label' => 'Fav Icon Code', 'mode' => 'html']),
  2155. ],
  2156. 'Custom CSS' => [
  2157. $this->settingsOption('code-editor', 'customCss', ['label' => 'Custom CSS', 'mode' => 'css']),
  2158. ],
  2159. 'Theme CSS' => [
  2160. $this->settingsOption('code-editor', 'customThemeCss', ['label' => 'Theme CSS', 'mode' => 'css']),
  2161. ],
  2162. 'Custom Javascript' => [
  2163. $this->settingsOption('code-editor', 'customJava', ['label' => 'Custom Javascript', 'mode' => 'javascript']),
  2164. ],
  2165. 'Theme Javascript' => [
  2166. $this->settingsOption('code-editor', 'customThemeJava', ['label' => 'Theme Javascript', 'mode' => 'javascript']),
  2167. ],
  2168. ];
  2169. }
  2170. public function loadAppearance()
  2171. {
  2172. $appearance['logo'] = $this->config['logo'];
  2173. $appearance['title'] = $this->config['title'];
  2174. $appearance['useLogo'] = $this->config['useLogo'];
  2175. $appearance['useLogoLogin'] = $this->config['useLogoLogin'];
  2176. $appearance['headerColor'] = $this->config['headerColor'];
  2177. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2178. $appearance['sidebarColor'] = $this->config['sidebarColor'];
  2179. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2180. $appearance['sidebarTextColor'] = $this->config['sidebarTextColor'];
  2181. $appearance['accentColor'] = $this->config['accentColor'];
  2182. $appearance['accentTextColor'] = $this->config['accentTextColor'];
  2183. $appearance['buttonColor'] = $this->config['buttonColor'];
  2184. $appearance['buttonTextColor'] = $this->config['buttonTextColor'];
  2185. $appearance['buttonTextHoverColor'] = $this->config['buttonTextHoverColor'];
  2186. $appearance['buttonHoverColor'] = $this->config['buttonHoverColor'];
  2187. $appearance['loginWallpaper'] = $this->config['loginWallpaper'];
  2188. $appearance['randomMediaImage'] = $this->getRandomMediaImage('np');
  2189. $appearance['loginLogo'] = $this->config['loginLogo'];
  2190. $appearance['customCss'] = $this->config['customCss'];
  2191. $appearance['customThemeCss'] = $this->config['customThemeCss'];
  2192. $appearance['customJava'] = $this->config['customJava'];
  2193. $appearance['customThemeJava'] = $this->config['customThemeJava'];
  2194. return $appearance;
  2195. }
  2196. public function getRandomMediaImage($type = null)
  2197. {
  2198. if (!$this->config['useRandomMediaImage']) {
  2199. return false;
  2200. }
  2201. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache')) {
  2202. $folder = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache';
  2203. try {
  2204. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  2205. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  2206. $image = null;
  2207. switch ($type) {
  2208. case 'np':
  2209. $i = 0;
  2210. $array = iterator_to_array($iteratorIterator);
  2211. if (count($array) > 0) {
  2212. shuffle($array);
  2213. $iteratorIterator = new ArrayIterator($array);
  2214. }
  2215. foreach ($iteratorIterator as $info) {
  2216. if (stripos($info->getFilename(), 'np') !== false) {
  2217. if ($i < 1) {
  2218. $imageInfo = getimagesize($folder . DIRECTORY_SEPARATOR . $info->getFilename());
  2219. if ($imageInfo[0] >= $this->getCacheImageSize('npw')) {
  2220. $image = 'data/cache/' . $info->getFilename();
  2221. $i++;
  2222. }
  2223. } else {
  2224. break;
  2225. }
  2226. }
  2227. }
  2228. return $image;
  2229. default:
  2230. return false;
  2231. }
  2232. } catch (Exception $e) {
  2233. return false;
  2234. }
  2235. } else {
  2236. return false;
  2237. }
  2238. }
  2239. public function getSettingsMain()
  2240. {
  2241. $certificateStatus = $this->hasCustomCert() ? '<span lang="en">Custom Certificate Loaded</span><br />Located at <span>' . $this->getCustomCert() . '</span>' : '<span lang="en">Custom Certificate not found - please upload below</span>';
  2242. $settings = [
  2243. 'Socks' => [
  2244. $this->settingsOption('switch', 'socksDebug', ['label' => 'Enable Debug Log', 'help' => 'Enable the option to have socks output to logs']),
  2245. $this->settingsOption('number', 'maxSocksDebugSize', ['label' => 'Max Debug Data Rows', 'help' => 'Max amount of rows in debug log', 'attr' => 'min="1"'])
  2246. ],
  2247. 'Settings Page' => [
  2248. $this->settingsOption('select', 'defaultSettingsTab', ['label' => 'Default Settings Tab', 'options' => $this->getSettingsTabs(), 'help' => 'Choose which Settings Tab to be default when opening settings page']),
  2249. ],
  2250. 'Other' => [
  2251. $this->settingsOption('switch', 'checkForUpdate', ['label' => 'Check For Update', 'help' => 'Check for update on Organizr load']),
  2252. ],
  2253. 'Github' => [
  2254. $this->settingsOption('select', 'branch', ['label' => 'Branch', 'value' => $this->config['branch'], 'options' => $this->getBranches(), 'disabled' => $this->docker, 'help' => ($this->docker) ? 'Since you are using the Official Docker image, Change the image to change the branch' : 'Choose which branch to download from']),
  2255. $this->settingsOption('button', 'force-install-branch', ['label' => 'Force Install Branch', 'class' => 'updateNow', 'icon' => 'fa fa-download', 'text' => 'Retrieve', 'attr' => ($this->docker) ? 'title="You can just restart your docker to update"' : '', 'help' => ($this->docker) ? 'Since you are using the official Docker image, you can just restart your Docker container to update Organizr' : 'This will re-download all of the source files for Organizr']),
  2256. ],
  2257. 'API' => [
  2258. $this->settingsOption('password-alt-copy', 'organizrAPI', ['label' => 'Organizr API']),
  2259. $this->settingsOption('button', null, ['label' => 'Generate New API Key', 'class' => 'newAPIKey', 'icon' => 'fa fa-refresh', 'text' => 'Generate']),
  2260. $this->settingsOption('notice', null, ['title' => 'API Documentation', 'body' => 'The documentation for Organizr\'s API is included with this installation. To access the docs, use the button below.', 'bodyHTML' => '<br/><br/><div class="row"><div class="col-lg-2 col-sm-4 col-xs-12"><a href="' . $this->getServerPath() . 'docs/" target="_blank" class="btn btn-block btn-primary text-white" lang="en">Organizr Docs</a></div></div>'])
  2261. ],
  2262. 'Authentication' => [
  2263. $this->settingsOption('select', 'authType', ['id' => 'authSelect', 'label' => 'Authentication Type', 'value' => $this->config['authType'], 'options' => $this->getAuthTypes()]),
  2264. $this->settingsOption('select', 'authBackend', ['id' => 'authBackendSelect', 'label' => 'Authentication Backend', 'class' => 'backendAuth switchAuth', 'value' => $this->config['authBackend'], 'options' => $this->getAuthBackends()]),
  2265. $this->settingsOption('token', 'plexToken', ['class' => 'plexAuth switchAuth']),
  2266. $this->settingsOption('button', '', ['class' => 'getPlexTokenAuth plexAuth switchAuth', 'label' => 'Get Plex Token', 'icon' => 'fa fa-ticket', 'text' => 'Retrieve', 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#settings-main-form [name=plexToken]\')"']),
  2267. $this->settingsOption('password-alt', 'plexID', ['class' => 'plexAuth switchAuth', 'label' => 'Plex Machine', 'placeholder' => 'Use Get Plex Machine Button']),
  2268. $this->settingsOption('button', '', ['class' => 'getPlexMachineAuth plexAuth switchAuth', 'label' => 'Get Plex Machine', 'icon' => 'fa fa-id-badge', 'text' => 'Retrieve', 'attr' => 'onclick="showPlexMachineForm(\'#settings-main-form [name=plexID]\')"']),
  2269. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email', 'class' => 'plexAuth switchAuth', 'placeholder' => 'Admin username for Plex']),
  2270. $this->settingsOption('switch', 'plexoAuth', ['label' => 'Enable Plex oAuth', 'class' => 'plexAuth switchAuth']),
  2271. $this->settingsOption('switch', 'ignoreTFAIfPlexOAuth', ['label' => 'Ignore 2FA if Plex OAuth ', 'class' => 'plexAuth switchAuth', 'help' => 'Enabling this will disable Organizr 2FA (If applicable) if User uses Plex OAuth to login']),
  2272. $this->settingsOption('switch', 'plexStrictFriends', ['label' => 'Strict Plex Friends ', 'class' => 'plexAuth switchAuth', 'help' => 'Enabling this will only allow Friends that have shares to the Machine ID entered above to login, Having this disabled will allow all Friends on your Friends list to login']),
  2273. $this->settingsOption('switch', 'ignoreTFALocal', ['label' => 'Ignore External 2FA on Local Subnet', 'help' => 'Enabling this will bypass external 2FA security if user is on local Subnet']),
  2274. $this->settingsOption('url', 'authBackendHost', ['class' => 'ldapAuth ftpAuth switchAuth', 'label' => 'Host Address', 'placeholder' => 'http(s) | ftp(s) | ldap(s)://hostname:port']),
  2275. $this->settingsOption('input', 'authBaseDN', ['class' => 'ldapAuth switchAuth', 'label' => 'Host Base DN', 'placeholder' => 'cn=%s,dc=sub,dc=domain,dc=com']),
  2276. $this->settingsOption('input', 'authBackendHostPrefix', ['class' => 'ldapAuth switchAuth', 'label' => 'Account Prefix', 'id' => 'authBackendHostPrefix-input', 'placeholder' => 'Account prefix - i.e. Controller\ from Controller\Username for AD - uid= for OpenLDAP']),
  2277. $this->settingsOption('input', 'authBackendHostSuffix', ['class' => 'ldapAuth switchAuth', 'label' => 'Account Suffix', 'id' => 'authBackendHostSuffix-input', 'placeholder' => 'Account suffix - start with comma - ,ou=people,dc=domain,dc=tld']),
  2278. $this->settingsOption('input', 'ldapBindUsername', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Username']),
  2279. $this->settingsOption('password', 'ldapBindPassword', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Password']),
  2280. $this->settingsOption('select', 'ldapType', ['id' => 'ldapType', 'label' => 'LDAP Backend Type', 'class' => 'ldapAuth switchAuth', 'options' => $this->getLDAPOptions()]),
  2281. $this->settingsOption('html', null, ['class' => 'ldapAuth switchAuth', 'label' => 'Account DN', 'html' => '<span id="accountDN" class="ldapAuth switchAuth">' . $this->config['authBackendHostPrefix'] . 'TestAcct' . $this->config['authBackendHostSuffix'] . '</span>']),
  2282. $this->settingsOption('blank', null, ['class' => 'ldapAuth switchAuth']),
  2283. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP SSL', 'help' => 'This will enable the use of SSL for LDAP connections']),
  2284. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP TLS', 'help' => 'This will enable the use of TLS for LDAP connections']),
  2285. $this->settingsOption('test', 'ldap', ['class' => 'ldapAuth switchAuth']),
  2286. $this->settingsOption('test', '', ['label' => 'Test Login', 'class' => 'ldapAuth switchAuth', 'text' => 'Test Login', 'attr' => 'onclick="showLDAPLoginTest()"']),
  2287. $this->settingsOption('url', 'embyURL', ['class' => 'embyAuth switchAuth', 'label' => 'Emby URL', 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.']),
  2288. $this->settingsOption('token', 'embyToken', ['class' => 'embyAuth switchAuth', 'label' => 'Emby Token']),
  2289. $this->settingsOption('url', 'jellyfinURL', ['class' => 'jellyfinAuth switchAuth', 'label' => 'Jellyfin URL', 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.']),
  2290. $this->settingsOption('token', 'jellyfinToken', ['class' => 'jellyfinAuth switchAuth', 'label' => 'Jellyfin Token']),
  2291. ],
  2292. 'Security' => [
  2293. $this->settingsOption('number', 'loginAttempts', ['label' => 'Max Login Attempts']),
  2294. $this->settingsOption('select', 'loginLockout', ['label' => 'Login Lockout Seconds', 'options' => $this->timeOptions()]),
  2295. $this->settingsOption('number', 'lockoutTimeout', ['label' => 'Inactivity Timer [Minutes]']),
  2296. $this->settingsOption('switch', 'lockoutSystem', ['label' => 'Inactivity Lock']),
  2297. $this->settingsOption('select', 'lockoutMinAuth', ['label' => 'Lockout Groups From', 'options' => $this->groupSelect()]),
  2298. $this->settingsOption('select', 'lockoutMaxAuth', ['label' => 'Lockout Groups To', 'options' => $this->groupSelect()]),
  2299. $this->settingsOption('switch', 'matchUserAgents', ['label' => 'Match UserAgent', 'help' => 'Match Browser UserAgent to Token UserAgent - Can be very aggressive on matching']),
  2300. $this->settingsOption('switch', 'matchUserIP', ['label' => 'Match User IP', 'help' => 'Match User IP to Token IP - Also allows approval if user token is valid and is local to server']),
  2301. $this->settingsOption('switch', 'traefikAuthEnable', ['label' => 'Enable Traefik Auth Redirect', 'help' => 'This will enable the webserver to forward errors so traefik will accept them']),
  2302. $this->settingsOption('input', 'traefikDomainOverride', ['label' => 'Traefik Domain for Return Override', 'help' => 'Please use a FQDN on this URL Override', 'placeholder' => 'http(s)://domain']),
  2303. $this->settingsOption('select', 'debugAreaAuth', ['label' => 'Minimum Authentication for Debug Area', 'options' => $this->groupSelect(), 'settings' => '{}']),
  2304. $this->settingsOption('multiple', 'sandbox', ['override' => 12, 'label' => 'iFrame Sandbox', 'help' => 'WARNING! This can potentially mess up your iFrames', 'options' => $this->sandboxOptions()]),
  2305. $this->settingsOption('multiple', 'iframeAllow', ['override' => 12, 'label' => 'iFrame Allow', 'help' => 'WARNING! This can potentially mess up your iFrames', 'options' => $this->iframeAllowOptions()]),
  2306. $this->settingsOption('multiple', 'blacklisted', ['override' => 12, 'label' => 'Blacklisted IP\'s', 'help' => 'WARNING! This will block anyone with these IP\'s', 'options' => $this->makeOptionsFromValues($this->config['blacklisted']), 'settings' => '{tags: true}']),
  2307. $this->settingsOption('code-editor', 'blacklistedMessage', ['mode' => 'html']),
  2308. ],
  2309. 'Logs' => [
  2310. $this->settingsOption('folder', 'logLocation', ['label' => 'Log Save Path', 'help' => 'Folder path to save Organizr Logs - Please test before saving', 'value' => $this->logLocation()]),
  2311. $this->settingsOption('select', 'logLevel', ['label' => 'Log Level', 'options' => $this->logLevels()]),
  2312. $this->settingsOption('switch', 'includeDatabaseQueriesInDebug', ['label' => 'Include Database Queries', 'help' => 'Include Database queries in debug logs']),
  2313. $this->settingsOption('number', 'maxLogFiles', ['label' => 'Maximum Log Files', 'help' => 'Number of log files to preserve', 'attr' => 'min="1"']),
  2314. $this->settingsOption('select', 'logLiveUpdateRefresh', ['label' => 'Live Update Refresh', 'options' => $this->timeOptions()]),
  2315. $this->settingsOption('select', 'logPageSize', ['label' => 'Log Page Size', 'options' => [['name' => '10 Items', 'value' => '10'], ['name' => '25 Items', 'value' => '25'], ['name' => '50 Items', 'value' => '50'], ['name' => '100 Items', 'value' => '100']]]),
  2316. $this->settingsOption('switch', 'sendLogsToSlack', ['label' => 'Send Logs to Slack', 'help' => 'Send Logs to Slack as well']),
  2317. $this->settingsOption('select', 'slackLogLevel', ['label' => 'Slack Log Level', 'options' => $this->logLevels()]),
  2318. $this->settingsOption('url', 'slackLogWebhook', ['label' => 'Slack Webhook URL', 'help' => 'If using Discord make sure to end the URL with /slack']),
  2319. $this->settingsOption('input', 'slackLogWebHookChannel', ['label' => 'Slack Channel for Webhook', 'help' => 'Channel ID for webhook - Not needed for Discord']),
  2320. $this->settingsOption('blank'),
  2321. $this->settingsOption('test', 'slack-logs', ['label' => 'Test Slack', 'text' => 'Test Slack', 'help' => 'Test only sends a warning message so make sure Slack Log Level is Warning when testing']),
  2322. ],
  2323. 'Cron' => [
  2324. $this->settingsOption('cron-file'),
  2325. $this->settingsOption('blank'),
  2326. $this->settingsOption('enable', 'autoUpdateCronEnabled', ['label' => 'Auto-Update Organizr']),
  2327. $this->settingsOption('cron', 'autoUpdateCronSchedule'),
  2328. $this->settingsOption('enable', 'autoBackupCronEnabled', ['label' => 'Auto-Backup Organizr']),
  2329. $this->settingsOption('cron', 'autoBackupCronSchedule'),
  2330. $this->settingsOption('number', 'keepBackupsCountCron', ['label' => '# Backups Keep', 'help' => 'Number of backups to keep', 'attr' => 'min="1"']),
  2331. $this->settingsOption('folder', 'backupLocation', ['label' => 'Backup Save Path', 'help' => 'Folder path to save Organizr Backups - Please test before saving', 'value' => $this->getOrganizrBackupLocation()]),
  2332. $this->settingsOption('blank'),
  2333. ],
  2334. 'Login' => [
  2335. $this->settingsOption('password', 'registrationPassword', ['label' => 'Registration Password', 'help' => 'Sets the password for the Registration form on the login screen']),
  2336. $this->settingsOption('switch', 'hideRegistration', ['label' => 'Hide Registration', 'help' => 'Enable this to hide the Registration button on the login screen']),
  2337. $this->settingsOption('number', 'rememberMeDays', ['label' => 'Remember Me Length', 'help' => 'Number of days cookies and tokens will be valid for', 'attr' => 'min="1"']),
  2338. $this->settingsOption('switch', 'rememberMe', ['label' => 'Remember Me', 'help' => 'Default status of Remember Me button on login screen']),
  2339. $this->settingsOption('multiple-url', 'localIPList', ['label' => 'Override Local IP or Subnet', 'help' => 'IPv4 only at the moment - This will set your login as local if your IP falls within the From and To']),
  2340. $this->settingsOption('input', 'wanDomain', ['label' => 'WAN Domain', 'placeholder' => 'only domain and tld - i.e. domain.com', 'help' => 'Enter domain if you wish to be forwarded to a local address - Local Address filled out on next item']),
  2341. $this->settingsOption('url', 'localAddress', ['label' => 'Local Address', 'placeholder' => 'http://home.local', 'help' => 'Full local address of organizr install - i.e. http://home.local or http://192.168.0.100']),
  2342. $this->settingsOption('switch', 'enableLocalAddressForward', ['label' => 'Enable Local Address Forward', 'help' => 'Enables the local address forward if on local address and accessed from WAN Domain']),
  2343. $this->settingsOption('switch', 'disableRecoverPass', ['label' => 'Disable Recover Password', 'help' => 'Disables recover password area']),
  2344. $this->settingsOption('input', 'customForgotPassText', ['label' => 'Custom Recover Password Text', 'help' => 'Text or HTML for recovery password section']),
  2345. ],
  2346. 'Auth Proxy' => [
  2347. $this->settingsOption('switch', 'authProxyEnabled', ['label' => 'Auth Proxy', 'help' => 'Enable option to set Auth Proxy Header Login']),
  2348. $this->settingsOption('input', 'authProxyWhitelist', ['label' => 'Auth Proxy Whitelist', 'placeholder' => 'i.e. 10.0.0.0/24 or 10.0.0.20', 'help' => 'IPv4 only at the moment - This must be set to work, will accept subnet or IP address']),
  2349. $this->settingsOption('input', 'authProxyHeaderName', ['label' => 'Auth Proxy Header Name', 'placeholder' => 'i.e. X-Forwarded-User', 'help' => 'Please choose a unique value for added security']),
  2350. $this->settingsOption('input', 'authProxyHeaderNameEmail', ['label' => 'Auth Proxy Header Name for Email', 'placeholder' => 'i.e. X-Forwarded-Email', 'help' => 'Please choose a unique value for added security']),
  2351. $this->settingsOption('switch', 'authProxyOverrideLogout', ['label' => 'Override Logout', 'help' => 'Enable option to set custom Logout URL for Auth Proxy']),
  2352. $this->settingsOption('input', 'authProxyLogoutURL', ['label' => 'Logout URL', 'help' => 'Logout URL to redirect user for Auth Proxy']),
  2353. ],
  2354. 'Ping' => [
  2355. $this->settingsOption('auth', 'pingAuth'),
  2356. $this->settingsOption('auth', 'pingAuthMessage', ['label' => 'Minimum Authentication for Message and Sound']),
  2357. $this->settingsOption('select', 'pingOnlineSound', ['label' => 'Online Sound', 'options' => $this->getSounds()]),
  2358. $this->settingsOption('select', 'pingOfflineSound', ['label' => 'Offline Sound', 'options' => $this->getSounds()]),
  2359. $this->settingsOption('switch', 'pingMs', ['label' => 'Show Ping Time']),
  2360. $this->settingsOption('switch', 'statusSounds', ['label' => 'Enable Notify Sounds', 'help' => 'Will play a sound if the server goes down and will play sound if comes back up.']),
  2361. $this->settingsOption('auth', 'pingAuthMs', ['label' => 'Minimum Authentication for Time Display']),
  2362. $this->settingsOption('refresh', 'adminPingRefresh', ['label' => 'Admin Refresh Seconds']),
  2363. $this->settingsOption('refresh', 'otherPingRefresh', ['label' => 'Everyone Refresh Seconds']),
  2364. ],
  2365. 'Certificate' => [
  2366. $this->settingsOption('html', '', ['override' => 12,
  2367. 'html' => '
  2368. <script>
  2369. let myDropzone = new Dropzone("#upload-custom-certificate", {
  2370. url: "api/v2/certificate/custom",
  2371. headers:{ "formKey": local("g","formKey") },
  2372. init: function() {
  2373. this.on("complete", function(file) {
  2374. if(file["status"] === "success"){
  2375. $(".custom-certificate-status").html("<span lang=\"en\">Custom Certificate Loaded</span>");
  2376. }else{
  2377. $(".custom-certificate-status").html("<span lang=\"en\">Error Saving file...</span>");
  2378. }
  2379. });
  2380. }
  2381. });
  2382. </script>
  2383. <div class="row">
  2384. <div class="col-lg-12">
  2385. <div class="panel panel-info">
  2386. <div class="panel-heading"><span lang="en">Notice</span></div>
  2387. <div class="panel-wrapper collapse in" aria-expanded="true">
  2388. <div class="panel-body">
  2389. <span lang="en">By default, Organizr uses certificates from https://curl.se/docs/caextract.html<br/>If you would like to use your own certificate, please upload it below. You will then need to enable each homepage item to use it.</span>
  2390. </div>
  2391. </div>
  2392. </div>
  2393. </div>
  2394. </div>
  2395. <div class="row">
  2396. <div class="col-md-12">
  2397. <div class="white-box">
  2398. <h3 class="box-title m-b-0" lang="en">Custom Certificate Status</h3>
  2399. <p class="text-muted m-b-30 custom-certificate-status">' . $certificateStatus . '</p>
  2400. <form action="#" class="dropzone dz-clickable" id="upload-custom-certificate">
  2401. <div class="dz-default dz-message"><span lang="en">Drop Certificate file here to upload</span></div>
  2402. </form>
  2403. </div>
  2404. </div>
  2405. </div>
  2406. ']
  2407. )
  2408. ],
  2409. ];
  2410. if ($this->config['driver'] == 'sqlite3') {
  2411. $database = [
  2412. 'Database' => [
  2413. $this->settingsOption('notice', '', ['notice' => 'danger', 'title' => 'Warning', 'body' => 'This feature is experimental - You may face unexpected database is locked errors in logs']),
  2414. $this->settingsOption('html', '', ['label' => 'Journal Mode Status', 'html' => '<script>getJournalMode();</script><h4 class="journal-mode font-bold text-uppercase"><i class="fa fa-spin fa-circle-o-notch"></i></h4>']),
  2415. $this->settingsOption('button', '', ['label' => 'Set DELETE Mode (Default)', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'DELETE\')"']),
  2416. $this->settingsOption('button', '', ['label' => 'Set WAL Mode', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'WAL\')"']),
  2417. ]
  2418. ];
  2419. $settings = array_merge($settings, $database);
  2420. }
  2421. ksort($settings);
  2422. return $settings;
  2423. }
  2424. public function getSettingsSSO()
  2425. {
  2426. return [
  2427. 'FYI' => [
  2428. $this->settingsOption('html', '', ['override' => 12,
  2429. 'html' => '
  2430. <div class="row">
  2431. <div class="col-lg-12">
  2432. <div class="panel panel-primary">
  2433. <div class="panel-heading"><span lang="en">Please Read First</span></div>
  2434. <div class="panel-wrapper collapse in" aria-expanded="true">
  2435. <div class="panel-body">
  2436. <span lang="en">Using multiple SSO application will cause your Cookie Header item to increase. If you haven\'t increased it by now, please follow this guide</span>
  2437. <br/><br/>
  2438. <div class="row">
  2439. <div class="col-lg-2 col-sm-4 col-xs-12">
  2440. <a href="https://docs.organizr.app/help/faq/organizr-login-error" target="_blank" class="btn btn-block btn-primary text-white" lang="en">Cookie Header Guide</a>
  2441. </div>
  2442. </div>
  2443. <br/>
  2444. <span lang="en">This is not the same as database authentication - i.e. Plex Authentication | Emby Authentication | FTP Authentication<br/>Click Main on the sub-menu above.</span>
  2445. </div>
  2446. </div>
  2447. </div>
  2448. </div>
  2449. </div>'
  2450. ]
  2451. ),
  2452. ],
  2453. 'Plex' => [
  2454. $this->settingsOption('token', 'plexToken'),
  2455. $this->settingsOption('button', '', ['label' => 'Get Plex Token', 'icon' => 'fa fa-ticket', 'text' => 'Retrieve', 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#sso-form [name=plexToken]\')"']),
  2456. $this->settingsOption('password-alt', 'plexID', ['label' => 'Plex Machine']),
  2457. $this->settingsOption('button', '', ['label' => 'Get Plex Machine', 'icon' => 'fa fa-id-badge', 'text' => 'Retrieve', 'attr' => 'onclick="showPlexMachineForm(\'#sso-form [name=plexID]\')"']),
  2458. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email']),
  2459. $this->settingsOption('blank'),
  2460. $this->settingsOption('html', 'Plex Note', ['html' => '<span lang="en">Please make sure both Token and Machine are filled in</span>']),
  2461. $this->settingsOption('enable', 'ssoPlex'),
  2462. ],
  2463. 'Tautulli' => [
  2464. $this->settingsOption('multiple-url', 'tautulliURL'),
  2465. $this->settingsOption('auth', 'ssoTautulliAuth'),
  2466. $this->settingsOption('enable', 'ssoTautulli'),
  2467. ],
  2468. 'Overseerr' => [
  2469. $this->settingsOption('url', 'overseerrURL'),
  2470. $this->settingsOption('token', 'overseerrToken'),
  2471. $this->settingsOption('username', 'overseerrFallbackUser', ['label' => 'Overseerr Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2472. $this->settingsOption('password', 'overseerrFallbackPassword', ['label' => 'Overseerr Fallback Password']),
  2473. $this->settingsOption('enable', 'ssoOverseerr'),
  2474. ],
  2475. 'Petio' => [
  2476. $this->settingsOption('url', 'petioURL'),
  2477. $this->settingsOption('token', 'petioToken'),
  2478. $this->settingsOption('username', 'petioFallbackUser', ['label' => 'Petio Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2479. $this->settingsOption('password', 'petioFallbackPassword', ['label' => 'Petio Fallback Password']),
  2480. $this->settingsOption('enable', 'ssoPetio'),
  2481. ],
  2482. 'Ombi' => [
  2483. $this->settingsOption('url', 'ombiURL'),
  2484. $this->settingsOption('token', 'ombiToken'),
  2485. $this->settingsOption('username', 'ombiFallbackUser', ['label' => 'Ombi Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2486. $this->settingsOption('password', 'ombiFallbackPassword', ['label' => 'Ombi Fallback Password']),
  2487. $this->settingsOption('enable', 'ssoOmbi'),
  2488. ],
  2489. 'Jellyfin' => [
  2490. $this->settingsOption('url', 'jellyfinURL', ['label' => 'Jellyfin API URL', 'help' => 'Please make sure to use the local address to the API']),
  2491. $this->settingsOption('url', 'jellyfinSSOURL', ['label' => 'Jellyfin SSO URL', 'help' => 'Please make sure to use the same (sub)domain to access Jellyfin as Organizr\'s']),
  2492. $this->settingsOption('enable', 'ssoJellyfin'),
  2493. ],
  2494. 'Komga' => [
  2495. $this->settingsOption('url', 'komgaURL'),
  2496. $this->settingsOption('auth', 'ssoKomgaAuth'),
  2497. $this->settingsOption('enable', 'ssoKomga'),
  2498. $this->settingsOption('blank'),
  2499. $this->settingsOption('username', 'komgaFallbackUser', ['label' => 'Komga Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2500. $this->settingsOption('password', 'komgaFallbackPassword', ['label' => 'Komga Fallback Password']),
  2501. $this->settingsOption('password', 'komgaSSOMasterPassword', ['label' => 'Komga Master Password', 'help' => 'Sets master password if using oAuth backend - This will set the password on the login form for logins using oAuth where no password is supplied.']),
  2502. ],
  2503. ];
  2504. }
  2505. public function systemMenuLists()
  2506. {
  2507. $pluginsMenu = [
  2508. [
  2509. 'active' => false,
  2510. 'api' => 'api/v2/page/settings_plugins_enabled',
  2511. 'anchor' => 'settings-plugins-enabled-anchor',
  2512. 'name' => 'Active',
  2513. ],
  2514. [
  2515. 'active' => false,
  2516. 'api' => 'api/v2/page/settings_plugins_disabled',
  2517. 'anchor' => 'settings-plugins-disabled-anchor',
  2518. 'name' => 'Inactive',
  2519. ],
  2520. [
  2521. 'active' => false,
  2522. 'api' => 'api/v2/page/settings_plugins_settings',
  2523. 'anchor' => 'settings-plugins-settings-anchor',
  2524. 'name' => 'Settings',
  2525. ],
  2526. [
  2527. 'active' => false,
  2528. 'api' => false,
  2529. 'anchor' => 'settings-plugins-marketplace-anchor',
  2530. 'name' => 'Marketplace',
  2531. 'onclick' => 'loadPluginMarketplace();'
  2532. ],
  2533. ];
  2534. $userManagementMenu = [
  2535. [
  2536. 'active' => false,
  2537. 'api' => 'api/v2/page/settings_user_manage_users',
  2538. 'anchor' => 'settings-user-manage-users-anchor',
  2539. 'name' => 'Manage Users'
  2540. ],
  2541. [
  2542. 'active' => false,
  2543. 'api' => 'api/v2/page/settings_user_manage_groups',
  2544. 'anchor' => 'settings-user-manage-groups-anchor',
  2545. 'name' => 'Manage Groups'
  2546. ],
  2547. [
  2548. 'active' => false,
  2549. 'api' => false,
  2550. 'anchor' => 'settings-user-import-users-anchor',
  2551. 'name' => 'Import Users'
  2552. ],
  2553. ];
  2554. $customizeMenu = [
  2555. [
  2556. 'active' => false,
  2557. 'api' => 'api/v2/page/settings_customize_appearance',
  2558. 'anchor' => 'settings-customize-appearance-anchor',
  2559. 'name' => 'Appearance',
  2560. ],
  2561. [
  2562. 'active' => false,
  2563. 'api' => 'api/v2/page/settings_customize_settings',
  2564. 'anchor' => 'settings-customize-settings-anchor',
  2565. 'name' => 'Marketplace Settings',
  2566. ],
  2567. [
  2568. 'active' => false,
  2569. 'api' => false,
  2570. 'anchor' => 'settings-customize-marketplace-anchor',
  2571. 'name' => 'Marketplace',
  2572. 'onclick' => 'loadThemeMarketplace();'
  2573. ],
  2574. ];
  2575. $tabEditorMenu = [
  2576. [
  2577. 'active' => false,
  2578. 'api' => 'api/v2/page/settings_tab_editor_tabs',
  2579. 'anchor' => 'settings-tab-editor-tabs-anchor',
  2580. 'name' => 'Tabs'
  2581. ],
  2582. [
  2583. 'active' => false,
  2584. 'api' => 'api/v2/page/settings_tab_editor_categories',
  2585. 'anchor' => 'settings-tab-editor-categories-anchor',
  2586. 'name' => 'Categories'
  2587. ],
  2588. [
  2589. 'active' => false,
  2590. 'api' => 'api/v2/page/settings_tab_editor_homepage',
  2591. 'anchor' => 'settings-tab-editor-homepage-anchor',
  2592. 'name' => 'Homepage Items'
  2593. ],
  2594. [
  2595. 'active' => false,
  2596. 'api' => 'api/v2/page/settings_tab_editor_homepage_order',
  2597. 'anchor' => 'settings-tab-editor-homepage-order-anchor',
  2598. 'name' => 'Homepage Order'
  2599. ],
  2600. ];
  2601. $systemSettingsMenu = [
  2602. [
  2603. 'active' => true,
  2604. 'api' => false,
  2605. 'anchor' => 'settings-settings-about-anchor',
  2606. 'name' => 'About'
  2607. ],
  2608. [
  2609. 'active' => false,
  2610. 'api' => 'api/v2/page/settings_settings_main',
  2611. 'anchor' => 'settings-settings-main-anchor',
  2612. 'name' => 'Main'
  2613. ],
  2614. [
  2615. 'active' => false,
  2616. 'api' => 'api/v2/page/settings_settings_sso',
  2617. 'anchor' => 'settings-settings-sso-anchor',
  2618. 'name' => 'SSO'
  2619. ],
  2620. [
  2621. 'active' => false,
  2622. 'api' => 'api/v2/page/settings_settings_logs',
  2623. 'anchor' => 'settings-settings-logs-anchor',
  2624. 'name' => 'Logs'
  2625. ],
  2626. [
  2627. 'active' => false,
  2628. 'api' => false,
  2629. 'anchor' => 'settings-settings-updates-anchor',
  2630. 'name' => 'Updates'
  2631. ],
  2632. [
  2633. 'active' => false,
  2634. 'api' => 'api/v2/page/settings_settings_backup',
  2635. 'anchor' => 'settings-settings-backup-anchor',
  2636. 'name' => 'Backup'
  2637. ],
  2638. [
  2639. 'active' => false,
  2640. 'api' => false,
  2641. 'anchor' => 'settings-settings-donate-anchor',
  2642. 'name' => 'Donate'
  2643. ],
  2644. ];
  2645. $systemMenus['system_settings'] = $this->buildSettingsMenus($systemSettingsMenu, 'System Settings');
  2646. $systemMenus['tab_editor'] = $this->buildSettingsMenus($tabEditorMenu, 'Tab Editor');
  2647. $systemMenus['customize'] = $this->buildSettingsMenus($customizeMenu, 'Customize');
  2648. $systemMenus['user_management'] = $this->buildSettingsMenus($userManagementMenu, 'User Management');
  2649. $systemMenus['plugins'] = $this->buildSettingsMenus($pluginsMenu, 'Plugins');
  2650. return $systemMenus;
  2651. }
  2652. public function updateConfigMultiple($array)
  2653. {
  2654. return (bool)$this->updateConfig($array);
  2655. }
  2656. public function updateConfigItems($array)
  2657. {
  2658. if (!count($array)) {
  2659. $this->setAPIResponse('error', 'No data submitted', 409);
  2660. return false;
  2661. }
  2662. $newItems = [];
  2663. $updatedItems = [];
  2664. foreach ($array as $k => $v) {
  2665. $v = $v ?? '';
  2666. switch ($v) {
  2667. case 'true':
  2668. $v = (bool)true;
  2669. break;
  2670. case 'false':
  2671. $v = (bool)false;
  2672. break;
  2673. }
  2674. // Hash
  2675. if ((stripos($k, 'password') !== false)) {
  2676. if (!$this->isEncrypted($v)) {
  2677. if ($v !== '') {
  2678. $v = $this->encrypt($v);
  2679. }
  2680. }
  2681. }
  2682. switch ($k) {
  2683. case 'logLocation':
  2684. case 'dbLocation':
  2685. if (!empty($v)) {
  2686. $v = $this->cleanDirectory($v);
  2687. }
  2688. break;
  2689. default:
  2690. break;
  2691. }
  2692. if (strtolower($k) !== 'formkey') {
  2693. if ($this->config[$k] !== $v) {
  2694. $updatedItems[$k] = $v;
  2695. }
  2696. $newItems[$k] = $v;
  2697. $this->config[$k] = $v;
  2698. }
  2699. }
  2700. $this->setAPIResponse('success', 'Config items updated', 200);
  2701. $this->setLoggerChannel('Config')->notice('Config items updated', ['items' => array_keys($updatedItems)]);
  2702. return (bool)$this->updateConfig($newItems);
  2703. }
  2704. public function updateConfigItem($array)
  2705. {
  2706. $array['value'] = $array['value'] ?? '';
  2707. switch ($array['value']) {
  2708. case 'true':
  2709. $array['value'] = (bool)true;
  2710. break;
  2711. case 'false':
  2712. $array['value'] = (bool)false;
  2713. break;
  2714. }
  2715. // Hash
  2716. if ($array['type'] == 'password') {
  2717. $array['value'] = $this->encrypt($array['value']);
  2718. }
  2719. $newItem = array(
  2720. $array['name'] => $array['value']
  2721. );
  2722. $this->config[$array['name']] = $array['value'];
  2723. return (bool)$this->updateConfig($newItem);
  2724. }
  2725. public function ignoreNewsId($id)
  2726. {
  2727. if (!$id) {
  2728. $this->setAPIResponse('error', 'News id was not supplied', 409);
  2729. return false;
  2730. }
  2731. $id = array(intval($id));
  2732. $newsIds = $this->config['ignoredNewsIds'];
  2733. $newsIds = array_merge($newsIds, $id);
  2734. $newsIds = array_unique($newsIds);
  2735. $this->updateConfig(['ignoredNewsIds' => $newsIds]);
  2736. $this->setAPIResponse('success', 'News id is now ignored', 200, null);
  2737. }
  2738. public function getNewsIds()
  2739. {
  2740. $newsIds = $this->config['ignoredNewsIds'];
  2741. $this->setAPIResponse('success', null, 200, $newsIds);
  2742. return $newsIds;
  2743. }
  2744. public function testWizardPath($array)
  2745. {
  2746. if ($this->hasDB()) {
  2747. $this->setAPIResponse('error', 'Endpoint disabled as database already exists', 401);
  2748. return false;
  2749. }
  2750. $path = $array['path'] ?? null;
  2751. if (file_exists($path)) {
  2752. if (is_writable($path)) {
  2753. $this->setAPIResponse('success', 'Path exists and is writable', 200);
  2754. return true;
  2755. } else {
  2756. $this->setAPIResponse('error', 'Path exists but is not writable', 403);
  2757. return false;
  2758. }
  2759. } else {
  2760. if (mkdir($path, 0760, true)) {
  2761. $this->setAPIResponse('success', 'Path is writable - Creating now', 200);
  2762. return true;
  2763. } else {
  2764. $this->setAPIResponse('error', 'Failed making directory - Check permissions', 403);
  2765. return false;
  2766. }
  2767. }
  2768. }
  2769. public function formatDatabaseDriver($driver)
  2770. {
  2771. $driver = strtolower($driver);
  2772. switch ($driver) {
  2773. case 'sqlite':
  2774. case 'sqlite3':
  2775. return 'sqlite3';
  2776. case 'mysql':
  2777. case 'mysqli':
  2778. return 'mysqli';
  2779. case 'postgre':
  2780. case 'postgres':
  2781. case 'postgresql':
  2782. return 'postgre';
  2783. default:
  2784. return $driver;
  2785. }
  2786. }
  2787. public function wizardConfig($array)
  2788. {
  2789. $array['driver'] = $array['driver'] ?? 'sqlite3';
  2790. $driver = $this->formatDatabaseDriver($array['driver']);
  2791. $dbName = $array['dbName'] ?? null;
  2792. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2793. $license = $array['license'] ?? null;
  2794. $hashKey = $array['hashKey'] ?? null;
  2795. $api = $array['api'] ?? null;
  2796. $registrationPassword = $array['registrationPassword'] ?? null;
  2797. $username = $array['username'] ?? null;
  2798. $password = $array['password'] ?? null;
  2799. $email = $array['email'] ?? null;
  2800. $dbHost = $array['dbHost'] ?? null;
  2801. $dbUsername = $array['dbUsername'] ?? null;
  2802. $dbPassword = $array['dbPassword'] ?? null;
  2803. $validation = [
  2804. 'dbPath' => $path,
  2805. 'dbName' => $dbName,
  2806. 'license' => $license,
  2807. 'hashKey' => $hashKey,
  2808. 'api' => $api,
  2809. 'registrationPassword' => $registrationPassword,
  2810. 'username' => $username,
  2811. 'password' => $password,
  2812. 'email' => $email,
  2813. 'driver' => $driver
  2814. ];
  2815. $dbName = $this->dbExtension($dbName);
  2816. if ($driver == 'mysqli' || $driver == 'postgre') {
  2817. $dbName = $this->removeDbExtension($dbName);
  2818. $validation = array_merge($validation, [
  2819. 'dbHost' => $dbHost,
  2820. 'dbUsername' => $dbUsername,
  2821. 'dbPassword' => $dbPassword,
  2822. ]);
  2823. }
  2824. foreach ($validation as $k => $v) {
  2825. if ($v == null) {
  2826. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2827. return false;
  2828. }
  2829. }
  2830. if ($path) {
  2831. $path = $this->cleanDirectory($path);
  2832. if (file_exists($path)) {
  2833. if (!is_writable($path)) {
  2834. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2835. return false;
  2836. }
  2837. } else {
  2838. if (!mkdir($path, 0760, true)) {
  2839. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2840. return false;
  2841. }
  2842. }
  2843. }
  2844. $configVersion = $this->version;
  2845. $configArray = array(
  2846. 'dbLocation' => $path,
  2847. 'driver' => $driver,
  2848. 'dbName' => $dbName,
  2849. 'license' => $license,
  2850. 'organizrHash' => $hashKey,
  2851. 'organizrAPI' => $api,
  2852. 'registrationPassword' => $registrationPassword,
  2853. 'uuid' => $this->gen_uuid()
  2854. );
  2855. if ($driver == 'mysqli' || $driver == 'postgre') {
  2856. $configArray = array_merge($configArray, [
  2857. 'dbHost' => $dbHost,
  2858. 'dbUsername' => $dbUsername,
  2859. 'dbPassword' => $this->encrypt($dbPassword, $hashKey),
  2860. ]);
  2861. }
  2862. //Test Database Connection before saving config
  2863. $testDatabaseConnection = $this->testDatabaseConnection($array);
  2864. if (!$testDatabaseConnection) {
  2865. // setResponse already defined
  2866. return false;
  2867. }
  2868. // Create Config
  2869. if ($this->createConfig($configArray)) {
  2870. $this->config = $this->config();
  2871. $this->refreshCookieName();
  2872. $this->connectDB();
  2873. // Call DB Create
  2874. if (!$this->createNewDB($dbName, false)) {
  2875. $this->setAPIResponse('error', 'error creating database using driver: ' . $driver, 500);
  2876. return false;
  2877. }
  2878. if ($this->createDB($path)) {
  2879. // Add in first user
  2880. if ($this->createFirstAdmin($username, $password, $email)) {
  2881. if ($this->createToken($username, $email, 1)) {
  2882. return true;
  2883. } else {
  2884. $this->setAPIResponse('error', 'error creating token', 500);
  2885. }
  2886. } else {
  2887. $this->setAPIResponse('error', 'error creating admin', 500);
  2888. }
  2889. } else {
  2890. $this->setAPIResponse('error', 'error creating database', 500);
  2891. }
  2892. } else {
  2893. $this->setAPIResponse('error', 'error creating config', 500);
  2894. }
  2895. return false;
  2896. }
  2897. public function testDatabaseConnection($array)
  2898. {
  2899. $driver = $array['driver'] ?? 'sqlite3';
  2900. $driver = $this->formatDatabaseDriver($driver);
  2901. $dbName = $array['dbName'] ?? null;
  2902. $dbHost = $array['dbHost'] ?? null;
  2903. $dbUsername = $array['dbUsername'] ?? null;
  2904. $dbPassword = $array['dbPassword'] ?? null;
  2905. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2906. switch ($driver) {
  2907. case 'mysqli':
  2908. if (!extension_loaded('mysqli')) {
  2909. $this->setResponse(500, 'PHP Extension `mysqli` is not loaded');
  2910. return false;
  2911. }
  2912. $config = [
  2913. 'driver' => 'mysqli',
  2914. 'host' => $dbHost,
  2915. 'username' => $dbUsername,
  2916. 'password' => $dbPassword,
  2917. 'options' => [
  2918. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2919. ],
  2920. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2921. ];
  2922. $validation = [
  2923. 'dbHost' => $dbHost,
  2924. 'dbUsername' => $dbUsername,
  2925. 'dbPassword' => $dbPassword,
  2926. ];
  2927. break;
  2928. case 'postgre':
  2929. // DISABLE FOR NOW
  2930. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2931. return false;
  2932. $config = [
  2933. //host, hostaddr, port, dbname, user, password, connect_timeout, options, sslmode, service => see PostgreSQL API
  2934. 'driver' => 'postgre',
  2935. 'username' => $dbUsername,
  2936. 'password' => $dbPassword,
  2937. 'persistent' => true,
  2938. ];
  2939. $host = $this->qualifyURL($dbHost, true);
  2940. if ($host['port']) {
  2941. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  2942. }
  2943. if (($host['host'])) {
  2944. $config = array_merge($config, ['host' => $host['host']]);
  2945. }
  2946. if (!$host['host'] && $host['path']) {
  2947. $config = array_merge($config, ['host' => $host['path']]);
  2948. }
  2949. $validation = [
  2950. 'dbHost' => $dbHost,
  2951. 'dbUsername' => $dbUsername,
  2952. 'dbPassword' => $dbPassword,
  2953. ];
  2954. break;
  2955. case 'sqlite3':
  2956. $path = $this->cleanDirectory($path);
  2957. if (file_exists($path)) {
  2958. if (!is_writable($path)) {
  2959. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2960. return false;
  2961. }
  2962. } else {
  2963. if (is_writable(dirname($path, 1))) {
  2964. if (!mkdir($path, 0760, true)) {
  2965. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2966. return false;
  2967. }
  2968. } else {
  2969. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2970. return false;
  2971. }
  2972. }
  2973. return true;
  2974. default:
  2975. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2976. return false;
  2977. }
  2978. foreach ($validation as $k => $v) {
  2979. if ($v == null) {
  2980. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2981. return false;
  2982. }
  2983. }
  2984. try {
  2985. $connection = new Connection($config);
  2986. $testConnection = $connection->isConnected();
  2987. if ($testConnection) {
  2988. $this->setResponse(200, 'Database connection successful');
  2989. return true;
  2990. } else {
  2991. $this->setResponse(409, 'Database connection unsuccessful');
  2992. return false;
  2993. }
  2994. } catch (Dibi\Exception $e) {
  2995. $this->setResponse(500, $e->getMessage());
  2996. return false;
  2997. }
  2998. }
  2999. public function createNewDB($dbName, $migration = false)
  3000. {
  3001. if ($this->config['driver'] == 'mysqli') {
  3002. $config = [
  3003. 'driver' => 'mysqli',
  3004. 'host' => $this->config['dbHost'],
  3005. 'username' => $this->config['dbUsername'],
  3006. 'password' => $this->decrypt($this->config['dbPassword']),
  3007. 'options' => [
  3008. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  3009. ],
  3010. 'flags' => MYSQLI_CLIENT_COMPRESS,
  3011. ];
  3012. if ($migration) {
  3013. try {
  3014. $this->otherDb = new Connection($config);
  3015. } catch (Dibi\Exception $e) {
  3016. $this->otherDb = null;
  3017. }
  3018. } else {
  3019. try {
  3020. $this->db = new Connection($config);
  3021. } catch (Dibi\Exception $e) {
  3022. $this->db = null;
  3023. }
  3024. }
  3025. if ($dbName == 'tempMigration') {
  3026. $response = [
  3027. array(
  3028. 'function' => 'query',
  3029. 'query' => [
  3030. 'DROP DATABASE IF EXISTS tempMigration'
  3031. ]
  3032. ),
  3033. ];
  3034. $drop = $this->processQueries($response, $migration);
  3035. }
  3036. $response = [
  3037. array(
  3038. 'function' => 'query',
  3039. 'query' => ['CREATE DATABASE IF NOT EXISTS %n',
  3040. $dbName
  3041. ]
  3042. )
  3043. ];
  3044. $results = $this->processQueries($response, $migration);
  3045. if ($results) {
  3046. if ($migration) {
  3047. $this->connectOtherDB();
  3048. } else {
  3049. $this->connectDB();
  3050. }
  3051. return true;
  3052. } else {
  3053. return false;
  3054. }
  3055. } elseif ($this->config['driver'] == 'postgre') {
  3056. $config = [
  3057. 'driver' => 'postgre',
  3058. 'username' => $this->config['dbUsername'],
  3059. 'password' => $this->decrypt($this->config['dbPassword']),
  3060. 'persistent' => true,
  3061. ];
  3062. $host = $this->qualifyURL($this->config['dbHost'], true);
  3063. if ($host['port']) {
  3064. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  3065. }
  3066. if ($host['host']) {
  3067. $config = array_merge($config, ['host' => $host['host']]);
  3068. }
  3069. if (!$host['host'] && $host['path']) {
  3070. $config = array_merge($config, ['host' => $host['path']]);
  3071. }
  3072. try {
  3073. $this->db = new Connection($config);
  3074. } catch (Dibi\Exception $e) {
  3075. $this->db = null;
  3076. }
  3077. $response = [
  3078. array(
  3079. 'function' => 'query',
  3080. 'query' => ['CREATE DATABASE %n',
  3081. $dbName
  3082. ]
  3083. )
  3084. ];
  3085. $results = $this->processQueries($response, $migration);
  3086. if ($results) {
  3087. $this->connectDB();
  3088. return true;
  3089. } else {
  3090. return false;
  3091. }
  3092. } else {
  3093. return true;
  3094. }
  3095. }
  3096. public function getDefaultTablesFormatted()
  3097. {
  3098. $list = [];
  3099. $tables = $this->defaultTables();
  3100. foreach ($tables as $table) {
  3101. $string = trim($table['query']);
  3102. preg_match('/CREATE TABLE `(.*?)`/', $string, $output_array);
  3103. if (count($output_array) > 1) {
  3104. $list[] = $output_array[1];
  3105. }
  3106. }
  3107. return $list;
  3108. }
  3109. public function defaultTables()
  3110. {
  3111. return [
  3112. array(
  3113. 'function' => 'query',
  3114. 'query' => '
  3115. CREATE TABLE `users` (
  3116. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3117. `username` TEXT UNIQUE,
  3118. `password` TEXT,
  3119. `email` TEXT,
  3120. `plex_token` TEXT,
  3121. `group` TEXT,
  3122. `group_id` INTEGER,
  3123. `locked` INTEGER,
  3124. `image` TEXT,
  3125. `register_date` DATETIME,
  3126. `auth_service` TEXT DEFAULT \'internal\'
  3127. );
  3128. '
  3129. ),
  3130. array(
  3131. 'function' => 'query',
  3132. 'query' => 'CREATE TABLE `chatroom` (
  3133. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3134. `username` TEXT,
  3135. `gravatar` TEXT,
  3136. `uid` TEXT,
  3137. `date` DATETIME,
  3138. `ip` TEXT,
  3139. `message` TEXT
  3140. );'
  3141. ),
  3142. array(
  3143. 'function' => 'query',
  3144. 'query' => 'CREATE TABLE `tokens` (
  3145. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3146. `token` TEXT UNIQUE,
  3147. `user_id` INTEGER,
  3148. `browser` TEXT,
  3149. `ip` TEXT,
  3150. `created` DATETIME,
  3151. `expires` DATETIME
  3152. );'
  3153. ),
  3154. array(
  3155. 'function' => 'query',
  3156. 'query' => 'CREATE TABLE `groups` (
  3157. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3158. `group` TEXT UNIQUE,
  3159. `group_id` INTEGER,
  3160. `image` TEXT,
  3161. `default` INTEGER
  3162. );'
  3163. ),
  3164. array(
  3165. 'function' => 'query',
  3166. 'query' => 'CREATE TABLE `categories` (
  3167. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3168. `order` INTEGER,
  3169. `category` TEXT UNIQUE,
  3170. `category_id` INTEGER,
  3171. `image` TEXT,
  3172. `default` INTEGER
  3173. );'
  3174. ),
  3175. array(
  3176. 'function' => 'query',
  3177. 'query' => 'CREATE TABLE `tabs` (
  3178. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3179. `order` INTEGER,
  3180. `category_id` INTEGER,
  3181. `name` TEXT,
  3182. `url` TEXT,
  3183. `url_local` TEXT,
  3184. `default` INTEGER,
  3185. `enabled` INTEGER,
  3186. `group_id` INTEGER,
  3187. `group_id_max` INTEGER DEFAULT \'0\',
  3188. `add_to_admin` INTEGER DEFAULT \'0\',
  3189. `image` TEXT,
  3190. `type` INTEGER,
  3191. `splash` INTEGER,
  3192. `ping` INTEGER,
  3193. `ping_url` TEXT,
  3194. `timeout` INTEGER,
  3195. `timeout_ms` INTEGER,
  3196. `preload` INTEGER
  3197. );'
  3198. ),
  3199. array(
  3200. 'function' => 'query',
  3201. 'query' => 'CREATE TABLE `options` (
  3202. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3203. `name` TEXT UNIQUE,
  3204. `value` TEXT
  3205. );'
  3206. ),
  3207. array(
  3208. 'function' => 'query',
  3209. 'query' => 'CREATE TABLE `invites` (
  3210. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3211. `code` TEXT UNIQUE,
  3212. `date` DATETIME,
  3213. `email` TEXT,
  3214. `username` TEXT,
  3215. `dateused` TIMESTAMP,
  3216. `usedby` TEXT,
  3217. `ip` TEXT,
  3218. `valid` TEXT,
  3219. `type` TEXT,
  3220. `invitedby` TEXT
  3221. );'
  3222. ),
  3223. array(
  3224. 'function' => 'query',
  3225. 'query' => 'CREATE TABLE `BOOKMARK-categories` (
  3226. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3227. `order` INTEGER,
  3228. `category` TEXT UNIQUE,
  3229. `category_id` INTEGER,
  3230. `default` INTEGER
  3231. );'
  3232. ),
  3233. array(
  3234. 'function' => 'query',
  3235. 'query' => 'CREATE TABLE `BOOKMARK-tabs` (
  3236. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3237. `order` INTEGER,
  3238. `category_id` INTEGER,
  3239. `name` TEXT,
  3240. `url` TEXT,
  3241. `enabled` INTEGER,
  3242. `group_id` INTEGER,
  3243. `image` TEXT,
  3244. `background_color` TEXT,
  3245. `text_color` TEXT
  3246. );'
  3247. )
  3248. ];
  3249. }
  3250. public function createDB($path, $migration = false)
  3251. {
  3252. if (!file_exists($path)) {
  3253. mkdir($path, 0777, true);
  3254. }
  3255. $tables = $this->defaultTables();
  3256. return $this->processQueries($tables, $migration);
  3257. }
  3258. public function createFirstAdmin($username, $password, $email)
  3259. {
  3260. $userInfo = [
  3261. 'username' => $username,
  3262. 'password' => password_hash($password, PASSWORD_BCRYPT),
  3263. 'email' => $email,
  3264. 'group' => 'Admin',
  3265. 'group_id' => 0,
  3266. 'image' => $this->gravatar($email),
  3267. 'register_date' => gmdate('Y-m-d H:i:s'),
  3268. ];
  3269. $groupInfo0 = [
  3270. 'group' => 'Admin',
  3271. 'group_id' => 0,
  3272. 'default' => 0,
  3273. 'image' => 'plugins/images/groups/admin.png',
  3274. ];
  3275. $groupInfo1 = [
  3276. 'group' => 'Co-Admin',
  3277. 'group_id' => 1,
  3278. 'default' => 0,
  3279. 'image' => 'plugins/images/groups/coadmin.png',
  3280. ];
  3281. $groupInfo2 = [
  3282. 'group' => 'Super User',
  3283. 'group_id' => 2,
  3284. 'default' => 0,
  3285. 'image' => 'plugins/images/groups/superuser.png',
  3286. ];
  3287. $groupInfo3 = [
  3288. 'group' => 'Power User',
  3289. 'group_id' => 3,
  3290. 'default' => 0,
  3291. 'image' => 'plugins/images/groups/poweruser.png',
  3292. ];
  3293. $groupInfo4 = [
  3294. 'group' => 'User',
  3295. 'group_id' => 4,
  3296. 'default' => 1,
  3297. 'image' => 'plugins/images/groups/user.png',
  3298. ];
  3299. $groupInfoGuest = [
  3300. 'group' => 'Guest',
  3301. 'group_id' => 999,
  3302. 'default' => 0,
  3303. 'image' => 'plugins/images/groups/guest.png',
  3304. ];
  3305. $settingsInfo = [
  3306. 'order' => 1,
  3307. 'category_id' => 0,
  3308. 'name' => 'Settings',
  3309. 'url' => 'api/v2/page/settings',
  3310. 'default' => 0,
  3311. 'enabled' => 1,
  3312. 'group_id' => 1,
  3313. 'image' => 'fontawesome::cog',
  3314. 'type' => 0
  3315. ];
  3316. $homepageInfo = [
  3317. 'order' => 2,
  3318. 'category_id' => 0,
  3319. 'name' => 'Homepage',
  3320. 'url' => 'api/v2/page/homepage',
  3321. 'default' => 0,
  3322. 'enabled' => 0,
  3323. 'group_id' => 4,
  3324. 'image' => 'fontawesome::home',
  3325. 'type' => 0
  3326. ];
  3327. $unsortedInfo = [
  3328. 'order' => 1,
  3329. 'category' => 'Unsorted',
  3330. 'category_id' => 0,
  3331. 'image' => 'fontawesome::question',
  3332. 'default' => 1
  3333. ];
  3334. $response = [
  3335. array(
  3336. 'function' => 'query',
  3337. 'query' => array(
  3338. 'INSERT INTO [users]',
  3339. $userInfo
  3340. )
  3341. ),
  3342. array(
  3343. 'function' => 'query',
  3344. 'query' => array(
  3345. 'INSERT INTO [groups]',
  3346. $groupInfo0
  3347. )
  3348. ),
  3349. array(
  3350. 'function' => 'query',
  3351. 'query' => array(
  3352. 'INSERT INTO [groups]',
  3353. $groupInfo1
  3354. )
  3355. ),
  3356. array(
  3357. 'function' => 'query',
  3358. 'query' => array(
  3359. 'INSERT INTO [groups]',
  3360. $groupInfo2
  3361. )
  3362. ),
  3363. array(
  3364. 'function' => 'query',
  3365. 'query' => array(
  3366. 'INSERT INTO [groups]',
  3367. $groupInfo3
  3368. )
  3369. ),
  3370. array(
  3371. 'function' => 'query',
  3372. 'query' => array(
  3373. 'INSERT INTO [groups]',
  3374. $groupInfo4
  3375. )
  3376. ),
  3377. array(
  3378. 'function' => 'query',
  3379. 'query' => array(
  3380. 'INSERT INTO [groups]',
  3381. $groupInfoGuest
  3382. )
  3383. ),
  3384. array(
  3385. 'function' => 'query',
  3386. 'query' => array(
  3387. 'INSERT INTO [tabs]',
  3388. $settingsInfo
  3389. )
  3390. ),
  3391. array(
  3392. 'function' => 'query',
  3393. 'query' => array(
  3394. 'INSERT INTO [tabs]',
  3395. $homepageInfo
  3396. )
  3397. ),
  3398. array(
  3399. 'function' => 'query',
  3400. 'query' => array(
  3401. 'INSERT INTO [categories]',
  3402. $unsortedInfo
  3403. )
  3404. ),
  3405. ];
  3406. return $this->processQueries($response);
  3407. }
  3408. public function getUserByUsernameAndEmail($username, $email)
  3409. {
  3410. $response = [
  3411. array(
  3412. 'function' => 'fetch',
  3413. 'query' => array(
  3414. 'SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',
  3415. [$username],
  3416. [$email]
  3417. )
  3418. ),
  3419. ];
  3420. return $this->processQueries($response);
  3421. }
  3422. public function createToken($username, $email, $days = 1)
  3423. {
  3424. $this->setLoggerChannel('Authentication', $username);
  3425. $this->logger->debug('Starting token creation function');
  3426. $days = ($days > 365) ? 365 : $days;
  3427. //Quick get user ID
  3428. $result = $this->getUserByUsernameAndEmail($username, $email);
  3429. $config = $this->configToken();
  3430. assert($config instanceof Lcobucci\JWT\Configuration);
  3431. $now = new DateTimeImmutable();
  3432. $token = $config->builder()
  3433. // Configures the issuer (iss claim)
  3434. ->issuedBy('Organizr')
  3435. // Configures the audience (aud claim)
  3436. ->permittedFor('Organizr')
  3437. // Configures the id (jti claim)
  3438. ->identifiedBy('4f1g23a12aa')
  3439. // Configures the time that the token was issue (iat claim)
  3440. ->issuedAt($now)
  3441. // Configures the time that the token can be used (nbf claim)
  3442. ->canOnlyBeUsedAfter($now)
  3443. // Configures the expiration time of the token (exp claim)
  3444. ->expiresAt($now->modify('+' . $days . ' days'))
  3445. // Configures a new claim, called "uid"
  3446. ->withClaim('name', $result['username'])// Configures a new claim, called "name"
  3447. ->withClaim('group', $result['group'])// Configures a new claim, called "group"
  3448. ->withClaim('groupID', $result['group_id'])// Configures a new claim, called "groupID"
  3449. ->withClaim('email', $result['email'])// Configures a new claim, called "email"
  3450. ->withClaim('image', $result['image'])// Configures a new claim, called "image"
  3451. ->withClaim('userID', $result['id'])// Configures a new claim, called "image"
  3452. // Configures a new header, called "foo"
  3453. //->withHeader('foo', 'bar')
  3454. // Builds a new token
  3455. ->getToken($config->signer(), $config->signingKey());
  3456. //$token->headers(); // Retrieves the token headers
  3457. //$token->claims(); // Retrieves the token claims
  3458. $this->coookie('set', $this->cookieName, $token->toString(), $days);
  3459. // Add token to DB
  3460. $addToken = [
  3461. 'token' => $token->toString(),
  3462. 'user_id' => $result['id'],
  3463. 'created' => gmdate('Y-m-d H:i:s'),
  3464. 'browser' => $_SERVER ['HTTP_USER_AGENT'] ?? null,
  3465. 'ip' => $this->userIP(),
  3466. 'expires' => gmdate('Y-m-d H:i:s', time() + (86400 * $days))
  3467. ];
  3468. $response = [
  3469. [
  3470. 'function' => 'query',
  3471. 'query' => [
  3472. 'INSERT INTO [tokens]',
  3473. $addToken
  3474. ],
  3475. 'key' => 'insert'
  3476. ],
  3477. [
  3478. 'function' => 'fetchAll',
  3479. 'query' => [
  3480. 'SELECT * FROM `tokens` WHERE user_id = ? ORDER BY `id` DESC LIMIT 100',
  3481. [$result['id']]
  3482. ],
  3483. 'key' => 'tokens'
  3484. ],
  3485. ];
  3486. $query = $this->processQueries($response);
  3487. if ($token) {
  3488. $this->logger->debug('Token has been created');
  3489. $browserCount = array_column($query['tokens'], 'browser');
  3490. $browserCount = array_count_values($browserCount);
  3491. if (isset($browserCount[$_SERVER ['HTTP_USER_AGENT']])) {
  3492. if ($browserCount[$_SERVER ['HTTP_USER_AGENT']] <= 1) {
  3493. if ($this->config['PHPMAILER-enabled']) {
  3494. $PhpMailer = new PhpMailer();
  3495. $emailTemplate = array(
  3496. 'type' => 'device',
  3497. 'body' => '
  3498. <h2>Hey there {user}!</h2>
  3499. We noticed a login attempt to your account and want to make sure it\'s you.<br />
  3500. If this was you, please ignore this email.<br /><br />
  3501. If this wasn\'t you, please change your password and revoke all tokens.<br /><br />
  3502. <b>Details:</b><br/ >
  3503. IP: ' . $this->userIP() . '<br />
  3504. Browser: ' . $_SERVER ['HTTP_USER_AGENT'] . '<br />
  3505. ',
  3506. 'subject' => 'We noticed a login attempt to your account on a new device.',
  3507. 'user' => $result['username'],
  3508. 'password' => null,
  3509. 'inviteCode' => null,
  3510. );
  3511. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3512. $sendEmail = array(
  3513. 'to' => $result['email'],
  3514. 'subject' => $emailTemplate['subject'],
  3515. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3516. );
  3517. $response = $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3518. if ($response == true) {
  3519. $this->logger->debug('Sent new device email');
  3520. } else {
  3521. $this->logger->debug('Could not send new device email');
  3522. }
  3523. } else {
  3524. $this->logger->debug('Email not setup - cannot send new device email');
  3525. }
  3526. }
  3527. } else {
  3528. $this->logger->debug('Could not find token in database');
  3529. }
  3530. } else {
  3531. $this->logger->warning('Token creation error');
  3532. }
  3533. $this->logger->debug('Token creation function has finished');
  3534. return $token->toString();
  3535. }
  3536. public function login($array)
  3537. {
  3538. // Grab username, Password & other optional items from api call
  3539. $username = $array['username'] ?? null;
  3540. $password = $array['password'] ?? null;
  3541. $oAuth = $array['oAuth'] ?? null;
  3542. $oAuthType = $array['oAuthType'] ?? null;
  3543. $remember = $array['remember'] ?? null;
  3544. $tfaCode = $array['tfaCode'] ?? null;
  3545. $loginAttempts = $array['loginAttempts'] ?? null;
  3546. $output = $array['output'] ?? null;
  3547. $username = (strpos($this->config['authBackend'], 'emby') !== false) ? $username : strtolower($username);
  3548. $days = (isset($remember)) ? $this->config['rememberMeDays'] : 1;
  3549. // Set logger channel
  3550. $this->setLoggerChannel('Authentication', $username);
  3551. $this->logger->debug('Starting login function');
  3552. // Set other variables
  3553. $function = 'plugin_auth_' . $this->config['authBackend'];
  3554. $authSuccess = false;
  3555. $authProxy = false;
  3556. $addEmailToAuthProxy = true;
  3557. $bypassTFA = false;
  3558. // Check Login attempts and kill if over limit
  3559. if ($loginAttempts > $this->config['loginAttempts'] || isset($_COOKIE['lockout'])) {
  3560. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3561. $this->logger->warning('User is locked out');
  3562. $this->setAPIResponse('error', 'User is locked out', 403);
  3563. return false;
  3564. }
  3565. // Check if Auth Proxy is enabled
  3566. if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
  3567. if (isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])]) || isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])])) {
  3568. $usernameHeader = $this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])] ?? null;
  3569. $emailHeader = $this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])] ?? null;
  3570. $headerForLogin = $usernameHeader ?: ($emailHeader ?: null);
  3571. $this->setLoggerChannel('Authentication', $headerForLogin);
  3572. $this->logger->debug('Starting Auth Proxy verification');
  3573. $whitelistRange = $this->analyzeIP($this->config['authProxyWhitelist']);
  3574. $authProxy = $this->authProxyRangeCheck($whitelistRange['from'], $whitelistRange['to']);
  3575. $username = ($authProxy) ? $headerForLogin : $username;
  3576. $password = ($password == null) ? $this->random_ascii_string(10) : $password;
  3577. $addEmailToAuthProxy = ($authProxy && $emailHeader) ? ['email' => $emailHeader] : true;
  3578. if ($authProxy) {
  3579. $this->logger->info('User has been verified using Auth Proxy');
  3580. $bypassTFA = true;
  3581. } else {
  3582. $this->logger->warning('User has failed verification using Auth Proxy');
  3583. }
  3584. }
  3585. }
  3586. // Check if Login method was an oAuth login
  3587. if (!$oAuth) {
  3588. $result = $this->getUserByUsernameAndEmail($username, $username);
  3589. $result['password'] = $result['password'] ?? '';
  3590. // Switch AuthType - internal - external - both
  3591. switch ($this->config['authType']) {
  3592. case 'external':
  3593. if (method_exists($this, $function)) {
  3594. $authSuccess = $this->$function($username, $password);
  3595. }
  3596. break;
  3597. /** @noinspection PhpMissingBreakStatementInspection */
  3598. case 'both':
  3599. if (method_exists($this, $function)) {
  3600. $authSuccess = $this->$function($username, $password);
  3601. }
  3602. // no break
  3603. default: // Internal
  3604. if (!$authSuccess) {
  3605. // perform the internal authentication step
  3606. if (password_verify($password, $result['password'])) {
  3607. $this->logger->debug('User password has been verified');
  3608. $authSuccess = true;
  3609. }
  3610. }
  3611. }
  3612. $authSuccess = ($authProxy) ? $addEmailToAuthProxy : $authSuccess;
  3613. } else {
  3614. // Has oAuth Token!
  3615. switch ($oAuthType) {
  3616. case 'plex':
  3617. if ($this->config['plexoAuth']) {
  3618. $this->logger->debug('Starting Plex oAuth verification');
  3619. $tokenInfo = $this->checkPlexToken($oAuth);
  3620. if ($tokenInfo) {
  3621. $authSuccess = [
  3622. 'username' => $tokenInfo['user']['username'],
  3623. 'email' => $tokenInfo['user']['email'],
  3624. 'image' => $tokenInfo['user']['thumb'],
  3625. 'token' => $tokenInfo['user']['authToken'],
  3626. 'oauth' => 'plex'
  3627. ];
  3628. $this->logger->debug('User\'s Plex Token has been verified');
  3629. $this->coookie('set', 'oAuth', 'true', $this->config['rememberMeDays']);
  3630. $authSuccess = ((!empty($this->config['plexAdmin']) && strtolower($this->config['plexAdmin']) == strtolower($tokenInfo['user']['username'])) || (!empty($this->config['plexAdmin']) && strtolower($this->config['plexAdmin']) == strtolower($tokenInfo['user']['email'])) || $this->checkPlexUser($tokenInfo['user']['username'])) ? $authSuccess : false;
  3631. } else {
  3632. $this->logger->warning('User\'s Plex Token has failed verification');
  3633. }
  3634. } else {
  3635. $this->logger->debug('Plex oAuth is not setup');
  3636. $this->setAPIResponse('error', 'Plex oAuth is not setup', 422);
  3637. return false;
  3638. }
  3639. break;
  3640. default:
  3641. return ($output) ? 'No oAuthType defined' : 'error';
  3642. }
  3643. $result = ($authSuccess) ? $this->getUserByUsernameAndEmail($authSuccess['username'], $authSuccess['email']) : '';
  3644. }
  3645. if ($authSuccess) {
  3646. // Make sure user exists in database
  3647. $userExists = false;
  3648. $passwordMatches = $oAuth || $authProxy;
  3649. $token = (is_array($authSuccess) && isset($authSuccess['token']) ? $authSuccess['token'] : '');
  3650. if (isset($result['username'])) {
  3651. $userExists = true;
  3652. $username = $result['username'];
  3653. if ($passwordMatches == false) {
  3654. $passwordMatches = password_verify($password, $result['password']);
  3655. }
  3656. }
  3657. if ($userExists) {
  3658. //does org password need to be updated
  3659. if (!$passwordMatches) {
  3660. $this->updateUserPassword($password, $result['id']);
  3661. $this->setLoggerChannel('Authentication', $username);
  3662. $this->logger->info('User Password updated from backend');
  3663. }
  3664. if ($token !== '') {
  3665. if ($token !== $result['plex_token']) {
  3666. $this->updateUserPlexToken($token, $result['id']);
  3667. $this->setLoggerChannel('Authentication', $username);
  3668. $this->logger->info('User Plex Token updated from backend');
  3669. }
  3670. }
  3671. // 2FA might go here
  3672. if ($result['auth_service'] !== 'internal' && strpos($result['auth_service'], '::') !== false) {
  3673. $tfaProceed = true;
  3674. // Add check for local or not
  3675. if ($this->config['ignoreTFALocal'] !== false) {
  3676. $tfaProceed = !$this->isLocal();
  3677. }
  3678. // Is Plex Oauth?
  3679. if ($this->config['ignoreTFAIfPlexOAuth'] !== false) {
  3680. if (isset($authSuccess['oauth'])) {
  3681. if ($authSuccess['oauth'] == 'plex') {
  3682. $tfaProceed = false;
  3683. }
  3684. }
  3685. }
  3686. if ($bypassTFA) {
  3687. $tfaProceed = false;
  3688. $this->setLoggerChannel('Authentication', $username);
  3689. $this->logger->info('Bypassing 2FA');
  3690. }
  3691. if ($tfaProceed) {
  3692. $this->setLoggerChannel('Authentication', $username);
  3693. $this->logger->debug('Starting 2FA verification');
  3694. $TFA = explode('::', $result['auth_service']);
  3695. // Is code with login info?
  3696. if ($tfaCode == '') {
  3697. $this->logger->debug('Sending 2FA response to login UI');
  3698. $this->setAPIResponse('warning', '2FA Code Needed', 422);
  3699. return false;
  3700. } else {
  3701. if (!$this->verify2FA($TFA[1], $tfaCode, $TFA[0])) {
  3702. $this->logger->warning('Incorrect 2FA');
  3703. $this->setAPIResponse('error', 'Wrong 2FA', 422);
  3704. return false;
  3705. } else {
  3706. $this->logger->info('2FA verification passed');
  3707. }
  3708. }
  3709. }
  3710. }
  3711. // End 2FA
  3712. // authentication passed - 1) mark active and update token
  3713. $createToken = $this->createToken($result['username'], $result['email'], $days);
  3714. if ($createToken) {
  3715. $this->logger->info('User has logged in');
  3716. $ssoUserObject = ($token !== '') ? $authSuccess : $result;
  3717. $this->ssoCheck($ssoUserObject, $password, $token); //need to work on this
  3718. return ($output) ? array('name' => $this->cookieName, 'token' => (string)$createToken) : true;
  3719. } else {
  3720. $this->setAPIResponse('error', 'Token creation error', 500);
  3721. return false;
  3722. }
  3723. } else {
  3724. // Create User
  3725. $this->setLoggerChannel('Authentication', (is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username));
  3726. $this->logger->debug('Starting Registration function');
  3727. return $this->authRegister((is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username), $password, (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $token);
  3728. }
  3729. } else {
  3730. // authentication failed
  3731. $this->setLoggerChannel('Authentication', $username);
  3732. $this->logger->warning('Wrong Password');
  3733. if ($loginAttempts >= $this->config['loginAttempts']) {
  3734. $this->logger->warning('User exceeded maximum login attempts');
  3735. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3736. $this->setAPIResponse('error', 'User is locked out', 403);
  3737. return false;
  3738. } else {
  3739. $this->logger->debug('User has not exceeded maximum login attempts');
  3740. $this->setAPIResponse('error', 'User credentials incorrect', 401);
  3741. return false;
  3742. }
  3743. }
  3744. }
  3745. public function logout()
  3746. {
  3747. $this->setLoggerChannel('Authentication');
  3748. $this->logger->debug('Starting log out process');
  3749. $this->logger->info('User has logged out');
  3750. $this->coookie('delete', $this->cookieName);
  3751. $this->coookie('delete', 'mpt');
  3752. $this->coookie('delete', 'Auth');
  3753. $this->coookie('delete', 'oAuth');
  3754. $this->coookie('delete', 'connect.sid');
  3755. $this->coookie('delete', 'petio_jwt');
  3756. $this->clearTautulliTokens();
  3757. $this->clearJellyfinTokens();
  3758. $this->revokeTokenCurrentUser($this->user['token']);
  3759. $this->clearKomgaToken();
  3760. $this->refreshDeviceUUID();
  3761. $this->logger->debug('Log out process has finished');
  3762. $this->user = null;
  3763. return true;
  3764. }
  3765. public function recover($array)
  3766. {
  3767. $email = $array['email'] ?? null;
  3768. if (!$email) {
  3769. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3770. return false;
  3771. }
  3772. $newPassword = $this->randString(10);
  3773. $isUser = $this->getUserByEmail($email);
  3774. if ($isUser) {
  3775. $this->updateUserPassword($newPassword, $isUser['id']);
  3776. $this->setAPIResponse('success', 'User password has been reset', 200);
  3777. $this->setLoggerChannel('User Management');
  3778. $this->logger->info('User Management Function - User: ' . $isUser['username'] . '\'s password was reset');
  3779. if ($this->config['PHPMAILER-enabled']) {
  3780. $PhpMailer = new PhpMailer();
  3781. $emailTemplate = array(
  3782. 'type' => 'reset',
  3783. 'body' => $this->config['PHPMAILER-emailTemplateReset'],
  3784. 'subject' => $this->config['PHPMAILER-emailTemplateResetSubject'],
  3785. 'user' => $isUser['username'],
  3786. 'password' => $newPassword,
  3787. 'inviteCode' => null,
  3788. );
  3789. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3790. $sendEmail = array(
  3791. 'to' => $email,
  3792. 'user' => $isUser['username'],
  3793. 'subject' => $emailTemplate['subject'],
  3794. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3795. );
  3796. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3797. $this->setAPIResponse('success', 'User password has been reset and email has been sent', 200);
  3798. }
  3799. return true;
  3800. } else {
  3801. $this->setAPIResponse('error', 'User not found', 404);
  3802. return false;
  3803. }
  3804. }
  3805. public function register($array)
  3806. {
  3807. $email = $array['email'] ?? null;
  3808. $username = $array['username'] ?? null;
  3809. $password = $array['password'] ?? null;
  3810. $registrationPassword = $array['registrationPassword'] ?? null;
  3811. if (!$email) {
  3812. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3813. return false;
  3814. }
  3815. if (!$username) {
  3816. $this->setAPIResponse('error', 'Username was not supplied', 422);
  3817. return false;
  3818. }
  3819. if (!$password) {
  3820. $this->setAPIResponse('error', 'Password was not supplied', 422);
  3821. return false;
  3822. }
  3823. if (!$registrationPassword) {
  3824. $this->setAPIResponse('error', 'Registration Password was not supplied', 422);
  3825. return false;
  3826. }
  3827. $this->setLoggerChannel('User Registration');
  3828. if ($registrationPassword == $this->decrypt($this->config['registrationPassword'])) {
  3829. $this->logger->debug('Registration Password Verified');
  3830. if ($this->createUser($username, $password, $email)) {
  3831. $this->logger->info('A User has registered');
  3832. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3833. $this->setLoggerChannel('Authentication', $username);
  3834. $this->logger->info('User has logged in');
  3835. return true;
  3836. }
  3837. } else {
  3838. return false;
  3839. }
  3840. } else {
  3841. $this->logger->warning('Wrong Password');
  3842. $this->setAPIResponse('error', 'Registration Password was incorrect', 401);
  3843. return false;
  3844. }
  3845. }
  3846. public function authRegister($username, $password, $email, $token = null)
  3847. {
  3848. $this->setLoggerChannel('Authentication', $username);
  3849. if ($this->config['authBackend'] !== '') {
  3850. $this->ombiImport($this->config['authBackend']);
  3851. }
  3852. $this->ssoCheck($username, $password, $token);
  3853. if ($token && (!$password || $password == '')) {
  3854. $password = $this->random_ascii_string(10);
  3855. }
  3856. if ($this->createUser($username, $password, $email)) {
  3857. $this->logger->info('A User has registered');
  3858. if ($this->config['PHPMAILER-enabled'] && $email !== '') {
  3859. $PhpMailer = new PhpMailer();
  3860. $emailTemplate = array(
  3861. 'type' => 'registration',
  3862. 'body' => $this->config['PHPMAILER-emailTemplateRegisterUser'],
  3863. 'subject' => $this->config['PHPMAILER-emailTemplateRegisterUserSubject'],
  3864. 'user' => $username,
  3865. 'password' => null,
  3866. 'inviteCode' => null,
  3867. );
  3868. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3869. $sendEmail = array(
  3870. 'to' => $email,
  3871. 'user' => $username,
  3872. 'subject' => $emailTemplate['subject'],
  3873. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3874. );
  3875. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3876. }
  3877. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3878. $this->logger->info('User has logged in');
  3879. return true;
  3880. } else {
  3881. return false;
  3882. }
  3883. } else {
  3884. $this->logger->warning('Registration error occurred');
  3885. return false;
  3886. }
  3887. }
  3888. public function revokeTokenCurrentUser($token = null)
  3889. {
  3890. if ($token) {
  3891. $response = [
  3892. array(
  3893. 'function' => 'query',
  3894. 'query' => array(
  3895. 'DELETE FROM tokens WHERE token = ?',
  3896. [$token]
  3897. )
  3898. ),
  3899. ];
  3900. } else {
  3901. $response = [
  3902. array(
  3903. 'function' => 'query',
  3904. 'query' => array(
  3905. 'DELETE FROM tokens WHERE user_id = ?',
  3906. [$this->user['userID']]
  3907. )
  3908. ),
  3909. ];
  3910. }
  3911. return $this->processQueries($response);
  3912. }
  3913. public function revokeToken($token = null)
  3914. {
  3915. if (!$token) {
  3916. $this->setAPIResponse('error', 'Token was not supplied', 422);
  3917. return false;
  3918. }
  3919. $response = [
  3920. array(
  3921. 'function' => 'query',
  3922. 'query' => array(
  3923. 'DELETE FROM tokens WHERE token = ?',
  3924. [$token]
  3925. )
  3926. ),
  3927. ];
  3928. $this->setAPIResponse('success', 'Token revoked', 204);
  3929. return $this->processQueries($response);
  3930. }
  3931. public function revokeTokenByIdCurrentUser($id = null)
  3932. {
  3933. if (!$id) {
  3934. $this->setAPIResponse('error', 'Id was not supplied', 422);
  3935. return false;
  3936. }
  3937. $response = [
  3938. array(
  3939. 'function' => 'query',
  3940. 'query' => array(
  3941. 'DELETE FROM tokens WHERE id = ? AND user_id = ?',
  3942. $id,
  3943. $this->user['userID']
  3944. )
  3945. ),
  3946. ];
  3947. $this->setAPIResponse('success', 'Token revoked', 204);
  3948. return $this->processQueries($response);
  3949. }
  3950. public function revokeTokensByUserId($userId = null)
  3951. {
  3952. if (!$userId) {
  3953. $this->setAPIResponse('error', 'User Id was not supplied', 422);
  3954. return false;
  3955. }
  3956. $response = [
  3957. array(
  3958. 'function' => 'query',
  3959. 'query' => array(
  3960. 'DELETE FROM tokens WHERE user_id = ?',
  3961. $userId,
  3962. )
  3963. ),
  3964. ];
  3965. $this->setAPIResponse('success', 'User Tokens revoked', 204);
  3966. $this->setLoggerChannel('User Management')->info('Revoked all tokens for deleted user', ['id' => $userId]);
  3967. return $this->processQueries($response);
  3968. }
  3969. public function updateUserPassword($password, $id)
  3970. {
  3971. $response = [
  3972. array(
  3973. 'function' => 'query',
  3974. 'query' => array(
  3975. 'UPDATE users SET',
  3976. ['password' => password_hash($password, PASSWORD_BCRYPT)],
  3977. 'WHERE id = ?',
  3978. $id
  3979. )
  3980. ),
  3981. ];
  3982. return $this->processQueries($response);
  3983. }
  3984. public function updateUserPlexToken($token, $id)
  3985. {
  3986. $response = [
  3987. array(
  3988. 'function' => 'query',
  3989. 'query' => array(
  3990. 'UPDATE users SET',
  3991. ['plex_token' => $token],
  3992. 'WHERE id = ?',
  3993. $id
  3994. )
  3995. ),
  3996. ];
  3997. return $this->processQueries($response);
  3998. }
  3999. public function getUserTabsAndCategories($type = null)
  4000. {
  4001. if (!$this->hasDB()) {
  4002. return false;
  4003. }
  4004. $sort = ($this->config['unsortedTabs'] == 'top') ? 'DESC' : 'ASC';
  4005. $response = [
  4006. array(
  4007. 'function' => 'fetchAll',
  4008. 'query' => array(
  4009. 'SELECT * FROM tabs WHERE `group_id` >= ? AND `group_id_max` <= ? AND `enabled` = 1 ORDER BY `order` ' . $sort,
  4010. $this->user['groupID'],
  4011. $this->user['groupID'],
  4012. ),
  4013. 'key' => 'tabs'
  4014. ),
  4015. array(
  4016. 'function' => 'fetchAll',
  4017. 'query' => array(
  4018. 'SELECT * FROM tabs WHERE `add_to_admin` = 1 AND `enabled` = 1 ORDER BY `order` ' . $sort
  4019. ),
  4020. 'key' => 'tabs-admin'
  4021. ),
  4022. array(
  4023. 'function' => 'fetchAll',
  4024. 'query' => array(
  4025. 'SELECT * FROM categories ORDER BY `order` ASC',
  4026. ),
  4027. 'key' => 'categories'
  4028. ),
  4029. ];
  4030. $queries = $this->processQueries($response);
  4031. $this->applyTabVariables($queries['tabs']);
  4032. if ($this->qualifyRequest(1)) {
  4033. $this->applyTabVariables($queries['tabs-admin']);
  4034. $all['tabs'] = array_merge($queries['tabs'], $queries['tabs-admin']);
  4035. $newArray = [];
  4036. $ids = [];
  4037. foreach ($all['tabs'] as $key => $line) {
  4038. if (!in_array($line['id'], $ids)) {
  4039. $ids[] = $line['id'];
  4040. $newArray[$key] = $line;
  4041. }
  4042. }
  4043. $all['tabs'] = $newArray;
  4044. if (count($all['tabs']) > 0) {
  4045. usort($all['tabs'], function ($a, $b) {
  4046. if ($this->config['unsortedTabs'] == 'top') {
  4047. return $b['order'] <=> $a['order'];
  4048. } else {
  4049. return $a['order'] <=> $b['order'];
  4050. }
  4051. });
  4052. }
  4053. $newArray = NULL;
  4054. $ids = NULL;
  4055. } else {
  4056. $all['tabs'] = $queries['tabs'];
  4057. }
  4058. foreach ($all['tabs'] as $k => $v) {
  4059. $v['url_local'] = $v['type'] !== 0 ? $this->checkTabURL($v['url_local']) : $v['url_local'];
  4060. $v['url'] = $v['type'] !== 0 ? $this->checkTabURL($v['url']) : $v['url'];
  4061. $v['access_url'] = (!empty($v['url_local']) && ($v['url_local'] !== null) && ($v['url_local'] !== 'null') && $this->isLocal() && $v['type'] !== 0) ? $v['url_local'] : $v['url'];
  4062. }
  4063. $count = array_map(function ($element) {
  4064. return $element['category_id'];
  4065. }, $all['tabs']);
  4066. $count = (array_count_values($count));
  4067. foreach ($queries['categories'] as $k => $v) {
  4068. $v['count'] = $count[$v['category_id']] ?? 0;
  4069. }
  4070. $all['categories'] = $queries['categories'];
  4071. switch ($type) {
  4072. case 'categories':
  4073. return $all['categories'];
  4074. case 'tabs':
  4075. return $all['tabs'];
  4076. default:
  4077. return $all;
  4078. }
  4079. }
  4080. public function checkTabURL($url = null)
  4081. {
  4082. return $url !== '' && $url !== null & $url !== 'null' ? $this->qualifyURL($url, false, true) : '';
  4083. }
  4084. public function refreshList()
  4085. {
  4086. $searchTerm = "Refresh";
  4087. $list = array_filter($this->config, function ($k) use ($searchTerm) {
  4088. return stripos($k, $searchTerm) !== false;
  4089. }, ARRAY_FILTER_USE_KEY);
  4090. foreach ($list as $item => $value) {
  4091. if (!is_numeric($value)) {
  4092. unset($list[$item]);
  4093. }
  4094. }
  4095. return $list;
  4096. }
  4097. public function homepageOrderList()
  4098. {
  4099. $searchTerm = "homepageOrder";
  4100. $order = array_filter($this->config, function ($k) use ($searchTerm) {
  4101. return stripos($k, $searchTerm) !== false;
  4102. }, ARRAY_FILTER_USE_KEY);
  4103. asort($order);
  4104. return $order;
  4105. }
  4106. public function tautulliList()
  4107. {
  4108. $searchTerm = "tautulli_token";
  4109. return array_filter($this->config, function ($k) use ($searchTerm) {
  4110. return stripos($k, $searchTerm) !== false;
  4111. }, ARRAY_FILTER_USE_KEY);
  4112. }
  4113. public function checkPlexAdminFilled()
  4114. {
  4115. if ($this->config['plexAdmin'] == '') {
  4116. return false;
  4117. } else {
  4118. if ((strpos($this->config['plexAdmin'], '@') !== false)) {
  4119. return 'email';
  4120. } else {
  4121. return 'username';
  4122. }
  4123. }
  4124. }
  4125. public function organizrSpecialSettings()
  4126. {
  4127. // js activeInfo
  4128. return [
  4129. 'homepage' => [
  4130. 'refresh' => $this->refreshList(),
  4131. 'order' => $this->homepageOrderList(),
  4132. 'search' => [
  4133. 'enabled' => $this->qualifyRequest($this->config['mediaSearchAuth']) && $this->config['mediaSearch'] == true && $this->config['plexToken'],
  4134. 'type' => $this->config['mediaSearchType'],
  4135. ],
  4136. 'requests' => [
  4137. 'service' => $this->config['defaultRequestService'],
  4138. ],
  4139. 'ombi' => [
  4140. 'enabled' => $this->qualifyRequest($this->config['homepageOmbiAuth']) && $this->qualifyRequest($this->config['homepageOmbiRequestAuth']) && $this->config['homepageOmbiEnabled'] == true && $this->config['ssoOmbi'] && isset($_COOKIE['Auth']),
  4141. 'authView' => $this->qualifyRequest($this->config['homepageOmbiAuth']),
  4142. 'authRequest' => $this->qualifyRequest($this->config['homepageOmbiRequestAuth']),
  4143. 'sso' => (bool)$this->config['ssoOmbi'],
  4144. 'cookie' => isset($_COOKIE['Auth']),
  4145. 'alias' => (bool)$this->config['ombiAlias'],
  4146. 'ombiDefaultFilterAvailable' => (bool)$this->config['ombiDefaultFilterAvailable'],
  4147. 'ombiDefaultFilterUnavailable' => (bool)$this->config['ombiDefaultFilterUnavailable'],
  4148. 'ombiDefaultFilterApproved' => (bool)$this->config['ombiDefaultFilterApproved'],
  4149. 'ombiDefaultFilterUnapproved' => (bool)$this->config['ombiDefaultFilterUnapproved'],
  4150. 'ombiDefaultFilterDenied' => (bool)$this->config['ombiDefaultFilterDenied']
  4151. ],
  4152. 'overseerr' => [
  4153. 'enabled' => $this->qualifyRequest($this->config['homepageOverseerrAuth']) && $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']) && $this->config['homepageOverseerrEnabled'] == true && $this->config['ssoOverseerr'] && isset($_COOKIE['connect_sid']),
  4154. 'authView' => $this->qualifyRequest($this->config['homepageOverseerrAuth']),
  4155. 'authRequest' => $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']),
  4156. 'sso' => (bool)$this->config['ssoOverseerr'],
  4157. 'cookie' => isset($_COOKIE['connect_sid']),
  4158. 'userSelectTv' => (bool)$this->config['homepageOverseerrRequestAuth'] == 'user',
  4159. 'overseerrDefaultFilterAvailable' => (bool)$this->config['overseerrDefaultFilterAvailable'],
  4160. 'overseerrDefaultFilterUnavailable' => (bool)$this->config['overseerrDefaultFilterUnavailable'],
  4161. 'overseerrDefaultFilterApproved' => (bool)$this->config['overseerrDefaultFilterApproved'],
  4162. 'overseerrDefaultFilterUnapproved' => (bool)$this->config['overseerrDefaultFilterUnapproved'],
  4163. 'overseerrDefaultFilterDenied' => (bool)$this->config['overseerrDefaultFilterDenied']
  4164. ],
  4165. 'jackett' => [
  4166. 'homepageJackettBackholeDownload' => $this->config['homepageJackettBackholeDownload'] ? true : false
  4167. ],
  4168. 'prowlarr' => [
  4169. 'homepageProwlarrBackholeDownload' => $this->config['homepageProwlarrBackholeDownload'] ? true : false
  4170. ],
  4171. 'options' => [
  4172. 'alternateHomepageHeaders' => $this->config['alternateHomepageHeaders'],
  4173. 'healthChecksTags' => $this->config['healthChecksTags'],
  4174. 'titles' => [
  4175. 'tautulli' => $this->config['tautulliHeader']
  4176. ]
  4177. ],
  4178. 'media' => [
  4179. 'jellyfin' => $this->config['homepageJellyfinInstead']
  4180. ]
  4181. ],
  4182. 'sso' => [
  4183. 'misc' => [
  4184. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4185. 'rememberMe' => $this->config['rememberMe'],
  4186. 'rememberMeDays' => $this->config['rememberMeDays']
  4187. ],
  4188. 'plex' => [
  4189. 'enabled' => (bool)$this->config['ssoPlex'],
  4190. 'cookie' => isset($_COOKIE['mpt']),
  4191. 'machineID' => strlen($this->config['plexID']) == 40,
  4192. 'token' => $this->config['plexToken'] !== '',
  4193. 'plexAdmin' => $this->checkPlexAdminFilled(),
  4194. 'strict' => (bool)$this->config['plexStrictFriends'],
  4195. 'oAuthEnabled' => (bool)$this->config['plexoAuth'],
  4196. 'backend' => $this->config['authBackend'] == 'plex',
  4197. ],
  4198. 'tautulli' => [
  4199. 'enabled' => (bool)$this->config['ssoTautulli'],
  4200. 'cookie' => !empty($this->tautulliList()),
  4201. 'url' => ($this->config['tautulliURL'] !== '') ? $this->config['tautulliURL'] : false,
  4202. ],
  4203. 'overseerr' => [
  4204. 'enabled' => (bool)$this->config['ssoOverseerr'],
  4205. 'cookie' => isset($_COOKIE['connect.sid']),
  4206. 'url' => ($this->config['overseerrURL'] !== '') ? $this->config['overseerrURL'] : false,
  4207. 'api' => $this->config['overseerrToken'] !== '',
  4208. ],
  4209. 'petio' => [
  4210. 'enabled' => (bool)$this->config['ssoPetio'],
  4211. 'cookie' => isset($_COOKIE['petio_jwt']),
  4212. 'url' => ($this->config['petioURL'] !== '') ? $this->config['petioURL'] : false,
  4213. 'api' => $this->config['petioToken'] !== '',
  4214. ],
  4215. 'ombi' => [
  4216. 'enabled' => (bool)$this->config['ssoOmbi'],
  4217. 'cookie' => isset($_COOKIE['Auth']),
  4218. 'url' => ($this->config['ombiURL'] !== '') ? $this->config['ombiURL'] : false,
  4219. 'api' => $this->config['ombiToken'] !== '',
  4220. ],
  4221. 'jellyfin' => [
  4222. 'enabled' => (bool)$this->config['ssoJellyfin'],
  4223. 'url' => ($this->config['jellyfinURL'] !== '') ? $this->config['jellyfinURL'] : false,
  4224. 'ssoUrl' => ($this->config['jellyfinSSOURL'] !== '') ? $this->config['jellyfinSSOURL'] : false,
  4225. ],
  4226. 'komga' => [
  4227. 'enabled' => (bool)$this->config['ssoKomga'],
  4228. 'cookie' => isset($_COOKIE['komga_token']),
  4229. 'url' => ($this->config['komgaURL'] !== '') ? $this->config['komgaURL'] : false,
  4230. ]
  4231. ],
  4232. 'ping' => [
  4233. 'onlineSound' => $this->config['pingOnlineSound'],
  4234. 'offlineSound' => $this->config['pingOfflineSound'],
  4235. 'statusSounds' => $this->config['statusSounds'],
  4236. 'auth' => $this->config['pingAuth'],
  4237. 'authMessage' => $this->config['pingAuthMessage'],
  4238. 'authMs' => $this->config['pingAuthMs'],
  4239. 'ms' => $this->config['pingMs'],
  4240. 'adminRefresh' => $this->config['adminPingRefresh'],
  4241. 'everyoneRefresh' => $this->config['otherPingRefresh'],
  4242. ],
  4243. 'notifications' => [
  4244. 'backbone' => $this->config['notificationBackbone'],
  4245. 'position' => $this->config['notificationPosition']
  4246. ],
  4247. 'lockout' => [
  4248. 'enabled' => $this->config['lockoutSystem'],
  4249. 'timer' => $this->config['lockoutTimeout'],
  4250. 'minGroup' => $this->config['lockoutMinAuth'],
  4251. 'maxGroup' => $this->config['lockoutMaxAuth']
  4252. ],
  4253. 'user' => [
  4254. 'agent' => isset($_SERVER ['HTTP_USER_AGENT']) ? $_SERVER ['HTTP_USER_AGENT'] : null,
  4255. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4256. 'local' => $this->isLocal(),
  4257. 'ip' => $this->userIP()
  4258. ],
  4259. 'login' => [
  4260. 'rememberMe' => $this->config['rememberMe'],
  4261. 'rememberMeDays' => $this->config['rememberMeDays'],
  4262. 'wanDomain' => $this->config['wanDomain'],
  4263. 'localAddress' => $this->config['localAddress'],
  4264. 'enableLocalAddressForward' => $this->config['enableLocalAddressForward'],
  4265. ],
  4266. 'misc' => [
  4267. 'installedPlugins' => $this->qualifyRequest(1) ? $this->config['installedPlugins'] : '',
  4268. 'installedThemes' => $this->qualifyRequest(1) ? $this->config['installedThemes'] : '',
  4269. 'return' => $_SERVER['HTTP_REFERER'] ?? false,
  4270. 'authDebug' => $this->config['authDebug'],
  4271. 'minimalLoginScreen' => $this->config['minimalLoginScreen'],
  4272. 'unsortedTabs' => $this->config['unsortedTabs'],
  4273. 'authType' => $this->config['authType'],
  4274. 'authBackend' => $this->config['authBackend'],
  4275. 'newMessageSound' => (isset($this->config['CHAT-newMessageSound-include'])) ? $this->config['CHAT-newMessageSound-include'] : '',
  4276. 'uuid' => ($this->config['uuid']) ?? null,
  4277. 'docker' => $this->qualifyRequest(1) ? $this->docker : '',
  4278. 'githubCommit' => $this->qualifyRequest(1) ? $this->commit : '',
  4279. 'schema' => $this->qualifyRequest(1) ? $this->getSchema() : '',
  4280. 'debugArea' => $this->qualifyRequest($this->config['debugAreaAuth']),
  4281. 'debugErrors' => $this->config['debugErrors'],
  4282. 'sandbox' => $this->config['sandbox'],
  4283. 'iframeAllow' => $this->config['iframeAllow'],
  4284. 'expandCategoriesByDefault' => $this->config['expandCategoriesByDefault'],
  4285. 'autoCollapseCategories' => $this->config['autoCollapseCategories'],
  4286. 'autoExpandNavBar' => $this->config['autoExpandNavBar'],
  4287. 'sideMenuCollapsed' => $this->config['allowCollapsableSideMenu'] && $this->config['sideMenuCollapsed'],
  4288. 'collapseSideMenuOnClick' => $this->config['allowCollapsableSideMenu'] && $this->config['collapseSideMenuOnClick'],
  4289. 'authProxyOverrideLogout' => $this->config['authProxyOverrideLogout'],
  4290. 'authProxyLogoutURL' => $this->config['authProxyLogoutURL'],
  4291. 'disableHomepageModals' => $this->config['disableHomepageModals'],
  4292. 'checkForUpdate' => $this->config['checkForUpdate']
  4293. ],
  4294. 'menuLink' => [
  4295. 'githubMenuLink' => $this->config['githubMenuLink'],
  4296. 'organizrSupportMenuLink' => $this->config['organizrSupportMenuLink'],
  4297. 'organizrDocsMenuLink' => $this->config['organizrDocsMenuLink'],
  4298. 'organizrSignoutMenuLink' => $this->config['organizrSignoutMenuLink'],
  4299. 'organizrFeatureRequestLink' => $this->config['organizrFeatureRequestLink']
  4300. ]
  4301. ];
  4302. }
  4303. public function checkLog($path)
  4304. {
  4305. if (file_exists($path)) {
  4306. if (filesize($path) > 500000) {
  4307. rename($path, $path . '[' . date('Y-m-d') . '].json');
  4308. return false;
  4309. }
  4310. return true;
  4311. } else {
  4312. return false;
  4313. }
  4314. }
  4315. public function isApprovedRequest($method, $data)
  4316. {
  4317. $requesterToken = $this->getallheadersi()['token'] ?? ($_GET['apikey'] ?? false);
  4318. $apiKey = ($this->config['organizrAPI']) ?? null;
  4319. if (isset($data['formKey'])) {
  4320. $formKey = $data['formKey'];
  4321. } elseif (isset($this->getallheadersi()['formkey'])) {
  4322. $formKey = $this->getallheadersi()['formkey'];
  4323. } else {
  4324. $formKey = false;
  4325. }
  4326. // Check token or API key
  4327. // If API key, return 0 for admin
  4328. if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
  4329. //DO API CHECK
  4330. return true;
  4331. } elseif ($method == 'POST') {
  4332. if ($this->checkFormKey($formKey)) {
  4333. return true;
  4334. } else {
  4335. $this->setLoggerChannel('Authentication');
  4336. $this->logger->warning('Unable to authenticate Form Key: ' . $formKey);
  4337. return false;
  4338. }
  4339. } else {
  4340. return true;
  4341. }
  4342. return false;
  4343. }
  4344. public function checkFormKey($formKey = '')
  4345. {
  4346. return password_verify(substr($this->config['organizrHash'], 2, 10), $formKey);
  4347. }
  4348. public function buildHomepage()
  4349. {
  4350. $homepageOrder = $this->homepageOrderList();
  4351. $homepageBuilt = '';
  4352. foreach ($homepageOrder as $key => $value) {
  4353. //new way
  4354. if (method_exists($this, $key)) {
  4355. $homepageBuilt .= $this->$key();
  4356. } elseif (strpos($key, 'homepageOrdercustomhtml') !== false) {
  4357. $iteration = substr($key, -2);
  4358. $homepageBuilt .= $this->homepageOrdercustomhtml($iteration);
  4359. } else {
  4360. $homepageBuilt .= '<div id="' . $key . '"></div>';
  4361. }
  4362. //old way
  4363. //$homepageBuilt .= $this->buildHomepageItem($key);
  4364. }
  4365. return $homepageBuilt;
  4366. }
  4367. public function buildHomepageSettings()
  4368. {
  4369. $homepageOrder = $this->homepageOrderList();
  4370. $homepageList = '<div class="col-lg-12"><h4 lang="en">Drag Homepage Items to Order Them</h4></div><div id="homepage-items-sort" class="external-events">';
  4371. $inputList = '<form id="homepage-values" class="row">';
  4372. foreach ($homepageOrder as $key => $val) {
  4373. switch ($key) {
  4374. case 'homepageOrdercustomhtml01':
  4375. case 'homepageOrdercustomhtml02':
  4376. case 'homepageOrdercustomhtml03':
  4377. case 'homepageOrdercustomhtml04':
  4378. case 'homepageOrdercustomhtml05':
  4379. case 'homepageOrdercustomhtml06':
  4380. case 'homepageOrdercustomhtml07':
  4381. case 'homepageOrdercustomhtml08':
  4382. $iteration = substr($key, -2);
  4383. $class = 'bg-info';
  4384. $image = 'plugins/images/tabs/HTML5.png';
  4385. if (!$this->config['homepageCustomHTML' . $iteration . 'Enabled']) {
  4386. $class .= ' faded';
  4387. }
  4388. break;
  4389. case 'homepageOrdertransmission':
  4390. $class = 'bg-transmission';
  4391. $image = 'plugins/images/tabs/transmission.png';
  4392. if (!$this->config['homepageTransmissionEnabled']) {
  4393. $class .= ' faded';
  4394. }
  4395. break;
  4396. case 'homepageOrdernzbget':
  4397. $class = 'bg-nzbget';
  4398. $image = 'plugins/images/tabs/nzbget.png';
  4399. if (!$this->config['homepageNzbgetEnabled']) {
  4400. $class .= ' faded';
  4401. }
  4402. break;
  4403. case 'homepageOrderjdownloader':
  4404. $class = 'bg-sab';
  4405. $image = 'plugins/images/tabs/jdownloader.png';
  4406. if (!$this->config['homepageJdownloaderEnabled']) {
  4407. $class .= ' faded';
  4408. }
  4409. break;
  4410. case 'homepageOrdersabnzbd':
  4411. $class = 'bg-sab';
  4412. $image = 'plugins/images/tabs/sabnzbd.png';
  4413. if (!$this->config['homepageSabnzbdEnabled']) {
  4414. $class .= ' faded';
  4415. }
  4416. break;
  4417. case 'homepageOrderdeluge':
  4418. $class = 'bg-deluge';
  4419. $image = 'plugins/images/tabs/deluge.png';
  4420. if (!$this->config['homepageDelugeEnabled']) {
  4421. $class .= ' faded';
  4422. }
  4423. break;
  4424. case 'homepageOrderqBittorrent':
  4425. $class = 'bg-qbit';
  4426. $image = 'plugins/images/tabs/qBittorrent.png';
  4427. if (!$this->config['homepageqBittorrentEnabled']) {
  4428. $class .= ' faded';
  4429. }
  4430. break;
  4431. case 'homepageOrderuTorrent':
  4432. $class = 'bg-qbit';
  4433. $image = 'plugins/images/tabs/utorrent.png';
  4434. if (!$this->config['homepageuTorrentEnabled']) {
  4435. $class .= ' faded';
  4436. }
  4437. break;
  4438. case 'homepageOrderrTorrent':
  4439. $class = 'bg-qbit';
  4440. $image = 'plugins/images/tabs/rTorrent.png';
  4441. if (!$this->config['homepagerTorrentEnabled']) {
  4442. $class .= ' faded';
  4443. }
  4444. break;
  4445. case 'homepageOrderplexnowplaying':
  4446. case 'homepageOrderplexrecent':
  4447. case 'homepageOrderplexplaylist':
  4448. $class = 'bg-plex';
  4449. $image = 'plugins/images/tabs/plex.png';
  4450. if (!$this->config['homepagePlexEnabled']) {
  4451. $class .= ' faded';
  4452. }
  4453. break;
  4454. case 'homepageOrderembynowplaying':
  4455. case 'homepageOrderembyrecent':
  4456. $class = 'bg-emby';
  4457. $image = 'plugins/images/tabs/emby.png';
  4458. if (!$this->config['homepageEmbyEnabled']) {
  4459. $class .= ' faded';
  4460. }
  4461. break;
  4462. case 'homepageOrderjellyfinnowplaying':
  4463. case 'homepageOrderjellyfinrecent':
  4464. $class = 'bg-jellyfin';
  4465. $image = 'plugins/images/tabs/jellyfin.png';
  4466. if (!$this->config['homepageJellyfinEnabled']) {
  4467. $class .= ' faded';
  4468. }
  4469. break;
  4470. case 'homepageOrderombi':
  4471. $class = 'bg-inverse';
  4472. $image = 'plugins/images/tabs/ombi.png';
  4473. if (!$this->config['homepageOmbiEnabled']) {
  4474. $class .= ' faded';
  4475. }
  4476. break;
  4477. case 'homepageOrderoverseerr':
  4478. $class = 'bg-inverse';
  4479. $image = 'plugins/images/tabs/overseerr.png';
  4480. if (!$this->config['homepageOverseerrEnabled']) {
  4481. $class .= ' faded';
  4482. }
  4483. break;
  4484. case 'homepageOrderDonate':
  4485. $class = 'bg-primary';
  4486. $image = 'plugins/images/tabs/donate.png';
  4487. if (!$this->config['homepageDonateEnabled']) {
  4488. $class .= ' faded';
  4489. }
  4490. break;
  4491. case 'homepageOrdercalendar':
  4492. $class = 'bg-primary';
  4493. $image = 'plugins/images/tabs/calendar.png';
  4494. if (!$this->config['homepageCalendarEnabled'] && !$this->config['homepageSonarrEnabled'] && !$this->config['homepageRadarrEnabled'] && !$this->config['homepageSickrageEnabled'] && !$this->config['homepageCouchpotatoEnabled']) {
  4495. $class .= ' faded';
  4496. }
  4497. break;
  4498. case 'homepageOrderdownloader':
  4499. $class = 'bg-inverse';
  4500. $image = 'plugins/images/tabs/downloader.png';
  4501. if (!$this->config['jdownloaderCombine'] && !$this->config['sabnzbdCombine'] && !$this->config['nzbgetCombine'] && !$this->config['rTorrentCombine'] && !$this->config['delugeCombine'] && !$this->config['transmissionCombine'] && !$this->config['qBittorrentCombine'] && !$this->config['uTorrentCombine']) {
  4502. $class .= ' faded';
  4503. }
  4504. break;
  4505. case 'homepageOrderhealthchecks':
  4506. $class = 'bg-healthchecks';
  4507. $image = 'plugins/images/tabs/healthchecks.png';
  4508. if (!$this->config['homepageHealthChecksEnabled']) {
  4509. $class .= ' faded';
  4510. }
  4511. break;
  4512. case 'homepageOrderunifi':
  4513. $class = 'bg-info';
  4514. $image = 'plugins/images/tabs/ubnt.png';
  4515. if (!$this->config['homepageUnifiEnabled']) {
  4516. $class .= ' faded';
  4517. }
  4518. break;
  4519. case 'homepageOrdertautulli':
  4520. $class = 'bg-info';
  4521. $image = 'plugins/images/tabs/tautulli.png';
  4522. if (!$this->config['homepageTautulliEnabled']) {
  4523. $class .= ' faded';
  4524. }
  4525. break;
  4526. case 'homepageOrderPihole':
  4527. $class = 'bg-info';
  4528. $image = 'plugins/images/tabs/pihole.png';
  4529. if (!$this->config['homepagePiholeEnabled']) {
  4530. $class .= ' faded';
  4531. }
  4532. break;
  4533. case 'homepageOrderAdGuard':
  4534. $class = 'bg-info';
  4535. $image = 'plugins/images/tabs/AdGuardHomepageItem';
  4536. if (!$this->config['homepageAdGuardEnabled']) {
  4537. $class .= ' faded';
  4538. }
  4539. break;
  4540. case 'homepageOrderMonitorr':
  4541. $class = 'bg-info';
  4542. $image = 'plugins/images/tabs/monitorr.png';
  4543. if (!$this->config['homepageMonitorrEnabled']) {
  4544. $class .= ' faded';
  4545. }
  4546. break;
  4547. case 'homepageOrderUptimeKuma':
  4548. $class = 'bg-info';
  4549. $image = 'plugins/images/tabs/kuma.png';
  4550. if (!$this->config['homepageUptimeKumaEnabled']) {
  4551. $class .= ' faded';
  4552. }
  4553. break;
  4554. case 'homepageOrderPromPage':
  4555. $class = 'bg-info';
  4556. $image = 'plugins/images/tabs/prompage.png';
  4557. if (!$this->config['homepagePromPageEnabled']) {
  4558. $class .= ' faded';
  4559. }
  4560. break;
  4561. case 'homepageOrderWeatherAndAir':
  4562. $class = 'bg-success';
  4563. $image = 'plugins/images/tabs/wind.png';
  4564. if (!$this->config['homepageWeatherAndAirEnabled']) {
  4565. $class .= ' faded';
  4566. }
  4567. break;
  4568. case 'homepageOrderSpeedtest':
  4569. $class = 'bg-success';
  4570. $image = 'plugins/images/tabs/speedtest-icon.png';
  4571. if (!$this->config['homepageSpeedtestEnabled']) {
  4572. $class .= ' faded';
  4573. }
  4574. break;
  4575. case 'homepageOrderNetdata':
  4576. $class = 'bg-success';
  4577. $image = 'plugins/images/tabs/netdata.png';
  4578. if (!$this->config['homepageNetdataEnabled']) {
  4579. $class .= ' faded';
  4580. }
  4581. break;
  4582. case 'homepageOrderOctoprint':
  4583. $class = 'bg-success';
  4584. $image = 'plugins/images/tabs/octoprint.png';
  4585. if (!$this->config['homepageOctoprintEnabled']) {
  4586. $class .= ' faded';
  4587. }
  4588. break;
  4589. case 'homepageOrderSonarrQueue':
  4590. $class = 'bg-sonarr';
  4591. $image = 'plugins/images/tabs/sonarr.png';
  4592. if (!$this->config['homepageSonarrQueueEnabled']) {
  4593. $class .= ' faded';
  4594. }
  4595. break;
  4596. case 'homepageOrderRadarrQueue':
  4597. $class = 'bg-radarr';
  4598. $image = 'plugins/images/tabs/radarr.png';
  4599. if (!$this->config['homepageRadarrQueueEnabled']) {
  4600. $class .= ' faded';
  4601. }
  4602. break;
  4603. case 'homepageOrderJackett':
  4604. $class = 'bg-inverse';
  4605. $image = 'plugins/images/tabs/jackett.png';
  4606. if (!$this->config['homepageJackettEnabled']) {
  4607. $class .= ' faded';
  4608. }
  4609. break;
  4610. case 'homepageOrderProwlarr':
  4611. $class = 'bg-inverse';
  4612. $image = 'plugins/images/tabs/prowlarr.png';
  4613. if (!$this->config['homepageProwlarrEnabled']) {
  4614. $class .= ' faded';
  4615. }
  4616. break;
  4617. case 'homepageOrderBookmarks':
  4618. $class = 'bg-bookmarks';
  4619. $image = 'plugins/images/bookmark.png';
  4620. if (!$this->config['homepageBookmarksEnabled']) {
  4621. $class .= ' faded';
  4622. }
  4623. break;
  4624. default:
  4625. $class = 'blue-bg';
  4626. $image = '';
  4627. break;
  4628. }
  4629. $homepageList .= '
  4630. <div class="col-md-3 col-xs-12 sort-homepage m-t-10 hvr-grow clearfix">
  4631. <div class="homepage-drag fc-event ' . $class . ' lazyload" data-src="' . $image . '">
  4632. <span class="ordinal-position text-uppercase badge bg-org homepage-number" data-link="' . $key . '" style="float:left;width: 30px;">' . $val . '</span>
  4633. <span class="homepage-text">&nbsp; ' . strtoupper(substr($key, 13)) . '</span>
  4634. </div>
  4635. </div>
  4636. ';
  4637. $inputList .= '<input type="hidden" name="' . $key . '">';
  4638. }
  4639. $homepageList .= '</div>';
  4640. $inputList .= '</form>';
  4641. return $homepageList . $inputList;
  4642. }
  4643. public function setGroupOptionsVariable()
  4644. {
  4645. $this->groupOptions = $this->groupSelect();
  4646. }
  4647. public function getSettingsHomepageItem($item)
  4648. {
  4649. $items = $this->getSettingsHomepage();
  4650. foreach ($items as $k => $v) {
  4651. if (strtolower($v['name']) === strtolower($item)) {
  4652. $functionName = $v['settingsArray'];
  4653. return $this->$functionName();
  4654. }
  4655. }
  4656. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4657. return null;
  4658. }
  4659. public function getSettingsHomepageItemDebug($service)
  4660. {
  4661. $service = $this->getSettingsHomepageItem($service);
  4662. if ($service) {
  4663. $debug = [];
  4664. foreach ($service['settings'] as $category => $items) {
  4665. if ($category !== 'About' && $category !== 'Test Connection') {
  4666. foreach ($items as $item) {
  4667. if ($item['type'] !== 'html' && $item['type'] !== 'blank' && $item['type'] !== 'button') {
  4668. if ((stripos($item['name'], 'token') !== false) || (stripos($item['name'], 'key') !== false) || (stripos($item['name'], 'password'))) {
  4669. if ($item['value'] !== '') {
  4670. $item['value'] = '***redacted***';
  4671. }
  4672. }
  4673. $debug[$category][$item['name']] = $item['value'];
  4674. }
  4675. }
  4676. }
  4677. }
  4678. return $debug;
  4679. }
  4680. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4681. return null;
  4682. }
  4683. public function getSettingsHomepage()
  4684. {
  4685. $this->setGroupOptionsVariable();
  4686. return $this->getHomepageSettingsCombined();
  4687. }
  4688. public function isTabNameTaken($name, $id = null)
  4689. {
  4690. if ($id) {
  4691. $response = [
  4692. array(
  4693. 'function' => 'fetchAll',
  4694. 'query' => array(
  4695. 'SELECT * FROM tabs WHERE `name` LIKE ? AND `id` != ?',
  4696. $name,
  4697. $id
  4698. )
  4699. ),
  4700. ];
  4701. } else {
  4702. $response = [
  4703. array(
  4704. 'function' => 'fetchAll',
  4705. 'query' => array(
  4706. 'SELECT * FROM tabs WHERE `name` LIKE ?',
  4707. $name
  4708. )
  4709. ),
  4710. ];
  4711. }
  4712. return $this->processQueries($response);
  4713. }
  4714. public function isCategoryNameTaken($name, $id = null)
  4715. {
  4716. if ($id) {
  4717. $response = [
  4718. array(
  4719. 'function' => 'fetchAll',
  4720. 'query' => array(
  4721. 'SELECT * FROM categories WHERE `category` LIKE ? AND `id` != ?',
  4722. $name,
  4723. $id
  4724. )
  4725. ),
  4726. ];
  4727. } else {
  4728. $response = [
  4729. array(
  4730. 'function' => 'fetchAll',
  4731. 'query' => array(
  4732. 'SELECT * FROM categories WHERE `category` LIKE ?',
  4733. $name
  4734. )
  4735. ),
  4736. ];
  4737. }
  4738. return $this->processQueries($response);
  4739. }
  4740. public function isGroupNameTaken($name, $id = null)
  4741. {
  4742. if ($id) {
  4743. $response = [
  4744. array(
  4745. 'function' => 'fetchAll',
  4746. 'query' => array(
  4747. 'SELECT * FROM groups WHERE `group` LIKE ? AND `id` != ?',
  4748. $name,
  4749. $id
  4750. )
  4751. ),
  4752. ];
  4753. } else {
  4754. $response = [
  4755. array(
  4756. 'function' => 'fetchAll',
  4757. 'query' => array(
  4758. 'SELECT * FROM groups WHERE `group` LIKE ?',
  4759. $name
  4760. )
  4761. ),
  4762. ];
  4763. }
  4764. return $this->processQueries($response);
  4765. }
  4766. public function getTableColumns($table)
  4767. {
  4768. if ($this->config['driver'] == 'sqlite3') {
  4769. $query = 'PRAGMA table_info(?)';
  4770. } else {
  4771. $query = 'DESCRIBE %n';
  4772. }
  4773. $response = [
  4774. array(
  4775. 'function' => 'fetchAll',
  4776. 'query' => [
  4777. $query, $table
  4778. ]
  4779. ),
  4780. ];
  4781. return $this->processQueries($response);
  4782. }
  4783. public function getTableColumnsFormatted($table)
  4784. {
  4785. if ($this->config['driver'] == 'sqlite3') {
  4786. $name = 'name';
  4787. } else {
  4788. $name = 'Field';
  4789. }
  4790. $columns = $this->getTableColumns($table);
  4791. if ($columns) {
  4792. $columnsFormatted = [];
  4793. foreach ($columns as $k => $v) {
  4794. $columnsFormatted[$v[$name]] = $v;
  4795. }
  4796. return $columnsFormatted;
  4797. } else {
  4798. return false;
  4799. }
  4800. }
  4801. public function getTabById($id)
  4802. {
  4803. $response = [
  4804. array(
  4805. 'function' => 'fetch',
  4806. 'query' => array(
  4807. 'SELECT * FROM tabs WHERE `id` = ?',
  4808. $id
  4809. )
  4810. ),
  4811. ];
  4812. return $this->processQueries($response);
  4813. }
  4814. public function getTabGroupByTabName($tab)
  4815. {
  4816. $response = [
  4817. array(
  4818. 'function' => 'fetch',
  4819. 'query' => array(
  4820. 'SELECT group_id FROM tabs WHERE name LIKE %~like~',
  4821. $tab
  4822. )
  4823. ),
  4824. ];
  4825. $query = $this->processQueries($response);
  4826. return $query ? $query['group_id'] : 0;
  4827. }
  4828. public function getCategoryById($id)
  4829. {
  4830. $response = [
  4831. array(
  4832. 'function' => 'fetch',
  4833. 'query' => array(
  4834. 'SELECT * FROM categories WHERE `id` = ?',
  4835. $id
  4836. )
  4837. ),
  4838. ];
  4839. return $this->processQueries($response);
  4840. }
  4841. public function getGroupUserCountById($id)
  4842. {
  4843. $response = [
  4844. array(
  4845. 'function' => 'fetchSingle',
  4846. 'query' => array(
  4847. 'SELECT count(username) AS count FROM groups INNER JOIN users ON users.group_id = groups.group_id AND groups.id = ?',
  4848. $id
  4849. )
  4850. ),
  4851. ];
  4852. return $this->processQueries($response);
  4853. }
  4854. public function getGroupById($id)
  4855. {
  4856. $response = [
  4857. array(
  4858. 'function' => 'fetch',
  4859. 'query' => array(
  4860. 'SELECT * FROM groups WHERE `id` = ?',
  4861. $id
  4862. )
  4863. ),
  4864. ];
  4865. return $this->processQueries($response);
  4866. }
  4867. public function getGroupByGroupId($id)
  4868. {
  4869. $response = [
  4870. array(
  4871. 'function' => 'fetch',
  4872. 'query' => array(
  4873. 'SELECT * FROM groups WHERE `group_id` = ?',
  4874. $id
  4875. )
  4876. ),
  4877. ];
  4878. return $this->processQueries($response);
  4879. }
  4880. public function getDefaultGroup()
  4881. {
  4882. $response = [
  4883. array(
  4884. 'function' => 'fetch',
  4885. 'query' => array(
  4886. 'SELECT * FROM groups WHERE `default` = 1'
  4887. )
  4888. ),
  4889. ];
  4890. return $this->processQueries($response);
  4891. }
  4892. public function getDefaultGroupId()
  4893. {
  4894. $response = [
  4895. array(
  4896. 'function' => 'fetchSingle',
  4897. 'query' => array(
  4898. 'SELECT `group_id` FROM groups WHERE `default` = 1'
  4899. )
  4900. ),
  4901. ];
  4902. return $this->processQueries($response);
  4903. }
  4904. public function getDefaultCategory()
  4905. {
  4906. $response = [
  4907. array(
  4908. 'function' => 'fetch',
  4909. 'query' => array(
  4910. 'SELECT * FROM categories WHERE `default` = 1'
  4911. )
  4912. ),
  4913. ];
  4914. return $this->processQueries($response);
  4915. }
  4916. public function getDefaultCategoryId()
  4917. {
  4918. $response = [
  4919. array(
  4920. 'function' => 'fetchSingle',
  4921. 'query' => array(
  4922. 'SELECT `category_id` FROM categories WHERE `default` = 1'
  4923. )
  4924. ),
  4925. ];
  4926. return $this->processQueries($response);
  4927. }
  4928. public function getNextTabOrder()
  4929. {
  4930. $response = [
  4931. array(
  4932. 'function' => 'fetchSingle',
  4933. 'query' => array(
  4934. 'SELECT `order` from tabs ORDER BY `order` DESC'
  4935. )
  4936. ),
  4937. ];
  4938. return $this->processQueries($response);
  4939. }
  4940. public function getNextCategoryOrder()
  4941. {
  4942. $response = [
  4943. array(
  4944. 'function' => 'fetchSingle',
  4945. 'query' => array(
  4946. 'SELECT `order` from categories ORDER BY `order` DESC'
  4947. )
  4948. ),
  4949. ];
  4950. return $this->processQueries($response);
  4951. }
  4952. public function getNextGroupOrder()
  4953. {
  4954. $response = [
  4955. array(
  4956. 'function' => 'fetchSingle',
  4957. 'query' => array(
  4958. 'SELECT `group_id` from groups WHERE `group_id` != "999" ORDER BY `group_id` DESC'
  4959. )
  4960. ),
  4961. ];
  4962. return $this->processQueries($response);
  4963. }
  4964. public function getNextCategoryId()
  4965. {
  4966. $response = [
  4967. array(
  4968. 'function' => 'fetchSingle',
  4969. 'query' => array(
  4970. 'SELECT `category_id` from categories ORDER BY `category_id` DESC'
  4971. )
  4972. ),
  4973. ];
  4974. return $this->processQueries($response);
  4975. }
  4976. public function clearTabDefault()
  4977. {
  4978. $response = [
  4979. array(
  4980. 'function' => 'query',
  4981. 'query' => array(
  4982. 'UPDATE tabs SET `default` = 0'
  4983. )
  4984. ),
  4985. ];
  4986. return $this->processQueries($response);
  4987. }
  4988. public function clearCategoryDefault()
  4989. {
  4990. $response = [
  4991. array(
  4992. 'function' => 'query',
  4993. 'query' => array(
  4994. 'UPDATE categories SET `default` = 0'
  4995. )
  4996. ),
  4997. ];
  4998. return $this->processQueries($response);
  4999. }
  5000. public function clearGroupDefault()
  5001. {
  5002. $response = [
  5003. array(
  5004. 'function' => 'query',
  5005. 'query' => array(
  5006. 'UPDATE groups SET `default` = 0'
  5007. )
  5008. ),
  5009. ];
  5010. return $this->processQueries($response);
  5011. }
  5012. public function checkKeys($tabInfo, $newData)
  5013. {
  5014. foreach ($newData as $k => $v) {
  5015. if (!array_key_exists($k, $tabInfo)) {
  5016. unset($newData[$k]);
  5017. }
  5018. }
  5019. return $newData;
  5020. }
  5021. public function getTabByIdCheckUser($id)
  5022. {
  5023. $tabInfo = $this->getTabById($id);
  5024. if ($tabInfo) {
  5025. if ($this->qualifyRequest($tabInfo['group_id'], true)) {
  5026. return $tabInfo;
  5027. }
  5028. } else {
  5029. $this->setAPIResponse('error', 'id not found', 404);
  5030. return false;
  5031. }
  5032. }
  5033. public function deleteTab($id)
  5034. {
  5035. $response = [
  5036. array(
  5037. 'function' => 'query',
  5038. 'query' => array(
  5039. 'DELETE FROM tabs WHERE id = ?',
  5040. $id
  5041. )
  5042. ),
  5043. ];
  5044. $tabInfo = $this->getTabById($id);
  5045. if ($tabInfo) {
  5046. $this->setLoggerChannel('Tab Management');
  5047. $this->logger->debug('Deleted Tab [' . $tabInfo['name'] . ']');
  5048. $this->setAPIResponse('success', 'Tab deleted', 204);
  5049. return $this->processQueries($response);
  5050. } else {
  5051. $this->setAPIResponse('error', 'id not found', 404);
  5052. return false;
  5053. }
  5054. }
  5055. public function addTab($array)
  5056. {
  5057. if (!$array) {
  5058. $this->setAPIResponse('error', 'no data was sent', 422);
  5059. return null;
  5060. }
  5061. $array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
  5062. $array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
  5063. $array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
  5064. $array['enabled'] = ($array['enabled']) ?? 0;
  5065. $array['default'] = ($array['default']) ?? 0;
  5066. $array['type'] = ($array['type']) ?? 1;
  5067. $array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
  5068. if (array_key_exists('name', $array)) {
  5069. $array['name'] = $this->sanitizeUserString($array['name']);
  5070. if ($this->isTabNameTaken($array['name'])) {
  5071. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  5072. return false;
  5073. }
  5074. if (!$this->qualifyLength($array['name'], 50, true)) {
  5075. return false;
  5076. }
  5077. } else {
  5078. $this->setAPIResponse('error', 'Tab name was not supplied', 422);
  5079. return false;
  5080. }
  5081. if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
  5082. $this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
  5083. return false;
  5084. }
  5085. if (!array_key_exists('image', $array)) {
  5086. $this->setAPIResponse('error', 'Tab image was not supplied', 422);
  5087. return false;
  5088. } else {
  5089. $array['image'] = $this->sanitizeUserString($array['image']);
  5090. }
  5091. $response = [
  5092. array(
  5093. 'function' => 'query',
  5094. 'query' => array(
  5095. 'INSERT INTO [tabs]',
  5096. $array
  5097. )
  5098. ),
  5099. ];
  5100. $this->setAPIResponse(null, 'Tab added');
  5101. $this->setLoggerChannel('Tab Management');
  5102. $this->logger->debug('Added Tab for [' . $array['name'] . ']');
  5103. return $this->processQueries($response);
  5104. }
  5105. public function updateTab($id, $array)
  5106. {
  5107. if (!$id || $id == '') {
  5108. $this->setAPIResponse('error', 'id was not set', 422);
  5109. return null;
  5110. }
  5111. if (!$array) {
  5112. $this->setAPIResponse('error', 'no data was sent', 422);
  5113. return null;
  5114. }
  5115. $tabInfo = $this->getTabById($id);
  5116. if ($tabInfo) {
  5117. $array = $this->checkKeys($tabInfo, $array);
  5118. } else {
  5119. $this->setAPIResponse('error', 'No tab info found', 404);
  5120. return false;
  5121. }
  5122. if (array_key_exists('name', $array)) {
  5123. $array['name'] = $this->sanitizeUserString($array['name']);
  5124. if ($this->isTabNameTaken($array['name'], $id)) {
  5125. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  5126. return false;
  5127. }
  5128. if (!$this->qualifyLength($array['name'], 50, true)) {
  5129. return false;
  5130. }
  5131. }
  5132. if (array_key_exists('default', $array)) {
  5133. if ($array['default']) {
  5134. $this->clearTabDefault();
  5135. }
  5136. }
  5137. if (array_key_exists('image', $array)) {
  5138. $array['image'] = $this->sanitizeUserString($array['image']);
  5139. }
  5140. if (array_key_exists('group_id', $array)) {
  5141. $groupCheck = (array_key_exists('group_id_max', $array)) ? $array['group_id_max'] : $tabInfo['group_id_max'];
  5142. if ($array['group_id'] < $groupCheck) {
  5143. $this->setAPIResponse('error', 'Tab name: ' . $tabInfo['name'] . ' cannot have a lower Group Id Max than Group Id Min', 409);
  5144. return false;
  5145. }
  5146. }
  5147. if (array_key_exists('group_id_max', $array)) {
  5148. $groupCheck = (array_key_exists('group_id', $array)) ? $array['group_id'] : $tabInfo['group_id'];
  5149. if ($array['group_id_max'] > $groupCheck) {
  5150. $this->setAPIResponse('error', 'Tab name: ' . $tabInfo['name'] . ' cannot have a higher Group Id Min than Group Id Max', 409);
  5151. return false;
  5152. }
  5153. }
  5154. $response = [
  5155. array(
  5156. 'function' => 'query',
  5157. 'query' => array(
  5158. 'UPDATE tabs SET',
  5159. $array,
  5160. 'WHERE id = ?',
  5161. $id
  5162. )
  5163. ),
  5164. ];
  5165. $this->setAPIResponse(null, 'Tab info updated');
  5166. $this->setLoggerChannel('Tab Management');
  5167. $this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
  5168. return $this->processQueries($response);
  5169. }
  5170. public function updateTabOrder($array)
  5171. {
  5172. if (count($array) >= 1) {
  5173. foreach ($array as $tab) {
  5174. if (count($tab) !== 2) {
  5175. $this->setAPIResponse('error', 'data is malformed', 422);
  5176. break;
  5177. }
  5178. $id = $tab['id'] ?? null;
  5179. $order = $tab['order'] ?? null;
  5180. if ($id && $order) {
  5181. $response = [
  5182. array(
  5183. 'function' => 'query',
  5184. 'query' => array(
  5185. 'UPDATE tabs set `order` = ? WHERE `id` = ?',
  5186. $order,
  5187. $id
  5188. )
  5189. ),
  5190. ];
  5191. $this->processQueries($response);
  5192. $this->setAPIResponse(null, 'Tab Order updated');
  5193. } else {
  5194. $this->setAPIResponse('error', 'data is malformed', 422);
  5195. }
  5196. }
  5197. } else {
  5198. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5199. return false;
  5200. }
  5201. }
  5202. public function addCategory($array)
  5203. {
  5204. if (!$array) {
  5205. $this->setAPIResponse('error', 'no data was sent', 422);
  5206. return null;
  5207. }
  5208. $array = $this->checkKeys($this->getTableColumnsFormatted('categories'), $array);
  5209. $array['default'] = ($array['default']) ?? 0;
  5210. $array['order'] = ($array['order']) ?? $this->getNextCategoryOrder() + 1;
  5211. $array['category_id'] = ($array['category_id']) ?? $this->getNextCategoryId() + 1;
  5212. if (array_key_exists('category', $array)) {
  5213. $array['category'] = $this->sanitizeUserString($array['category']);
  5214. if ($this->isCategoryNameTaken($array['category'])) {
  5215. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  5216. return false;
  5217. }
  5218. if (!$this->qualifyLength($array['category'], 50, true)) {
  5219. return false;
  5220. }
  5221. } else {
  5222. $this->setAPIResponse('error', 'Category name was not supplied', 422);
  5223. return false;
  5224. }
  5225. if (!array_key_exists('image', $array)) {
  5226. $this->setAPIResponse('error', 'Category image was not supplied', 422);
  5227. return false;
  5228. } else {
  5229. $array['image'] = $this->sanitizeUserString($array['image']);
  5230. }
  5231. $response = [
  5232. array(
  5233. 'function' => 'query',
  5234. 'query' => array(
  5235. 'INSERT INTO [categories]',
  5236. $array
  5237. )
  5238. ),
  5239. ];
  5240. $this->setAPIResponse(null, 'Category added');
  5241. $this->setLoggerChannel('Category Management');
  5242. $this->logger->debug('Added Category for [' . $array['category'] . ']');
  5243. return $this->processQueries($response);
  5244. }
  5245. public function updateCategory($id, $array)
  5246. {
  5247. if (!$id || $id == '') {
  5248. $this->setAPIResponse('error', 'id was not set', 422);
  5249. return null;
  5250. }
  5251. if (!$array) {
  5252. $this->setAPIResponse('error', 'no data was sent', 422);
  5253. return null;
  5254. }
  5255. $categoryInfo = $this->getCategoryById($id);
  5256. if ($categoryInfo) {
  5257. $array = $this->checkKeys($categoryInfo, $array);
  5258. } else {
  5259. $this->setAPIResponse('error', 'No category info found', 404);
  5260. return false;
  5261. }
  5262. if (array_key_exists('category', $array)) {
  5263. $array['category'] = $this->sanitizeUserString($array['category']);
  5264. if ($this->isCategoryNameTaken($array['category'], $id)) {
  5265. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  5266. return false;
  5267. }
  5268. if (!$this->qualifyLength($array['category'], 50, true)) {
  5269. return false;
  5270. }
  5271. }
  5272. if (array_key_exists('image', $array)) {
  5273. $array['image'] = $this->sanitizeUserString($array['image']);
  5274. }
  5275. if (array_key_exists('default', $array)) {
  5276. if ($array['default']) {
  5277. $this->clearCategoryDefault();
  5278. }
  5279. }
  5280. $response = [
  5281. array(
  5282. 'function' => 'query',
  5283. 'query' => array(
  5284. 'UPDATE categories SET',
  5285. $array,
  5286. 'WHERE id = ?',
  5287. $id
  5288. )
  5289. ),
  5290. ];
  5291. $this->setAPIResponse(null, 'Category info updated');
  5292. $this->setLoggerChannel('Category Management');
  5293. $this->logger->debug('Edited Category [' . $categoryInfo['category'] . ']');
  5294. return $this->processQueries($response);
  5295. }
  5296. public function updateCategoryOrder($array)
  5297. {
  5298. if (count($array) >= 1) {
  5299. foreach ($array as $category) {
  5300. if (count($category) !== 2) {
  5301. $this->setAPIResponse('error', 'data is malformed', 422);
  5302. break;
  5303. }
  5304. $id = $category['id'] ?? null;
  5305. $order = $category['order'] ?? null;
  5306. if ($id && $order) {
  5307. $response = [
  5308. array(
  5309. 'function' => 'query',
  5310. 'query' => array(
  5311. 'UPDATE categories set `order` = ? WHERE `id` = ?',
  5312. $order,
  5313. $id
  5314. )
  5315. ),
  5316. ];
  5317. $this->processQueries($response);
  5318. $this->setAPIResponse(null, 'Category Order updated');
  5319. } else {
  5320. $this->setAPIResponse('error', 'data is malformed', 422);
  5321. }
  5322. }
  5323. } else {
  5324. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5325. return false;
  5326. }
  5327. }
  5328. public function deleteCategory($id)
  5329. {
  5330. $response = [
  5331. array(
  5332. 'function' => 'query',
  5333. 'query' => array(
  5334. 'DELETE FROM categories WHERE id = ?',
  5335. $id
  5336. )
  5337. ),
  5338. ];
  5339. $categoryInfo = $this->getCategoryById($id);
  5340. if ($categoryInfo) {
  5341. $this->setLoggerChannel('Category Management');
  5342. $this->logger->debug('Deleted Category [' . $categoryInfo['category'] . ']');
  5343. $this->setAPIResponse('success', 'Category deleted', 204);
  5344. return $this->processQueries($response);
  5345. } else {
  5346. $this->setAPIResponse('error', 'id not found', 404);
  5347. return false;
  5348. }
  5349. }
  5350. public function inconspicuous(): string
  5351. {
  5352. if ($this->hasDB()) {
  5353. if ($this->config['easterEggs']) {
  5354. return '
  5355. <div class="org-rox-trigger">
  5356. <div class="org-rox">
  5357. <div class="hair"></div>
  5358. <div class="head">
  5359. <div class="ear left"></div>
  5360. <div class="ear right"></div>
  5361. <div class="face">
  5362. <div class="eye left"></div>
  5363. <div class="eye right"></div>
  5364. <div class="nose"></div>
  5365. <div class="mouth"></div>
  5366. </div>
  5367. </div>
  5368. </div>
  5369. </div>';
  5370. }
  5371. }
  5372. return '';
  5373. }
  5374. public function marketplaceFileListFormat($files, $folder, $type)
  5375. {
  5376. foreach ($files as $k => $v) {
  5377. $splitFiles = explode('|', $v);
  5378. $prePath = (strlen($k) !== 1) ? $k . '/' : $k;
  5379. foreach ($splitFiles as $file) {
  5380. $filesList[] = array(
  5381. 'fileName' => $file,
  5382. 'path' => $prePath,
  5383. 'githubPath' => 'https://raw.githubusercontent.com/causefx/Organizr/v2-' . $type . '/' . $folder . $prePath . $file
  5384. );
  5385. }
  5386. }
  5387. return $filesList;
  5388. }
  5389. public function removeTheme($theme)
  5390. {
  5391. $this->setLoggerChannel('Theme Marketplace');
  5392. $theme = $this->cleanClassName($theme, '_');
  5393. $array = $this->getThemesMarketplace();
  5394. $arrayLower = array_change_key_case($array);
  5395. if (!$array) {
  5396. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5397. return false;
  5398. }
  5399. if (!isset($arrayLower[$theme])) {
  5400. $this->setAPIResponse('error', 'Theme does not exist in marketplace', 404);
  5401. return false;
  5402. } else {
  5403. $key = array_search($theme, array_keys($arrayLower));
  5404. $theme = array_keys($array)[$key];
  5405. }
  5406. $array = $array[$theme];
  5407. $themeDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5408. $dirExists = file_exists($themeDir);
  5409. if ($dirExists) {
  5410. if (!$this->rrmdir($themeDir)) {
  5411. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5412. return false;
  5413. }
  5414. } else {
  5415. $this->setAPIResponse('error', 'Theme is not installed', 404);
  5416. return false;
  5417. }
  5418. $this->updateInstalledThemes('uninstall', $theme, $array);
  5419. $this->setAPIResponse('success', 'Theme removed', 200, $array);
  5420. return true;
  5421. }
  5422. public function installTheme($theme)
  5423. {
  5424. $this->setLoggerChannel('Theme Marketplace');
  5425. $theme = $this->cleanClassName($theme, '_');
  5426. $array = $this->getThemesMarketplace();
  5427. $arrayLower = array_change_key_case($array);
  5428. if (!$array) {
  5429. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5430. return false;
  5431. }
  5432. if (!isset($arrayLower[$theme])) {
  5433. $this->setAPIResponse('error', 'Theme [' . $theme . '] does not exist in marketplace', 404, $arrayLower);
  5434. return false;
  5435. } else {
  5436. $key = array_search($theme, array_keys($arrayLower));
  5437. $theme = array_keys($array)[$key];
  5438. }
  5439. $array = $array[$theme];
  5440. // Check Version of Organizr against minimum version needed
  5441. $compare = new Composer\Semver\Comparator;
  5442. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5443. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5444. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5445. return true;
  5446. }
  5447. // It is okay to user Plugin function - we should rename it so it is universal
  5448. $files = $this->getPluginFilesFromRepo($theme, $array);
  5449. if ($files) {
  5450. $downloadList = $this->themeFileListFormat($files, $array['project_folder']);
  5451. } else {
  5452. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5453. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5454. return false;
  5455. }
  5456. if (!$downloadList) {
  5457. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5458. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5459. return false;
  5460. }
  5461. foreach ($downloadList as $k => $v) {
  5462. $file = array(
  5463. 'from' => $v['githubPath'],
  5464. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5465. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5466. );
  5467. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes');
  5468. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5469. $this->setLoggerChannel('Theme Marketplace');
  5470. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5471. $this->setAPIResponse('error', 'Theme download failed', 500);
  5472. return false;
  5473. }
  5474. }
  5475. $this->updateInstalledThemes('install', $theme, $array);
  5476. $this->setAPIResponse('success', 'Theme installed', 200, $array);
  5477. return true;
  5478. }
  5479. public function themeFileListFormat($files, $folder)
  5480. {
  5481. $filesList = false;
  5482. foreach ($files as $k => $v) {
  5483. if ($v['type'] !== 'dir') {
  5484. $filesList[] = array(
  5485. 'fileName' => $v['name'],
  5486. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5487. 'githubPath' => $v['download_url']
  5488. );
  5489. }
  5490. }
  5491. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder);
  5492. return $filesList;
  5493. }
  5494. public function pluginFileListFormat($files, $folder)
  5495. {
  5496. $filesList = false;
  5497. foreach ($files as $k => $v) {
  5498. if ($v['type'] !== 'dir') {
  5499. $filesList[] = array(
  5500. 'fileName' => $v['name'],
  5501. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5502. 'githubPath' => $v['download_url']
  5503. );
  5504. }
  5505. }
  5506. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder);
  5507. return $filesList;
  5508. }
  5509. public function getPluginFilesFromGithub($plugin = 'test')
  5510. {
  5511. $url = 'https://api.github.com/repos/causefx/organizr/contents/' . $plugin . '?ref=v2-plugins';
  5512. $options = array('verify' => false);
  5513. $response = Requests::get($url, array(), $options);
  5514. if ($response->success) {
  5515. return json_decode($response->body, true);
  5516. }
  5517. return false;
  5518. }
  5519. public function getBranchFromGithub($repo)
  5520. {
  5521. $url = 'https://api.github.com/repos/' . $repo;
  5522. $options = array('verify' => false);
  5523. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5524. try {
  5525. if ($response->success) {
  5526. $github = json_decode($response->body, true);
  5527. return $github['default_branch'] ?? null;
  5528. } else {
  5529. $this->setLoggerChannel('Plugins');
  5530. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5531. return false;
  5532. }
  5533. } catch (Requests_Exception $e) {
  5534. $this->logger->error($e);
  5535. $this->setAPIResponse('error', $e->getMessage(), 401);
  5536. return false;
  5537. }
  5538. }
  5539. public function getFilesFromGithub($repo, $branch)
  5540. {
  5541. if (!$repo || !$branch) {
  5542. return false;
  5543. }
  5544. $url = 'https://api.github.com/repos/' . $repo . '/git/trees/' . $branch . '?recursive=1';
  5545. $options = array('verify' => false);
  5546. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5547. try {
  5548. if ($response->success) {
  5549. $github = json_decode($response->body, true);
  5550. return is_array($github) ? $github : null;
  5551. } else {
  5552. $this->setLoggerChannel('Plugins');
  5553. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5554. return false;
  5555. }
  5556. } catch (Requests_Exception $e) {
  5557. $this->logger->error($e);
  5558. $this->setAPIResponse('error', $e->getMessage(), 401);
  5559. return false;
  5560. }
  5561. }
  5562. public function formatFilesFromGithub($files, $repo, $branch, $folder)
  5563. {
  5564. if (!$files || !$repo || !$branch || !$folder) {
  5565. return false;
  5566. }
  5567. if (isset($files['tree'])) {
  5568. $fileList = [];
  5569. foreach ($files['tree'] as $k => $v) {
  5570. if ($v['type'] !== 'tree') {
  5571. $fileInfo = pathinfo($v['path']);
  5572. $v['name'] = $fileInfo['basename'];
  5573. $v['download_url'] = 'https://raw.githubusercontent.com/' . $repo . '/' . $branch . '/' . $v['path'];
  5574. if ($folder == 'root') {
  5575. $fileList[] = $v;
  5576. } else {
  5577. if (stripos($v['path'], $folder) !== false) {
  5578. $v['path'] = (substr($v['path'], 0, strlen($folder)) == $folder) ? substr($v['path'], (strlen($folder) + 1)) : $v['path'];
  5579. $fileList[] = $v;
  5580. }
  5581. }
  5582. }
  5583. }
  5584. return $fileList;
  5585. }
  5586. return false;
  5587. }
  5588. public function getPluginFilesFromRepo($plugin, $pluginDetails)
  5589. {
  5590. if (stripos($pluginDetails['repo'], 'github.com') !== false) {
  5591. $repo = explode('https://github.com/', $pluginDetails['repo']);
  5592. } else {
  5593. return false;
  5594. }
  5595. $branch = $this->getBranchFromGithub($repo[1]);
  5596. if ($branch) {
  5597. return $this->formatFilesFromGithub($this->getFilesFromGithub($repo[1], $branch), $repo[1], $branch, $pluginDetails['github_folder']);
  5598. }
  5599. return false;
  5600. }
  5601. public function installPlugin($plugin)
  5602. {
  5603. $this->setLoggerChannel('Plugin Marketplace');
  5604. $plugin = $this->reverseCleanClassName($plugin);
  5605. $array = $this->getPluginsMarketplace();
  5606. $arrayLower = array_change_key_case($array);
  5607. if (!$array) {
  5608. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5609. return false;
  5610. }
  5611. if (!$arrayLower[$plugin]) {
  5612. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5613. return false;
  5614. } else {
  5615. $key = array_search($plugin, array_keys($arrayLower));
  5616. $plugin = array_keys($array)[$key];
  5617. }
  5618. $array = $array[$plugin];
  5619. // Check Version of Organizr against minimum version needed
  5620. $compare = new Composer\Semver\Comparator;
  5621. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5622. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5623. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5624. return true;
  5625. }
  5626. $files = $this->getPluginFilesFromRepo($plugin, $array);
  5627. if ($files) {
  5628. $downloadList = $this->pluginFileListFormat($files, $array['project_folder']);
  5629. } else {
  5630. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5631. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5632. return false;
  5633. }
  5634. if (!$downloadList) {
  5635. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5636. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5637. return false;
  5638. }
  5639. foreach ($downloadList as $k => $v) {
  5640. $file = array(
  5641. 'from' => $v['githubPath'],
  5642. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5643. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5644. );
  5645. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins');
  5646. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5647. $this->setLoggerChannel('Plugin Marketplace');
  5648. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5649. $this->setAPIResponse('error', 'Plugin download failed', 500);
  5650. return false;
  5651. }
  5652. }
  5653. $this->updateInstalledPlugins('install', $plugin, $array);
  5654. $this->setAPIResponse('success', 'Plugin installed', 200, $array);
  5655. return true;
  5656. }
  5657. public function removePlugin($plugin)
  5658. {
  5659. $this->setLoggerChannel('Plugin Marketplace');
  5660. $plugin = $this->reverseCleanClassName($plugin);
  5661. $array = $this->getPluginsMarketplace();
  5662. $arrayLower = array_change_key_case($array);
  5663. if (!$array) {
  5664. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5665. return false;
  5666. }
  5667. if (!$arrayLower[$plugin]) {
  5668. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5669. return false;
  5670. } else {
  5671. $key = array_search($plugin, array_keys($arrayLower));
  5672. $plugin = array_keys($array)[$key];
  5673. }
  5674. $array = $array[$plugin];
  5675. $pluginDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5676. $dirExists = file_exists($pluginDir);
  5677. if ($dirExists) {
  5678. if (!$this->rrmdir($pluginDir)) {
  5679. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5680. return false;
  5681. }
  5682. } else {
  5683. $this->setAPIResponse('error', 'Plugin is not installed', 404);
  5684. return false;
  5685. }
  5686. $this->updateInstalledPlugins('uninstall', $plugin, $array);
  5687. $this->setAPIResponse('success', 'Plugin removed', 200, $array);
  5688. return true;
  5689. }
  5690. public function updateInstalledPlugins($action, $plugin, $pluginDetails)
  5691. {
  5692. if (!$action || !$plugin || !$pluginDetails) {
  5693. return false;
  5694. }
  5695. $config = $this->config['installedPlugins'];
  5696. $config = is_array($config) ? $config : [];
  5697. switch ($action) {
  5698. case 'install':
  5699. case 'update':
  5700. $update[$plugin] = [
  5701. 'name' => $plugin,
  5702. 'version' => $pluginDetails['version'],
  5703. 'repo' => $pluginDetails['repo']
  5704. ];
  5705. $config = array_merge($config, $update);
  5706. break;
  5707. default:
  5708. unset($config[$plugin]);
  5709. break;
  5710. }
  5711. $this->updateConfig(['installedPlugins' => $config]);
  5712. }
  5713. public function updateInstalledThemes($action, $theme, $themeDetails)
  5714. {
  5715. if (!$action || !$theme || !$themeDetails) {
  5716. return false;
  5717. }
  5718. $config = $this->config['installedThemes'];
  5719. $config = is_array($config) ? $config : [];
  5720. switch ($action) {
  5721. case 'install':
  5722. case 'update':
  5723. $update[$theme] = [
  5724. 'name' => $theme,
  5725. 'version' => $themeDetails['version'],
  5726. 'repo' => $themeDetails['repo'],
  5727. 'path' => 'data/themes/' . $themeDetails['project_folder']
  5728. ];
  5729. $config = array_merge($config, $update);
  5730. break;
  5731. default:
  5732. unset($config[$theme]);
  5733. break;
  5734. }
  5735. $this->updateConfig(['installedThemes' => $config]);
  5736. }
  5737. public function getThemesGithub()
  5738. {
  5739. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-themes/themes.json';
  5740. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5741. $response = Requests::get($url, array(), $options);
  5742. if ($response->success) {
  5743. return json_decode($response->body, true);
  5744. }
  5745. return false;
  5746. }
  5747. public function getPluginsGithub()
  5748. {
  5749. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-plugins/plugins.json';
  5750. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5751. try {
  5752. $response = Requests::get($url, array(), $options);
  5753. if ($response->success) {
  5754. return json_decode($response->body, true);
  5755. }
  5756. } catch (Requests_Exception $e) {
  5757. return false;
  5758. }
  5759. return false;
  5760. }
  5761. public function getPluginsMarketplace()
  5762. {
  5763. $plugins = $this->getPluginsGithubCombined();
  5764. foreach ($plugins as $pluginName => $pluginDetails) {
  5765. $plugins[$pluginName]['installed'] = (isset($this->config['installedPlugins'][$pluginName]));
  5766. $plugins[$pluginName]['installed_version'] = $this->config['installedPlugins'][$pluginName]['version'] ?? null;
  5767. $plugins[$pluginName]['needs_update'] = ($plugins[$pluginName]['installed'] && ($plugins[$pluginName]['installed_version'] !== $plugins[$pluginName]['version']));
  5768. $plugins[$pluginName]['status'] = $this->getPluginStatus($plugins[$pluginName]);
  5769. }
  5770. return $plugins;
  5771. }
  5772. public function getThemesMarketplace()
  5773. {
  5774. $themes = $this->getThemesGithubCombined();
  5775. foreach ($themes as $themeName => $themeDetails) {
  5776. $themes[$themeName]['installed'] = (isset($this->config['installedThemes'][$themeName]));
  5777. $themes[$themeName]['installed_version'] = $this->config['installedThemes'][$themeName]['version'] ?? null;
  5778. $themes[$themeName]['needs_update'] = ($themes[$themeName]['installed'] && ($themes[$themeName]['installed_version'] !== $themes[$themeName]['version']));
  5779. $themes[$themeName]['status'] = $this->getPluginStatus($themes[$themeName]);
  5780. }
  5781. return $themes;
  5782. }
  5783. public function getThemesGithubCombined()
  5784. {
  5785. // Organizr Repo
  5786. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Themes')];
  5787. foreach (explode(',', $this->config['externalThemeMarketplaceRepos']) as $repo) {
  5788. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5789. }
  5790. $themes = [];
  5791. foreach ($urls as $repo) {
  5792. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5793. try {
  5794. $response = Requests::get($repo, array(), $options);
  5795. if ($response->success) {
  5796. $themes = array_merge($themes, json_decode($response->body, true));
  5797. } else {
  5798. $this->setLoggerChannel('Themes');
  5799. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5800. return false;
  5801. }
  5802. } catch (Requests_Exception $e) {
  5803. //return false;
  5804. }
  5805. }
  5806. return $themes;
  5807. }
  5808. public function getPluginStatus($pluginDetails)
  5809. {
  5810. if ($pluginDetails['needs_update']) {
  5811. return 'Update Available';
  5812. } elseif ($pluginDetails['installed']) {
  5813. return 'Up to date';
  5814. } else {
  5815. return 'Not Installed';
  5816. }
  5817. }
  5818. public function getPluginsGithubCombined()
  5819. {
  5820. // Organizr Repo
  5821. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Plugins')];
  5822. foreach (explode(',', $this->config['externalPluginMarketplaceRepos']) as $repo) {
  5823. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5824. }
  5825. $plugins = [];
  5826. foreach ($urls as $repo) {
  5827. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5828. try {
  5829. $response = Requests::get($repo, array(), $options);
  5830. if ($response->success) {
  5831. $plugins = array_merge($plugins, json_decode($response->body, true));
  5832. } else {
  5833. $this->setLoggerChannel('Plugins');
  5834. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5835. return false;
  5836. }
  5837. } catch (Requests_Exception $e) {
  5838. //return false;
  5839. }
  5840. }
  5841. return $plugins;
  5842. }
  5843. public function getMarketplaceJSONFromRepo($url)
  5844. {
  5845. if (stripos($url, '.json') !== false) {
  5846. return $url;
  5847. } elseif (stripos($url, 'github.com') !== false) {
  5848. $repo = explode('https://github.com/', $url);
  5849. $newURL = 'https://api.github.com/repos/' . $repo[1] . '/contents';
  5850. $options = ($this->localURL($newURL)) ? array('verify' => false) : array();
  5851. try {
  5852. $response = Requests::get($newURL, $this->setGithubAccessToken(), $options);
  5853. if ($response->success) {
  5854. $jsonFiles = json_decode($response->body, true);
  5855. foreach ($jsonFiles as $file) {
  5856. if (stripos($file['name'], '.json') !== false) {
  5857. return $file['download_url'];
  5858. }
  5859. }
  5860. return false;
  5861. } else {
  5862. $this->setLoggerChannel('Plugins');
  5863. $this->logger->warning('Getting Marketplace JSON from Github', $this->apiResponseFormatter($response->body));
  5864. return false;
  5865. }
  5866. } catch (Requests_Exception $e) {
  5867. return false;
  5868. }
  5869. }
  5870. return false;
  5871. }
  5872. public function setGithubAccessToken()
  5873. {
  5874. return ($this->config['githubAccessToken'] !== '') ? ['Authorization' => 'token ' . $this->config['githubAccessToken']] : [];
  5875. }
  5876. public function formatGithubAccessToken()
  5877. {
  5878. $accessToken = $this->setGithubAccessToken();
  5879. if (count($accessToken) >= 1) {
  5880. return key($accessToken) . ': ' . $accessToken[key($accessToken)];
  5881. } else {
  5882. return '';
  5883. }
  5884. }
  5885. public function getOpenCollectiveBackers()
  5886. {
  5887. $url = 'https://opencollective.com/organizr/members/users.json?limit=100&offset=0';
  5888. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5889. try {
  5890. $response = Requests::get($url, array(), $options);
  5891. if ($response->success) {
  5892. $api = json_decode($response->body, true);
  5893. foreach ($api as $k => $backer) {
  5894. $api[$k] = array_merge($api[$k], ['sortName' => strtolower($backer['name'])]);
  5895. }
  5896. $this->setAPIResponse('success', '', 200, $api);
  5897. return $api;
  5898. }
  5899. } catch (Requests_Exception $e) {
  5900. $this->setResponse(500, $e->getMessage());
  5901. return false;
  5902. }
  5903. $this->setAPIResponse('error', 'Error connecting to Open Collective', 409);
  5904. return false;
  5905. }
  5906. public function getGithubSponsors()
  5907. {
  5908. $url = 'https://github.com/sponsors/causefx';
  5909. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5910. $response = Requests::get($url, array(), $options);
  5911. if ($response->success) {
  5912. $sponsors = [];
  5913. $dom = new PHPHtmlParser\Dom;
  5914. try {
  5915. $dom->loadStr($response->body);
  5916. $contents = $dom->find('div#sponsors a');
  5917. foreach ($contents as $content) {
  5918. $html = $content->innerHtml;
  5919. preg_match('/(@[a-zA-Z])\w+/', $html, $username);
  5920. preg_match('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»""\'\']))/', $html, $image);
  5921. if (isset($image[0]) && isset($username[0])) {
  5922. $sponsors[] = [
  5923. 'name' => str_replace('@', '', $username[0]),
  5924. 'sortName' => str_replace('@', '', strtolower($username[0])),
  5925. 'image' => str_replace('s=60', 's=200', $image[0]),
  5926. 'isActive' => true,
  5927. 'type' => 'USER',
  5928. 'role' => 'BACKER'
  5929. ];
  5930. }
  5931. }
  5932. $this->setAPIResponse('success', '', 200, $sponsors);
  5933. return $sponsors;
  5934. } catch (\PHPHtmlParser\Exceptions\ChildNotFoundException|\PHPHtmlParser\Exceptions\CircularException|\PHPHtmlParser\Exceptions\LogicalException|\PHPHtmlParser\Exceptions\StrictException|\PHPHtmlParser\Exceptions\ContentLengthException|\PHPHtmlParser\Exceptions\NotLoadedException $e) {
  5935. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5936. return false;
  5937. }
  5938. }
  5939. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5940. return false;
  5941. }
  5942. public function getAllSponsors()
  5943. {
  5944. $sponsors = [];
  5945. $list = [
  5946. 'openCollective' => $this->getOpenCollectiveBackers(),
  5947. 'github' => $this->getGithubSponsors()
  5948. ];
  5949. foreach ($list as $k => $sponsor) {
  5950. if ($sponsor) {
  5951. $sponsors = array_merge($sponsor, $sponsors);
  5952. }
  5953. }
  5954. if ($sponsors) {
  5955. usort($sponsors, function ($a, $b) {
  5956. return $a['sortName'] <=> $b['sortName'];
  5957. });
  5958. }
  5959. $this->setAPIResponse('success', '', 200, $sponsors);
  5960. return $sponsors;
  5961. }
  5962. public function getOrganizrSmtpFromAPI()
  5963. {
  5964. $url = 'https://api.organizr.app/?cmd=smtp';
  5965. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5966. try {
  5967. $response = Requests::get($url, array(), $options);
  5968. if ($response->success) {
  5969. return json_decode($response->body, true);
  5970. }
  5971. } catch (Requests_Exception $e) {
  5972. $this->setResponse(500, $e->getMessage());
  5973. return false;
  5974. }
  5975. return false;
  5976. }
  5977. public function saveOrganizrSmtpFromAPI()
  5978. {
  5979. $api = $this->getOrganizrSmtpFromAPI();
  5980. if ($api) {
  5981. $this->updateConfigItems($api['response']['data']);
  5982. $this->setAPIResponse(null, 'SMTP activated with Organizr SMTP account');
  5983. return true;
  5984. } else {
  5985. return false;
  5986. }
  5987. }
  5988. public function guestHash($start, $end)
  5989. {
  5990. $ip = $this->userIP();
  5991. $ip = md5($ip);
  5992. return substr($ip, $start, $end);
  5993. }
  5994. public function rrmdir($dir)
  5995. {
  5996. ini_set('max_execution_time', 0);
  5997. set_time_limit(0);
  5998. if (is_dir($dir)) {
  5999. $files = scandir($dir);
  6000. foreach ($files as $file) {
  6001. if ($file != "." && $file != "..") {
  6002. $this->rrmdir("$dir/$file");
  6003. }
  6004. }
  6005. rmdir($dir);
  6006. } elseif (file_exists($dir)) {
  6007. unlink($dir);
  6008. }
  6009. return true;
  6010. }
  6011. public function rcopy($src, $dst)
  6012. {
  6013. ini_set('max_execution_time', 0);
  6014. set_time_limit(0);
  6015. $src = $this->cleanPath($src);
  6016. $dst = $this->cleanPath($dst);
  6017. if (is_dir($src)) {
  6018. if (!file_exists($dst)) : mkdir($dst);
  6019. endif;
  6020. $files = scandir($src);
  6021. foreach ($files as $file) {
  6022. if ($file != "." && $file != "..") {
  6023. $this->rcopy("$src/$file", "$dst/$file");
  6024. }
  6025. }
  6026. } elseif (file_exists($src)) {
  6027. copy($src, $dst);
  6028. }
  6029. return true;
  6030. }
  6031. public function unzipFile($zipFile)
  6032. {
  6033. ini_set('max_execution_time', 0);
  6034. set_time_limit(0);
  6035. $zip = new ZipArchive;
  6036. $extractPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade/";
  6037. $this->setLoggerChannel('File Management');
  6038. if ($zip->open($extractPath . $zipFile) != "true") {
  6039. $this->logger->warning('organizr could not unzip upgrade.zip');
  6040. } else {
  6041. $this->logger->debug('organizr unzipped upgrade.zip');
  6042. }
  6043. /* Extract Zip File */
  6044. $zip->extractTo($extractPath);
  6045. $zip->close();
  6046. return true;
  6047. }
  6048. public function downloadFile($url, $path)
  6049. {
  6050. ini_set('max_execution_time', 0);
  6051. set_time_limit(0);
  6052. $folderPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade" . DIRECTORY_SEPARATOR;
  6053. $this->setLoggerChannel('File Management');
  6054. if (!file_exists($folderPath)) {
  6055. if (@!mkdir($folderPath)) {
  6056. $this->logger->warning('Folder Creation failed');
  6057. return false;
  6058. }
  6059. }
  6060. $newfname = $folderPath . $path;
  6061. $context = stream_context_create(
  6062. array(
  6063. 'ssl' => array(
  6064. 'verify_peer' => true,
  6065. 'cafile' => $this->getCert()
  6066. )
  6067. )
  6068. );
  6069. $file = fopen($url, 'rb', false, $context);
  6070. if ($file) {
  6071. $newf = fopen($newfname, 'wb');
  6072. if ($newf) {
  6073. while (!feof($file)) {
  6074. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  6075. }
  6076. }
  6077. } else {
  6078. $this->logger->warning('Organizr could not download ' . $url);
  6079. return false;
  6080. }
  6081. if ($file) {
  6082. fclose($file);
  6083. $this->logger->debug('Organizr finished downloading the github zip file');
  6084. } else {
  6085. $this->logger->warning('Organizr could not download the github zip file');
  6086. return false;
  6087. }
  6088. if ($newf) {
  6089. fclose($newf);
  6090. $this->logger->debug('Organizr created upgrade zip file from github zip file');
  6091. } else {
  6092. $this->logger->warning('Organizr could not create upgrade zip file from github zip file');
  6093. return false;
  6094. }
  6095. return true;
  6096. }
  6097. public function downloadFileToPath($from, $to, $path)
  6098. {
  6099. if (((stripos($from, 'api.github.com') !== false) || (stripos($from, 'raw.githubusercontent.com') !== false)) && $this->config['githubAccessToken'] !== '') {
  6100. $context = stream_context_create(
  6101. array(
  6102. 'ssl' => array(
  6103. 'verify_peer' => false,
  6104. 'cafile' => $this->getCert()
  6105. ),
  6106. 'http' => array(
  6107. 'method' => 'GET',
  6108. 'header' => $this->formatGithubAccessToken()
  6109. )
  6110. )
  6111. );
  6112. } else {
  6113. $context = stream_context_create([]);
  6114. }
  6115. ini_set('max_execution_time', 0);
  6116. set_time_limit(0);
  6117. $this->makeDir($path);
  6118. $file = fopen($from, 'rb', false, $context);
  6119. if ($file) {
  6120. $newf = fopen($to, 'wb', false, $context);
  6121. if ($newf) {
  6122. while (!feof($file)) {
  6123. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  6124. }
  6125. }
  6126. } else {
  6127. $this->logger->warning('Organizr could not download file');
  6128. }
  6129. if ($file) {
  6130. fclose($file);
  6131. $this->logger->debug('Organizr finished downloading the file');
  6132. } else {
  6133. $this->logger->warning('Organizr could not download file');
  6134. }
  6135. if ($newf) {
  6136. fclose($newf);
  6137. $this->logger->debug('Organizr saved and/or moved the file');
  6138. } else {
  6139. $this->logger->warning('Organizr could not save and/or move the file');
  6140. }
  6141. return true;
  6142. }
  6143. public function getAllUsers($includeGroups = false)
  6144. {
  6145. $response = [
  6146. array(
  6147. 'function' => 'fetchAll',
  6148. 'query' => array(
  6149. 'SELECT * FROM users'
  6150. ),
  6151. 'key' => 'users'
  6152. ),
  6153. ];
  6154. $groups = array(
  6155. 'function' => 'fetchAll',
  6156. 'query' => array(
  6157. 'SELECT * FROM groups ORDER BY group_id ASC'
  6158. ),
  6159. 'key' => 'groups'
  6160. );
  6161. $addGroups = (isset($_GET['includeGroups']) || $includeGroups) ?? false;
  6162. if ($addGroups) {
  6163. array_push($response, $groups);
  6164. }
  6165. return $this->processQueries($response);
  6166. }
  6167. public function getAllGroups()
  6168. {
  6169. $response = [
  6170. array(
  6171. 'function' => 'fetchAll',
  6172. 'query' => array(
  6173. 'SELECT * FROM groups ORDER BY group_id ASC'
  6174. ),
  6175. 'key' => 'groups'
  6176. ),
  6177. ];
  6178. $users = array(
  6179. 'function' => 'fetchAll',
  6180. 'query' => array(
  6181. 'SELECT * FROM users'
  6182. ),
  6183. 'key' => 'users'
  6184. );
  6185. $addUsers = (isset($_GET['includeUsers'])) ?? false;
  6186. if ($addUsers) {
  6187. array_push($response, $users);
  6188. }
  6189. return $this->processQueries($response);
  6190. }
  6191. public function importUsers($array)
  6192. {
  6193. $imported = 0;
  6194. if ($array) {
  6195. foreach ($array as $user) {
  6196. $password = $this->random_ascii_string(30);
  6197. if ($user['username'] !== '' && $user['email'] !== '' && $password !== '') {
  6198. $newUser = $this->createUser($user['username'], $password, $user['email']);
  6199. if (!$newUser) {
  6200. $this->setLoggerChannel('User Management');
  6201. $this->logger->warning('An error occurred during user import');
  6202. } else {
  6203. $imported++;
  6204. }
  6205. }
  6206. }
  6207. }
  6208. $this->setAPIResponse('success', 'Imported ' . $imported . ' users', 200);
  6209. return true;
  6210. }
  6211. public function importUsersType($type)
  6212. {
  6213. if ($type !== '') {
  6214. switch ($type) {
  6215. case 'plex':
  6216. return $this->importUsers($this->allPlexUsers(true));
  6217. case 'jellyfin':
  6218. return $this->importUsers($this->allJellyfinUsers(true));
  6219. case 'emby':
  6220. return $this->importUsers($this->allEmbyUsers(true));
  6221. default:
  6222. return false;
  6223. }
  6224. }
  6225. return false;
  6226. }
  6227. public function allPlexUsers($newOnly = false, $friendsOnly = false)
  6228. {
  6229. try {
  6230. if (!empty($this->config['plexToken'])) {
  6231. $url = 'https://plex.tv/api/users';
  6232. $headers = array(
  6233. 'X-Plex-Token' => $this->config['plexToken'],
  6234. );
  6235. $response = Requests::get($url, $headers);
  6236. if ($response->success) {
  6237. libxml_use_internal_errors(true);
  6238. $userXML = simplexml_load_string($response->body);
  6239. if (is_array($userXML) || is_object($userXML)) {
  6240. $results = array();
  6241. foreach ($userXML as $child) {
  6242. if (((string)$child['restricted'] == '0')) {
  6243. if ($newOnly) {
  6244. $taken = $this->usernameTaken((string)$child['username'], (string)$child['email']);
  6245. if (!$taken) {
  6246. $results[] = array(
  6247. 'username' => (string)$child['username'],
  6248. 'email' => (string)$child['email'],
  6249. 'id' => (string)$child['id'],
  6250. );
  6251. }
  6252. } elseif ($friendsOnly) {
  6253. $machineMatches = false;
  6254. foreach ($child->Server as $server) {
  6255. if ((string)$server['machineIdentifier'] == $this->config['plexID']) {
  6256. $machineMatches = true;
  6257. $shareId = $server['id'];
  6258. }
  6259. }
  6260. if ($machineMatches) {
  6261. $results[] = array(
  6262. 'username' => (string)$child['username'],
  6263. 'email' => (string)$child['email'],
  6264. 'id' => (string)$child['id'],
  6265. 'shareId' => (string)$shareId
  6266. );
  6267. }
  6268. } else {
  6269. $results[] = array(
  6270. 'username' => (string)$child['username'],
  6271. 'email' => (string)$child['email'],
  6272. 'id' => (string)$child['id'],
  6273. );
  6274. }
  6275. }
  6276. }
  6277. return $results;
  6278. }
  6279. }
  6280. }
  6281. return false;
  6282. } catch (Requests_Exception $e) {
  6283. $this->setLoggerChannel('User Management');
  6284. $this->logger->error($e);
  6285. }
  6286. return false;
  6287. }
  6288. public function allJellyfinUsers($newOnly = false)
  6289. {
  6290. try {
  6291. if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
  6292. $url = $this->qualifyURL($this->config['jellyfinURL']) . '/Users?api_key=' . $this->config['jellyfinToken'];
  6293. $headers = array();
  6294. $response = Requests::get($url, $headers);
  6295. if ($response->success) {
  6296. $users = json_decode($response->body, true);
  6297. if (is_array($users) || is_object($users)) {
  6298. $results = array();
  6299. foreach ($users as $child) {
  6300. // Jellyfin doesn't list emails for some reason
  6301. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6302. if ($newOnly) {
  6303. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6304. if (!$taken) {
  6305. $results[] = array(
  6306. 'username' => (string)$child['Name'],
  6307. 'email' => $email
  6308. );
  6309. }
  6310. } else {
  6311. $results[] = array(
  6312. 'username' => (string)$child['Name'],
  6313. 'email' => $email,
  6314. );
  6315. }
  6316. }
  6317. return $results;
  6318. }
  6319. }
  6320. }
  6321. return false;
  6322. } catch (Requests_Exception $e) {
  6323. $this->setLoggerChannel('User Management');
  6324. $this->logger->error($e);
  6325. }
  6326. return false;
  6327. }
  6328. public function allEmbyUsers($newOnly = false)
  6329. {
  6330. try {
  6331. if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
  6332. $url = $this->qualifyURL($this->config['embyURL']) . '/Users?api_key=' . $this->config['embyToken'];
  6333. $headers = array();
  6334. $response = Requests::get($url, $headers);
  6335. if ($response->success) {
  6336. $users = json_decode($response->body, true);
  6337. if (is_array($users) || is_object($users)) {
  6338. $results = array();
  6339. foreach ($users as $child) {
  6340. // Emby doesn't list emails for some reason
  6341. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6342. if ($newOnly) {
  6343. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6344. if (!$taken) {
  6345. $results[] = array(
  6346. 'username' => (string)$child['Name'],
  6347. 'email' => $email
  6348. );
  6349. }
  6350. } else {
  6351. $results[] = array(
  6352. 'username' => (string)$child['Name'],
  6353. 'email' => $email,
  6354. );
  6355. }
  6356. }
  6357. return $results;
  6358. }
  6359. }
  6360. }
  6361. return false;
  6362. } catch (Requests_Exception $e) {
  6363. $this->setLoggerChannel('User Management');
  6364. $this->logger->error($e);
  6365. }
  6366. return false;
  6367. }
  6368. public function validateEmail($email)
  6369. {
  6370. return filter_var(trim($email), FILTER_VALIDATE_EMAIL);
  6371. }
  6372. public function sanitizeEmail($email)
  6373. {
  6374. return filter_var(trim($email), FILTER_SANITIZE_EMAIL);
  6375. }
  6376. public function sanitizeUserString($string)
  6377. {
  6378. return htmlspecialchars(trim($string));
  6379. }
  6380. public function updateUser($id, $array)
  6381. {
  6382. if (!$id) {
  6383. $this->setAPIResponse('error', 'Id was not supplied', 422);
  6384. return false;
  6385. }
  6386. if ((int)$id !== $this->user['userID']) {
  6387. if (!$this->qualifyRequest('1', true)) {
  6388. return false;
  6389. }
  6390. }
  6391. $user = $this->getUserById($id);
  6392. if ($user) {
  6393. $array = $this->checkKeys($user, $array);
  6394. } else {
  6395. $this->setAPIResponse('error', 'User was not found', 404);
  6396. return false;
  6397. }
  6398. if ($user['group_id'] == 0 && $this->user['groupID'] !== 0) {
  6399. $this->setAPIResponse('error', 'Cannot update admin unless you are admin', 401);
  6400. return false;
  6401. }
  6402. if (array_key_exists('username', $array)) {
  6403. if ($array['username'] == '') {
  6404. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6405. return false;
  6406. }
  6407. $array['username'] = $this->sanitizeUserString($array['username']);
  6408. if ($this->usernameTaken($array['username'], $array['username'], $id)) {
  6409. $this->setAPIResponse('error', 'Username: ' . $array['username'] . ' is already taken', 409);
  6410. return false;
  6411. }
  6412. if (!$this->qualifyLength($array['username'], 50, true)) {
  6413. return false;
  6414. }
  6415. }
  6416. if (array_key_exists('email', $array)) {
  6417. if ($array['email'] == '') {
  6418. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6419. return false;
  6420. }
  6421. if ($this->validateEmail($array['email'])) {
  6422. $array['email'] = $this->sanitizeEmail($array['email']);
  6423. } else {
  6424. $this->setResponse(409, 'Email is not a valid email', ['email' => $array['email']]);
  6425. return false;
  6426. }
  6427. if ($this->usernameTaken($array['email'], $array['email'], $id)) {
  6428. $this->setAPIResponse('error', 'Email: ' . $array['email'] . ' is already taken', 409);
  6429. return false;
  6430. }
  6431. if (!$this->qualifyLength($array['email'], 50, true)) {
  6432. return false;
  6433. }
  6434. }
  6435. if (array_key_exists('group_id', $array)) {
  6436. if ($array['group_id'] == '') {
  6437. $array['group_id'] = 0;
  6438. //$this->setAPIResponse('error', 'group_id was set but empty', 409);
  6439. //return false;
  6440. }
  6441. if (!$this->qualifyRequest('1', false)) {
  6442. $this->setAPIResponse('error', 'Cannot change your own group_id', 401);
  6443. return false;
  6444. }
  6445. if (($id == $this->user['userID']) && $this->user['groupID'] == 0) {
  6446. $array['group_id'] = 0;
  6447. }
  6448. if (($id == $this->user['userID']) && ($array['group_id'] == 0 && $this->user['groupID'] !== 0)) {
  6449. $this->setAPIResponse('error', 'Only admins can make others admins', 401);
  6450. return false;
  6451. }
  6452. $array['group'] = $this->getGroupByGroupId($array['group_id'])['group'];
  6453. if (!$array['group']) {
  6454. $this->setAPIResponse('error', 'group_id does not exist', 404);
  6455. return false;
  6456. }
  6457. }
  6458. if (array_key_exists('locked', $array)) {
  6459. //$this->setAPIResponse('error', 'Cannot use endpoint to unlock or lock user - please use /users/{id}/lock', 409);
  6460. //return false;
  6461. }
  6462. if (array_key_exists('password', $array)) {
  6463. if ($array['password'] == '') {
  6464. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6465. return false;
  6466. }
  6467. $array['password'] = password_hash($array['password'], PASSWORD_BCRYPT);
  6468. }
  6469. if (array_key_exists('image', $array)) {
  6470. $array['image'] = $this->sanitizeUserString($array['image']);
  6471. }
  6472. if (array_key_exists('register_date', $array)) {
  6473. $this->setAPIResponse('error', 'Cannot update register date', 409);
  6474. return false;
  6475. }
  6476. $response = [
  6477. array(
  6478. 'function' => 'query',
  6479. 'query' => array(
  6480. 'UPDATE users SET',
  6481. $array,
  6482. 'WHERE id = ?',
  6483. $id
  6484. )
  6485. ),
  6486. ];
  6487. $this->setAPIResponse(null, 'User info updated');
  6488. $this->setLoggerChannel('User Management');
  6489. $this->logger->info('Updated User Info for [' . $user['username'] . ']');
  6490. return $this->processQueries($response);
  6491. }
  6492. public function deleteUser($id)
  6493. {
  6494. $response = [
  6495. array(
  6496. 'function' => 'query',
  6497. 'query' => array(
  6498. 'DELETE FROM users WHERE id = ?',
  6499. $id
  6500. )
  6501. ),
  6502. ];
  6503. $userInfo = $this->getUserById($id);
  6504. if ($id == $this->user['userID']) {
  6505. $this->setAPIResponse('error', 'Cannot delete your own user', 409);
  6506. return false;
  6507. }
  6508. if (!$userInfo) {
  6509. $this->setAPIResponse('error', 'id not found', 404);
  6510. return false;
  6511. }
  6512. $this->setLoggerChannel('User Management');
  6513. $this->logger->info('Deleted User [' . $userInfo['username'] . ']');
  6514. $this->revokeTokensByUserId($id);
  6515. $this->setAPIResponse('success', 'User deleted', 204);
  6516. return $this->processQueries($response);
  6517. }
  6518. public function addUser($array)
  6519. {
  6520. $username = $array['username'] ?? null;
  6521. $password = $array['password'] ?? null;
  6522. $email = $array['email'] ?? null;
  6523. if (!$username) {
  6524. $this->setAPIResponse('error', 'Username was not supplied', 409);
  6525. return false;
  6526. }
  6527. if ($username == '') {
  6528. $this->setResponse(409, 'Username was set but empty');
  6529. return false;
  6530. } else {
  6531. $username = $this->sanitizeUserString($username);
  6532. }
  6533. if (!$password) {
  6534. $this->setAPIResponse('error', 'Password was not supplied', 409);
  6535. return false;
  6536. }
  6537. if (!$email) {
  6538. $this->setAPIResponse('error', 'Email was set not supplied', 409);
  6539. return false;
  6540. }
  6541. if ($email == '') {
  6542. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6543. return false;
  6544. }
  6545. if ($this->validateEmail($email)) {
  6546. $email = $this->sanitizeEmail($email);
  6547. } else {
  6548. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6549. return false;
  6550. }
  6551. if (!$this->qualifyLength($username, 50, true)) {
  6552. return false;
  6553. }
  6554. if (!$this->qualifyLength($email, 50, true)) {
  6555. return false;
  6556. }
  6557. if (!$this->qualifyLength($password, 200, true)) {
  6558. return false;
  6559. }
  6560. $this->setLoggerChannel('User Management');
  6561. if ($this->createUser($username, $password, $email)) {
  6562. $this->logger->info('Account created for [' . $username . ']');
  6563. return true;
  6564. } else {
  6565. $this->logger->warning('An error occurred');
  6566. return false;
  6567. }
  6568. }
  6569. public function createUser($username, $password, $email = null)
  6570. {
  6571. $username = $username ?? null;
  6572. $password = $password ?? null;
  6573. $email = ($email) ? $email : $this->random_ascii_string(10) . '@placeholder.eml';
  6574. if (!$username) {
  6575. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6576. return false;
  6577. }
  6578. $username = $this->sanitizeUserString($username);
  6579. if (!$password) {
  6580. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6581. return false;
  6582. }
  6583. if ($email == '') {
  6584. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6585. return false;
  6586. }
  6587. if ($this->validateEmail($email)) {
  6588. $email = $this->sanitizeEmail($email);
  6589. } else {
  6590. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6591. return false;
  6592. }
  6593. if ($this->usernameTaken($username, $email)) {
  6594. $this->setAPIResponse('error', 'Username: ' . $username . ' or Email: ' . $email . ' is already taken', 409);
  6595. return false;
  6596. }
  6597. if (!$this->qualifyLength($username, 50, true)) {
  6598. return false;
  6599. }
  6600. if (!$this->qualifyLength($email, 50, true)) {
  6601. return false;
  6602. }
  6603. if (!$this->qualifyLength($password, 200, true)) {
  6604. return false;
  6605. }
  6606. $defaults = $this->getDefaultGroup();
  6607. $userInfo = [
  6608. 'username' => $username,
  6609. 'password' => password_hash($password, PASSWORD_BCRYPT),
  6610. 'email' => $email,
  6611. 'group' => $defaults['group'],
  6612. 'group_id' => $defaults['group_id'],
  6613. 'image' => $this->gravatar($email),
  6614. 'register_date' => gmdate('Y-m-d H:i:s'),
  6615. ];
  6616. $response = [
  6617. array(
  6618. 'function' => 'query',
  6619. 'query' => array(
  6620. 'INSERT INTO [users]',
  6621. $userInfo
  6622. )
  6623. ),
  6624. ];
  6625. $this->setAPIResponse('success', 'User created', 200);
  6626. return $this->processQueries($response);
  6627. }
  6628. public function updateGroup($id, $array)
  6629. {
  6630. if (!$id || $id == '') {
  6631. $this->setAPIResponse('error', 'id was not set', 422);
  6632. return null;
  6633. }
  6634. if (!$array) {
  6635. $this->setAPIResponse('error', 'no data was sent', 422);
  6636. return null;
  6637. }
  6638. $groupInfo = $this->getGroupById($id);
  6639. if ($groupInfo) {
  6640. $array = $this->checkKeys($groupInfo, $array);
  6641. } else {
  6642. $this->setAPIResponse('error', 'No category info found', 404);
  6643. return false;
  6644. }
  6645. if (array_key_exists('group_id', $array)) {
  6646. $this->setAPIResponse('error', 'Cannot change group_id', 409);
  6647. return false;
  6648. }
  6649. if (array_key_exists('group', $array)) {
  6650. if ($array['group'] == '') {
  6651. $this->setAPIResponse('error', 'Group was set but empty', 409);
  6652. return false;
  6653. }
  6654. $array['group'] = $this->sanitizeUserString($array['group']);
  6655. if ($this->isGroupNameTaken($array['group'], $id)) {
  6656. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6657. return false;
  6658. }
  6659. if (!$this->qualifyLength($array['group'], 50, true)) {
  6660. return false;
  6661. }
  6662. }
  6663. if (array_key_exists('image', $array)) {
  6664. if ($array['image'] == '') {
  6665. $this->setAPIResponse('error', 'Image was set but empty', 409);
  6666. return false;
  6667. }
  6668. $array['image'] = $this->sanitizeUserString($array['image']);
  6669. }
  6670. if (array_key_exists('default', $array)) {
  6671. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6672. $this->setAPIResponse('error', 'Setting ' . $groupInfo['group'] . ' as default group is not allowed', 409);
  6673. return false;
  6674. }
  6675. if ($array['default']) {
  6676. $this->clearGroupDefault();
  6677. $array['default'] = 1;
  6678. }
  6679. }
  6680. $response = [
  6681. array(
  6682. 'function' => 'query',
  6683. 'query' => array(
  6684. 'UPDATE groups SET',
  6685. $array,
  6686. 'WHERE id = ?',
  6687. $id
  6688. )
  6689. ),
  6690. ];
  6691. $this->setAPIResponse(null, 'Group info updated');
  6692. $this->setLoggerChannel('Group Management');
  6693. $this->logger->info('Edited Group Info for [' . $groupInfo['group'] . ']');
  6694. return $this->processQueries($response);
  6695. }
  6696. public function deleteGroup($id)
  6697. {
  6698. $response = [
  6699. array(
  6700. 'function' => 'query',
  6701. 'query' => array(
  6702. 'DELETE FROM groups WHERE id = ?',
  6703. $id
  6704. )
  6705. ),
  6706. ];
  6707. $groupInfo = $this->getGroupById($id);
  6708. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6709. $this->setAPIResponse('error', 'Cannot delete group: ' . $groupInfo['group'] . ' as it is not allowed', 409);
  6710. return false;
  6711. }
  6712. if ($this->getGroupUserCountById($id) >= 1) {
  6713. $this->setAPIResponse('error', 'Cannot delete group as group still has users assigned to it', 409);
  6714. return false;
  6715. }
  6716. if ($groupInfo) {
  6717. $this->setLoggerChannel('Group Management');
  6718. $this->logger->info('Deleted Group [' . $groupInfo['group'] . ']');
  6719. $this->setAPIResponse('success', 'Group deleted', 204);
  6720. return $this->processQueries($response);
  6721. } else {
  6722. $this->setAPIResponse('error', 'id not found', 404);
  6723. return false;
  6724. }
  6725. }
  6726. public function addGroup($array)
  6727. {
  6728. if (!$array) {
  6729. $this->setAPIResponse('error', 'no data was sent', 422);
  6730. return null;
  6731. }
  6732. $array = $this->checkKeys($this->getTableColumnsFormatted('groups'), $array);
  6733. $array['default'] = ($array['default']) ?? 0;
  6734. $array['group_id'] = $this->getNextGroupOrder() + 1;
  6735. if (array_key_exists('group', $array)) {
  6736. $array['group'] = $this->sanitizeUserString($array['group']);
  6737. if ($this->isGroupNameTaken($array['group'])) {
  6738. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6739. return false;
  6740. }
  6741. if (!$this->qualifyLength($array['group'], 50, true)) {
  6742. return false;
  6743. }
  6744. } else {
  6745. $this->setAPIResponse('error', 'Group name was not supplied', 422);
  6746. return false;
  6747. }
  6748. if (array_key_exists('image', $array)) {
  6749. if ($array['image'] == '') {
  6750. $this->setAPIResponse('error', 'Group image cannot be empty', 422);
  6751. return false;
  6752. }
  6753. $array['image'] = $this->sanitizeUserString($array['image']);
  6754. } else {
  6755. $this->setAPIResponse('error', 'Group image was not supplied', 422);
  6756. return false;
  6757. }
  6758. $response = [
  6759. array(
  6760. 'function' => 'query',
  6761. 'query' => array(
  6762. 'INSERT INTO [groups]',
  6763. $array
  6764. )
  6765. ),
  6766. ];
  6767. $this->setAPIResponse(null, 'Group added');
  6768. $this->setLoggerChannel('Group Management');
  6769. $this->logger->info('Added Group for [' . $array['group'] . ']');
  6770. return $this->processQueries($response);
  6771. }
  6772. public function userList($type = null)
  6773. {
  6774. switch ($type) {
  6775. case 'plex':
  6776. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  6777. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'] . '/shared_servers';
  6778. try {
  6779. $headers = array(
  6780. "Accept" => "application/json",
  6781. "X-Plex-Token" => $this->config['plexToken']
  6782. );
  6783. $response = Requests::get($url, $headers, array());
  6784. libxml_use_internal_errors(true);
  6785. if ($response->success) {
  6786. $libraryList = array();
  6787. $plex = simplexml_load_string($response->body);
  6788. foreach ($plex->SharedServer as $child) {
  6789. if (!empty($child['username'])) {
  6790. $username = (string)strtolower($child['username']);
  6791. $email = (string)strtolower($child['email']);
  6792. $libraryList['users'][$username] = (string)$child['id'];
  6793. $libraryList['emails'][$email] = (string)$child['id'];
  6794. $libraryList['both'][$username] = $email;
  6795. }
  6796. }
  6797. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  6798. return $libraryList;
  6799. }
  6800. } catch (Requests_Exception $e) {
  6801. $this->setLoggerChannel('User Management');
  6802. $this->logger->error($e);
  6803. }
  6804. }
  6805. break;
  6806. default:
  6807. # code...
  6808. break;
  6809. }
  6810. return false;
  6811. }
  6812. public function encrypt($password, $key = null)
  6813. {
  6814. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6815. return openssl_encrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6816. }
  6817. public function decrypt($password, $key = null)
  6818. {
  6819. if (empty($password)) {
  6820. return '';
  6821. }
  6822. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6823. return openssl_decrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6824. }
  6825. public function checkValidCert($file)
  6826. {
  6827. if (file_exists($file)) {
  6828. return filesize($file) > 0;
  6829. } else {
  6830. return false;
  6831. }
  6832. }
  6833. public function getCert()
  6834. {
  6835. $url = 'http://curl.haxx.se/ca/cacert.pem';
  6836. $file = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  6837. $file2 = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  6838. $useCert = ($this->checkValidCert($file)) ? $file : $file2;
  6839. if ($this->config['selfSignedCert'] !== '') {
  6840. if (file_exists($this->config['selfSignedCert'])) {
  6841. return $this->config['selfSignedCert'];
  6842. }
  6843. }
  6844. $context = stream_context_create(
  6845. array(
  6846. 'ssl' => array(
  6847. 'verify_peer' => true,
  6848. 'cafile' => $useCert
  6849. )
  6850. )
  6851. );
  6852. if (!$this->checkValidCert($file) || (file_exists($file) && time() - 2592000 > filemtime($file))) {
  6853. file_put_contents($file, fopen($url, 'r', false, $context));
  6854. }
  6855. return ($this->checkValidCert($file)) ? $file : $file2;
  6856. }
  6857. public function hasCustomCert()
  6858. {
  6859. return file_exists($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem');
  6860. }
  6861. public function getCustomCert()
  6862. {
  6863. return ($this->hasCustomCert()) ? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem' : false;
  6864. }
  6865. public function uploadCert()
  6866. {
  6867. $filesCheck = array_filter($_FILES);
  6868. if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'cert')) {
  6869. ini_set('upload_max_filesize', '10M');
  6870. ini_set('post_max_size', '10M');
  6871. $tempFile = $_FILES['file']['tmp_name'];
  6872. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR;
  6873. $targetFile = $targetPath . 'custom.pem';
  6874. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  6875. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert');
  6876. return move_uploaded_file($tempFile, $targetFile);
  6877. } else {
  6878. $this->setAPIResponse('error', pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' is not approved to be uploaded', 403);
  6879. return false;
  6880. }
  6881. }
  6882. public function createCronFile()
  6883. {
  6884. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6885. file_put_contents($file, time());
  6886. }
  6887. public function checkCronFile()
  6888. {
  6889. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6890. return file_exists($file) && time() - 120 < filemtime($file);
  6891. }
  6892. public function plexJoinAPI($array)
  6893. {
  6894. $username = ($array['username']) ?? null;
  6895. $email = ($array['email']) ?? null;
  6896. $password = ($array['password']) ?? null;
  6897. if (!$username) {
  6898. $this->setAPIResponse('error', 'Username not supplied', 409);
  6899. return false;
  6900. }
  6901. if (!$email) {
  6902. $this->setAPIResponse('error', 'Email not supplied', 409);
  6903. return false;
  6904. }
  6905. if (!$password) {
  6906. $this->setAPIResponse('error', 'Password not supplied', 409);
  6907. return false;
  6908. }
  6909. return $this->plexJoin($username, $email, $password);
  6910. }
  6911. public function plexJoin($username, $email, $password)
  6912. {
  6913. try {
  6914. $url = 'https://plex.tv/api/v2/users';
  6915. $headers = array(
  6916. 'Accept' => 'application/json',
  6917. 'Content-Type' => 'application/x-www-form-urlencoded',
  6918. 'X-Plex-Product' => 'Organizr',
  6919. 'X-Plex-Version' => '2.0',
  6920. 'X-Plex-Client-Identifier' => $this->config['uuid'],
  6921. );
  6922. $data = array(
  6923. 'email' => $email,
  6924. 'username' => $username,
  6925. 'password' => $password,
  6926. );
  6927. $response = Requests::post($url, $headers, $data, array());
  6928. $json = json_decode($response->body, true);
  6929. $errors = !empty($json['errors']);
  6930. $success = empty($json['errors']);
  6931. //Use This for later
  6932. $errorMessage = '';
  6933. if ($errors) {
  6934. foreach ($json['errors'] as $error) {
  6935. if (isset($error['message']) && isset($error['field'])) {
  6936. $errorMessage .= "[Plex.tv Error: " . $error['message'] . " for field: (" . $error['field'] . ")]";
  6937. }
  6938. }
  6939. }
  6940. $msg = (!empty($success) && empty($errors)) ? 'User has joined Plex' : $errorMessage;
  6941. $status = (!empty($success) && empty($errors)) ? 'success' : 'error';
  6942. $code = (!empty($success) && empty($errors)) ? 200 : 422;
  6943. $this->setAPIResponse($status, $msg, $code);
  6944. return (!empty($success) && empty($errors));
  6945. } catch (Requests_Exception $e) {
  6946. $this->setLoggerChannel('User Management');
  6947. $this->logger->error($e);
  6948. $this->setAPIResponse('error', 'An Error Occurred', 409);
  6949. return false;
  6950. }
  6951. return false;
  6952. }
  6953. public function lockCurrentUser()
  6954. {
  6955. if ($this->user['userID'] == '999') {
  6956. $this->setAPIResponse('error', 'Locking not allowed on Guest users', 409);
  6957. return false;
  6958. }
  6959. return $this->lockUser($this->user['userID']);
  6960. }
  6961. public function lockUser($id)
  6962. {
  6963. $user = $this->getUserById($id);
  6964. if (!$user) {
  6965. $this->setAPIResponse('error', 'User not found', 404);
  6966. return false;
  6967. }
  6968. $response = [
  6969. array(
  6970. 'function' => 'query',
  6971. 'query' => array(
  6972. 'UPDATE users SET',
  6973. ['locked' => '1'],
  6974. 'WHERE id = ?',
  6975. $id
  6976. )
  6977. ),
  6978. ];
  6979. $this->setLoggerChannel('User Management');
  6980. $this->logger->info('User: ' . $user['username'] . ' account locked');
  6981. $this->setAPIResponse('success', 'User account locked', 200);
  6982. return $this->processQueries($response);
  6983. }
  6984. public function unlockCurrentUser($array)
  6985. {
  6986. if ($array['password'] == '') {
  6987. $this->setAPIResponse('error', 'Password Not Set', 422);
  6988. return false;
  6989. }
  6990. $user = $this->getUserById($this->user['userID']);
  6991. if (!password_verify($array['password'], $user['password'])) {
  6992. $this->setAPIResponse('error', 'Password Incorrect', 401);
  6993. return false;
  6994. }
  6995. return $this->unlockUser($this->user['userID']);
  6996. }
  6997. public function unlockUser($id)
  6998. {
  6999. $user = $this->getUserById($id);
  7000. if (!$user) {
  7001. $this->setAPIResponse('error', 'User not found', 404);
  7002. return false;
  7003. }
  7004. $response = [
  7005. array(
  7006. 'function' => 'query',
  7007. 'query' => array(
  7008. 'UPDATE users SET',
  7009. ['locked' => '0'],
  7010. 'WHERE id = ?',
  7011. $id
  7012. )
  7013. ),
  7014. ];
  7015. $this->setLoggerChannel('User Management');
  7016. $this->logger->info('User: ' . $user['username'] . ' account unlocked');
  7017. $this->setAPIResponse('success', 'User account unlocked', 200);
  7018. return $this->processQueries($response);
  7019. }
  7020. public function youtubeSearch($query)
  7021. {
  7022. if (!$query) {
  7023. $this->setAPIResponse('error', 'No query supplied', 422);
  7024. return false;
  7025. }
  7026. $keys = array(
  7027. 'AIzaSyBsdt8nLJRMTwOq5PY5A5GLZ2q7scgn01w',
  7028. 'AIzaSyD-8SHutB60GCcSM8q_Fle38rJUV7ujd8k',
  7029. 'AIzaSyBzOpVBT6VII-b-8gWD0MOEosGg4hyhCsQ',
  7030. 'AIzaSyBKnRe1P8fpfBHgooJpmT0WOsrdUtZ4cpk'
  7031. );
  7032. $randomKeyIndex = array_rand($keys);
  7033. $key = $keys[$randomKeyIndex];
  7034. $apikey = ($this->config['youtubeAPI'] !== '') ? $this->config['youtubeAPI'] : $key;
  7035. $results = false;
  7036. $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=$query+official+trailer&part=snippet&maxResults=1&type=video&videoDuration=short&key=$apikey";
  7037. $response = Requests::get($url);
  7038. if ($response->success) {
  7039. $results = json_decode($response->body, true);
  7040. $this->setAPIResponse('success', null, 200, $results);
  7041. return $results;
  7042. } else {
  7043. $this->setAPIResponse('error', 'Bad response from YouTube', 500);
  7044. return false;
  7045. }
  7046. }
  7047. public function scrapePage($array)
  7048. {
  7049. try {
  7050. $url = $array['url'] ?? false;
  7051. $type = $array['type'] ?? false;
  7052. if (!$url) {
  7053. $this->setAPIResponse('error', 'URL was not supplied', 422);
  7054. return false;
  7055. }
  7056. $url = $this->qualifyURL($url);
  7057. $data = array(
  7058. 'full_url' => $url,
  7059. 'drill_url' => $this->qualifyURL($url, true)
  7060. );
  7061. $options = array('verify' => false);
  7062. $response = Requests::get($url, array(), $options);
  7063. $data['response_code'] = $response->status_code;
  7064. if ($response->success) {
  7065. $data['result'] = 'Success';
  7066. switch ($type) {
  7067. case 'html':
  7068. $data['data'] = html_entity_decode($response->body);
  7069. break;
  7070. case 'json':
  7071. $data['data'] = json_decode($response->body);
  7072. break;
  7073. default:
  7074. $data['data'] = $response->body;
  7075. }
  7076. $this->setAPIResponse('success', null, 200, $data);
  7077. return $data;
  7078. } else {
  7079. $this->setAPIResponse('error', 'Error getting successful response', 500);
  7080. return false;
  7081. }
  7082. } catch (Requests_Exception $e) {
  7083. $this->setResponse(500, $e->getMessage());
  7084. return false;
  7085. }
  7086. }
  7087. public function chooseInstance($url = null, $token = null, $instance = 0, $type = null)
  7088. {
  7089. if (!$url || !$token) {
  7090. return false;
  7091. }
  7092. $list = $this->csvHomepageUrlToken($url, $token);
  7093. if ($type) {
  7094. $type = strtolower($type);
  7095. switch ($type) {
  7096. case 'url':
  7097. case 'token':
  7098. break;
  7099. default:
  7100. $type = 'url';
  7101. break;
  7102. }
  7103. if (is_numeric($instance)) {
  7104. return $list[$instance][$type];
  7105. } else {
  7106. return $list;
  7107. }
  7108. }
  7109. if (is_numeric($instance)) {
  7110. return $list[$instance];
  7111. } else {
  7112. return $list;
  7113. }
  7114. }
  7115. public function CBPFWTabs()
  7116. {
  7117. return '
  7118. <script>
  7119. /**
  7120. * cbpFWTabs.js v1.0.0
  7121. * http://www.codrops.com
  7122. *
  7123. * Licensed under the MIT license.
  7124. * http://www.opensource.org/licenses/mit-license.php
  7125. *
  7126. * Copyright 2014, Codrops
  7127. * http://www.codrops.com
  7128. */
  7129. ;( function( window ) {
  7130. \'use strict\';
  7131. function extend( a, b ) {
  7132. for( var key in b ) {
  7133. if( b.hasOwnProperty( key ) ) {
  7134. a[key] = b[key];
  7135. }
  7136. }
  7137. return a;
  7138. }
  7139. function CBPFWTabs( el, options ) {
  7140. this.el = el;
  7141. this.options = extend( {}, this.options );
  7142. extend( this.options, options );
  7143. this._init();
  7144. }
  7145. CBPFWTabs.prototype.options = {
  7146. start : 0
  7147. };
  7148. CBPFWTabs.prototype._init = function() {
  7149. // tabs elems
  7150. this.tabs = [].slice.call( this.el.querySelectorAll( \'nav > ul > li\' ) );
  7151. // content items
  7152. this.items = [].slice.call( this.el.querySelectorAll( \'.content-wrap > section\' ) );
  7153. // current index
  7154. this.current = -1;
  7155. // show current content item
  7156. try{
  7157. if(this.tabs[0].innerHTML.indexOf(\'#settings\') >= 0){
  7158. this._show(' . $this->config['defaultSettingsTab'] . ');
  7159. let tabId = $(this.items[' . $this->config['defaultSettingsTab'] . ']).attr("id") + "-anchor";
  7160. $("#" + tabId).click();
  7161. $("#" + tabId + " a").click();
  7162. }else{
  7163. this._show();
  7164. }
  7165. }catch{
  7166. this._show();
  7167. }
  7168. // init events
  7169. this._initEvents();
  7170. };
  7171. CBPFWTabs.prototype._initEvents = function() {
  7172. var self = this;
  7173. this.tabs.forEach( function( tab, idx ) {
  7174. tab.addEventListener( \'click\', function( ev ) {
  7175. ev.preventDefault();
  7176. self._show( idx );
  7177. } );
  7178. } );
  7179. };
  7180. CBPFWTabs.prototype._show = function( idx ) {
  7181. if( this.current >= 0 ) {
  7182. this.tabs[ this.current ].className = this.items[ this.current ].className = \'\';
  7183. }
  7184. // change current
  7185. this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
  7186. this.tabs[ this.current ].className = \'tab-current\';
  7187. this.items[ this.current ].className = \'content-current\';
  7188. };
  7189. // add to global namespace
  7190. window.CBPFWTabs = CBPFWTabs;
  7191. })( window );
  7192. </script>
  7193. ';
  7194. }
  7195. public function socksHeadingHTML($app)
  7196. {
  7197. return '
  7198. <h3 lang="en">' . ucwords($app) . ' SOCKS API Connection</h3>
  7199. <p>Using this feature allows you to access the API without having to reverse proxy it. Just access it from: </p>
  7200. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/socks/' . $app . '/</code>
  7201. <p>If you are using multiple URL\'s (using the csv method) you will have to use the url like these: </p>
  7202. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/1</code>
  7203. <br/>
  7204. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/2</code>
  7205. ';
  7206. }
  7207. public function socksListing($app = null)
  7208. {
  7209. switch ($app) {
  7210. case 'sonarr':
  7211. $appDetails = [
  7212. 'url' => 'sonarrURL',
  7213. 'enabled' => 'sonarrSocksEnabled',
  7214. 'auth' => 'sonarrSocksAuth',
  7215. 'header' => 'X-Api-Key'
  7216. ];
  7217. break;
  7218. case 'radarr':
  7219. $appDetails = [
  7220. 'url' => 'radarrURL',
  7221. 'enabled' => 'radarrSocksEnabled',
  7222. 'auth' => 'radarrSocksAuth',
  7223. 'header' => 'X-Api-Key'
  7224. ];
  7225. break;
  7226. case 'lidarr':
  7227. $appDetails = [
  7228. 'url' => 'lidarrURL',
  7229. 'enabled' => 'lidarrSocksEnabled',
  7230. 'auth' => 'lidarrSocksAuth',
  7231. 'header' => 'X-Api-Key'
  7232. ];
  7233. break;
  7234. case 'sabnzbd':
  7235. $appDetails = [
  7236. 'url' => 'sabnzbdURL',
  7237. 'enabled' => 'sabnzbdSocksEnabled',
  7238. 'auth' => 'sabnzbdSocksAuth',
  7239. 'header' => null
  7240. ];
  7241. break;
  7242. case 'nzbget':
  7243. $appDetails = [
  7244. 'url' => 'nzbgetURL',
  7245. 'enabled' => 'nzbgetSocksEnabled',
  7246. 'auth' => 'nzbgetSocksAuth',
  7247. 'header' => 'Authorization'
  7248. ];
  7249. break;
  7250. case 'tautulli':
  7251. $appDetails = [
  7252. 'url' => 'tautulliURL',
  7253. 'enabled' => 'tautulliSocksEnabled',
  7254. 'auth' => 'tautulliSocksAuth',
  7255. 'header' => null
  7256. ];
  7257. break;
  7258. case 'qbittorrent':
  7259. $appDetails = [
  7260. 'url' => 'qBittorrentURL',
  7261. 'enabled' => 'qBittorrentSocksEnabled',
  7262. 'auth' => 'qBittorrentSocksAuth',
  7263. 'header' => null
  7264. ];
  7265. break;
  7266. default:
  7267. $appDetails = null;
  7268. }
  7269. return $appDetails;
  7270. }
  7271. public function socks($appDetails, $requestObject, $multiple = null)
  7272. {
  7273. $url = $appDetails['url'];
  7274. $enabled = $appDetails['enabled'];
  7275. $auth = $appDetails['auth'];
  7276. $header = $appDetails['header'];
  7277. $error = false;
  7278. if (!$this->config[$enabled]) {
  7279. $error = true;
  7280. $this->setAPIResponse('error', 'SOCKS module is not enabled', 409);
  7281. }
  7282. if (!$this->qualifyRequest($this->config[$auth], true)) {
  7283. $error = true;
  7284. }
  7285. if (strpos($this->config[$url], ',') !== false) {
  7286. if (!$multiple) {
  7287. $error = true;
  7288. $this->setAPIResponse('error', 'Multiple URLs found in field, please use /api/v2/multiple/socks endpoint', 409);
  7289. }
  7290. } else {
  7291. if ($multiple) {
  7292. $error = true;
  7293. $this->setAPIResponse('error', 'Multiple endpoint accessed but multiple URLs not found in field, please use /api/v2/socks endpoint', 409);
  7294. }
  7295. }
  7296. if ($error) {
  7297. return null;
  7298. }
  7299. if ($multiple) {
  7300. $instance = $multiple - 1;
  7301. $pre = explode('/api/v2/multiple/socks/', $requestObject->getUri()->getPath());
  7302. $pre[1] = $this->replace_first('/' . $multiple . '/', '/', $pre[1]);
  7303. // sent url twice since we arent using tokens
  7304. $list = $this->csvHomepageUrlToken($this->config[$url], $this->config[$url]);
  7305. $appURL = $list[$instance]['url'];
  7306. } else {
  7307. $pre = explode('/api/v2/socks/', $requestObject->getUri()->getPath());
  7308. $appURL = $this->config[$url];
  7309. }
  7310. $endpoint = explode('/', $pre[1]);
  7311. $new = urldecode(preg_replace('/' . $endpoint[0] . '/', '', $pre[1], 1));
  7312. $getParams = ($_GET) ? '?' . http_build_query($_GET) : '';
  7313. $url = $this->qualifyURL($appURL) . $new . $getParams;
  7314. $url = $this->cleanPath($url);
  7315. $options = ($this->localURL($appURL)) ? ['verify' => false, 'timeout' => 120] : ['timeout' => 120];
  7316. $headers = [];
  7317. $apiData = $this->apiData($requestObject, false);
  7318. if ($header) {
  7319. if ($requestObject->hasHeader($header)) {
  7320. $headerKey = $requestObject->getHeaderLine($header);
  7321. $headers[$header] = $headerKey;
  7322. }
  7323. }
  7324. if ($requestObject->hasHeader('Content-Type')) {
  7325. $headerKey = $requestObject->getHeaderLine('Content-Type');
  7326. $headers['Content-Type'] = $headerKey;
  7327. }
  7328. $debugInformation = [
  7329. 'type' => $requestObject->getMethod(),
  7330. 'headerType' => $requestObject->getHeaderLine('Content-Type'),
  7331. 'header' => $header,
  7332. 'headers' => $headers,
  7333. 'url' => $url,
  7334. 'options' => $options,
  7335. 'data' => $apiData,
  7336. ];
  7337. $this->setLoggerChannel('Socks')->debug('Sending Socks request', $debugInformation);
  7338. try {
  7339. switch ($requestObject->getMethod()) {
  7340. case 'GET':
  7341. $call = Requests::get($url, $headers, $options);
  7342. break;
  7343. case 'POST':
  7344. $call = Requests::post($url, $headers, $apiData, $options);
  7345. break;
  7346. case 'DELETE':
  7347. $call = Requests::delete($url, $headers, $options);
  7348. break;
  7349. case 'PUT':
  7350. $call = Requests::put($url, $headers, $apiData, $options);
  7351. break;
  7352. default:
  7353. $call = Requests::get($url, $headers, $options);
  7354. }
  7355. if ($this->config['socksDebug']) {
  7356. if ($this->json_validator($call->body)) {
  7357. $logData = json_decode($call->body, true);
  7358. $size = (!is_numeric($this->config['maxSocksDebugSize']) || $this->config['maxSocksDebugSize'] == 0) ? 1 : $this->config['maxSocksDebugSize'];
  7359. if (count($logData) > $size) {
  7360. $logData = 'Count too large to output';
  7361. }
  7362. } else {
  7363. $logData = $call->body;
  7364. }
  7365. } else {
  7366. $logData = 'Debug not enabled';
  7367. }
  7368. $this->setLoggerChannel('Socks')->debug('Socks Response', ['body' => $logData, 'debug' => $debugInformation]);
  7369. return $call->body;
  7370. } catch (Requests_Exception $e) {
  7371. $this->setResponse(500, $e->getMessage());
  7372. $this->setLoggerChannel('Socks')->critical($e, $debugInformation);
  7373. return null;
  7374. }
  7375. }
  7376. public function getPlexServers()
  7377. {
  7378. if ($this->config['plexToken'] == '') {
  7379. $this->setAPIResponse('error', 'Plex Token cannot be empty', 422);
  7380. return false;
  7381. }
  7382. $ownedOnly = isset($_GET['owned']) ?? false;
  7383. $url = $this->qualifyURL('https://plex.tv/pms/servers');
  7384. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  7385. $headers = [
  7386. 'X-Plex-Product' => 'Organizr',
  7387. 'X-Plex-Version' => '2.0',
  7388. 'X-Plex-Client-Identifier' => '01010101-10101010',
  7389. 'X-Plex-Token' => $this->config['plexToken'],
  7390. ];
  7391. try {
  7392. $response = Requests::get($url, $headers, $options);
  7393. libxml_use_internal_errors(true);
  7394. if ($response->success) {
  7395. $items = array();
  7396. $plex = simplexml_load_string($response->body);
  7397. foreach ($plex as $server) {
  7398. if ($ownedOnly) {
  7399. if ($server['owned'] == 1) {
  7400. $items[] = array(
  7401. 'name' => (string)$server['name'],
  7402. 'address' => (string)$server['address'],
  7403. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7404. 'owned' => (float)$server['owned'],
  7405. );
  7406. }
  7407. } else {
  7408. $items[] = array(
  7409. 'name' => (string)$server['name'],
  7410. 'address' => (string)$server['address'],
  7411. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7412. 'owned' => (float)$server['owned'],
  7413. );
  7414. }
  7415. }
  7416. $this->setResponse(200, null, $items);
  7417. return $items;
  7418. } else {
  7419. $message = $this->testAndFormatString($response->body);
  7420. $this->setResponse(500, 'Plex Error occurred', $message['data']);
  7421. $this->setLoggerChannel('Plex Connection')->warning('Plex Error', $message);
  7422. return $message;
  7423. }
  7424. } catch (Requests_Exception $e) {
  7425. $this->setLoggerChannel('Plex Connection')->error($e);
  7426. $this->setResponse(500, $e->getMessage());
  7427. return false;
  7428. }
  7429. }
  7430. public function getIcons()
  7431. {
  7432. $term = $_GET['search'] ?? null;
  7433. $page = $_GET['page'] ?? 1;
  7434. $limit = $_GET['limit'] ?? 20;
  7435. $offset = ($page * $limit) - $limit;
  7436. $goodIcons['results'] = [];
  7437. $goodIcons['limit'] = $limit;
  7438. $goodIcons['page'] = $page;
  7439. $goodIcons['term'] = $term;
  7440. $allIcons = file_get_contents($this->root . '/js/icons.json');
  7441. $iconListing = json_decode($allIcons, true);
  7442. foreach ($iconListing as $setKey => $set) {
  7443. foreach ($set['children'] as $k => $v) {
  7444. if ($term) {
  7445. if (stripos($v['text'], $term) !== false) {
  7446. $goodIcons['results'][] = $v;
  7447. }
  7448. } else {
  7449. $goodIcons['results'][] = $v;
  7450. }
  7451. }
  7452. }
  7453. $total = count($goodIcons['results']);
  7454. $goodIcons['total'] = $total;
  7455. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  7456. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  7457. return $goodIcons;
  7458. }
  7459. public function getJournalMode()
  7460. {
  7461. $response = [
  7462. array(
  7463. 'function' => 'fetch',
  7464. 'query' => 'PRAGMA journal_mode',
  7465. ),
  7466. ];
  7467. $query = $this->processQueries($response);
  7468. if ($query) {
  7469. if ($query['journal_mode']) {
  7470. $this->setResponse(200, null, $query);
  7471. } else {
  7472. $this->setResponse(500, 'Error getting Journal Mode');
  7473. }
  7474. } else {
  7475. $this->setResponse(404, 'Journal Mode not found');
  7476. }
  7477. return $query;
  7478. }
  7479. public function setJournalMode($option = 'WAL')
  7480. {
  7481. $option = strtoupper($option);
  7482. switch ($option) {
  7483. case 'WAL':
  7484. case 'DELETE':
  7485. break;
  7486. default:
  7487. return false;
  7488. }
  7489. $response = [
  7490. array(
  7491. 'function' => 'fetch',
  7492. 'query' => 'PRAGMA journal_mode = \'' . $option . '\';',
  7493. ),
  7494. ];
  7495. $query = $this->processQueries($response);
  7496. if ($query) {
  7497. if ($query['journal_mode']) {
  7498. $this->setResponse(200, 'Journal Mode updated to: ' . $option, $query);
  7499. } else {
  7500. $this->setResponse(500, 'Error getting Journal Mode');
  7501. }
  7502. } else {
  7503. $this->setResponse(404, 'Journal Mode not found');
  7504. }
  7505. return $query;
  7506. }
  7507. public function testCronSchedule($schedule = null)
  7508. {
  7509. if (is_array($schedule)) {
  7510. $schedule = str_replace('_', ' ', array_keys($schedule)[0]);
  7511. }
  7512. if (!$schedule) {
  7513. $this->setResponse(409, 'Schedule was not supplied');
  7514. return false;
  7515. }
  7516. try {
  7517. $schedule = new Cron\CronExpression($schedule);
  7518. $this->setResponse(200, 'Schedule was validated');
  7519. return true;
  7520. } catch (InvalidArgumentException $e) {
  7521. $this->setResponse(500, $e->getMessage());
  7522. return false;
  7523. }
  7524. }
  7525. public function testFolder($folder = null)
  7526. {
  7527. $folder = $folder['folder'] ?? null;
  7528. if (!$folder) {
  7529. $this->setResponse(409, 'Folder was not supplied');
  7530. return false;
  7531. }
  7532. $testFolder = $this->makeDir($folder);
  7533. if ($testFolder) {
  7534. $this->setResponse(200, 'Folder approved for logs');
  7535. return true;
  7536. } else {
  7537. $this->setResponse(409, 'Folder path is not valid or permissions insufficient');
  7538. return false;
  7539. }
  7540. }
  7541. public function replaceStringInDatabase($string)
  7542. {
  7543. $databaseStringList = [
  7544. 'AUTOINCREMENT' => [
  7545. 'sqlite3' => 'AUTOINCREMENT',
  7546. 'mysqli' => 'AUTO_INCREMENT',
  7547. 'postgre' => 'AUTOINCREMENT'
  7548. ],
  7549. 'COLLATE NOCASE' => [
  7550. 'sqlite3' => 'COLLATE NOCASE',
  7551. 'mysqli' => '',
  7552. 'postgre' => ''
  7553. ],
  7554. 'INTEGER PRIMARY KEY AUTOINCREMENT' => [
  7555. 'sqlite3' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7556. 'mysqli' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7557. 'postgre' => 'SERIAL PRIMARY KEY'
  7558. ],
  7559. 'DATETIME' => [
  7560. 'sqlite3' => 'DATETIME',
  7561. 'mysqli' => 'DATETIME',
  7562. 'postgre' => 'TIMESTAMP'
  7563. ],
  7564. ];
  7565. if (gettype($string) == 'string') {
  7566. foreach ($databaseStringList as $item => $value) {
  7567. if (stripos($string, $item) !== false) {
  7568. $string = str_ireplace($item, $databaseStringList[$item][$this->config['driver']], $string);
  7569. }
  7570. }
  7571. }
  7572. return $string;
  7573. }
  7574. public function cleanDatabaseQuery($query)
  7575. {
  7576. if (is_array($query)) {
  7577. foreach ($query as $key => $value) {
  7578. $query[$key] = $this->cleanDatabaseQuery($value);
  7579. }
  7580. return $query;
  7581. } else {
  7582. return $this->replaceStringInDatabase($query);
  7583. }
  7584. }
  7585. protected function processQueries(array $request, $migration = false)
  7586. {
  7587. $results = array();
  7588. $firstKey = '';
  7589. if ($this->config['includeDatabaseQueriesInDebug']) {
  7590. $this->setLoggerChannel('Database');
  7591. $this->logger->debug('Query to database', $request);
  7592. }
  7593. foreach ($request as $k => $v) {
  7594. try {
  7595. $v['query'] = $this->cleanDatabaseQuery($v['query']);
  7596. $query = ($migration) ? $this->otherDb->query($v['query']) : $this->db->query($v['query']);
  7597. $keyName = (isset($v['key'])) ? $v['key'] : $k;
  7598. $firstKey = (isset($v['key']) && $k == 0) ? $v['key'] : $k;
  7599. switch ($v['function']) {
  7600. case 'fetchAll':
  7601. $results[$keyName] = $query->fetchAll();
  7602. break;
  7603. case 'fetch':
  7604. // PHP 8 Fix?
  7605. $query->setRowClass(null);
  7606. $results[$keyName] = $query->fetch();
  7607. break;
  7608. case 'getAffectedRows':
  7609. $results[$keyName] = $query->getAffectedRows();
  7610. break;
  7611. case 'getRowCount':
  7612. $results[$keyName] = $query->getRowCount();
  7613. break;
  7614. case 'fetchSingle':
  7615. // PHP 8 Fix?
  7616. $query->setRowClass(null);
  7617. $results[$keyName] = $query->fetchSingle();
  7618. break;
  7619. case 'query':
  7620. $results[$keyName] = $query;
  7621. break;
  7622. default:
  7623. return false;
  7624. }
  7625. } catch (Exception $e) {
  7626. $this->setLoggerChannel('Database');
  7627. $this->logger->critical($e, $v['query']);
  7628. return false;
  7629. }
  7630. }
  7631. if ($this->config['includeDatabaseQueriesInDebug']) {
  7632. $this->logger->debug('Results from database', $results);
  7633. }
  7634. return count($request) > 1 ? $results : $results[$firstKey];
  7635. }
  7636. }