organizr.class.php 257 KB

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