| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421 |
- <?php
- use Dibi\Connection;
- class Organizr
- {
- // Use Custom Functions From Traits;
- use TwoFAFunctions;
- use ApiFunctions;
- use AuthFunctions;
- use BackupFunctions;
- use ConfigFunctions;
- use DemoFunctions;
- use HomepageConnectFunctions;
- use HomepageFunctions;
- use LogFunctions;
- use NetDataFunctions;
- use NormalFunctions;
- use OAuthFunctions;
- use OptionsFunction;
- use OrganizrFunctions;
- use PluginFunctions;
- use StaticFunctions;
- use SSOFunctions;
- use TokenFunctions;
- use UpdateFunctions;
- use UpgradeFunctions;
-
- // Use homepage item functions
- use CalendarHomepageItem;
- use CouchPotatoHomepageItem;
- use DelugeHomepageItem;
- use EmbyHomepageItem;
- use HealthChecksHomepageItem;
- use HTMLHomepageItem;
- use ICalHomepageItem;
- use JackettHomepageItem;
- use JDownloaderHomepageItem;
- use JellyfinHomepageItem;
- use LidarrHomepageItem;
- use MiscHomepageItem;
- use MonitorrHomepageItem;
- use NetDataHomepageItem;
- use NZBGetHomepageItem;
- use OctoPrintHomepageItem;
- use OmbiHomepageItem;
- use OverseerrHomepageItem;
- use PiHoleHomepageItem;
- use PlexHomepageItem;
- use QBitTorrentHomepageItem;
- use RadarrHomepageItem;
- use RTorrentHomepageItem;
- use SabNZBdHomepageItem;
- use SickRageHomepageItem;
- use SonarrHomepageItem;
- use SpeedTestHomepageItem;
- use TautulliHomepageItem;
- use TraktHomepageItem;
- use TransmissionHomepageItem;
- use UnifiHomepageItem;
- use WeatherHomepageItem;
- use uTorrentHomepageItem;
-
- // ===================================
- // Organizr Version
- public $version = '2.1.730';
- // ===================================
- // Quick php Version check
- public $minimumPHP = '7.3';
- // ===================================
- protected $db;
- protected $otherDb;
- public $config;
- public $user;
- public $userConfigPath;
- public $defaultConfigPath;
- public $currentTime;
- public $docker;
- public $dev;
- public $demo;
- public $commit;
- public $fileHash;
- public $cookieName;
- public $organizrLog;
- public $organizrLoginLog;
- public $timeExecution;
- public $root;
- public $paths;
- public $updating;
- public $groupOptions;
- public $warnings;
- public $errors;
-
- public function __construct($updating = false)
- {
- // First Check PHP Version
- $this->checkPHP();
- // Check Disk Space
- $this->checkDiskSpace();
- // Constructed from Updater?
- $this->updating = $updating;
- // Set Project Root directory
- $this->root = dirname(__DIR__, 2);
- // Set Start Execution Time
- $this->timeExecution = $this->timeExecution();
- // Set location path to user config path
- $this->userConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
- // Set location path to default config path
- $this->defaultConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'default.php';
- // Set current time
- $this->currentTime = gmdate("Y-m-d\TH:i:s\Z");
- // Set variable if install is for official docker
- $this->docker = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Docker.txt'));
- // Set variable if install is for develop and set php Error levels
- $this->dev = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Dev.txt'));
- $this->phpErrors();
- // Set variable if install is for demo
- $this->demo = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Demo.txt'));
- // Set variable if install has commit hash
- $this->commit = ($this->docker && !$this->dev) ? file_get_contents(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Github.txt') : null;
- // Set variable to be used as hash for files
- $this->fileHash = ($this->commit) ?? $this->version;
- $this->fileHash = trim($this->fileHash);
- // Load Config file
- $this->config = $this->config();
- // Set organizr Log file location
- $this->organizrLog = ($this->hasDB()) ? $this->config['dbLocation'] . 'organizrLog.json' : false;
- // Set organizr Login Log file location
- $this->organizrLoginLog = ($this->hasDB()) ? $this->config['dbLocation'] . 'organizrLoginLog.json' : false;
- // Set Paths
- $this->paths = array(
- 'Root Folder' => dirname(__DIR__, 2) . DIRECTORY_SEPARATOR,
- 'Cache Folder' => dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR,
- 'Tab Folder' => dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR,
- 'API Folder' => dirname(__DIR__, 1) . DIRECTORY_SEPARATOR,
- 'DB Folder' => ($this->hasDB()) ? $this->config['dbLocation'] : false
- );
- // Connect to DB
- $this->connectDB();
- // Check DB Writable
- $this->checkWritableDB();
- // Set cookie name for Organizr Instance
- $this->cookieName = ($this->hasDB()) ? $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp' : 'organizr_token_temp';
- // Get token form cookie and validate
- $this->setCurrentUser();
- // might just run this at index
- $this->upgradeCheck();
- // Is Page load Organizr OAuth?
- $this->checkForOrganizrOAuth();
- // Is user Blacklisted?
- $this->checkIfUserIsBlacklisted();
- }
-
- public function __destruct()
- {
- $this->disconnectDB();
- }
-
- protected function connectDB()
- {
- if ($this->hasDB()) {
- try {
- $connect = [
- 'driver' => 'sqlite3',
- 'database' => $this->config['dbLocation'] . $this->config['dbName']
- ];
- $this->db = new Connection($connect);
- } catch (Dibi\Exception $e) {
- $this->db = null;
- }
- } else {
- $this->db = null;
- }
- }
-
- public function disconnectDB()
- {
- if ($this->hasDB()) {
- $this->db->disconnect();
- $this->db = null;
- unset($this->db);
- }
- }
-
- public function connectOtherDB($file = null)
- {
- $file = $file ?? $this->config['dbLocation'] . 'tempMigration.db';
- try {
- $this->otherDb = new Connection([
- 'driver' => 'sqlite3',
- 'database' => $file,
- ]);
- } catch (Dibi\Exception $e) {
- $this->otherDb = null;
- }
- }
-
- public function setCurrentUser($validate = true)
- {
- $user = false;
- if ($this->hasDB()) {
- if ($this->hasCookie()) {
- $user = $this->getUserFromToken($_COOKIE[$this->cookieName]);
- }
- }
- $this->user = ($user) ?: $this->guestUser();
- if ($validate) {
- $this->checkUserTokenForValidation();
- }
- }
-
- public function checkUserTokenForValidation()
- {
- if ($this->hasDB()) {
- if ($this->hasCookie()) {
- $this->validateToken($_COOKIE[$this->cookieName]);
- }
- }
- }
-
- public function phpErrors()
- {
- $errorTypes = $this->dev ? E_ERROR | E_WARNING | E_PARSE | E_NOTICE : 0;
- $displayErrors = $this->dev ? 1 : 0;
- error_reporting($errorTypes);
- ini_set('display_errors', $displayErrors);
- }
-
- public function checkForOrganizrOAuth()
- {
- // Oauth?
- if ($this->config['authProxyEnabled'] && $this->config['authProxyHeaderName'] !== '' && $this->config['authProxyWhitelist'] !== '') {
- if (isset(getallheaders()[$this->config['authProxyHeaderName']])) {
- $this->coookieSeconds('set', 'organizrOAuth', 'true', 20000, false);
- }
- }
- }
-
- public function checkIfUserIsBlacklisted()
- {
- if ($this->hasDB()) {
- $currentIP = $this->userIP();
- if ($this->config['blacklisted'] !== '') {
- if (in_array($currentIP, $this->arrayIP($this->config['blacklisted']))) {
- $this->debug('User was sent to blackhole - Blacklisted IPs: ' . $this->config['blacklisted']);
- die($this->showHTML('Blacklisted', $this->config['blacklistedMessage']));
- }
- }
- }
- }
-
- public function checkDiskSpace($directory = './')
- {
- $readable = @is_readable($directory);
- if ($readable) {
- $disk = $this->checkDisk($directory);
- $diskLevels = [
- 'warn' => 1000000000,
- 'error' => 100000000
- ];
- if ($disk['free'] <= $diskLevels['error']) {
- 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>'));
- } elseif ($disk['free'] <= $diskLevels['warn']) {
- $this->warnings[] = 'You are low on disk space. There is only ' . $disk['free']['human_readable'] . ' remaining.';
- }
- }
- return true;
- }
-
- public function getFreeSpace($directory = './')
- {
- $disk = disk_free_space($directory);
- return [
- 'raw' => $disk,
- 'human_readable' => $this->human_filesize($disk, 0)
- ];
- }
-
- public function getDiskSpace($directory = './')
- {
- $disk = disk_total_space($directory);
- return [
- 'raw' => $disk,
- 'human_readable' => $this->human_filesize($disk, 0)
- ];
- }
-
- public function getUsedSpace($directory = './')
- {
- $diskFree = $this->getFreeSpace($directory);
- $diskTotal = $this->getDiskSpace($directory);
- $diskUsed = $diskTotal['raw'] - $diskFree['raw'];
- $percentUsed = ($diskUsed / $diskTotal['raw']) * 100;
- $percentFree = 100 - $percentUsed;
- return [
- 'raw' => $diskUsed,
- 'human_readable' => $this->human_filesize($diskUsed, 0),
- 'percent_used' => round($percentUsed),
- 'percent_free' => round($percentFree)
- ];
- }
-
- public function checkDisk($directory = './')
- {
- $readable = @is_readable($directory);
- if ($readable) {
- return [
- 'free' => $this->getFreeSpace($directory),
- 'used' => $this->getUsedSpace($directory),
- 'total' => $this->getDiskSpace($directory),
- ];
- } else {
- return [
- 'free' => 'error accessing path',
- 'used' => 'error accessing path',
- 'total' => 'error accessing path',
- ];
- }
-
- }
-
- public function errorCodes($error = 000)
- {
- $errorCodes = [
- 400 => [
- 'type' => 'Bad Request',
- 'description' => 'The request was incorrect'
- ],
- 401 => [
- 'type' => 'Unauthorized ',
- 'description' => 'You are not authorized to view this page'
- ],
- 402 => [
- 'type' => 'Payment Required',
- 'description' => 'Payment required before you can view this page'
- ],
- 403 => [
- 'type' => 'Forbidden',
- 'description' => 'You are forbidden to view this page'
- ],
- 404 => [
- 'type' => 'Not Found',
- 'description' => 'The requested resource was not found'
- ],
- 405 => [
- 'type' => 'Method Not Allowed',
- 'description' => 'The requested method is not allowed'
- ],
- 406 => [
- 'type' => 'Not Acceptable',
- 'description' => 'There was an issue with the requests Headers'
- ],
- 407 => [
- 'type' => 'Proxy Authentication Required',
- 'description' => 'Authentication is required and was not passed'
- ],
- 408 => [
- 'type' => 'Request Time-out',
- 'description' => 'The request has timed out'
- ],
- 409 => [
- 'type' => 'Conflict',
- 'description' => 'An error has occurred'
- ],
- 410 => [
- 'type' => 'Gone',
- 'description' => 'The requested resource is no longer available and has been permanently removed'
- ],
- 411 => [
- 'type' => 'Length Required',
- 'description' => 'The request can not be processed without a "Content-Length" header field'
- ],
- 412 => [
- 'type' => 'Precondition Failed',
- 'description' => ' A header needed was not found'
- ],
- 413 => [
- 'type' => 'Request Entity Too Large',
- 'description' => 'The query was too large to be processed by the server'
- ],
- 414 => [
- 'type' => 'Request-URI Too Long',
- 'description' => 'The URI of the request was too long'
- ],
- 415 => [
- 'type' => 'Unsupported Media Type',
- 'description' => 'The contents of the request has been submitted with invalid or out of defined media type'
- ],
- 416 => [
- 'type' => 'Requested range not satisfiable',
- 'description' => 'The requested resource was part of an invalid or is not on the server'
- ],
- 417 => [
- 'type' => 'Expectation Failed',
- 'description' => 'Expected Header was not found'
- ],
- 444 => [
- 'type' => 'No Response',
- 'description' => 'Nothing was returned from server'
- ],
- 500 => [
- 'type' => 'Internal Server Error',
- 'description' => 'An unexpected server error'
- ],
- 501 => [
- 'type' => 'Not Implemented',
- 'description' => 'The functionality to process the request is not available from this server'
- ],
- 502 => [
- 'type' => 'Bad Gateway',
- 'description' => 'The server could not fulfill its function as a gateway or proxy'
- ],
- 503 => [
- 'type' => 'Service Unavailable',
- 'description' => 'The server is temporarily unavailable, due to overloading or maintenance'
- ],
- 504 => [
- 'type' => 'Gateway Time-out',
- 'description' => 'The server could not fulfill its function as a gateway or proxy'
- ],
- 505 => [
- 'type' => 'HTTP version not supported',
- 'description' => 'The used version of HTTP is not supported by the server or rejected'
- ],
- 507 => [
- 'type' => 'Insufficient Storage',
- 'description' => 'The request could not be processed because the server disk space it currently is not sufficient'
- ],
- 509 => [
- 'type' => 'Bandwidth Limit Exceeded',
- 'description' => 'The request was rejected, because otherwise the bandwidth would be exceeded'
- ],
- 510 => [
- 'type' => 'Not Extended',
- 'description' => 'The request does not contain all information that is waiting for the requested server extension imperative'
- ],
- 000 => [
- 'type' => 'Unexpected Error',
- 'description' => 'An unexpected error occurred'
- ],
- ];
- return (isset($errorCodes[$error])) ? $errorCodes[$error] : $errorCodes[000];
- }
-
- public function showTopBarHamburger()
- {
- if ($this->config['allowCollapsableSideMenu']) {
- if ($this->config['sideMenuCollapsed']) {
- return '<a class="toggle-side-menu" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
- } else {
- return '<a class="toggle-side-menu hidden" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
- }
- }
- return '';
- }
-
- public function showSideBarHamburger()
- {
- if ($this->config['allowCollapsableSideMenu']) {
- if (!$this->config['sideMenuCollapsed']) {
- return '<i class="hidden-xs ti-shift-left mouse"></i>';
- }
- }
- return '<i class="ti-menu hidden-xs"></i>';
- }
-
- public function showSideBarText()
- {
- if ($this->config['allowCollapsableSideMenu']) {
- if (!$this->config['sideMenuCollapsed']) {
- return '<span class="hide-menu hidden-xs" lang="en">Hide Menu</span>';
- }
- }
- return '<span class="hide-menu hidden-xs" lang="en">Navigation</span>';
- }
-
- public function auth()
- {
- if ($this->hasDB()) {
- if (isset($_GET['type'])) {
- switch (strtolower($_GET['type'])) {
- case 'whitelist':
- case 'white':
- case 'w':
- case 'wl':
- case 'allow':
- $_GET['whitelist'] = $_GET['ips'] ?? false;
- break;
- case 'blacklist':
- case 'black':
- case 'b':
- case 'bl':
- case 'deny':
- $_GET['blacklist'] = $_GET['ips'] ?? false;
- break;
- default:
- $this->setAPIResponse('error', $_GET['type'] . ' is not a valid type', 401);
- return true;
- }
- }
- $whitelist = $_GET['whitelist'] ?? false;
- $blacklist = $_GET['blacklist'] ?? false;
- $group = 0;
- $groupParam = ($_GET['group']) ?? 0;
- $redirect = false;
- if (isset($groupParam)) {
- if (is_numeric($groupParam)) {
- $group = (int)$groupParam;
- } else {
- $group = $this->getTabGroupByTabName($groupParam);
- }
- }
- $currentIP = $this->userIP();
- $unlocked = !($this->user['locked'] == '1');
- if (isset($this->user)) {
- $currentUser = $this->user['username'];
- $currentGroup = $this->user['groupID'];
- $currentEmail = $this->user['email'];
- } else {
- $currentUser = 'Guest';
- $currentGroup = $this->getUserLevel();
- $currentEmail = 'guest@guest.com';
- }
- $userInfo = [
- "user" => $currentUser,
- "group" => $currentGroup,
- "email" => $currentEmail,
- "user_ip" => $currentIP,
- "requested_group" => $group
- ];
- $responseMessage = 'User is not Authorized or User is locked';
- if ($whitelist) {
- if (in_array($currentIP, $this->arrayIP($whitelist))) {
- $responseMessage = 'User is whitelisted';
- $this->setAPIResponse('success', $responseMessage, 200, $userInfo);
- return true;
- }
- }
- if ($blacklist) {
- if (in_array($currentIP, $this->arrayIP($blacklist))) {
- $responseMessage = 'User is blacklisted';
- $this->setAPIResponse('error', $responseMessage, 401, $userInfo);
- return true;
- }
- }
- if ($group !== null) {
- if ((isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER'] == 'traefik') || $this->config['traefikAuthEnable']) {
- $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'] : '';
- $redirectDomain = ($this->config['traefikDomainOverride'] !== '') ? $this->config['traefikDomainOverride'] : $this->getServerPath();
- $redirect = 'Location: ' . $redirectDomain . $return;
- }
- if ($this->qualifyRequest($group) && $unlocked) {
- header("X-Organizr-User: $currentUser");
- header("X-Organizr-Email: $currentEmail");
- header("X-Organizr-Group: $currentGroup");
- $responseMessage = 'User is authorized';
- $this->setAPIResponse('success', $responseMessage, 200, $userInfo);
- } else {
- if (!$redirect) {
- $this->setAPIResponse('error', $responseMessage, 401, $userInfo);
- } else {
- exit(http_response_code(401) . header($redirect));
- }
- }
- } else {
- $this->setAPIResponse('error', 'Missing info', 401);
- }
- }
- return true;
- }
-
- public function getIpInfo($ip = null)
- {
- if (!$ip) {
- $this->setResponse(422, 'No IP Address supplied');
- return false;
- }
- try {
- $options = array('verify' => false);
- $response = Requests::get('https://ipinfo.io/' . $ip . '/?token=ddd0c072ad5021', array(), $options);
- if ($response->success) {
- $api = json_decode($response->body, true);
- $this->setResponse(200, null, $api);
- return true;
- } else {
- $this->setResponse(500, 'An error occurred', null);
- }
- } catch (Requests_Exception $e) {
- $this->setResponse(500, 'An error occurred', $e->getMessage());
- }
- return false;
- }
-
- public function setAPIResponse($result = null, $message = null, $responseCode = null, $data = null)
- {
- if ($result) {
- $GLOBALS['api']['response']['result'] = $result;
- }
- if ($message) {
- $GLOBALS['api']['response']['message'] = $message;
- }
- if ($responseCode) {
- $GLOBALS['responseCode'] = $responseCode;
- }
- if ($data) {
- $GLOBALS['api']['response']['data'] = $data;
- }
- }
-
- public function setResponse(int $responseCode = 200, string $message = null, $data = null)
- {
- switch ($responseCode) {
- case 200:
- case 201:
- case 204:
- $result = 'success';
- break;
- default:
- $result = 'error';
- break;
- }
- $GLOBALS['api']['response']['result'] = $result;
- if ($message) {
- $GLOBALS['api']['response']['message'] = $message;
- }
- if ($responseCode) {
- $GLOBALS['responseCode'] = $responseCode;
- }
- if ($data) {
- $GLOBALS['api']['response']['data'] = $data;
- }
- }
-
- public function checkRoute($request)
- {
- $route = '/api/v2/' . explode('api/v2/', $request->getUri()->getPath())[1];
- $method = $request->getMethod();
- $data = $this->apiData($request);
- if (!in_array($route, $GLOBALS['bypass'])) {
- if ($this->isApprovedRequest($method, $data) === false) {
- $this->setAPIResponse('error', 'Not authorized for current Route: ' . $route, 401);
- $this->writeLog('success', 'Killed Attack From [' . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'No Referer') . ']', $this->user['username']);
- return false;
- }
- }
- return true;
- }
-
- public function apiData($request)
- {
- switch ($request->getMethod()) {
- case 'POST':
- if (stripos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
- return json_decode(file_get_contents('php://input', 'r'), true);
- } else {
- return $request->getParsedBody();
- }
- default:
- if (stripos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
- return json_decode(file_get_contents('php://input', 'r'), true);
- } else {
- return null;
- }
- }
- }
-
- public function getPlugins()
- {
- if ($this->hasDB()) {
- $pluginList = [];
- foreach ($GLOBALS['plugins'] as $plugin) {
- foreach ($plugin as $key => $value) {
- if (strpos($value['license'], $this->config['license']) !== false) {
- $plugin[$key]['enabled'] = $this->config[$value['configPrefix'] . '-enabled'];
- $pluginList[$key] = $plugin[$key];
- }
- }
- }
- asort($pluginList);
- return $pluginList;
- }
- return false;
- }
-
- public function refreshCookieName()
- {
- $this->cookieName = $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp';
- }
-
- public function favIcons($rootPath = '')
- {
- $favicon = '
- <link rel="apple-touch-icon" sizes="180x180" href="' . $rootPath . 'plugins/images/favicon/apple-touch-icon.png">
- <link rel="icon" type="image/png" sizes="32x32" href="' . $rootPath . 'plugins/images/favicon/favicon-32x32.png">
- <link rel="icon" type="image/png" sizes="16x16" href="' . $rootPath . 'plugins/images/favicon/favicon-16x16.png">
- <link rel="manifest" href="' . $rootPath . 'plugins/images/favicon/site.webmanifest" crossorigin="use-credentials">
- <link rel="mask-icon" href="' . $rootPath . 'plugins/images/favicon/safari-pinned-tab.svg" color="#5bbad5">
- <link rel="shortcut icon" href="' . $rootPath . 'plugins/images/favicon/favicon.ico">
- <meta name="msapplication-TileColor" content="#da532c">
- <meta name="msapplication-TileImage" content="' . $rootPath . 'plugins/images/favicon/mstile-144x144.png">
- <meta name="msapplication-config" content="' . $rootPath . 'plugins/images/favicon/browserconfig.xml">
- <meta name="theme-color" content="#ffffff">
- ';
- if ($this->config['favIcon'] !== '' && $rootPath !== '') {
- $this->config['favIcon'] = str_replace('plugins/images/faviconCustom', $rootPath . 'plugins/images/faviconCustom', $this->config['favIcon']);
- }
- return ($this->config['favIcon'] == '') ? $favicon : $this->config['favIcon'];
- }
-
- public function pluginGlobalList()
- {
- $pluginSearch = '-enabled';
- $pluginInclude = '-include';
- $plugins = array_filter($this->config, function ($k) use ($pluginSearch) {
- return stripos($k, $pluginSearch) !== false;
- }, ARRAY_FILTER_USE_KEY);
- $plugins['includes'] = array_filter($this->config, function ($k) use ($pluginInclude) {
- return stripos($k, $pluginInclude) !== false;
- }, ARRAY_FILTER_USE_KEY);
- return $plugins;
- }
-
- public function googleTracking()
- {
- if ($this->config['gaTrackingID'] !== '') {
- return '
- <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
- <script async src="https://www.googletagmanager.com/gtag/js?id=' . $this->config['gaTrackingID'] . '"></script>
- <script>
- window.dataLayer = window.dataLayer || [];
- function gtag(){dataLayer.push(arguments);}
- gtag("js", new Date());
- gtag("config","' . $this->config['gaTrackingID'] . '");
- </script>
- ';
- }
- return null;
- }
-
- public function matchBrackets($text, $brackets = 's')
- {
- switch ($brackets) {
- case 's':
- case 'square':
- $pattern = '#\[(.*?)\]#';
- break;
- case 'c':
- case 'curly':
- $pattern = '#\((.*?)\)#';
- break;
- default:
- return null;
- }
- preg_match($pattern, $text, $match);
- return $match[1];
- }
-
- public function languagePacks($encode = false)
- {
- $files = array();
- foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'langpack' . DIRECTORY_SEPARATOR . "*.json") as $filename) {
- if (strpos(basename($filename), '[') !== false) {
- $explode = explode('[', basename($filename));
- $files[] = array(
- 'filename' => basename($filename),
- 'code' => $explode[0],
- 'language' => $this->matchBrackets(basename($filename))
- );
- }
- }
- usort($files, function ($a, $b) {
- return $a['language'] <=> $b['language'];
- });
- return ($encode) ? json_encode($files) : $files;
- }
-
- public function getRootPath()
- {
- $count = (count(explode('/', $_SERVER['REQUEST_URI']))) - 2;
- $rootPath = '';
- $rootPath .= str_repeat('../', $count);
- return $rootPath;
- }
-
- public function setTheme($theme = null, $rootPath = '')
- {
- $theme = $theme ?? $this->config['theme'];
- return '<link id="theme" href="' . $rootPath . 'css/themes/' . $theme . '.css?v=' . $this->fileHash . '" rel="stylesheet">';
- }
-
- public function pluginFiles($type, $settings = false, $rootPath = '')
- {
- $files = '';
- $folder = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'plugins';
- $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
- $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
- switch ($type) {
- case 'js':
- foreach ($iteratorIterator as $info) {
- if (pathinfo($info->getPathname(), PATHINFO_EXTENSION) == 'js') {
- $pluginEnabled = false;
- $keyOriginal = strtoupper(basename(dirname($info->getPathname())));
- $key = str_replace('-SETTINGS', '', $keyOriginal);
- $continue = false;
- if ($settings) {
- if ($info->getFilename() == 'settings.js') {
- $continue = true;
- }
- } else {
- if ($info->getFilename() !== 'settings.js') {
- $continue = true;
- }
- }
- switch ($key) {
- case 'PHP-MAILER':
- $key = 'PHPMAILER';
- break;
- case 'NGXC':
- $key = 'ngxc';
- break;
- default:
- $key = $key;
- }
- if (isset($this->config[$key . '-enabled'])) {
- if ($this->config[$key . '-enabled']) {
- $pluginEnabled = true;
- }
- }
- if ($pluginEnabled || $settings) {
- if ($continue) {
- $files .= '<script src="' . $rootPath . 'api/plugins/' . basename(dirname($info->getPathname())) . '/' . basename($info->getFilename()) . '?v=' . $this->fileHash . '" defer="true"></script>';
- }
- }
- }
- }
- break;
- case 'css':
- foreach ($iteratorIterator as $info) {
- if (pathinfo($info->getPathname(), PATHINFO_EXTENSION) == 'css') {
- $files .= '<link href="' . $rootPath . 'api/plugins/' . basename(dirname($info->getPathname())) . '/' . basename($info->getFilename()) . '?v=' . $this->fileHash . '" rel="stylesheet">';
- }
- }
- break;
- default:
- break;
- }
- return $files;
- }
-
- public function formKey($script = true)
- {
- if (isset($this->config['organizrHash'])) {
- if ($this->config['organizrHash'] !== '') {
- $hash = password_hash(substr($this->config['organizrHash'], 2, 10), PASSWORD_BCRYPT);
- return ($script) ? '<script>local("s","formKey","' . $hash . '");</script>' : $hash;
- }
- }
- }
-
- private function checkPHP()
- {
- if (!(version_compare(PHP_VERSION, $this->minimumPHP) >= 0)) {
- die($this->showHTML('PHP Version', 'Organizr needs PHP Version: ' . $this->minimumPHP . '<br/> You have PHP Version: ' . PHP_VERSION));
- }
- }
-
- private function checkWritableDB()
- {
- if ($this->hasDB()) {
- if (isset($this->config['dbLocation']) && isset($this->config['dbName'])) {
- $db = is_writable($this->config['dbLocation'] . $this->config['dbName']);
- if (!$db) {
- die($this->showHTML('Organizr DB is not writable!', 'Please check permissions and/or disk space'));
- }
- } else {
- die($this->showHTML('Config File Malformed', 'dbLocation and/or dbName is not listed in config.php'));
- }
- }
- }
-
- public function upgradeCheck()
- {
- if ($this->hasDB()) {
- $tempLock = $this->config['dbLocation'] . 'DBLOCK.txt';
- $updateComplete = $this->config['dbLocation'] . 'completed.txt';
- $cleanup = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'upgrade' . DIRECTORY_SEPARATOR;
- if (file_exists($updateComplete)) {
- @unlink($updateComplete);
- @$this->rrmdir($cleanup);
- }
- if (file_exists($tempLock)) {
- die($this->showHTML('Upgrading', 'Please wait...'));
- }
- $updateDB = false;
- $updateSuccess = true;
- $compare = new Composer\Semver\Comparator;
- $oldVer = $this->config['configVersion'];
- // Upgrade check start for version below
- $versionCheck = '2.0.0-beta-200';
- if ($compare->lessThan($oldVer, $versionCheck)) {
- $updateDB = true;
- $oldVer = $versionCheck;
- }
- // End Upgrade check start for version above
- // Upgrade check start for version below
- $versionCheck = '2.0.0-beta-500';
- if ($compare->lessThan($oldVer, $versionCheck)) {
- $updateDB = true;
- $oldVer = $versionCheck;
- }
- // End Upgrade check start for version above
- // Upgrade check start for version below
- $versionCheck = '2.0.0-beta-800';
- if ($compare->lessThan($oldVer, $versionCheck)) {
- $updateDB = true;
- $oldVer = $versionCheck;
- }
- // End Upgrade check start for version above
- // Upgrade check start for version below
- $versionCheck = '2.1.0';
- if ($compare->lessThan($oldVer, $versionCheck)) {
- $updateDB = false;
- $oldVer = $versionCheck;
- $this->upgradeToVersion($versionCheck);
- }
- // End Upgrade check start for version above
- // Upgrade check start for version below
- $versionCheck = '2.1.400';
- if ($compare->lessThan($oldVer, $versionCheck)) {
- $updateDB = false;
- $oldVer = $versionCheck;
- $this->upgradeToVersion($versionCheck);
- }
- // End Upgrade check start for version above
- // Upgrade check start for version below
- $versionCheck = '2.1.525';
- if ($compare->lessThan($oldVer, $versionCheck)) {
- $updateDB = false;
- $oldVer = $versionCheck;
- $this->upgradeToVersion($versionCheck);
- }
- // End Upgrade check start for version above
- if ($updateDB == true) {
- //return 'Upgraded Needed - Current Version '.$oldVer.' - New Version: '.$versionCheck;
- // Upgrade database to latest version
- $updateSuccess = $this->updateDB($oldVer);
- }
- // Update config.php version if different to the installed version
- if ($updateSuccess && $this->version !== $this->config['configVersion']) {
- $this->updateConfig(array('apply_CONFIG_VERSION' => $this->version));
- $this->debug('Updated config version to ' . $this->version);
- }
- if ($updateSuccess == false) {
- die($this->showHTML('Database update failed', 'Please manually check logs and fix - Then reload this page'));
- }
- return true;
- }
- }
-
- public function updateDB($oldVerNum = false)
- {
- $tempLock = $this->config['dbLocation'] . 'DBLOCK.txt';
- if (!file_exists($tempLock)) {
- touch($tempLock);
- $migrationDB = 'tempMigration.db';
- $pathDigest = pathinfo($this->config['dbLocation'] . $this->config['dbName']);
- if (file_exists($this->config['dbLocation'] . $migrationDB)) {
- unlink($this->config['dbLocation'] . $migrationDB);
- }
- // Create Temp DB First
- $this->connectOtherDB();
- $backupDB = $pathDigest['dirname'] . '/' . $pathDigest['filename'] . '[' . date('Y-m-d_H-i-s') . ']' . ($oldVerNum ? '[' . $oldVerNum . ']' : '') . '.bak.db';
- copy($this->config['dbLocation'] . $this->config['dbName'], $backupDB);
- $success = $this->createDB($this->config['dbLocation'], true);
- if ($success) {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT name FROM sqlite_master WHERE type="table"'
- )
- ),
- ];
- $tables = $this->processQueries($response);
- foreach ($tables as $table) {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM ' . $table['name']
- )
- ),
- ];
- $data = $this->processQueries($response);
- $this->writeLog('success', 'Update Function - Grabbed Table data for Table: ' . $table['name'], 'Database');
- foreach ($data as $row) {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT into ' . $table['name'],
- $row
- )
- ),
- ];
- $this->processQueries($response, true);
- }
- $this->writeLog('success', 'Update Function - Wrote Table data for Table: ' . $table['name'], 'Database');
- }
- $this->writeLog('success', 'Update Function - All Table data converted - Starting Movement', 'Database');
- $this->db->disconnect();
- $this->otherDb->disconnect();
- // Remove Current Database
- if (file_exists($this->config['dbLocation'] . $migrationDB)) {
- $oldFileSize = filesize($this->config['dbLocation'] . $this->config['dbName']);
- $newFileSize = filesize($this->config['dbLocation'] . $migrationDB);
- if ($newFileSize > 0) {
- $this->writeLog('success', 'Update Function - Table Size of new DB ok..', 'Database');
- @unlink($this->config['dbLocation'] . $this->config['dbName']);
- copy($this->config['dbLocation'] . $migrationDB, $this->config['dbLocation'] . $this->config['dbName']);
- @unlink($this->config['dbLocation'] . $migrationDB);
- $this->writeLog('success', 'Update Function - Migrated Old Info to new Database', 'Database');
- @unlink($tempLock);
- return true;
- } else {
- $this->writeLog('error', 'Update Function - Filesize is zero', 'Database');
- }
- } else {
- $this->writeLog('error', 'Update Function - Migration DB does not exist', 'Database');
- }
- @unlink($tempLock);
- return false;
-
- } else {
- $this->writeLog('error', 'Update Function - Could not create migration DB', 'Database');
- }
- @unlink($tempLock);
- return false;
- }
- return false;
- }
-
- // Create config file in the return syntax
- public function createConfig($array, $path = null, $nest = 0)
- {
- $path = ($path) ? $path : $this->userConfigPath;
- // Define Initial Value
- $output = array();
- // Sort Items
- ksort($array);
- // Update the current config version
- if (!$nest) {
- // Inject Current Version
- $output[] = "\t'configVersion' => '" . (isset($array['apply_CONFIG_VERSION']) ? $array['apply_CONFIG_VERSION'] : $this->version) . "'";
- }
- unset($array['configVersion']);
- unset($array['apply_CONFIG_VERSION']);
- // Process Settings
- foreach ($array as $k => $v) {
- $allowCommit = true;
- $item = '';
- switch (gettype($v)) {
- case 'boolean':
- $item = ($v ? 'true' : 'false');
- break;
- case 'integer':
- case 'double':
- case 'NULL':
- $item = $v;
- break;
- case 'string':
- $item = "'" . str_replace(array('\\', "'"), array('\\\\', "\'"), $v) . "'";
- break;
- case 'array':
- $item = $this->createConfig($v, false, $nest + 1);
- break;
- default:
- $allowCommit = false;
- }
- if ($allowCommit) {
- $output[] = str_repeat("\t", $nest + 1) . "'$k' => $item";
- }
- }
- // Build output
- $output = (!$nest ? "<?php\nreturn " : '') . "[\n" . implode(",\n", $output) . "\n" . str_repeat("\t", $nest) . ']' . (!$nest ? ';' : '');
- if (!$nest && $path) {
- $pathDigest = pathinfo($path);
- @mkdir($pathDigest['dirname'], 0770, true);
- if (file_exists($path)) {
- rename($path, $pathDigest['dirname'] . '/' . $pathDigest['filename'] . '.bak.php');
- }
- $file = fopen($path, 'w');
- fwrite($file, $output);
- fclose($file);
- if (file_exists($path)) {
- return true;
- }
- return false;
- } else {
- return $output;
- }
- }
-
- // Commit new values to the configuration
- public function updateConfig($new, $current = false)
- {
- // Get config if not supplied
- if ($current === false) {
- //$current = $this->loadConfig();
- $current = $this->config;
- } elseif (is_string($current) && is_file($current)) {
- $current = $this->loadConfig($current);
- }
- // Inject Parts
- foreach ($new as $k => $v) {
- $current[$k] = $v;
- $this->config[$k] = $v;
- }
- // Return Create
- return $this->createConfig($current);
- }
-
- public function removeConfigItem($new, $current = false)
- {
- // Get config if not supplied
- if ($current === false) {
- $current = $this->config;
- } elseif (is_string($current) && is_file($current)) {
- $current = $this->loadConfig($current);
- }
- // Inject Parts
- foreach ($new as $k) {
- if (isset($current[$k])) {
- $current['deletedConfigItems'][$k] = $current[$k];
- $this->config['deletedConfigItems'][$k] = $current[$k];
- }
- unset($current[$k]);
- unset($this->config[$k]);
- }
- // Return Create
- return $this->createConfig($current);
- }
-
- public function loadConfig($path = null)
- {
- $path = ($path) ? $path : $this->userConfigPath;
- if (!is_file($path)) {
- return null;
- } else {
- return (array)call_user_func(function () use ($path) {
- return include($path);
- });
- }
- }
-
- public function fillDefaultConfig($array)
- {
- $path = $this->defaultConfigPath;
- if (is_string($path)) {
- $loadedDefaults = $this->loadConfig($path);
- } else {
- $loadedDefaults = $path;
- }
- // Include all plugin config files
- $folder = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'plugins';
- $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
- $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
- foreach ($iteratorIterator as $info) {
- if ($info->getFilename() == 'config.php') {
- $loadedDefaults = array_merge($loadedDefaults, $this->loadConfig($info->getPathname()));
- }
- }
- return (is_array($loadedDefaults) ? $this->fillDefaultConfig_recurse($array, $loadedDefaults) : false);
- }
-
- public function fillDefaultConfig_recurse($current, $defaults)
- {
- foreach ($defaults as $k => $v) {
- if (!isset($current[$k])) {
- $current[$k] = $v;
- } elseif (is_array($current[$k]) && is_array($v)) {
- $current[$k] = $this->fillDefaultConfig_recurse($current[$k], $v);
- }
- }
- return $current;
- }
-
- public function config($tries = 1)
- {
- // Load config or default
- if (file_exists($this->userConfigPath)) {
- $config = $this->fillDefaultConfig($this->loadConfig($this->userConfigPath));
- } else {
- $config = $this->fillDefaultConfig($this->loadConfig($this->defaultConfigPath));
- }
- if ((!is_array($config) || !file_exists($this->userConfigPath)) && $tries < 5) {
- $tries++;
- return $this->config($tries);
- }
- return $config;
- }
-
- public function combineConfig($array)
- {
- $this->config = array_merge($this->config, $array);
- return $this->config;
- }
-
- public function status()
- {
- $status = array();
- $dependenciesActive = array();
- $dependenciesInactive = array();
- $extensions = array("PDO_SQLITE", "PDO", "SQLITE3", "zip", "cURL", "openssl", "simplexml", "json", "session", "filter");
- $functions = array("hash", "fopen", "fsockopen", "fwrite", "fclose", "readfile");
- foreach ($extensions as $check) {
- if (extension_loaded($check)) {
- array_push($dependenciesActive, $check);
- } else {
- array_push($dependenciesInactive, $check);
- }
- }
- foreach ($functions as $check) {
- if (function_exists($check)) {
- array_push($dependenciesActive, $check);
- } else {
- array_push($dependenciesInactive, $check);
- }
- }
- if (!file_exists($this->userConfigPath)) {
- $status['status'] = "wizard";//wizard - ok for test
- }
- if (count($dependenciesInactive) > 0 || !is_writable(dirname(__DIR__, 2)) || !(version_compare(PHP_VERSION, $this->minimumPHP) >= 0)) {
- $status['status'] = "dependencies";
- }
- $status['status'] = ($status['status']) ?? "ok";
- $status['writable'] = is_writable(dirname(__DIR__, 2)) ? 'yes' : 'no';
- $status['minVersion'] = (version_compare(PHP_VERSION, $this->minimumPHP) >= 0) ? 'yes' : 'no';
- $status['dependenciesActive'] = $dependenciesActive;
- $status['dependenciesInactive'] = $dependenciesInactive;
- $status['version'] = $this->version;
- $status['os'] = $this->getOS();
- $status['php'] = phpversion();
- $status['php_user'] = get_current_user();
- $status['userConfigPath'] = $this->userConfigPath;
- return $status;
- }
-
- public function hasDB()
- {
- return (file_exists($this->userConfigPath)) ?? false;
- }
-
- public function hasCookie()
- {
- return ($_COOKIE[$this->cookieName]) ?? false;
- }
-
- public function getGuest()
- {
- $guest = array(
- 'group' => 'Guest',
- 'group_id' => 999,
- 'image' => 'plugins/images/groups/guest.png'
- );
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => 'SELECT * FROM groups WHERE `group_id` = 999'
- ),
- ];
- return $this->hasDB() ? $this->processQueries($response) : $guest;
-
- }
-
- public function getSchema()
- {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => 'SELECT name, sql FROM sqlite_master WHERE type=\'table\' ORDER BY name'
- ),
- ];
- return $this->hasDB() ? $this->processQueries($response) : 'Database not setup yet';
- }
-
- public function guestUser()
- {
- if ($this->hasDB()) {
- if ($this->getUserLevel() !== 999) {
- $guest = array(
- "token" => null,
- "tokenDate" => null,
- "tokenExpire" => null,
- "username" => "Organizr API",
- "uid" => $this->guestHash(0, 5),
- "group" => 'Admin',
- "groupID" => 0,
- "email" => null,
- //"groupImage"=>getGuest()['image'],
- "image" => $this->getGuest()['image'],
- "userID" => null,
- "loggedin" => false,
- "locked" => false,
- "tokenList" => null,
- "authService" => null
- );
- }
- }
- $guest = $guest ?? array(
- "token" => null,
- "tokenDate" => null,
- "tokenExpire" => null,
- "username" => "Guest",
- "uid" => $this->guestHash(0, 5),
- "group" => $this->getGuest()['group'],
- "groupID" => $this->getGuest()['group_id'],
- "email" => null,
- //"groupImage"=>getGuest()['image'],
- "image" => $this->getGuest()['image'],
- "userID" => null,
- "loggedin" => false,
- "locked" => false,
- "tokenList" => null,
- "authService" => null
- );
- return $guest;
- }
-
- public function getAllUserTokens($id)
- {
-
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM `tokens` WHERE user_id = ? AND expires > ?',
- [$id],
- [$this->currentTime]
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getUserById($id)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM users WHERE id = ?',
- $id
- )
- )
- ];
- return $this->processQueries($response);
- }
-
- public function getUserByEmail($email)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM users WHERE email = ? COLLATE NOCASE',
- $email
- )
- )
- ];
- return $this->processQueries($response);
- }
-
- protected function invalidToken($token)
- {
- if (isset($_COOKIE[$this->cookieName])) {
- if ($token == $_COOKIE[$this->cookieName]) {
- $this->coookie('delete', $this->cookieName);
- $this->user = null;
- $this->debug('Token was invalid - deleting cookie and user session');
- }
- }
- }
-
- public function validateToken($token, $api = false)
- {
- // Validate script
- $userInfo = $this->jwtParse($token);
- $validated = (bool)$userInfo;
- if ($validated == true) {
- $allTokens = $this->getAllUserTokens($userInfo['userID']);
- $user = $this->getUserById($userInfo['userID']);
- $tokenCheck = ($this->searchArray($allTokens, 'token', $token) !== false);
- if (!$tokenCheck) {
- $this->debug('Token failed check Token listing: ' . json_encode($allTokens) . ' User Id: ' . $userInfo['userID']);
- $this->invalidToken($token);
- if ($api) {
- $this->setResponse(403, 'Token was not in approved list');
- }
- return false;
- } else {
- if ($api) {
- $this->setResponse(200, 'Token is valid');
- }
- return array(
- 'token' => $token,
- 'tokenDate' => $userInfo['tokenDate'],
- 'tokenExpire' => $userInfo['tokenExpire'],
- 'username' => $user['username'] ?? $userInfo['username'],
- 'uid' => $this->guestHash(0, 5),
- 'group' => $user['group'] ?? $userInfo['group'],
- 'groupID' => $user['group_id'] ?? $userInfo['groupID'],
- 'email' => $user['email'] ?? $userInfo['email'],
- 'image' => $user['image'] ?? $userInfo['image'],
- 'userID' => $user['id'] ?? $userInfo['userID'],
- 'loggedin' => true,
- 'locked' => $user['locked'] ?? 0,
- 'tokenList' => $allTokens,
- 'authService' => (isset($user['auth_service'])) ? explode('::', $user['auth_service'])[0] : 'internal'
- );
- }
- } else {
- if ($api) {
- $this->setResponse(403, 'Token was invalid');
- }
- $this->debug('Token was invalid');
- $this->invalidToken($token);
- }
- if ($api) {
- $this->setResponse(403, 'Token was invalid');
- }
- return false;
- }
-
- public function getUserFromToken($token)
- {
- // Validate script
- $userInfo = $this->jwtParse($token);
- $validated = (bool)$userInfo;
- if ($validated == true) {
- $user = $this->getUserById($userInfo['userID']);
- $allTokens = $this->getAllUserTokens($userInfo['userID']);
- return array(
- 'token' => $token,
- 'tokenDate' => $userInfo['tokenDate'],
- 'tokenExpire' => $userInfo['tokenExpire'],
- 'username' => $user['username'] ?? $userInfo['username'],
- 'uid' => $this->guestHash(0, 5),
- 'group' => $user['group'] ?? $userInfo['group'],
- 'groupID' => $user['group_id'] ?? $userInfo['groupID'],
- 'email' => $user['email'] ?? $userInfo['email'],
- 'image' => $user['image'] ?? $userInfo['image'],
- 'userID' => $user['id'] ?? $userInfo['userID'],
- 'loggedin' => true,
- 'locked' => $user['locked'] ?? 0,
- 'tokenList' => $allTokens,
- 'authService' => (isset($user['auth_service'])) ? explode('::', $user['auth_service'])[0] : 'internal'
- );
- }
- return false;
- }
-
- public function defaultUserGroup()
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => 'SELECT * FROM groups WHERE `default` = 1'
- )
- ];
- return $this->processQueries($response);
- }
-
- public function getAllTabs()
- {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => 'SELECT * FROM tabs ORDER BY `order` ASC',
- 'key' => 'tabs'
- ),
- array(
- 'function' => 'fetchAll',
- 'query' => 'SELECT * FROM categories ORDER BY `order` ASC',
- 'key' => 'categories'
- ),
- array(
- 'function' => 'fetchAll',
- 'query' => 'SELECT * FROM groups ORDER BY `group_id` ASC',
- 'key' => 'groups'
- ),
- ];
- $query = $this->processQueries($response);
- $this->applyTabVariables($query['tabs']);
- return $query;
- }
-
- public function applyTabVariables($tabs)
- {
- $variables = [
- '{domain}' => $this->getServer(),
- '{username}' => $this->user['username'],
- '{username_lower}' => $this->user['username'],
- '{email}' => $this->user['email'],
- '{group}' => $this->user['group'],
- '{group_id}' => $this->user['groupID'],
- '{komga}' => $_COOKIE['komga_token'] ?? ''
- ];
- if (empty($tabs)) {
- return $tabs;
- }
- foreach ($tabs as $id => $tab) {
- $tabs[$id]['url'] = $this->userDefinedIdReplacementLink($tab['url'], $variables);
- $tabs[$id]['url_local'] = $this->userDefinedIdReplacementLink($tab['url_local'], $variables);
- }
- return $tabs;
- }
-
- public function getUsers()
- {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => 'SELECT * FROM users'
- ),
- array(
- 'function' => 'fetchAll',
- 'query' => 'SELECT * FROM groups ORDER BY group_id ASC'
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function usernameTaken($username, $email, $id = null)
- {
- if ($id) {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM users WHERE `id` != ? AND (username = ? COLLATE NOCASE or email = ? COLLATE NOCASE)',
- $id,
- $username,
- $email
- )
- ),
- ];
- } else {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM users WHERE username = ? COLLATE NOCASE or email = ? COLLATE NOCASE',
- [$username],
- [$email]
- )
- ),
- ];
- }
- return $this->processQueries($response);
- }
-
- public function cleanPageName($page)
- {
- return ($page) ? strtolower(str_replace(array('%20', ' ', '-', '_'), '_', $page)) : '';
- }
-
- public function cleanClassName($name)
- {
- return ($name) ? (str_replace(array('%20', ' ', '-', '_'), '-', $name)) : '';
- }
-
- public function reverseCleanClassName($name)
- {
- return ($name) ? (str_replace(array('%20', '-', '_'), ' ', strtolower($name))) : '';
- }
-
- public function getPageList()
- {
- return $GLOBALS['organizrPages'];
- }
-
- public function getPage($page)
- {
- if (!$page) {
- $this->setAPIResponse('error', 'Page not setup', 409);
- return null;
- }
- $pageFunction = 'get_page_' . $this->cleanPageName($page);
- if (function_exists($pageFunction)) {
- return $pageFunction($this);
- } else {
- $this->setAPIResponse('error', 'Page not setup', 409);
- return null;
- }
- }
-
- public function getUserLevel()
- {
- // Grab token
- $requesterToken = $this->getallheaders()['Token'] ?? ($_GET['apikey'] ?? false);
- $apiKey = ($this->config['organizrAPI']) ?? null;
- // Check token or API key
- // If API key, return 0 for admin
- if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
- //DO API CHECK
- return 0;
- } elseif (isset($this->user)) {
- return $this->user['groupID'];
- }
- // All else fails? return guest id
- return 999;
- }
-
- public function qualifyRequest($accessLevelNeeded, $api = false)
- {
- if ($this->getUserLevel() <= $accessLevelNeeded && $this->getUserLevel() !== null) {
- return true;
- } else {
- if ($api) {
- $this->setAPIResponse('error', 'Not Authorized', 401);
- }
- return false;
- }
- }
-
- public function getImages()
- {
- $allIconsPrep = array();
- $allIcons = array();
- $ignore = array(".", "..", "._.DS_Store", ".DS_Store", ".pydio_id", "index.html");
- $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'tabs' . DIRECTORY_SEPARATOR;
- $path = 'plugins/images/tabs/';
- $images = scandir($dirname);
- foreach ($images as $image) {
- if (!in_array($image, $ignore)) {
- $allIconsPrep[$image] = array(
- 'path' => $path,
- 'name' => $image
- );
- }
- }
- $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
- $path = 'plugins/images/userTabs/';
- $images = scandir($dirname);
- foreach ($images as $image) {
- if (!in_array($image, $ignore)) {
- $allIconsPrep[$image] = array(
- 'path' => $path,
- 'name' => $image
- );
- }
- }
- uksort($allIconsPrep, 'strcasecmp');
- foreach ($allIconsPrep as $item) {
- $allIcons[] = $item['path'] . $item['name'];
- }
- return $allIcons;
- }
-
- public function getImagesSelect()
- {
- $term = $_GET['search'] ?? null;
- $page = $_GET['page'] ?? 1;
- $limit = $_GET['limit'] ?? 20;
- $offset = ($page * $limit) - $limit;
- $goodIcons['results'] = [];
- $goodIcons['limit'] = $limit;
- $goodIcons['page'] = $page;
- $goodIcons['term'] = $term;
- $imageListing = $this->getImages();
- $newImageListing = [];
- foreach ($imageListing as $image) {
- $newImageListing[] = [
- 'id' => $image,
- 'text' => basename($image)
- ];
- }
- foreach ($newImageListing as $k => $v) {
- if (stripos($v['text'], $term) !== false || !$term) {
- $goodIcons['results'][] = $v;
- }
- }
- $total = count($goodIcons['results']);
- $goodIcons['total'] = $total;
- $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
- $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
- return $goodIcons;
- }
-
- public function removeImage($image = null)
- {
- if (!$image) {
- $this->setAPIResponse('error', 'No image supplied', 422);
- return false;
- }
- $approvedPath = 'plugins/images/userTabs/';
- $removeImage = $approvedPath . pathinfo($image, PATHINFO_BASENAME);
- if ($this->approvedFileExtension($removeImage, 'image')) {
- if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage)) {
- $this->writeLog('success', 'Image Manager Function - Deleted Image [' . pathinfo($image, PATHINFO_BASENAME) . ']', $this->user['username']);
- $this->setAPIResponse(null, pathinfo($image, PATHINFO_BASENAME) . ' has been deleted', null);
- return (unlink(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage));
- } else {
- $this->setAPIResponse('error', $removeImage . ' does not exist', 404);
- return false;
- }
- } else {
- $this->setAPIResponse('error', $removeImage . ' is not approved to be deleted', 409);
- return false;
- }
- }
-
- public function uploadImage()
- {
- $filesCheck = array_filter($_FILES);
- if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'image') && strpos($_FILES['file']['type'], 'image/') !== false) {
- ini_set('upload_max_filesize', '10M');
- ini_set('post_max_size', '10M');
- $tempFile = $_FILES['file']['tmp_name'];
- $targetPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
- $targetFile = $targetPath . $_FILES['file']['name'];
- $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
- return move_uploaded_file($tempFile, $targetFile);
- }
- }
-
- public function ping($pings)
- {
- if ($this->qualifyRequest($this->config['pingAuth'], true)) {
- if (!$pings['list']) {
- $this->setAPIResponse('error', 'No ping hostname/IP\'s entered', 409);
- return null;
- }
- $pings = $pings['list'];
- $type = gettype($pings);
- $ping = new Ping("");
- $ping->setTtl(128);
- $ping->setTimeout(2);
- switch ($type) {
- case "array":
- $results = [];
- foreach ($pings as $k => $v) {
- if (strpos($v, ':') !== false) {
- $domain = explode(':', $v)[0];
- $port = explode(':', $v)[1];
- $ping->setHost($domain);
- $ping->setPort($port);
- $latency = $ping->ping('fsockopen');
- } else {
- $ping->setHost($v);
- $latency = $ping->ping();
- }
- if ($latency || $latency === 0) {
- $results[$v] = $latency;
- } else {
- $results[$v] = false;
- }
- }
- break;
- case "string":
- if (strpos($pings, ':') !== false) {
- $domain = explode(':', $pings)[0];
- $port = explode(':', $pings)[1];
- $ping->setHost($domain);
- $ping->setPort($port);
- $latency = $ping->ping('fsockopen');
- } else {
- $ping->setHost($pings);
- $latency = $ping->ping();
- }
- if ($latency || $latency === 0) {
- $results = $latency;
- } else {
- $results = null;
- }
- break;
- }
- return ($results) ?? null;
- }
- return null;
- }
-
- public function getCustomizeAppearance()
- {
- return array(
- 'Top Bar' => array(
- array(
- 'type' => 'input',
- 'name' => 'logo',
- 'label' => 'Logo',
- 'value' => $this->config['logo']
- ),
- array(
- 'type' => 'input',
- 'name' => 'title',
- 'label' => 'Title',
- 'value' => $this->config['title']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'useLogo',
- 'label' => 'Use Logo instead of Title',
- 'value' => $this->config['useLogo'],
- 'help' => 'Also sets the title of your site'
- ),
- array(
- 'type' => 'input',
- 'name' => 'description',
- 'label' => 'Meta Description',
- 'value' => $this->config['description'],
- 'help' => 'Used to set the description for SEO meta tags'
- ),
- ),
- 'Side Menu' => array(
- $this->settingsOption('switch', 'allowCollapsableSideMenu', ['label' => 'Allow Side Menu to be Collapsable']),
- $this->settingsOption('switch', 'sideMenuCollapsed', ['label' => 'Side Menu Collapsed at Launch']),
- $this->settingsOption('switch', 'collapseSideMenuOnClick', ['label' => 'Collapse Side Menu after clicking Tab']),
- array(
- 'type' => 'switch',
- 'name' => 'githubMenuLink',
- 'label' => 'Show GitHub Repo Link',
- 'value' => $this->config['githubMenuLink']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'organizrFeatureRequestLink',
- 'label' => 'Show Organizr Feature Request Link',
- 'value' => $this->config['organizrFeatureRequestLink']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'organizrSupportMenuLink',
- 'label' => 'Show Organizr Support Link',
- 'value' => $this->config['organizrSupportMenuLink']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'organizrDocsMenuLink',
- 'label' => 'Show Organizr Docs Link',
- 'value' => $this->config['organizrDocsMenuLink']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'organizrSignoutMenuLink',
- 'label' => 'Show Organizr Sign out & in Button on Sidebar',
- 'value' => $this->config['organizrSignoutMenuLink']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'expandCategoriesByDefault',
- 'label' => 'Expand All Categories',
- 'value' => $this->config['expandCategoriesByDefault']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'autoCollapseCategories',
- 'label' => 'Auto-Collapse Categories',
- 'value' => $this->config['autoCollapseCategories']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'autoExpandNavBar',
- 'label' => 'Auto-Expand Nav Bar',
- 'value' => $this->config['autoExpandNavBar']
- ),
- array(
- 'type' => 'select',
- 'name' => 'unsortedTabs',
- 'label' => 'Unsorted Tab Placement',
- 'value' => $this->config['unsortedTabs'],
- 'options' => array(
- array(
- 'name' => 'Top',
- 'value' => 'top'
- ),
- array(
- 'name' => 'Bottom',
- 'value' => 'bottom'
- )
- )
- ),
- ),
- 'Login Page' => array(
- array(
- 'type' => 'input',
- 'name' => 'loginLogo',
- 'label' => 'Login Logo',
- 'value' => $this->config['loginLogo'],
- ),
- array(
- 'type' => 'input',
- 'name' => 'loginWallpaper',
- 'label' => 'Login Wallpaper',
- 'value' => $this->config['loginWallpaper'],
- 'help' => 'You may enter multiple URL\'s using the CSV format. i.e. link#1,link#2,link#3'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'useLogoLogin',
- 'label' => 'Use Logo instead of Title on Login Page',
- 'value' => $this->config['useLogoLogin']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'minimalLoginScreen',
- 'label' => 'Minimal Login Screen',
- 'value' => $this->config['minimalLoginScreen']
- )
- ),
- 'Options' => array(
- array(
- 'type' => 'switch',
- 'name' => 'alternateHomepageHeaders',
- 'label' => 'Alternate Homepage Titles',
- 'value' => $this->config['alternateHomepageHeaders']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'debugErrors',
- 'label' => 'Show Debug Errors',
- 'value' => $this->config['debugErrors']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'easterEggs',
- 'label' => 'Show Easter Eggs',
- 'value' => $this->config['easterEggs']
- ),
- array(
- 'type' => 'input',
- 'name' => 'gaTrackingID',
- 'label' => 'Google Analytics Tracking ID',
- 'placeholder' => 'e.g. UA-XXXXXXXXX-X',
- 'value' => $this->config['gaTrackingID']
- )
- ),
- 'Colors & Themes' => array(
- array(
- 'type' => 'html',
- 'override' => 12,
- 'label' => '',
- 'html' => '
- <div class="row">
- <div class="col-lg-12">
- <div class="panel panel-info">
- <div class="panel-heading">
- <span lang="en">Notice</span>
- </div>
- <div class="panel-wrapper collapse in" aria-expanded="true">
- <div class="panel-body">
- <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>
- </div>
- </div>
- </div>
- </div>
- </div>
- ',
- ),
- array(
- 'type' => 'blank',
- 'label' => ''
- ),
- $this->settingsOption('button', '', ['label' => 'Reset Colors', 'icon' => 'fa fa-ticket', 'text' => 'Reset', 'attr' => 'onclick="resetCustomColors()"']),
- $this->settingsOption('blank'),
- array(
- 'type' => 'input',
- 'name' => 'headerColor',
- 'label' => 'Nav Bar Color',
- 'value' => $this->config['headerColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['headerColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'headerTextColor',
- 'label' => 'Nav Bar Text Color',
- 'value' => $this->config['headerTextColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['headerTextColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'sidebarColor',
- 'label' => 'Side Bar Color',
- 'value' => $this->config['sidebarColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['sidebarColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'sidebarTextColor',
- 'label' => 'Side Bar Text Color',
- 'value' => $this->config['sidebarTextColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['sidebarTextColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'accentColor',
- 'label' => 'Accent Color',
- 'value' => $this->config['accentColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['accentColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'accentTextColor',
- 'label' => 'Accent Text Color',
- 'value' => $this->config['accentTextColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['accentTextColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'buttonColor',
- 'label' => 'Button Color',
- 'value' => $this->config['buttonColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['buttonColor'] . '"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'buttonTextColor',
- 'label' => 'Button Text Color',
- 'value' => $this->config['buttonTextColor'],
- 'class' => 'pick-a-color-custom-options',
- 'attr' => 'data-original="' . $this->config['buttonTextColor'] . '"'
- ),
- array(
- 'type' => 'select',
- 'name' => 'theme',
- 'label' => 'Theme',
- 'class' => 'themeChanger',
- 'value' => $this->config['theme'],
- 'options' => $this->getThemes()
- ),
- array(
- 'type' => 'select',
- 'name' => 'style',
- 'label' => 'Style',
- 'class' => 'styleChanger',
- 'value' => $this->config['style'],
- 'options' => array(
- array(
- 'name' => 'Light',
- 'value' => 'light'
- ),
- array(
- 'name' => 'Dark',
- 'value' => 'dark'
- ),
- array(
- 'name' => 'Horizontal',
- 'value' => 'horizontal'
- )
- )
- )
- ),
- 'Notifications' => array(
- array(
- 'type' => 'select',
- 'name' => 'notificationBackbone',
- 'class' => 'notifyChanger',
- 'label' => 'Type',
- 'value' => $this->config['notificationBackbone'],
- 'options' => $this->notificationTypesOptions()
- ),
- array(
- 'type' => 'select',
- 'name' => 'notificationPosition',
- 'class' => 'notifyPositionChanger',
- 'label' => 'Position',
- 'value' => $this->config['notificationPosition'],
- 'options' => $this->notificationPositionsOptions()
- ),
- array(
- 'type' => 'html',
- 'label' => 'Test Message',
- 'html' => '
- <div class="btn-group m-r-10 dropup">
- <button aria-expanded="false" data-toggle="dropdown" class="btn btn-info btn-outline dropdown-toggle waves-effect waves-light" type="button">
- <i class="fa fa-comment m-r-5"></i>
- <span>Test </span>
- </button>
- <ul role="menu" class="dropdown-menu">
- <li><a onclick="message(\'Test Message\',\'This is a success Message\',activeInfo.settings.notifications.position,\'#FFF\',\'success\',\'5000\');">Success</a></li>
- <li><a onclick="message(\'Test Message\',\'This is a info Message\',activeInfo.settings.notifications.position,\'#FFF\',\'info\',\'5000\');">Info</a></li>
- <li><a onclick="message(\'Test Message\',\'This is a warning Message\',activeInfo.settings.notifications.position,\'#FFF\',\'warning\',\'5000\');">Warning</a></li>
- <li><a onclick="message(\'Test Message\',\'This is a error Message\',activeInfo.settings.notifications.position,\'#FFF\',\'error\',\'5000\');">Error</a></li>
- </ul>
- </div>
- '
- )
- ),
- 'FavIcon' => array(
- array(
- 'type' => 'textbox',
- 'name' => 'favIcon',
- 'class' => '',
- 'label' => 'Fav Icon Code',
- 'value' => $this->config['favIcon'],
- 'placeholder' => 'Paste Contents from https://realfavicongenerator.net/',
- 'attr' => 'rows="10"',
- ),
- array(
- 'type' => 'html',
- 'label' => 'Instructions',
- 'html' => '
- <div class="panel panel-default">
- <div class="panel-heading">
- <a href="https://realfavicongenerator.net/" target="_blank"><span class="label label-info m-l-5">Visit FavIcon Site</span></a>
- </div>
- <div class="panel-wrapper collapse in">
- <div class="panel-body">
- <ul class="list-icons">
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Select your Favicon picture]</li>
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Choose your image to use</li>
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Edit settings to your liking</li>
- <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>
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Enter this path <code>plugins/images/faviconCustom</code></li>
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Generate your Favicons and HTML code]</li>
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Download and unzip file and place in <code>plugins/images/faviconCustom</code></li>
- <li lang="en"><i class="fa fa-caret-right text-info"></i> Copy code and paste inside left box</li>
- </ul>
- </div>
- </div>
- </div>
- '
- ),
- ),
- 'Custom CSS' => array(
- array(
- 'type' => 'html',
- 'override' => 12,
- 'label' => 'Custom CSS [Can replace colors from above]',
- 'html' => '<button type="button" class="hidden saveCss btn btn-info btn-circle pull-right m-r-5 m-l-10"><i class="fa fa-save"></i> </button><div id="customCSSEditor" style="height:300px">' . htmlentities($this->config['customCss']) . '</div>'
- ),
- array(
- 'type' => 'textbox',
- 'name' => 'customCss',
- 'class' => 'hidden cssTextarea',
- 'label' => '',
- 'value' => $this->config['customCss'],
- 'placeholder' => 'No <style> tags needed',
- 'attr' => 'rows="10"',
- ),
- ),
- 'Theme CSS' => array(
- array(
- 'type' => 'html',
- 'override' => 12,
- 'label' => 'Theme CSS [Can replace colors from above]',
- 'html' => '<button type="button" class="hidden saveCssTheme btn btn-info btn-circle pull-right m-r-5 m-l-10"><i class="fa fa-save"></i> </button><div id="customThemeCSSEditor" style="height:300px">' . htmlentities($this->config['customThemeCss']) . '</div>'
- ),
- array(
- 'type' => 'textbox',
- 'name' => 'customThemeCss',
- 'class' => 'hidden cssThemeTextarea',
- 'label' => '',
- 'value' => $this->config['customThemeCss'],
- 'placeholder' => 'No <style> tags needed',
- 'attr' => 'rows="10"',
- ),
- ),
- 'Custom Javascript' => array(
- array(
- 'type' => 'html',
- 'override' => 12,
- 'label' => 'Custom Javascript',
- 'html' => '<button type="button" class="hidden saveJava btn btn-info btn-circle pull-right m-r-5 m-l-10"><i class="fa fa-save"></i> </button><div id="customJavaEditor" style="height:300px">' . htmlentities($this->config['customJava']) . '</div>'
- ),
- array(
- 'type' => 'textbox',
- 'name' => 'customJava',
- 'class' => 'hidden javaTextarea',
- 'label' => '',
- 'value' => $this->config['customJava'],
- 'placeholder' => 'No <script> tags needed',
- 'attr' => 'rows="10"',
- ),
- ),
- 'Theme Javascript' => array(
- array(
- 'type' => 'html',
- 'override' => 12,
- 'label' => 'Theme Javascript',
- 'html' => '<button type="button" class="hidden saveJavaTheme btn btn-info btn-circle pull-right m-r-5 m-l-10"><i class="fa fa-save"></i> </button><div id="customThemeJavaEditor" style="height:300px">' . htmlentities($this->config['customThemeJava']) . '</div>'
- ),
- array(
- 'type' => 'textbox',
- 'name' => 'customThemeJava',
- 'class' => 'hidden javaThemeTextarea',
- 'label' => '',
- 'value' => $this->config['customThemeJava'],
- 'placeholder' => 'No <script> tags needed',
- 'attr' => 'rows="10"',
- ),
- ),
- );
- }
-
- public function loadAppearance()
- {
- $appearance['logo'] = $this->config['logo'];
- $appearance['title'] = $this->config['title'];
- $appearance['useLogo'] = $this->config['useLogo'];
- $appearance['useLogoLogin'] = $this->config['useLogoLogin'];
- $appearance['headerColor'] = $this->config['headerColor'];
- $appearance['headerTextColor'] = $this->config['headerTextColor'];
- $appearance['sidebarColor'] = $this->config['sidebarColor'];
- $appearance['headerTextColor'] = $this->config['headerTextColor'];
- $appearance['sidebarTextColor'] = $this->config['sidebarTextColor'];
- $appearance['accentColor'] = $this->config['accentColor'];
- $appearance['accentTextColor'] = $this->config['accentTextColor'];
- $appearance['buttonColor'] = $this->config['buttonColor'];
- $appearance['buttonTextColor'] = $this->config['buttonTextColor'];
- $appearance['buttonTextHoverColor'] = $this->config['buttonTextHoverColor'];
- $appearance['buttonHoverColor'] = $this->config['buttonHoverColor'];
- $appearance['loginWallpaper'] = $this->config['loginWallpaper'];
- $appearance['loginLogo'] = $this->config['loginLogo'];
- $appearance['customCss'] = $this->config['customCss'];
- $appearance['customThemeCss'] = $this->config['customThemeCss'];
- $appearance['customJava'] = $this->config['customJava'];
- $appearance['customThemeJava'] = $this->config['customThemeJava'];
- return $appearance;
- }
-
- public function getSettingsMain()
- {
- $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>';
- return array(
- 'Settings Page' => array(
- array(
- 'type' => 'select',
- 'name' => 'defaultSettingsTab',
- 'label' => 'Default Settings Tab',
- 'value' => $this->config['defaultSettingsTab'],
- 'options' => $this->getSettingsTabs(),
- 'help' => 'Choose which Settings Tab to be default when opening settings page'
- ),
- ),
- 'Database' => [
- $this->settingsOption('notice', '', ['notice' => 'danger', 'title' => 'Warning', 'body' => 'This feature is experimental - You may face unexpected database is locked errors in logs']),
- $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>']),
- //$this->settingsOption('blank'),
- $this->settingsOption('button', '', ['label' => 'Set DELETE Mode (Default)', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'DELETE\')"']),
- $this->settingsOption('button', '', ['label' => 'Set WAL Mode', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'WAL\')"']),
- ],
- 'Github' => array(
- array(
- 'type' => 'select',
- 'name' => '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'
- ),
- array(
- 'type' => 'button',
- 'name' => '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'
- )
- ),
- 'API' => array(
- array(
- 'type' => 'password-alt-copy',
- 'name' => 'organizrAPI',
- 'label' => 'Organizr API',
- 'value' => $this->config['organizrAPI']
- ),
- array(
- 'type' => 'button',
- 'label' => 'Generate New API Key',
- 'class' => 'newAPIKey',
- 'icon' => 'fa fa-refresh',
- 'text' => 'Generate'
- ),
- $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>'])
- ),
- 'Authentication' => array(
- array(
- 'type' => 'select',
- 'name' => 'authType',
- 'id' => 'authSelect',
- 'label' => 'Authentication Type',
- 'value' => $this->config['authType'],
- 'options' => $this->getAuthTypes()
- ),
- array(
- 'type' => 'select',
- 'name' => 'authBackend',
- 'id' => 'authBackendSelect',
- 'label' => 'Authentication Backend',
- 'class' => 'backendAuth switchAuth',
- 'value' => $this->config['authBackend'],
- 'options' => $this->getAuthBackends()
- ),
- array(
- 'type' => 'password-alt',
- 'name' => 'plexToken',
- 'class' => 'plexAuth switchAuth',
- 'label' => 'Plex Token',
- 'value' => $this->config['plexToken'],
- 'placeholder' => 'Use Get Token Button'
- ),
- array(
- 'type' => 'button',
- 'label' => 'Get Plex Token',
- 'class' => 'getPlexTokenAuth plexAuth switchAuth',
- 'icon' => 'fa fa-ticket',
- 'text' => 'Retrieve',
- 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#settings-main-form [name=plexToken]\')"'
- ),
- array(
- 'type' => 'password-alt',
- 'name' => 'plexID',
- 'class' => 'plexAuth switchAuth',
- 'label' => 'Plex Machine',
- 'value' => $this->config['plexID'],
- 'placeholder' => 'Use Get Plex Machine Button'
- ),
- array(
- 'type' => 'button',
- 'label' => 'Get Plex Machine',
- 'class' => 'getPlexMachineAuth plexAuth switchAuth',
- 'icon' => 'fa fa-id-badge',
- 'text' => 'Retrieve',
- 'attr' => 'onclick="showPlexMachineForm(\'#settings-main-form [name=plexID]\')"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'plexAdmin',
- 'label' => 'Plex Admin Username',
- 'class' => 'plexAuth switchAuth',
- 'value' => $this->config['plexAdmin'],
- 'placeholder' => 'Admin username for Plex'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'plexoAuth',
- 'label' => 'Enable Plex oAuth',
- 'class' => 'plexAuth switchAuth',
- 'value' => $this->config['plexoAuth']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'ignoreTFAIfPlexOAuth',
- 'label' => 'Ignore 2FA if Plex OAuth ',
- 'class' => 'plexAuth switchAuth',
- 'value' => $this->config['ignoreTFAIfPlexOAuth'],
- 'help' => 'Enabling this will disable Organizr 2FA (If applicable) if User uses Plex OAuth to login'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'plexStrictFriends',
- 'label' => 'Strict Plex Friends ',
- 'class' => 'plexAuth switchAuth',
- 'value' => $this->config['plexStrictFriends'],
- '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'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'ignoreTFALocal',
- 'label' => 'Ignore External 2FA on Local Subnet',
- 'value' => $this->config['ignoreTFALocal'],
- 'help' => 'Enabling this will bypass external 2FA security if user is on local Subnet'
- ),
- array(
- 'type' => 'input',
- 'name' => 'authBackendHost',
- 'class' => 'ldapAuth ftpAuth switchAuth',
- 'label' => 'Host Address',
- 'value' => $this->config['authBackendHost'],
- 'placeholder' => 'http(s) | ftp(s) | ldap(s)://hostname:port'
- ),
- array(
- 'type' => 'input',
- 'name' => 'authBaseDN',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Host Base DN',
- 'value' => $this->config['authBaseDN'],
- 'placeholder' => 'cn=%s,dc=sub,dc=domain,dc=com'
- ),
- array(
- 'type' => 'input',
- 'name' => 'authBackendHostPrefix',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Account Prefix',
- 'id' => 'authBackendHostPrefix-input',
- 'value' => $this->config['authBackendHostPrefix'],
- 'placeholder' => 'Account prefix - i.e. Controller\ from Controller\Username for AD - uid= for OpenLDAP'
- ),
- array(
- 'type' => 'input',
- 'name' => 'authBackendHostSuffix',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Account Suffix',
- 'id' => 'authBackendHostSuffix-input',
- 'value' => $this->config['authBackendHostSuffix'],
- 'placeholder' => 'Account suffix - start with comma - ,ou=people,dc=domain,dc=tld'
- ),
- array(
- 'type' => 'input',
- 'name' => 'ldapBindUsername',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Bind Username',
- 'value' => $this->config['ldapBindUsername'],
- 'placeholder' => ''
- ),
- array(
- 'type' => 'password',
- 'name' => 'ldapBindPassword',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Bind Password',
- 'value' => $this->config['ldapBindPassword']
- ),
- array(
- 'type' => 'select',
- 'name' => 'ldapType',
- 'id' => 'ldapType',
- 'label' => 'LDAP Backend Type',
- 'class' => 'ldapAuth switchAuth',
- 'value' => $this->config['ldapType'],
- 'options' => $this->getLDAPOptions()
- ),
- array(
- 'type' => 'html',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Account DN',
- 'html' => '<span id="accountDN" class="ldapAuth switchAuth">' . $this->config['authBackendHostPrefix'] . 'TestAcct' . $this->config['authBackendHostSuffix'] . '</span>'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'ldapSSL',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Enable LDAP SSL',
- 'value' => $this->config['ldapSSL'],
- 'help' => 'This will enable the use of SSL for LDAP connections'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'ldapSSL',
- 'class' => 'ldapAuth switchAuth',
- 'label' => 'Enable LDAP TLS',
- 'value' => $this->config['ldapTLS'],
- 'help' => 'This will enable the use of TLS for LDAP connections'
- ),
- array(
- 'type' => 'button',
- 'name' => 'test-button-ldap',
- 'label' => 'Test Connection',
- 'icon' => 'fa fa-flask',
- 'class' => 'ldapAuth switchAuth',
- 'text' => 'Test Connection',
- 'attr' => 'onclick="testAPIConnection(\'ldap\')"',
- 'help' => 'Remember! Please save before using the test button!'
- ),
- array(
- 'type' => 'button',
- 'name' => 'test-button-ldap-login',
- 'label' => 'Test Login',
- 'icon' => 'fa fa-flask',
- 'class' => 'ldapAuth switchAuth',
- 'text' => 'Test Login',
- 'attr' => 'onclick="showLDAPLoginTest()"'
- ),
- array(
- 'type' => 'input',
- 'name' => 'embyURL',
- 'class' => 'embyAuth switchAuth',
- 'label' => 'Emby URL',
- 'value' => $this->config['embyURL'],
- 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.',
- 'placeholder' => 'http(s)://hostname:port'
- ),
- array(
- 'type' => 'password-alt',
- 'name' => 'embyToken',
- 'class' => 'embyAuth switchAuth',
- 'label' => 'Emby Token',
- 'value' => $this->config['embyToken'],
- 'placeholder' => ''
- ),
- array(
- 'type' => 'input',
- 'name' => 'jellyfinURL',
- 'class' => 'jellyfinAuth switchAuth',
- 'label' => 'Jellyfin URL',
- 'value' => $this->config['jellyfinURL'],
- 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.',
- 'placeholder' => 'http(s)://hostname:port'
- ),
- array(
- 'type' => 'password-alt',
- 'name' => 'jellyfinToken',
- 'class' => 'jellyfinAuth switchAuth',
- 'label' => 'Jellyfin Token',
- 'value' => $this->config['jellyfinToken'],
- 'placeholder' => ''
- ),
- ),
- 'Security' => array(
- array(
- 'type' => 'number',
- 'name' => 'loginAttempts',
- 'label' => 'Max Login Attempts',
- 'value' => $this->config['loginAttempts'],
- 'placeholder' => ''
- ),
- array(
- 'type' => 'select',
- 'name' => 'loginLockout',
- 'label' => 'Login Lockout Seconds',
- 'value' => $this->config['loginLockout'],
- 'options' => $this->timeOptions()
- ),
- array(
- 'type' => 'number',
- 'name' => 'lockoutTimeout',
- 'label' => 'Inactivity Timer [Minutes]',
- 'value' => $this->config['lockoutTimeout'],
- 'placeholder' => ''
- ),
- array(
- 'type' => 'switch',
- 'name' => 'lockoutSystem',
- 'label' => 'Inactivity Lock',
- 'value' => $this->config['lockoutSystem']
- ),
- array(
- 'type' => 'select',
- 'name' => 'lockoutMinAuth',
- 'label' => 'Lockout Groups From',
- 'value' => $this->config['lockoutMinAuth'],
- 'options' => $this->groupSelect()
- ),
- array(
- 'type' => 'select',
- 'name' => 'lockoutMaxAuth',
- 'label' => 'Lockout Groups To',
- 'value' => $this->config['lockoutMaxAuth'],
- 'options' => $this->groupSelect()
- ),
- array(
- 'type' => 'switch',
- 'name' => 'traefikAuthEnable',
- 'label' => 'Enable Traefik Auth Redirect',
- 'help' => 'This will enable the webserver to forward errors so traefik will accept them',
- 'value' => $this->config['traefikAuthEnable']
- ),
- array(
- 'type' => 'input',
- 'name' => 'traefikDomainOverride',
- 'label' => 'Traefik Domain for Return Override',
- 'value' => $this->config['traefikDomainOverride'],
- 'help' => 'Please use a FQDN on this URL Override',
- 'placeholder' => 'http(s)://domain'
- ),
- array(
- 'type' => 'select',
- 'name' => 'debugAreaAuth',
- 'label' => 'Minimum Authentication for Debug Area',
- 'value' => $this->config['debugAreaAuth'],
- 'options' => $this->groupSelect(),
- 'settings' => '{}'
- ),
- array(
- 'type' => 'select2',
- 'class' => 'select2-multiple',
- 'id' => 'sandbox-select',
- 'name' => 'sandbox',
- 'label' => 'iFrame Sandbox',
- 'value' => $this->config['sandbox'],
- 'help' => 'WARNING! This can potentially mess up your iFrames',
- 'options' => array(
- array(
- 'name' => 'Allow Presentation',
- 'value' => 'allow-presentation'
- ),
- array(
- 'name' => 'Allow Forms',
- 'value' => 'allow-forms'
- ),
- array(
- 'name' => 'Allow Same Origin',
- 'value' => 'allow-same-origin'
- ),
- array(
- 'name' => 'Allow Orientation Lock',
- 'value' => 'allow-orientation-lock'
- ),
- array(
- 'name' => 'Allow Pointer Lock',
- 'value' => 'allow-pointer-lock'
- ),
- array(
- 'name' => 'Allow Scripts',
- 'value' => 'allow-scripts'
- ),
- array(
- 'name' => 'Allow Popups',
- 'value' => 'allow-popups'
- ),
- array(
- 'name' => 'Allow Popups To Escape Sandbox',
- 'value' => 'allow-popups-to-escape-sandbox'
- ),
- array(
- 'name' => 'Allow Modals',
- 'value' => 'allow-modals'
- ),
- array(
- 'name' => 'Allow Top Navigation',
- 'value' => 'allow-top-navigation'
- ),
- array(
- 'name' => 'Allow Top Navigation By User Activation',
- 'value' => 'allow-top-navigation-by-user-activation'
- ),
- array(
- 'name' => 'Allow Downloads',
- 'value' => 'allow-downloads'
- ),
- )
- ),
- array(
- 'type' => 'select2',
- 'class' => 'select2-multiple',
- 'id' => 'blacklisted-select',
- 'name' => 'blacklisted',
- 'label' => 'Blacklisted IP\'s',
- 'value' => $this->config['blacklisted'],
- 'help' => 'WARNING! This will block anyone with these IP\'s',
- 'options' => $this->makeOptionsFromValues($this->config['blacklisted']),
- 'settings' => '{tags: true}',
- ),
- array(
- 'type' => 'textbox',
- 'name' => 'blacklistedMessage',
- 'class' => '',
- 'label' => 'Blacklisted Error Message',
- 'value' => $this->config['blacklistedMessage'],
- 'attr' => 'rows="10"',
- ),
- ),
- 'Login' => array(
- array(
- 'type' => 'password-alt',
- 'name' => 'registrationPassword',
- 'label' => 'Registration Password',
- 'help' => 'Sets the password for the Registration form on the login screen',
- 'value' => $this->config['registrationPassword'],
- ),
- array(
- 'type' => 'switch',
- 'name' => 'hideRegistration',
- 'label' => 'Hide Registration',
- 'help' => 'Enable this to hide the Registration button on the login screen',
- 'value' => $this->config['hideRegistration'],
- ),
- array(
- 'type' => 'number',
- 'name' => 'rememberMeDays',
- 'label' => 'Remember Me Length',
- 'help' => 'Number of days cookies and tokens will be valid for',
- 'value' => $this->config['rememberMeDays'],
- 'placeholder' => '',
- 'attr' => 'min="1"'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'rememberMe',
- 'label' => 'Remember Me',
- 'help' => 'Default status of Remember Me button on login screen',
- 'value' => $this->config['rememberMe'],
- ),
- $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']),
- array(
- 'type' => 'input',
- 'name' => 'wanDomain',
- 'label' => 'WAN Domain',
- 'value' => $this->config['wanDomain'],
- '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'
- ),
- array(
- 'type' => 'input',
- 'name' => 'localAddress',
- 'label' => 'Local Address',
- 'value' => $this->config['localAddress'],
- 'placeholder' => 'http://home.local',
- 'help' => 'Full local address of organizr install - i.e. http://home.local or http://192.168.0.100'
- ),
- array(
- 'type' => 'switch',
- 'name' => 'enableLocalAddressForward',
- 'label' => 'Enable Local Address Forward',
- 'help' => 'Enables the local address forward if on local address and accessed from WAN Domain',
- 'value' => $this->config['enableLocalAddressForward'],
- ),
- array(
- 'type' => 'switch',
- 'name' => 'disableRecoverPass',
- 'label' => 'Disable Recover Password',
- 'help' => 'Disables recover password area',
- 'value' => $this->config['disableRecoverPass'],
- ),
- array(
- 'type' => 'input',
- 'name' => 'customForgotPassText',
- 'label' => 'Custom Recover Password Text',
- 'value' => $this->config['customForgotPassText'],
- 'placeholder' => '',
- 'help' => 'Text or HTML for recovery password section'
- ),
- ),
- 'Auth Proxy' => array(
- array(
- 'type' => 'switch',
- 'name' => 'authProxyEnabled',
- 'label' => 'Auth Proxy',
- 'help' => 'Enable option to set Auth Proxy Header Login',
- 'value' => $this->config['authProxyEnabled'],
- ),
- array(
- 'type' => 'input',
- 'name' => 'authProxyWhitelist',
- 'label' => 'Auth Proxy Whitelist',
- 'value' => $this->config['authProxyWhitelist'],
- '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'
- ),
- array(
- 'type' => 'input',
- 'name' => 'authProxyHeaderName',
- 'label' => 'Auth Proxy Header Name',
- 'value' => $this->config['authProxyHeaderName'],
- 'placeholder' => 'i.e. X-Forwarded-User',
- 'help' => 'Please choose a unique value for added security'
- ),
- array(
- 'type' => 'input',
- 'name' => 'authProxyHeaderNameEmail',
- 'label' => 'Auth Proxy Header Name for Email',
- 'value' => $this->config['authProxyHeaderNameEmail'],
- 'placeholder' => 'i.e. X-Forwarded-Email',
- 'help' => 'Please choose a unique value for added security'
- )
- ),
- 'Ping' => array(
- array(
- 'type' => 'select',
- 'name' => 'pingAuth',
- 'label' => 'Minimum Authentication',
- 'value' => $this->config['pingAuth'],
- 'options' => $this->groupSelect()
- ),
- array(
- 'type' => 'select',
- 'name' => 'pingAuthMessage',
- 'label' => 'Minimum Authentication for Message and Sound',
- 'value' => $this->config['pingAuthMessage'],
- 'options' => $this->groupSelect()
- ),
- array(
- 'type' => 'select',
- 'name' => 'pingOnlineSound',
- 'label' => 'Online Sound',
- 'value' => $this->config['pingOnlineSound'],
- 'options' => $this->getSounds()
- ),
- array(
- 'type' => 'select',
- 'name' => 'pingOfflineSound',
- 'label' => 'Offline Sound',
- 'value' => $this->config['pingOfflineSound'],
- 'options' => $this->getSounds()
- ),
- array(
- 'type' => 'switch',
- 'name' => 'pingMs',
- 'label' => 'Show Ping Time',
- 'value' => $this->config['pingMs']
- ),
- array(
- 'type' => 'switch',
- 'name' => 'statusSounds',
- 'label' => 'Enable Notify Sounds',
- 'value' => $this->config['statusSounds'],
- 'help' => 'Will play a sound if the server goes down and will play sound if comes back up.',
- ),
- array(
- 'type' => 'select',
- 'name' => 'pingAuthMs',
- 'label' => 'Minimum Authentication for Time Display',
- 'value' => $this->config['pingAuthMs'],
- 'options' => $this->groupSelect()
- ),
- array(
- 'type' => 'select',
- 'name' => 'adminPingRefresh',
- 'label' => 'Admin Refresh Seconds',
- 'value' => $this->config['adminPingRefresh'],
- 'options' => $this->timeOptions()
- ),
- array(
- 'type' => 'select',
- 'name' => 'otherPingRefresh',
- 'label' => 'Everyone Refresh Seconds',
- 'value' => $this->config['otherPingRefresh'],
- 'options' => $this->timeOptions()
- ),
- ),
- 'Certificate' => array(
- array(
- 'type' => 'html',
- 'label' => '',
- 'override' => 12,
- 'html' => '
- <script>
- let myDropzone = new Dropzone("#upload-custom-certificate", {
- url: "api/v2/certificate/custom",
- headers:{ "formKey": local("g","formKey") },
- init: function() {
- this.on("complete", function(file) {
- if(file["status"] === "success"){
- $(".custom-certificate-status").html("<span lang=\"en\">Custom Certificate Loaded</span>");
- }else{
- $(".custom-certificate-status").html("<span lang=\"en\">Error Saving file...</span>");
- }
- });
- }
- });
- </script>
- <div class="row">
- <div class="col-lg-12">
- <div class="panel panel-info">
- <div class="panel-heading"><span lang="en">Notice</span></div>
- <div class="panel-wrapper collapse in" aria-expanded="true">
- <div class="panel-body">
- <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>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-12">
- <div class="white-box">
- <h3 class="box-title m-b-0" lang="en">Custom Certificate Status</h3>
- <p class="text-muted m-b-30 custom-certificate-status">' . $certificateStatus . '</p>
- <form action="#" class="dropzone dz-clickable" id="upload-custom-certificate">
- <div class="dz-default dz-message"><span lang="en">Drop Certificate file here to upload</span></div>
- </form>
- </div>
- </div>
- </div>
- '
- )
- ),
- );
- }
-
- public function getSettingsSSO()
- {
- return [
- 'FYI' => [
- [
- 'type' => 'html',
- 'label' => '',
- 'override' => 12,
- 'html' => '
- <div class="row">
- <div class="col-lg-12">
- <div class="panel panel-primary">
- <div class="panel-heading"><span lang="en">Please Read First</span></div>
- <div class="panel-wrapper collapse in" aria-expanded="true">
- <div class="panel-body">
- <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>
- <br/><br/>
- <div class="row">
- <div class="col-lg-2 col-sm-4 col-xs-12">
- <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>
- </div>
- </div>
- <br/>
- <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>
- </div>
- </div>
- </div>
- </div>
- </div>
- '
- ]
- ],
- 'Plex' => [
- [
- 'type' => 'password-alt',
- 'name' => 'plexToken',
- 'label' => 'Plex Token',
- 'value' => $this->config['plexToken'],
- 'placeholder' => 'Use Get Token Button'
- ],
- [
- 'type' => 'button',
- 'label' => 'Get Plex Token',
- 'icon' => 'fa fa-ticket',
- 'text' => 'Retrieve',
- 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#sso-form [name=plexToken]\')"'
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'plexID',
- 'label' => 'Plex Machine',
- 'value' => $this->config['plexID'],
- 'placeholder' => 'Use Get Plex Machine Button'
- ],
- [
- 'type' => 'button',
- 'label' => 'Get Plex Machine',
- 'icon' => 'fa fa-id-badge',
- 'text' => 'Retrieve',
- 'attr' => 'onclick="showPlexMachineForm(\'#sso-form [name=plexID]\')"'
- ],
- [
- 'type' => 'input',
- 'name' => 'plexAdmin',
- 'label' => 'Admin Username',
- 'value' => $this->config['plexAdmin'],
- 'placeholder' => 'Admin username for Plex'
- ],
- [
- 'type' => 'blank',
- 'label' => ''
- ],
- [
- 'type' => 'html',
- 'label' => 'Plex Note',
- 'html' => '<span lang="en">Please make sure both Token and Machine are filled in</span>'
- ],
- [
- 'type' => 'switch',
- 'name' => 'ssoPlex',
- 'label' => 'Enable',
- 'value' => $this->config['ssoPlex']
- ]
- ],
- 'Tautulli' => [
- $this->settingsOption('multiple-url', 'tautulliURL'),
- $this->settingsOption('auth', 'ssoTautulliAuth'),
- $this->settingsOption('enable', 'ssoTautulli'),
- ],
- 'Overseerr' => [
- [
- 'type' => 'input',
- 'name' => 'overseerrURL',
- 'label' => 'Overseerr URL',
- 'value' => $this->config['overseerrURL'],
- 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.',
- 'placeholder' => 'http(s)://hostname:port'
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'overseerrToken',
- 'label' => 'Token',
- 'value' => $this->config['overseerrToken']
- ],
- [
- 'type' => 'input',
- 'name' => 'overseerrFallbackUser',
- 'label' => 'Overseerr Fallback Email',
- 'value' => $this->config['overseerrFallbackUser'],
- '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',
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'overseerrFallbackPassword',
- 'label' => 'Overseerr Fallback Password',
- 'value' => $this->config['overseerrFallbackPassword'],
- ],
- [
- 'type' => 'switch',
- 'name' => 'ssoOverseerr',
- 'label' => 'Enable',
- 'value' => $this->config['ssoOverseerr']
- ]
- ],
- 'Petio' => [
- [
- 'type' => 'input',
- 'name' => 'petioURL',
- 'label' => 'Petio URL',
- 'value' => $this->config['petioURL'],
- 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.',
- 'placeholder' => 'http(s)://hostname:port'
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'petioToken',
- 'label' => 'Token',
- 'value' => $this->config['petioToken']
- ],
- [
- 'type' => 'input',
- 'name' => 'petioFallbackUser',
- 'label' => 'Petio Fallback User',
- 'value' => $this->config['petioFallbackUser'],
- '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',
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'petioFallbackPassword',
- 'label' => 'Petio Fallback Password',
- 'value' => $this->config['petioFallbackPassword'],
- ],
- [
- 'type' => 'switch',
- 'name' => 'ssoPetio',
- 'label' => 'Enable',
- 'value' => $this->config['ssoPetio']
- ]
- ],
- 'Ombi' => [
- [
- 'type' => 'input',
- 'name' => 'ombiURL',
- 'label' => 'Ombi URL',
- 'value' => $this->config['ombiURL'],
- 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.',
- 'placeholder' => 'http(s)://hostname:port'
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'ombiToken',
- 'label' => 'Token',
- 'value' => $this->config['ombiToken']
- ],
- [
- 'type' => 'input',
- 'name' => 'ombiFallbackUser',
- 'label' => 'Ombi Fallback User',
- 'value' => $this->config['ombiFallbackUser'],
- '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'
- ],
- [
- 'type' => 'password-alt',
- 'name' => 'ombiFallbackPassword',
- 'label' => 'Ombi Fallback Password',
- 'value' => $this->config['ombiFallbackPassword']
- ],
- [
- 'type' => 'switch',
- 'name' => 'ssoOmbi',
- 'label' => 'Enable',
- 'value' => $this->config['ssoOmbi']
- ]
- ],
- 'Jellyfin' => [
- [
- 'type' => 'input',
- 'name' => 'jellyfinURL',
- 'label' => 'Jellyfin API URL',
- 'value' => $this->config['jellyfinURL'],
- 'help' => 'Please make sure to use the local address to the API',
- 'placeholder' => 'http(s)://hostname:port'
- ],
- [
- 'type' => 'input',
- 'name' => 'jellyfinSSOURL',
- 'label' => 'Jellyfin SSO URL',
- 'value' => $this->config['jellyfinSSOURL'],
- 'help' => 'Please make sure to use the same (sub)domain to access Jellyfin as Organizr\'s',
- 'placeholder' => 'http(s)://domain.com'
- ],
- [
- 'type' => 'switch',
- 'name' => 'ssoJellyfin',
- 'label' => 'Enable',
- 'value' => $this->config['ssoJellyfin']
- ]
- ],
- 'Komga' => [
- $this->settingsOption('url', 'komgaURL'),
- $this->settingsOption('auth', 'ssoKomgaAuth'),
- $this->settingsOption('enable', 'ssoKomga'),
- ],
- ];
- }
-
- public function systemMenuLists()
- {
- $userManagementMenu = [
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_user_manage_users',
- 'anchor' => 'settings-user-manage-users-anchor',
- 'name' => 'Manage Users'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_user_manage_groups',
- 'anchor' => 'settings-user-manage-groups-anchor',
- 'name' => 'Manage Groups'
- ],
- [
- 'active' => false,
- 'api' => false,
- 'anchor' => 'settings-user-import-users-anchor',
- 'name' => 'Import Users'
- ],
- ];
- $customizeMenu = [
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_customize_appearance',
- 'anchor' => 'settings-customize-appearance-anchor',
- 'name' => 'Appearance',
- ],
- [
- 'active' => false,
- 'api' => false,
- 'anchor' => 'settings-customize-marketplace-anchor',
- 'name' => 'Marketplace',
- 'onclick' => 'loadMarketplace(\'themes\');'
- ],
- ];
- $tabEditorMenu = [
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_tab_editor_tabs',
- 'anchor' => 'settings-tab-editor-tabs-anchor',
- 'name' => 'Tabs'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_tab_editor_categories',
- 'anchor' => 'settings-tab-editor-categories-anchor',
- 'name' => 'Categories'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_tab_editor_homepage',
- 'anchor' => 'settings-tab-editor-homepage-anchor',
- 'name' => 'Homepage Items'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_tab_editor_homepage_order',
- 'anchor' => 'settings-tab-editor-homepage-order-anchor',
- 'name' => 'Homepage Order'
- ],
- ];
- $systemSettingsMenu = [
- [
- 'active' => true,
- 'api' => false,
- 'anchor' => 'settings-settings-about-anchor',
- 'name' => 'About'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_settings_main',
- 'anchor' => 'settings-settings-main-anchor',
- 'name' => 'Main'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_settings_sso',
- 'anchor' => 'settings-settings-sso-anchor',
- 'name' => 'SSO'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_settings_logs',
- 'anchor' => 'settings-settings-logs-anchor',
- 'name' => 'Logs'
- ],
- [
- 'active' => false,
- 'api' => false,
- 'anchor' => 'settings-settings-updates-anchor',
- 'name' => 'Updates'
- ],
- [
- 'active' => false,
- 'api' => 'api/v2/page/settings_settings_backup',
- 'anchor' => 'settings-settings-backup-anchor',
- 'name' => 'Backup'
- ],
- [
- 'active' => false,
- 'api' => false,
- 'anchor' => 'settings-settings-donate-anchor',
- 'name' => 'Donate'
- ],
- ];
- $systemMenus['system_settings'] = $this->buildSettingsMenus($systemSettingsMenu, 'System Settings');
- $systemMenus['tab_editor'] = $this->buildSettingsMenus($tabEditorMenu, 'Tab Editor');
- $systemMenus['customize'] = $this->buildSettingsMenus($customizeMenu, 'Customize');
- $systemMenus['user_management'] = $this->buildSettingsMenus($userManagementMenu, 'User Management');
- return $systemMenus;
- }
-
- public function updateConfigMultiple($array)
- {
- return (bool)$this->updateConfig($array);
- }
-
- public function updateConfigItems($array)
- {
- if (!count($array)) {
- $this->setAPIResponse('error', 'No data submitted', 409);
- return false;
- }
- $newItem = array();
- foreach ($array as $k => $v) {
- $v = $v ?? '';
- switch ($v) {
- case 'true':
- $v = (bool)true;
- break;
- case 'false':
- $v = (bool)false;
- break;
- }
- // Hash
- if ((stripos($k, 'password') !== false)) {
- if (!$this->isEncrypted($v)) {
- if ($v !== '') {
- $v = $this->encrypt($v);
- }
- }
- }
- if (strtolower($k) !== 'formkey') {
- $newItem[$k] = $v;
- $this->config[$k] = $v;
- }
- }
- $this->setAPIResponse('success', 'Config items updated', 200);
- return (bool)$this->updateConfig($newItem);
- }
-
- public function updateConfigItem($array)
- {
- $array['value'] = $array['value'] ?? '';
- switch ($array['value']) {
- case 'true':
- $array['value'] = (bool)true;
- break;
- case 'false':
- $array['value'] = (bool)false;
- break;
- }
- // Hash
- if ($array['type'] == 'password') {
- $array['value'] = $this->encrypt($array['value']);
- }
- $newItem = array(
- $array['name'] => $array['value']
- );
- $this->config[$array['name']] = $array['value'];
- return (bool)$this->updateConfig($newItem);
- }
-
- public function ignoreNewsId($id)
- {
- if (!$id) {
- $this->setAPIResponse('error', 'News id was not supplied', 409);
- return false;
- }
- $id = array(intval($id));
- $newsIds = $this->config['ignoredNewsIds'];
- $newsIds = array_merge($newsIds, $id);
- $newsIds = array_unique($newsIds);
- $this->updateConfig(['ignoredNewsIds' => $newsIds]);
- $this->setAPIResponse('success', 'News id is now ignored', 200, null);
- }
-
- public function getNewsIds()
- {
- $newsIds = $this->config['ignoredNewsIds'];
- $this->setAPIResponse('success', null, 200, $newsIds);
- return $newsIds;
- }
-
- public function testWizardPath($array)
- {
- if ($this->hasDB()) {
- $this->setAPIResponse('error', 'Endpoint disabled as database already exists', 401);
- return false;
- }
- $path = $array['path'] ?? null;
- if (file_exists($path)) {
- if (is_writable($path)) {
- $this->setAPIResponse('success', 'Path exists and is writable', 200);
- return true;
- }
- } else {
- if (is_writable(dirname($path, 1))) {
- if (mkdir($path, 0760, true)) {
- $this->setAPIResponse('success', 'Path is writable - Creating now', 200);
- return true;
- }
- }
- }
- $this->setAPIResponse('error', 'Path is not writable', 401);
- return false;
- }
-
- public function wizardConfig($array)
- {
- $dbName = $array['dbName'] ?? null;
- $path = $array['dbPath'] ?? null;
- $license = $array['license'] ?? null;
- $hashKey = $array['hashKey'] ?? null;
- $api = $array['api'] ?? null;
- $registrationPassword = $array['registrationPassword'] ?? null;
- $username = $array['username'] ?? null;
- $password = $array['password'] ?? null;
- $email = $array['email'] ?? null;
- $validation = array(
- 'dbName' => $dbName,
- 'dbPath' => $path,
- 'license' => $license,
- 'hashKey' => $hashKey,
- 'api' => $api,
- 'registrationPassword' => $registrationPassword,
- 'username' => $username,
- 'password' => $password,
- 'email' => $email,
- );
- foreach ($validation as $k => $v) {
- if ($v == null) {
- $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
- return false;
- }
- }
- $path = $this->cleanDirectory($path);
- if (file_exists($path)) {
- if (!is_writable($path)) {
- $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
- return false;
- }
- } else {
- if (is_writable(dirname($path, 1))) {
- if (!mkdir($path, 0760, true)) {
- $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
- return false;
- }
- } else {
- $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
- return false;
- }
- }
- $dbName = $this->dbExtension($dbName);
- $configVersion = $this->version;
- $configArray = array(
- 'dbName' => $dbName,
- 'dbLocation' => $path,
- 'license' => $license,
- 'organizrHash' => $hashKey,
- 'organizrAPI' => $api,
- 'registrationPassword' => $registrationPassword,
- 'uuid' => $this->gen_uuid()
- );
- // Create Config
- if ($this->createConfig($configArray)) {
- $this->config = $this->config();
- $this->refreshCookieName();
- $this->connectDB();
- // Call DB Create
- if ($this->createDB($path)) {
- // Add in first user
- if ($this->createFirstAdmin($username, $password, $email)) {
- if ($this->createToken($username, $email, 1)) {
- return true;
- } else {
- $this->setAPIResponse('error', 'error creating token', 500);
- }
- } else {
- $this->setAPIResponse('error', 'error creating admin', 500);
- }
- } else {
- $this->setAPIResponse('error', 'error creating database', 500);
- }
-
- } else {
- $this->setAPIResponse('error', 'error creating config', 500);
- }
- return false;
- }
-
- public function createDB($path, $migration = false)
- {
-
- if (!file_exists($path)) {
- mkdir($path, 0777, true);
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `users` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `username` TEXT UNIQUE,
- `password` TEXT,
- `email` TEXT,
- `plex_token` TEXT,
- `group` TEXT,
- `group_id` INTEGER,
- `locked` INTEGER,
- `image` TEXT,
- `register_date` DATE,
- `auth_service` TEXT DEFAULT \'internal\'
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `chatroom` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `username` TEXT,
- `gravatar` TEXT,
- `uid` TEXT,
- `date` DATE,
- `ip` TEXT,
- `message` TEXT
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `tokens` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `token` TEXT UNIQUE,
- `user_id` INTEGER,
- `browser` TEXT,
- `ip` TEXT,
- `created` DATE,
- `expires` DATE
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `groups` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `group` TEXT UNIQUE,
- `group_id` INTEGER,
- `image` TEXT,
- `default` INTEGER
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `categories` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `order` INTEGER,
- `category` TEXT UNIQUE,
- `category_id` INTEGER,
- `image` TEXT,
- `default` INTEGER
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `tabs` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `order` INTEGER,
- `category_id` INTEGER,
- `name` TEXT,
- `url` TEXT,
- `url_local` TEXT,
- `default` INTEGER,
- `enabled` INTEGER,
- `group_id` INTEGER,
- `image` TEXT,
- `type` INTEGER,
- `splash` INTEGER,
- `ping` INTEGER,
- `ping_url` TEXT,
- `timeout` INTEGER,
- `timeout_ms` INTEGER,
- `preload` INTEGER
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `options` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `name` TEXT UNIQUE,
- `value` TEXT
- );'
- ),
- array(
- 'function' => 'query',
- 'query' => 'CREATE TABLE `invites` (
- `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
- `code` TEXT UNIQUE,
- `date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- `email` TEXT,
- `username` TEXT,
- `dateused` TIMESTAMP,
- `usedby` TEXT,
- `ip` TEXT,
- `valid` TEXT,
- `type` TEXT
- );'
- ),
- ];
- return $this->processQueries($response, $migration);
- }
-
- public function createFirstAdmin($username, $password, $email)
- {
-
- $userInfo = [
- 'username' => $username,
- 'password' => password_hash($password, PASSWORD_BCRYPT),
- 'email' => $email,
- 'group' => 'Admin',
- 'group_id' => 0,
- 'image' => $this->gravatar($email),
- 'register_date' => $this->currentTime,
- ];
- $groupInfo0 = [
- 'group' => 'Admin',
- 'group_id' => 0,
- 'default' => false,
- 'image' => 'plugins/images/groups/admin.png',
- ];
- $groupInfo1 = [
- 'group' => 'Co-Admin',
- 'group_id' => 1,
- 'default' => false,
- 'image' => 'plugins/images/groups/coadmin.png',
- ];
- $groupInfo2 = [
- 'group' => 'Super User',
- 'group_id' => 2,
- 'default' => false,
- 'image' => 'plugins/images/groups/superuser.png',
- ];
- $groupInfo3 = [
- 'group' => 'Power User',
- 'group_id' => 3,
- 'default' => false,
- 'image' => 'plugins/images/groups/poweruser.png',
- ];
- $groupInfo4 = [
- 'group' => 'User',
- 'group_id' => 4,
- 'default' => true,
- 'image' => 'plugins/images/groups/user.png',
- ];
- $groupInfoGuest = [
- 'group' => 'Guest',
- 'group_id' => 999,
- 'default' => false,
- 'image' => 'plugins/images/groups/guest.png',
- ];
- $settingsInfo = [
- 'order' => 1,
- 'category_id' => 0,
- 'name' => 'Settings',
- 'url' => 'api/v2/page/settings',
- 'default' => false,
- 'enabled' => true,
- 'group_id' => 1,
- 'image' => 'fontawesome::cog',
- 'type' => 0
- ];
- $homepageInfo = [
- 'order' => 2,
- 'category_id' => 0,
- 'name' => 'Homepage',
- 'url' => 'api/v2/page/homepage',
- 'default' => false,
- 'enabled' => false,
- 'group_id' => 4,
- 'image' => 'fontawesome::home',
- 'type' => 0
- ];
- $unsortedInfo = [
- 'order' => 1,
- 'category' => 'Unsorted',
- 'category_id' => 0,
- 'image' => 'fontawesome::question',
- 'default' => true
- ];
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [users]',
- $userInfo
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $groupInfo0
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $groupInfo1
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $groupInfo2
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $groupInfo3
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $groupInfo4
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $groupInfoGuest
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [tabs]',
- $settingsInfo
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [tabs]',
- $homepageInfo
- )
- ),
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [categories]',
- $unsortedInfo
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getUserByUsernameAndEmail($username, $email)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',
- [$username],
- [$email]
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function createToken($username, $email, $days = 1)
- {
- $days = ($days > 365) ? 365 : $days;
- //Quick get user ID
- $result = $this->getUserByUsernameAndEmail($username, $email);
- // Create JWT
- // Set key
- // SHA256 Encryption
- $signer = new Lcobucci\JWT\Signer\Hmac\Sha256();
- // Start Builder
- $jwttoken = (new Lcobucci\JWT\Builder())->issuedBy('Organizr')// Configures the issuer (iss claim)
- ->permittedFor('Organizr')// Configures the audience (aud claim)
- ->identifiedBy('4f1g23a12aa', true)// Configures the id (jti claim), replicating as a header item
- ->issuedAt(time())// Configures the time that the token was issue (iat claim)
- ->expiresAt(time() + (86400 * $days))// Configures the expiration time of the token (exp claim)
- ->withClaim('name', $result['username'])// Configures a new claim, called "name"
- ->withClaim('group', $result['group'])// Configures a new claim, called "group"
- ->withClaim('groupID', $result['group_id'])// Configures a new claim, called "groupID"
- ->withClaim('email', $result['email'])// Configures a new claim, called "email"
- ->withClaim('image', $result['image'])// Configures a new claim, called "image"
- ->withClaim('userID', $result['id'])// Configures a new claim, called "image"
- ->sign($signer, $this->config['organizrHash'])// creates a signature using "testing" as key
- ->getToken(); // Retrieves the generated token
- $jwttoken->getHeaders(); // Retrieves the token headers
- $jwttoken->getClaims(); // Retrieves the token claims
- $this->coookie('set', $this->cookieName, $jwttoken, $days);
- // Add token to DB
- $addToken = [
- 'token' => (string)$jwttoken,
- 'user_id' => $result['id'],
- 'created' => $this->currentTime,
- 'browser' => isset($_SERVER ['HTTP_USER_AGENT']) ? $_SERVER ['HTTP_USER_AGENT'] : null,
- 'ip' => $this->userIP(),
- 'expires' => gmdate("Y-m-d\TH:i:s\Z", time() + (86400 * $days))
- ];
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [tokens]',
- $addToken
- )
- ),
- ];
- $token = $this->processQueries($response);
- return $jwttoken;
-
- }
-
- public function login($array)
- {
- // Grab username, Password & other optional items from api call
- $username = $array['username'] ?? null;
- $password = $array['password'] ?? null;
- $oAuth = $array['oAuth'] ?? null;
- $oAuthType = $array['oAuthType'] ?? null;
- $remember = $array['remember'] ?? null;
- $tfaCode = $array['tfaCode'] ?? null;
- $loginAttempts = $array['loginAttempts'] ?? null;
- $output = $array['output'] ?? null;
- $username = (strpos($this->config['authBackend'], 'emby') !== false) ? $username : strtolower($username);
- $days = (isset($remember)) ? $this->config['rememberMeDays'] : 1;
- // Set other variables
- $function = 'plugin_auth_' . $this->config['authBackend'];
- $authSuccess = false;
- $authProxy = false;
- $addEmailToAuthProxy = true;
- // Check Login attempts and kill if over limit
- if ($loginAttempts > $this->config['loginAttempts'] || isset($_COOKIE['lockout'])) {
- $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
- $this->setAPIResponse('error', 'User is locked out', 403);
- return false;
- }
- // Check if Auth Proxy is enabled
- if ($this->config['authProxyEnabled'] && $this->config['authProxyHeaderName'] !== '' && $this->config['authProxyWhitelist'] !== '') {
- if (isset($this->getallheaders()[$this->config['authProxyHeaderName']])) {
- $usernameHeader = $this->getallheaders()[$this->config['authProxyHeaderName']] ?? $username;
- $emailHeader = $this->getallheaders()[$this->config['authProxyHeaderNameEmail']] ?? null;
- $this->writeLog('success', 'Auth Proxy Function - Starting Verification for IP: ' . $this->userIP() . ' for request on: ' . $_SERVER['REMOTE_ADDR'] . ' against IP/Subnet: ' . $this->config['authProxyWhitelist'], $usernameHeader);
- $whitelistRange = $this->analyzeIP($this->config['authProxyWhitelist']);
- $authProxy = $this->authProxyRangeCheck($whitelistRange['from'], $whitelistRange['to']);
- $username = ($authProxy) ? $usernameHeader : $username;
- $password = ($password == null) ? $this->random_ascii_string(10) : $password;
- $addEmailToAuthProxy = ($authProxy && $emailHeader) ? ['email' => $emailHeader] : true;
- if ($authProxy) {
- $this->writeLog('success', 'Auth Proxy Function - IP: ' . $this->userIP() . ' has been verified', $usernameHeader);
- } else {
- $this->writeLog('error', 'Auth Proxy Function - IP: ' . $this->userIP() . ' has failed verification', $usernameHeader);
- }
- }
- }
- // Check if Login method was an oAuth login
- if (!$oAuth) {
- $result = $this->getUserByUsernameAndEmail($username, $username);
- $result['password'] = $result['password'] ?? '';
- // Switch AuthType - internal - external - both
- switch ($this->config['authType']) {
- case 'external':
- if (method_exists($this, $function)) {
- $authSuccess = $this->$function($username, $password);
- }
- break;
- /** @noinspection PhpMissingBreakStatementInspection */
- case 'both':
- if (method_exists($this, $function)) {
- $authSuccess = $this->$function($username, $password);
- }
- // no break
- default: // Internal
- if (!$authSuccess) {
- // perform the internal authentication step
- if (password_verify($password, $result['password'])) {
- $authSuccess = true;
- }
- }
- }
- $authSuccess = ($authProxy) ? $addEmailToAuthProxy : $authSuccess;
- } else {
- // Has oAuth Token!
- switch ($oAuthType) {
- case 'plex':
- if ($this->config['plexoAuth']) {
- $tokenInfo = $this->checkPlexToken($oAuth);
- if ($tokenInfo) {
- $authSuccess = array(
- 'username' => $tokenInfo['user']['username'],
- 'email' => $tokenInfo['user']['email'],
- 'image' => $tokenInfo['user']['thumb'],
- 'token' => $tokenInfo['user']['authToken'],
- 'oauth' => 'plex'
- );
- $this->coookie('set', 'oAuth', 'true', $this->config['rememberMeDays']);
- $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;
- }
- } else {
- $this->setAPIResponse('error', 'Plex oAuth is not setup', 422);
- return false;
- }
- break;
- default:
- return ($output) ? 'No oAuthType defined' : 'error';
- }
- $result = ($authSuccess) ? $this->getUserByUsernameAndEmail($authSuccess['username'], $authSuccess['email']) : '';
- }
- if ($authSuccess) {
- // Make sure user exists in database
- $userExists = false;
- $passwordMatches = $oAuth || $authProxy;
- $token = (is_array($authSuccess) && isset($authSuccess['token']) ? $authSuccess['token'] : '');
- if (isset($result['username'])) {
- $userExists = true;
- $username = $result['username'];
- if ($passwordMatches == false) {
- $passwordMatches = password_verify($password, $result['password']);
- }
- }
- if ($userExists) {
- //does org password need to be updated
- if (!$passwordMatches) {
- $this->updateUserPassword($password, $result['id']);
- $this->writeLog('success', 'Login Function - User Password updated from backend', $username);
- }
- if ($token !== '') {
- if ($token !== $result['plex_token']) {
- $this->updateUserPlexToken($token, $result['id']);
- $this->writeLog('success', 'Login Function - User Plex Token updated from backend', $username);
- }
- }
- // 2FA might go here
- if ($result['auth_service'] !== 'internal' && strpos($result['auth_service'], '::') !== false) {
- $tfaProceed = true;
- // Add check for local or not
- if ($this->config['ignoreTFALocal'] !== false) {
- $tfaProceed = !$this->isLocal();
- }
- // Is Plex Oauth?
- if ($this->config['ignoreTFAIfPlexOAuth'] !== false) {
- if (isset($authSuccess['oauth'])) {
- if ($authSuccess['oauth'] == 'plex') {
- $tfaProceed = false;
- }
- }
- }
- if ($tfaProceed) {
- $TFA = explode('::', $result['auth_service']);
- // Is code with login info?
- if ($tfaCode == '') {
- $this->setAPIResponse('warning', '2FA Code Needed', 422);
- return false;
- } else {
- if (!$this->verify2FA($TFA[1], $tfaCode, $TFA[0])) {
- $this->writeLoginLog($username, 'error');
- $this->writeLog('error', 'Login Function - Wrong 2FA', $username);
- $this->setAPIResponse('error', 'Wrong 2FA', 422);
- return false;
- }
- }
- }
- }
- // End 2FA
- // authentication passed - 1) mark active and update token
- $createToken = $this->createToken($result['username'], $result['email'], $days);
- if ($createToken) {
- $this->writeLoginLog($username, 'success');
- $this->writeLog('success', 'Login Function - A User has logged in', $username);
- $this->ssoCheck($result, $password, $token); //need to work on this
- return ($output) ? array('name' => $this->cookieName, 'token' => (string)$createToken) : true;
- } else {
- $this->setAPIResponse('error', 'Token creation error', 500);
- return false;
- }
- } else {
- // Create User
- return $this->authRegister((is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username), $password, (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $token);
- }
- } else {
- // authentication failed
- $this->writeLoginLog($username, 'error');
- $this->writeLog('error', 'Login Function - Wrong Password', $username);
- if ($loginAttempts >= $this->config['loginAttempts']) {
- $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
- $this->setAPIResponse('error', 'User is locked out', 403);
- return false;
- } else {
- $this->setAPIResponse('error', 'User credentials incorrect', 401);
- return false;
- }
- }
- }
-
- public function logout()
- {
- $this->coookie('delete', $this->cookieName);
- $this->coookie('delete', 'mpt');
- $this->coookie('delete', 'Auth');
- $this->coookie('delete', 'oAuth');
- $this->coookie('delete', 'connect.sid');
- $this->coookie('delete', 'petio_jwt');
- $this->clearTautulliTokens();
- $this->clearJellyfinTokens();
- $this->revokeTokenCurrentUser($this->user['token']);
- $this->clearKomgaToken();
- $this->user = null;
- return true;
- }
-
- public function recover($array)
- {
- $email = $array['email'] ?? null;
- if (!$email) {
- $this->setAPIResponse('error', 'Email was not supplied', 422);
- return false;
- }
- $newPassword = $this->randString(10);
- $isUser = $this->getUserByEmail($email);
- if ($isUser) {
- $this->updateUserPassword($newPassword, $isUser['id']);
- $this->setAPIResponse('success', 'User password has been reset', 200);
- $this->writeLog('success', 'User Management Function - User: ' . $isUser['username'] . '\'s password was reset', $isUser['username']);
- if ($this->config['PHPMAILER-enabled']) {
- $PhpMailer = new PhpMailer();
- $emailTemplate = array(
- 'type' => 'reset',
- 'body' => $this->config['PHPMAILER-emailTemplateReset'],
- 'subject' => $this->config['PHPMAILER-emailTemplateResetSubject'],
- 'user' => $isUser['username'],
- 'password' => $newPassword,
- 'inviteCode' => null,
- );
- $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
- $sendEmail = array(
- 'to' => $email,
- 'user' => $isUser['username'],
- 'subject' => $emailTemplate['subject'],
- 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
- );
- $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
- $this->setAPIResponse('success', 'User password has been reset and email has been sent', 200);
- }
- return true;
- } else {
- $this->setAPIResponse('error', 'User not found', 404);
- return false;
- }
- }
-
- public function register($array)
- {
- $email = $array['email'] ?? null;
- $username = $array['username'] ?? null;
- $password = $array['password'] ?? null;
- $registrationPassword = $array['registrationPassword'] ?? null;
- if (!$email) {
- $this->setAPIResponse('error', 'Email was not supplied', 422);
- return false;
- }
- if (!$username) {
- $this->setAPIResponse('error', 'Username was not supplied', 422);
- return false;
- }
- if (!$password) {
- $this->setAPIResponse('error', 'Password was not supplied', 422);
- return false;
- }
- if (!$registrationPassword) {
- $this->setAPIResponse('error', 'Registration Password was not supplied', 422);
- return false;
- }
- if ($registrationPassword == $this->decrypt($this->config['registrationPassword'])) {
- $this->writeLog('success', 'Registration Function - Registration Password Verified', $username);
- if ($this->createUser($username, $password, $email)) {
- $this->writeLog('success', 'Registration Function - A User has registered', $username);
- if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
- $this->writeLoginLog($username, 'success');
- $this->writeLog('success', 'Login Function - A User has logged in', $username);
- return true;
- }
- } else {
- return false;
- }
- } else {
- $this->writeLog('warning', 'Registration Function - Wrong Password', $username);
- $this->setAPIResponse('error', 'Registration Password was incorrect', 401);
- return false;
- }
- }
-
- public function authRegister($username, $password, $email, $token = null)
- {
- if ($this->config['authBackend'] !== '') {
- $this->ombiImport($this->config['authBackend']);
- }
- $this->ssoCheck($username, $password, $token);
- if ($token && (!$password || $password == '')) {
- $password = $this->random_ascii_string(10);
- }
- if ($this->createUser($username, $password, $email)) {
- $this->writeLog('success', 'Registration Function - A User has registered', $username);
- if ($this->config['PHPMAILER-enabled'] && $email !== '') {
- $PhpMailer = new PhpMailer();
- $emailTemplate = array(
- 'type' => 'registration',
- 'body' => $this->config['PHPMAILER-emailTemplateRegisterUser'],
- 'subject' => $this->config['PHPMAILER-emailTemplateRegisterUserSubject'],
- 'user' => $username,
- 'password' => null,
- 'inviteCode' => null,
- );
- $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
- $sendEmail = array(
- 'to' => $email,
- 'user' => $username,
- 'subject' => $emailTemplate['subject'],
- 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
- );
- $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
- }
- if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
- $this->writeLoginLog($username, 'success');
- $this->writeLog('success', 'Login Function - A User has logged in', $username);
- return true;
- } else {
- return false;
- }
- } else {
- $this->writeLog('error', 'Registration Function - An error occurred', $username);
- return false;
- }
- }
-
- public function revokeTokenCurrentUser($token = null)
- {
- if ($token) {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM tokens WHERE token = ?',
- [$token]
- )
- ),
- ];
- } else {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM tokens WHERE user_id = ?',
- [$this->user['userID']]
- )
- ),
- ];
- }
- return $this->processQueries($response);
- }
-
- public function revokeToken($token = null)
- {
- if (!$token) {
- $this->setAPIResponse('error', 'Token was not supplied', 422);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM tokens WHERE token = ?',
- [$token]
- )
- ),
- ];
- $this->setAPIResponse('success', 'Token revoked', 204);
- return $this->processQueries($response);
- }
-
- public function revokeTokenByIdCurrentUser($id = null)
- {
- if (!$id) {
- $this->setAPIResponse('error', 'Id was not supplied', 422);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM tokens WHERE id = ? AND user_id = ?',
- $id,
- $this->user['userID']
- )
- ),
- ];
- $this->setAPIResponse('success', 'Token revoked', 204);
- return $this->processQueries($response);
- }
-
- public function updateUserPassword($password, $id)
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE users SET',
- ['password' => password_hash($password, PASSWORD_BCRYPT)],
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function updateUserPlexToken($token, $id)
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE users SET',
- ['plex_token' => $token],
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getUserTabsAndCategories($type = null)
- {
- if (!$this->hasDB()) {
- return false;
- }
- $sort = ($this->config['unsortedTabs'] == 'top') ? 'DESC' : 'ASC';
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM tabs WHERE `group_id` >= ? AND `enabled` = 1 ORDER BY `order` ' . $sort,
- $this->user['groupID']
- ),
- 'key' => 'tabs'
- ),
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM categories ORDER BY `order` ASC',
- ),
- 'key' => 'categories'
- ),
- ];
- $queries = $this->processQueries($response);
- $this->applyTabVariables($queries['tabs']);
- $all['tabs'] = $queries['tabs'];
- foreach ($queries['tabs'] as $k => $v) {
- $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'];
- }
- $count = array_map(function ($element) {
- return $element['category_id'];
- }, $queries['tabs']);
- $count = (array_count_values($count));
- foreach ($queries['categories'] as $k => $v) {
- $v['count'] = isset($count[$v['category_id']]) ? $count[$v['category_id']] : 0;
- }
- $all['categories'] = $queries['categories'];
- switch ($type) {
- case 'categories':
- return $all['categories'];
- case 'tabs':
- return $all['tabs'];
- default:
- return $all;
- }
- }
-
- public function refreshList()
- {
- $searchTerm = "Refresh";
- return array_filter($this->config, function ($k) use ($searchTerm) {
- return stripos($k, $searchTerm) !== false;
- }, ARRAY_FILTER_USE_KEY);
- }
-
- public function homepageOrderList()
- {
- $searchTerm = "homepageOrder";
- $order = array_filter($this->config, function ($k) use ($searchTerm) {
- return stripos($k, $searchTerm) !== false;
- }, ARRAY_FILTER_USE_KEY);
- asort($order);
- return $order;
- }
-
- public function tautulliList()
- {
- $searchTerm = "tautulli_token";
- return array_filter($this->config, function ($k) use ($searchTerm) {
- return stripos($k, $searchTerm) !== false;
- }, ARRAY_FILTER_USE_KEY);
- }
-
- public function checkPlexAdminFilled()
- {
- if ($this->config['plexAdmin'] == '') {
- return false;
- } else {
- if ((strpos($this->config['plexAdmin'], '@') !== false)) {
- return 'email';
- } else {
- return 'username';
- }
- }
- }
-
- public function organizrSpecialSettings()
- {
- // js activeInfo
- return array(
- 'homepage' => array(
- 'refresh' => $this->refreshList(),
- 'order' => $this->homepageOrderList(),
- 'search' => array(
- 'enabled' => $this->qualifyRequest($this->config['mediaSearchAuth']) && $this->config['mediaSearch'] == true && $this->config['plexToken'],
- 'type' => $this->config['mediaSearchType'],
- ),
- 'requests' => [
- 'service' => $this->config['defaultRequestService'],
- ],
- 'ombi' => array(
- 'enabled' => $this->qualifyRequest($this->config['homepageOmbiAuth']) && $this->qualifyRequest($this->config['homepageOmbiRequestAuth']) && $this->config['homepageOmbiEnabled'] == true && $this->config['ssoOmbi'] && isset($_COOKIE['Auth']),
- 'authView' => $this->qualifyRequest($this->config['homepageOmbiAuth']),
- 'authRequest' => $this->qualifyRequest($this->config['homepageOmbiRequestAuth']),
- 'sso' => (bool)$this->config['ssoOmbi'],
- 'cookie' => isset($_COOKIE['Auth']),
- 'alias' => (bool)$this->config['ombiAlias'],
- 'ombiDefaultFilterAvailable' => (bool)$this->config['ombiDefaultFilterAvailable'],
- 'ombiDefaultFilterUnavailable' => (bool)$this->config['ombiDefaultFilterUnavailable'],
- 'ombiDefaultFilterApproved' => (bool)$this->config['ombiDefaultFilterApproved'],
- 'ombiDefaultFilterUnapproved' => (bool)$this->config['ombiDefaultFilterUnapproved'],
- 'ombiDefaultFilterDenied' => (bool)$this->config['ombiDefaultFilterDenied']
- ),
- 'overseerr' => array(
- 'enabled' => $this->qualifyRequest($this->config['homepageOverseerrAuth']) && $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']) && $this->config['homepageOverseerrEnabled'] == true && $this->config['ssoOverseerr'] && isset($_COOKIE['connect_sid']),
- 'authView' => $this->qualifyRequest($this->config['homepageOverseerrAuth']),
- 'authRequest' => $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']),
- 'sso' => (bool)$this->config['ssoOverseerr'],
- 'cookie' => isset($_COOKIE['connect_sid']),
- 'userSelectTv' => (bool)$this->config['homepageOverseerrRequestAuth'] == 'user',
- 'overseerrDefaultFilterAvailable' => (bool)$this->config['overseerrDefaultFilterAvailable'],
- 'overseerrDefaultFilterUnavailable' => (bool)$this->config['overseerrDefaultFilterUnavailable'],
- 'overseerrDefaultFilterApproved' => (bool)$this->config['overseerrDefaultFilterApproved'],
- 'overseerrDefaultFilterUnapproved' => (bool)$this->config['overseerrDefaultFilterUnapproved'],
- 'overseerrDefaultFilterDenied' => (bool)$this->config['overseerrDefaultFilterDenied']
- ),
- 'jackett' => array(
- 'homepageJackettBackholeDownload' => $this->config['homepageJackettBackholeDownload'] ? true : false
- ),
- 'options' => array(
- 'alternateHomepageHeaders' => $this->config['alternateHomepageHeaders'],
- 'healthChecksTags' => $this->config['healthChecksTags'],
- 'titles' => array(
- 'tautulli' => $this->config['tautulliHeader']
- )
- ),
- 'media' => array(
- 'jellyfin' => $this->config['homepageJellyfinInstead']
- )
- ),
- 'sso' => array(
- 'misc' => array(
- 'oAuthLogin' => isset($_COOKIE['oAuth']),
- 'rememberMe' => $this->config['rememberMe'],
- 'rememberMeDays' => $this->config['rememberMeDays']
- ),
- 'plex' => array(
- 'enabled' => (bool)$this->config['ssoPlex'],
- 'cookie' => isset($_COOKIE['mpt']),
- 'machineID' => strlen($this->config['plexID']) == 40,
- 'token' => $this->config['plexToken'] !== '',
- 'plexAdmin' => $this->checkPlexAdminFilled(),
- 'strict' => (bool)$this->config['plexStrictFriends'],
- 'oAuthEnabled' => (bool)$this->config['plexoAuth'],
- 'backend' => $this->config['authBackend'] == 'plex',
- ),
- 'tautulli' => array(
- 'enabled' => (bool)$this->config['ssoTautulli'],
- 'cookie' => !empty($this->tautulliList()),
- 'url' => ($this->config['tautulliURL'] !== '') ? $this->config['tautulliURL'] : false,
- ),
- 'overseerr' => array(
- 'enabled' => (bool)$this->config['ssoOverseerr'],
- 'cookie' => isset($_COOKIE['connect.sid']),
- 'url' => ($this->config['overseerrURL'] !== '') ? $this->config['overseerrURL'] : false,
- 'api' => $this->config['overseerrToken'] !== '',
- ),
- 'petio' => array(
- 'enabled' => (bool)$this->config['ssoPetio'],
- 'cookie' => isset($_COOKIE['petio_jwt']),
- 'url' => ($this->config['petioURL'] !== '') ? $this->config['petioURL'] : false,
- 'api' => $this->config['petioToken'] !== '',
- ),
- 'ombi' => array(
- 'enabled' => (bool)$this->config['ssoOmbi'],
- 'cookie' => isset($_COOKIE['Auth']),
- 'url' => ($this->config['ombiURL'] !== '') ? $this->config['ombiURL'] : false,
- 'api' => $this->config['ombiToken'] !== '',
- ),
- 'jellyfin' => array(
- 'enabled' => (bool)$this->config['ssoJellyfin'],
- 'url' => ($this->config['jellyfinURL'] !== '') ? $this->config['jellyfinURL'] : false,
- 'ssoUrl' => ($this->config['jellyfinSSOURL'] !== '') ? $this->config['jellyfinSSOURL'] : false,
- ),
- ),
- 'ping' => array(
- 'onlineSound' => $this->config['pingOnlineSound'],
- 'offlineSound' => $this->config['pingOfflineSound'],
- 'statusSounds' => $this->config['statusSounds'],
- 'auth' => $this->config['pingAuth'],
- 'authMessage' => $this->config['pingAuthMessage'],
- 'authMs' => $this->config['pingAuthMs'],
- 'ms' => $this->config['pingMs'],
- 'adminRefresh' => $this->config['adminPingRefresh'],
- 'everyoneRefresh' => $this->config['otherPingRefresh'],
- ),
- 'notifications' => array(
- 'backbone' => $this->config['notificationBackbone'],
- 'position' => $this->config['notificationPosition']
- ),
- 'lockout' => array(
- 'enabled' => $this->config['lockoutSystem'],
- 'timer' => $this->config['lockoutTimeout'],
- 'minGroup' => $this->config['lockoutMinAuth'],
- 'maxGroup' => $this->config['lockoutMaxAuth']
- ),
- 'user' => array(
- 'agent' => isset($_SERVER ['HTTP_USER_AGENT']) ? $_SERVER ['HTTP_USER_AGENT'] : null,
- 'oAuthLogin' => isset($_COOKIE['oAuth']),
- 'local' => $this->isLocal(),
- 'ip' => $this->userIP()
- ),
- 'login' => array(
- 'rememberMe' => $this->config['rememberMe'],
- 'rememberMeDays' => $this->config['rememberMeDays'],
- 'wanDomain' => $this->config['wanDomain'],
- 'localAddress' => $this->config['localAddress'],
- 'enableLocalAddressForward' => $this->config['enableLocalAddressForward'],
- ),
- 'misc' => array(
- 'installedPlugins' => $this->qualifyRequest(1) ? $this->config['installedPlugins'] : '',
- 'installedThemes' => $this->qualifyRequest(1) ? $this->config['installedThemes'] : '',
- 'return' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false,
- 'authDebug' => $this->config['authDebug'],
- 'minimalLoginScreen' => $this->config['minimalLoginScreen'],
- 'unsortedTabs' => $this->config['unsortedTabs'],
- 'authType' => $this->config['authType'],
- 'authBackend' => $this->config['authBackend'],
- 'newMessageSound' => (isset($this->config['CHAT-newMessageSound-include'])) ? $this->config['CHAT-newMessageSound-include'] : '',
- 'uuid' => ($this->config['uuid']) ?? null,
- 'docker' => $this->qualifyRequest(1) ? $this->docker : '',
- 'githubCommit' => $this->qualifyRequest(1) ? $this->commit : '',
- 'schema' => $this->qualifyRequest(1) ? $this->getSchema() : '',
- 'debugArea' => $this->qualifyRequest($this->config['debugAreaAuth']),
- 'debugErrors' => $this->config['debugErrors'],
- 'sandbox' => $this->config['sandbox'],
- 'expandCategoriesByDefault' => $this->config['expandCategoriesByDefault'],
- 'autoCollapseCategories' => $this->config['autoCollapseCategories'],
- 'autoExpandNavBar' => $this->config['autoExpandNavBar'],
- 'sideMenuCollapsed' => $this->config['allowCollapsableSideMenu'] && $this->config['sideMenuCollapsed'],
- 'collapseSideMenuOnClick' => $this->config['allowCollapsableSideMenu'] && $this->config['collapseSideMenuOnClick']
- ),
- 'menuLink' => array(
- 'githubMenuLink' => $this->config['githubMenuLink'],
- 'organizrSupportMenuLink' => $this->config['organizrSupportMenuLink'],
- 'organizrDocsMenuLink' => $this->config['organizrDocsMenuLink'],
- 'organizrSignoutMenuLink' => $this->config['organizrSignoutMenuLink'],
- 'organizrFeatureRequestLink' => $this->config['organizrFeatureRequestLink']
- )
- );
- }
-
- public function getLog($log, $reverse = true)
- {
- switch ($log) {
- case 'login':
- case 'loginLog':
- case 'loginlog':
- $file = $this->organizrLoginLog;
- $parent = 'auth';
- break;
- case 'org':
- case 'organizr':
- case 'organizrLog':
- case 'orglog':
- $file = $this->organizrLog;
- $parent = 'log_items';
- break;
- default:
- $this->setAPIResponse('error', 'Log not defined', 404);
- return null;
- }
- if (!file_exists($file)) {
- $this->setAPIResponse('error', 'Log does not exist', 404);
- return null;
- }
- $getLog = str_replace("\r\ndate", "date", file_get_contents($file));
- $gotLog = json_decode($getLog, true);
- return ($reverse) ? array_reverse($gotLog[$parent]) : $gotLog[$parent];
- }
-
- public function purgeLog($log)
- {
-
- switch ($log) {
- case 'login':
- case 'loginLog':
- case 'loginlog':
- $file = $this->organizrLoginLog;
- break;
- case 'org':
- case 'organizr':
- case 'organizrLog':
- case 'orgLog':
- case 'orglog':
- $file = $this->organizrLog;
- break;
- default:
- $this->setAPIResponse('error', 'Log not defined', 404);
- return null;
- }
- if (file_exists($file)) {
- if (unlink($file)) {
- $this->writeLog('success', 'Log Management Function - Log: ' . $log . ' has been purged/deleted', 'SYSTEM');
- $this->setAPIResponse(null, 'Log purged');
- return true;
- } else {
- $this->writeLog('error', 'Log Management Function - Log: ' . $log . ' - Error Occurred', 'SYSTEM');
- $this->setAPIResponse('error', 'Log could not be purged', 500);
- return false;
- }
- } else {
- $this->setAPIResponse('error', 'Log does not exist', 404);
- return false;
- }
-
- }
-
- public function checkLog($path)
- {
- if (file_exists($path)) {
- if (filesize($path) > 500000) {
- rename($path, $path . '[' . date('Y-m-d') . '].json');
- return false;
- }
- return true;
- } else {
- return false;
- }
- }
-
- public function writeLoginLog($username, $authType)
- {
- $username = htmlspecialchars($username, ENT_QUOTES);
- if ($this->checkLog($this->organizrLoginLog)) {
- $getLog = str_replace("\r\ndate", "date", file_get_contents($this->organizrLoginLog));
- $gotLog = json_decode($getLog, true);
- }
- $logEntryFirst = array('logType' => 'login_log', 'auth' => array(array('date' => date("Y-m-d H:i:s"), 'utc_date' => $this->currentTime, 'username' => $username, 'ip' => $this->userIP(), 'auth_type' => $authType)));
- $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $this->currentTime, 'username' => $username, 'ip' => $this->userIP(), 'auth_type' => $authType);
- if (isset($gotLog)) {
- array_push($gotLog["auth"], $logEntry);
- $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
- } else {
- $writeFailLog = str_replace("date", "\r\ndate", json_encode($logEntryFirst));
- }
- file_put_contents($this->organizrLoginLog, $writeFailLog);
- }
-
- public function writeLog($type = 'error', $message = null, $username = null)
- {
- $this->timeExecution = $this->timeExecution($this->timeExecution);
- $message = $message . ' [Execution Time: ' . $this->formatSeconds($this->timeExecution) . ']';
- $username = ($username) ? htmlspecialchars($username, ENT_QUOTES) : $this->user['username'] ?? 'SYSTEM';
- if ($this->checkLog($this->organizrLog)) {
- $getLog = str_replace("\r\ndate", "date", file_get_contents($this->organizrLog));
- $gotLog = json_decode($getLog, true);
- }
- $logEntryFirst = array('logType' => 'organizr_log', 'log_items' => array(array('date' => date("Y-m-d H:i:s"), 'utc_date' => $this->currentTime, 'type' => $type, 'username' => $username, 'ip' => $this->userIP(), 'message' => $message)));
- $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $this->currentTime, 'type' => $type, 'username' => $username, 'ip' => $this->userIP(), 'message' => $message);
- if (isset($gotLog)) {
- array_push($gotLog["log_items"], $logEntry);
- $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
- } else {
- $writeFailLog = str_replace("date", "\r\ndate", json_encode($logEntryFirst));
- }
- file_put_contents($this->organizrLog, $writeFailLog);
- }
-
- public function isApprovedRequest($method, $data)
- {
- $requesterToken = $this->getallheaders()['Token'] ?? ($_GET['apikey'] ?? false);
- $apiKey = ($this->config['organizrAPI']) ?? null;
- if (isset($data['formKey'])) {
- $formKey = $data['formKey'];
- } elseif (isset($this->getallheaders()['Formkey'])) {
- $formKey = $this->getallheaders()['Formkey'];
- } elseif (isset($this->getallheaders()['formkey'])) {
- $formKey = $this->getallheaders()['formkey'];
- } elseif (isset($this->getallheaders()['formKey'])) {
- $formKey = $this->getallheaders()['formKey'];
- } elseif (isset($this->getallheaders()['FormKey'])) {
- $formKey = $this->getallheaders()['FormKey'];
- } else {
- $formKey = false;
- }
- // Check token or API key
- // If API key, return 0 for admin
- if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
- //DO API CHECK
- return true;
- } elseif ($method == 'POST') {
- if ($this->checkFormKey($formKey)) {
- return true;
- } else {
- $this->writeLog('error', 'API ERROR: Unable to authenticate Form Key: ' . $formKey, $this->user['username']);
- return false;
- }
- } else {
- return true;
- }
- return false;
- }
-
- public function checkFormKey($formKey = '')
- {
- return password_verify(substr($this->config['organizrHash'], 2, 10), $formKey);
- }
-
- public function buildHomepage()
- {
- $homepageOrder = $this->homepageOrderList();
- $homepageBuilt = '';
- foreach ($homepageOrder as $key => $value) {
- //new way
- if (method_exists($this, $key)) {
- $homepageBuilt .= $this->$key();
- } elseif (strpos($key, 'homepageOrdercustomhtml') !== false) {
- $iteration = substr($key, -2);
- $homepageBuilt .= $this->homepageOrdercustomhtml($iteration);
- } else {
- $homepageBuilt .= '<div id="' . $key . '"></div>';
- }
- //old way
- //$homepageBuilt .= $this->buildHomepageItem($key);
- }
- return $homepageBuilt;
- }
-
- public function buildHomepageSettings()
- {
- $homepageOrder = $this->homepageOrderList();
- $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">';
- $inputList = '<form id="homepage-values" class="row">';
- foreach ($homepageOrder as $key => $val) {
- switch ($key) {
- case 'homepageOrdercustomhtml01':
- case 'homepageOrdercustomhtml02':
- case 'homepageOrdercustomhtml03':
- case 'homepageOrdercustomhtml04':
- case 'homepageOrdercustomhtml05':
- case 'homepageOrdercustomhtml06':
- case 'homepageOrdercustomhtml07':
- case 'homepageOrdercustomhtml08':
- $iteration = substr($key, -2);
- $class = 'bg-info';
- $image = 'plugins/images/tabs/HTML5.png';
- if (!$this->config['homepageCustomHTML' . $iteration . 'Enabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrdertransmission':
- $class = 'bg-transmission';
- $image = 'plugins/images/tabs/transmission.png';
- if (!$this->config['homepageTransmissionEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrdernzbget':
- $class = 'bg-nzbget';
- $image = 'plugins/images/tabs/nzbget.png';
- if (!$this->config['homepageNzbgetEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderjdownloader':
- $class = 'bg-sab';
- $image = 'plugins/images/tabs/jdownloader.png';
- if (!$this->config['homepageJdownloaderEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrdersabnzbd':
- $class = 'bg-sab';
- $image = 'plugins/images/tabs/sabnzbd.png';
- if (!$this->config['homepageSabnzbdEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderdeluge':
- $class = 'bg-deluge';
- $image = 'plugins/images/tabs/deluge.png';
- if (!$this->config['homepageDelugeEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderqBittorrent':
- $class = 'bg-qbit';
- $image = 'plugins/images/tabs/qBittorrent.png';
- if (!$this->config['homepageqBittorrentEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderuTorrent':
- $class = 'bg-qbit';
- $image = 'plugins/images/tabs/utorrent.png';
- if (!$this->config['homepageuTorrentEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderrTorrent':
- $class = 'bg-qbit';
- $image = 'plugins/images/tabs/rTorrent.png';
- if (!$this->config['homepagerTorrentEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderplexnowplaying':
- case 'homepageOrderplexrecent':
- case 'homepageOrderplexplaylist':
- $class = 'bg-plex';
- $image = 'plugins/images/tabs/plex.png';
- if (!$this->config['homepagePlexEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderembynowplaying':
- case 'homepageOrderembyrecent':
- $class = 'bg-emby';
- $image = 'plugins/images/tabs/emby.png';
- if (!$this->config['homepageEmbyEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderjellyfinnowplaying':
- case 'homepageOrderjellyfinrecent':
- $class = 'bg-jellyfin';
- $image = 'plugins/images/tabs/jellyfin.png';
- if (!$this->config['homepageJellyfinEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderombi':
- $class = 'bg-inverse';
- $image = 'plugins/images/tabs/ombi.png';
- if (!$this->config['homepageOmbiEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderoverseerr':
- $class = 'bg-inverse';
- $image = 'plugins/images/tabs/overseerr.png';
- if (!$this->config['homepageOverseerrEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrdercalendar':
- $class = 'bg-primary';
- $image = 'plugins/images/tabs/calendar.png';
- if (!$this->config['homepageCalendarEnabled'] && !$this->config['homepageSonarrEnabled'] && !$this->config['homepageRadarrEnabled'] && !$this->config['homepageSickrageEnabled'] && !$this->config['homepageCouchpotatoEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderdownloader':
- $class = 'bg-inverse';
- $image = 'plugins/images/tabs/downloader.png';
- 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']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderhealthchecks':
- $class = 'bg-healthchecks';
- $image = 'plugins/images/tabs/healthchecks.png';
- if (!$this->config['homepageHealthChecksEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderunifi':
- $class = 'bg-info';
- $image = 'plugins/images/tabs/ubnt.png';
- if (!$this->config['homepageUnifiEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrdertautulli':
- $class = 'bg-info';
- $image = 'plugins/images/tabs/tautulli.png';
- if (!$this->config['homepageTautulliEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderPihole':
- $class = 'bg-info';
- $image = 'plugins/images/tabs/pihole.png';
- if (!$this->config['homepagePiholeEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderMonitorr':
- $class = 'bg-info';
- $image = 'plugins/images/tabs/monitorr.png';
- if (!$this->config['homepageMonitorrEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderWeatherAndAir':
- $class = 'bg-success';
- $image = 'plugins/images/tabs/wind.png';
- if (!$this->config['homepageWeatherAndAirEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderSpeedtest':
- $class = 'bg-success';
- $image = 'plugins/images/tabs/speedtest-icon.png';
- if (!$this->config['homepageSpeedtestEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderNetdata':
- $class = 'bg-success';
- $image = 'plugins/images/tabs/netdata.png';
- if (!$this->config['homepageNetdataEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderOctoprint':
- $class = 'bg-success';
- $image = 'plugins/images/tabs/octoprint.png';
- if (!$this->config['homepageOctoprintEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderSonarrQueue':
- $class = 'bg-sonarr';
- $image = 'plugins/images/tabs/sonarr.png';
- if (!$this->config['homepageSonarrQueueEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderRadarrQueue':
- $class = 'bg-radarr';
- $image = 'plugins/images/tabs/radarr.png';
- if (!$this->config['homepageRadarrQueueEnabled']) {
- $class .= ' faded';
- }
- break;
- case 'homepageOrderJackett':
- $class = 'bg-inverse';
- $image = 'plugins/images/tabs/jackett.png';
- if (!$this->config['homepageJackettEnabled']) {
- $class .= ' faded';
- }
- break;
- default:
- $class = 'blue-bg';
- $image = '';
- break;
- }
- $homepageList .= '
- <div class="col-md-3 col-xs-12 sort-homepage m-t-10 hvr-grow clearfix">
- <div class="homepage-drag fc-event ' . $class . ' lazyload" data-src="' . $image . '">
- <span class="ordinal-position text-uppercase badge bg-org homepage-number" data-link="' . $key . '" style="float:left;width: 30px;">' . $val . '</span>
- <span class="homepage-text"> ' . strtoupper(substr($key, 13)) . '</span>
- </div>
- </div>
- ';
- $inputList .= '<input type="hidden" name="' . $key . '">';
- }
- $homepageList .= '</div>';
- $inputList .= '</form>';
- return $homepageList . $inputList;
- }
-
- public function setGroupOptionsVariable()
- {
- $this->groupOptions = $this->groupSelect();
- }
-
- public function getSettingsHomepageItem($item)
- {
- $items = $this->getSettingsHomepage();
- foreach ($items as $k => $v) {
- if (strtolower($v['name']) === strtolower($item)) {
- $functionName = $v['settingsArray'];
- return $this->$functionName();
- }
- }
- $this->setAPIResponse('error', 'Homepage item was not found', 404);
- return null;
- }
-
- public function getSettingsHomepageItemDebug($service)
- {
- $service = $this->getSettingsHomepageItem($service);
- if ($service) {
- $debug = [];
- foreach ($service['settings'] as $category => $items) {
- if ($category !== 'About' && $category !== 'Test Connection') {
- foreach ($items as $item) {
- if ($item['type'] !== 'html' && $item['type'] !== 'blank' && $item['type'] !== 'button') {
- if ((stripos($item['name'], 'token') !== false) || (stripos($item['name'], 'key') !== false) || (stripos($item['name'], 'password'))) {
- if ($item['value'] !== '') {
- $item['value'] = '***redacted***';
- }
- }
- $debug[$category][$item['name']] = $item['value'];
- }
- }
- }
- }
- return $debug;
- }
- $this->setAPIResponse('error', 'Homepage item was not found', 404);
- return null;
- }
-
- public function getSettingsHomepage()
- {
- $this->setGroupOptionsVariable();
- return $this->getHomepageSettingsCombined();
- }
-
- public function isTabNameTaken($name, $id = null)
- {
- if ($id) {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM tabs WHERE `name` LIKE ? AND `id` != ?',
- $name,
- $id
- )
- ),
- ];
- } else {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM tabs WHERE `name` LIKE ?',
- $name
- )
- ),
- ];
- }
- return $this->processQueries($response);
- }
-
- public function isCategoryNameTaken($name, $id = null)
- {
- if ($id) {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM categories WHERE `category` LIKE ? AND `id` != ?',
- $name,
- $id
- )
- ),
- ];
- } else {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM categories WHERE `category` LIKE ?',
- $name
- )
- ),
- ];
- }
- return $this->processQueries($response);
- }
-
- public function isGroupNameTaken($name, $id = null)
- {
- if ($id) {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM groups WHERE `group` LIKE ? AND `id` != ?',
- $name,
- $id
- )
- ),
- ];
- } else {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM groups WHERE `group` LIKE ?',
- $name
- )
- ),
- ];
- }
- return $this->processQueries($response);
- }
-
- public function getTableColumns($table)
- {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'PRAGMA table_info(?)',
- $table
- )
- ),
- ];
- return $this->processQueries($response);
-
- }
-
- public function getTableColumnsFormatted($table)
- {
- $columns = $this->getTableColumns($table);
- if ($columns) {
- $columnsFormatted = [];
- foreach ($columns as $k => $v) {
- $columnsFormatted[$v['name']] = $v;
- }
- return $columnsFormatted;
- } else {
- return false;
- }
- }
-
- public function getTabById($id)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM tabs WHERE `id` = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getTabGroupByTabName($tab)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT group_id FROM tabs WHERE name LIKE %~like~',
- $tab
- )
- ),
- ];
- $query = $this->processQueries($response);
- return $query ? $query['group_id'] : 0;
- }
-
- public function getCategoryById($id)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM categories WHERE `id` = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getGroupUserCountById($id)
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT count(username) AS count FROM groups INNER JOIN users ON users.group_id = groups.group_id AND groups.id = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getGroupById($id)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM groups WHERE `id` = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getGroupByGroupId($id)
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM groups WHERE `group_id` = ?',
- $id
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getDefaultGroup()
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM groups WHERE `default` = 1'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getDefaultGroupId()
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT `group_id` FROM groups WHERE `default` = 1'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getDefaultCategory()
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => array(
- 'SELECT * FROM categories WHERE `default` = 1'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getDefaultCategoryId()
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT `category_id` FROM categories WHERE `default` = 1'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getNextTabOrder()
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT `order` from tabs ORDER BY `order` DESC'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getNextCategoryOrder()
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT `order` from categories ORDER BY `order` DESC'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getNextGroupOrder()
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT `group_id` from groups WHERE `group_id` != "999" ORDER BY `group_id` DESC'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function getNextCategoryId()
- {
- $response = [
- array(
- 'function' => 'fetchSingle',
- 'query' => array(
- 'SELECT `category_id` from categories ORDER BY `category_id` DESC'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function clearTabDefault()
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE tabs SET `default` = 0'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function clearCategoryDefault()
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE categories SET `default` = 0'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function clearGroupDefault()
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE groups SET `default` = 0'
- )
- ),
- ];
- return $this->processQueries($response);
- }
-
- public function checkKeys($tabInfo, $newData)
- {
- foreach ($newData as $k => $v) {
- if (!array_key_exists($k, $tabInfo)) {
- unset($newData[$k]);
- }
- }
- return $newData;
- }
-
- public function getTabByIdCheckUser($id)
- {
- $tabInfo = $this->getTabById($id);
- if ($tabInfo) {
- if ($this->qualifyRequest($tabInfo['group_id'], true)) {
- return $tabInfo;
- }
- } else {
- $this->setAPIResponse('error', 'id not found', 404);
- return false;
- }
- }
-
- public function deleteTab($id)
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM tabs WHERE id = ?',
- $id
- )
- ),
- ];
- $tabInfo = $this->getTabById($id);
- if ($tabInfo) {
- $this->writeLog('success', 'Tab Delete Function - Deleted Tab [' . $tabInfo['name'] . ']', $this->user['username']);
- $this->setAPIResponse('success', 'Tab deleted', 204);
- return $this->processQueries($response);
- } else {
- $this->setAPIResponse('error', 'id not found', 404);
- return false;
- }
- }
-
- public function addTab($array)
- {
- if (!$array) {
- $this->setAPIResponse('error', 'no data was sent', 422);
- return null;
- }
- $array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
- $array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
- $array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
- $array['enabled'] = ($array['enabled']) ?? 0;
- $array['default'] = ($array['default']) ?? 0;
- $array['type'] = ($array['type']) ?? 1;
- $array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
- if (array_key_exists('name', $array)) {
- if ($this->isTabNameTaken($array['name'])) {
- $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
- return false;
- }
- } else {
- $this->setAPIResponse('error', 'Tab name was not supplied', 422);
- return false;
- }
- if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
- $this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
- return false;
- }
- if (!array_key_exists('image', $array)) {
- $this->setAPIResponse('error', 'Tab image was not supplied', 422);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [tabs]',
- $array
- )
- ),
- ];
- $this->setAPIResponse(null, 'Tab added');
- $this->writeLog('success', 'Tab Editor Function - Added Tab for [' . $array['name'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function updateTab($id, $array)
- {
- if (!$id || $id == '') {
- $this->setAPIResponse('error', 'id was not set', 422);
- return null;
- }
- if (!$array) {
- $this->setAPIResponse('error', 'no data was sent', 422);
- return null;
- }
- $tabInfo = $this->getTabById($id);
- if ($tabInfo) {
- $array = $this->checkKeys($tabInfo, $array);
- } else {
- $this->setAPIResponse('error', 'No tab info found', 404);
- return false;
- }
- if (array_key_exists('name', $array)) {
- if ($this->isTabNameTaken($array['name'], $id)) {
- $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
- return false;
- }
- }
- if (array_key_exists('default', $array)) {
- if ($array['default']) {
- $this->clearTabDefault();
- }
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE tabs SET',
- $array,
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- $this->setAPIResponse(null, 'Tab info updated');
- $this->writeLog('success', 'Tab Editor Function - Edited Tab Info for [' . $tabInfo['name'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function updateTabOrder($array)
- {
- if (count($array) >= 1) {
- foreach ($array as $tab) {
- if (count($tab) !== 2) {
- $this->setAPIResponse('error', 'data is malformed', 422);
- break;
- }
- $id = $tab['id'] ?? null;
- $order = $tab['order'] ?? null;
- if ($id && $order) {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE tabs set `order` = ? WHERE `id` = ?',
- $order,
- $id
- )
- ),
- ];
- $this->processQueries($response);
- $this->setAPIResponse(null, 'Tab Order updated');
- } else {
- $this->setAPIResponse('error', 'data is malformed', 422);
- }
- }
- } else {
- $this->setAPIResponse('error', 'data is empty or not in array', 422);
- return false;
- }
- }
-
- public function addCategory($array)
- {
- if (!$array) {
- $this->setAPIResponse('error', 'no data was sent', 422);
- return null;
- }
- $array = $this->checkKeys($this->getTableColumnsFormatted('categories'), $array);
- $array['default'] = ($array['default']) ?? 0;
- $array['order'] = ($array['order']) ?? $this->getNextCategoryOrder() + 1;
- $array['category_id'] = ($array['category_id']) ?? $this->getNextCategoryId() + 1;
- if (array_key_exists('category', $array)) {
- if ($this->isCategoryNameTaken($array['category'])) {
- $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
- return false;
- }
- } else {
- $this->setAPIResponse('error', 'Category name was not supplied', 422);
- return false;
- }
- if (!array_key_exists('image', $array)) {
- $this->setAPIResponse('error', 'Category image was not supplied', 422);
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [categories]',
- $array
- )
- ),
- ];
- $this->setAPIResponse(null, 'Category added');
- $this->writeLog('success', 'Category Editor Function - Added Category for [' . $array['category'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function updateCategory($id, $array)
- {
- if (!$id || $id == '') {
- $this->setAPIResponse('error', 'id was not set', 422);
- return null;
- }
- if (!$array) {
- $this->setAPIResponse('error', 'no data was sent', 422);
- return null;
- }
- $categoryInfo = $this->getCategoryById($id);
- if ($categoryInfo) {
- $array = $this->checkKeys($categoryInfo, $array);
- } else {
- $this->setAPIResponse('error', 'No category info found', 404);
- return false;
- }
- if (array_key_exists('category', $array)) {
- if ($this->isCategoryNameTaken($array['category'], $id)) {
- $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
- return false;
- }
- }
- if (array_key_exists('default', $array)) {
- if ($array['default']) {
- $this->clearCategoryDefault();
- }
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE categories SET',
- $array,
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- $this->setAPIResponse(null, 'Category info updated');
- $this->writeLog('success', 'Category Editor Function - Edited Category Info for [' . $categoryInfo['category'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function updateCategoryOrder($array)
- {
- if (count($array) >= 1) {
- foreach ($array as $category) {
- if (count($category) !== 2) {
- $this->setAPIResponse('error', 'data is malformed', 422);
- break;
- }
- $id = $category['id'] ?? null;
- $order = $category['order'] ?? null;
- if ($id && $order) {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE categories set `order` = ? WHERE `id` = ?',
- $order,
- $id
- )
- ),
- ];
- $this->processQueries($response);
- $this->setAPIResponse(null, 'Category Order updated');
- } else {
- $this->setAPIResponse('error', 'data is malformed', 422);
- }
- }
- } else {
- $this->setAPIResponse('error', 'data is empty or not in array', 422);
- return false;
- }
- }
-
- public function deleteCategory($id)
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM categories WHERE id = ?',
- $id
- )
- ),
- ];
- $categoryInfo = $this->getCategoryById($id);
- if ($categoryInfo) {
- $this->writeLog('success', 'Category Delete Function - Deleted Category [' . $categoryInfo['category'] . ']', $this->user['username']);
- $this->setAPIResponse('success', 'Category deleted', 204);
- return $this->processQueries($response);
- } else {
- $this->setAPIResponse('error', 'id not found', 404);
- return false;
- }
- }
-
- public function inconspicuous(): string
- {
- if ($this->hasDB()) {
- if ($this->config['easterEggs']) {
- return '
- <div class="org-rox-trigger">
- <div class="org-rox">
- <div class="hair"></div>
- <div class="head">
- <div class="ear left"></div>
- <div class="ear right"></div>
- <div class="face">
- <div class="eye left"></div>
- <div class="eye right"></div>
- <div class="nose"></div>
- <div class="mouth"></div>
- </div>
- </div>
- </div>
- </div>';
- }
- }
- return '';
- }
-
- public function marketplaceFileListFormat($files, $folder, $type)
- {
- foreach ($files as $k => $v) {
- $splitFiles = explode('|', $v);
- $prePath = (strlen($k) !== 1) ? $k . '/' : $k;
- foreach ($splitFiles as $file) {
- $filesList[] = array(
- 'fileName' => $file,
- 'path' => $prePath,
- 'githubPath' => 'https://raw.githubusercontent.com/causefx/Organizr/v2-' . $type . '/' . $folder . $prePath . $file
- );
- }
- }
- return $filesList;
-
- }
-
- public function removeTheme($theme)
- {
- $theme = $this->reverseCleanClassName($theme);
- $array = $this->getThemesGithub();
- $arrayLower = array_change_key_case($array);
- if (!$array) {
- $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
- return false;
- }
- if (!$arrayLower[$theme]) {
- $this->setAPIResponse('error', 'Theme does not exist in marketplace', 404);
- return false;
- } else {
- $key = array_search($theme, array_keys($arrayLower));
- $theme = array_keys($array)[$key];
- }
- $array = $array[$theme];
- $downloadList = $this->marketplaceFileListFormat($array['files'], $array['github_folder'], 'themes');
- if (!$downloadList) {
- $this->setAPIResponse('error', 'Could not get download list for theme', 409);
- return false;
- }
- $name = $theme;
- $version = $array['version'];
- $installedThemesNew = '';
- foreach ($downloadList as $k => $v) {
- $file = array(
- 'from' => $v['githubPath'],
- 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->root . $v['path'] . $v['fileName']),
- 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->root . $v['path'])
- );
- if (!$this->rrmdir($file['to'])) {
- $this->writeLog('error', 'Theme Function - Remove File Failed for: ' . $v['githubPath'], $this->user['username']);
- return false;
- }
- }
- if ($this->config['installedThemes'] !== '') {
- $installedThemes = explode('|', $this->config['installedThemes']);
- foreach ($installedThemes as $k => $v) {
- $themes = explode(':', $v);
- $installedThemesList[$themes[0]] = $themes[1];
- }
- if (isset($installedThemesList[$name])) {
- foreach ($installedThemesList as $k => $v) {
- if ($k !== $name) {
- if ($installedThemesNew == '') {
- $installedThemesNew .= $k . ':' . $v;
- } else {
- $installedThemesNew .= '|' . $k . ':' . $v;
- }
- }
- }
- }
- }
- $this->updateConfig(array('installedThemes' => $installedThemesNew));
- $this->setAPIResponse('success', 'Theme removed', 200, $installedThemesNew);
- return true;
- }
-
- public function installTheme($theme)
- {
- $theme = $this->reverseCleanClassName($theme);
- $array = $this->getThemesGithub();
- $arrayLower = array_change_key_case($array);
- if (!$array) {
- $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
- return false;
- }
- if (!$arrayLower[$theme]) {
- $this->setAPIResponse('error', 'Theme does not exist in marketplace', 404);
- return false;
- } else {
- $key = array_search($theme, array_keys($arrayLower));
- $theme = array_keys($array)[$key];
- }
- $array = $array[$theme];
- $downloadList = $this->marketplaceFileListFormat($array['files'], $array['github_folder'], 'themes');
- if (!$downloadList) {
- $this->setAPIResponse('error', 'Could not get download list for theme', 409);
- return false;
- }
- $name = $theme;
- $version = $array['version'];
- foreach ($downloadList as $k => $v) {
- $file = array(
- 'from' => $v['githubPath'],
- 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->root . $v['path'] . $v['fileName']),
- 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->root . $v['path'])
- );
- if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
- $this->writeLog('error', 'Theme Function - Downloaded File Failed for: ' . $v['githubPath'], $this->user['username']);
- $this->setAPIResponse('error', 'Theme download failed', 500);
- return false;
- }
- }
- if ($this->config['installedThemes'] !== '') {
- $installedThemes = explode('|', $this->config['installedThemes']);
- foreach ($installedThemes as $k => $v) {
- $themes = explode(':', $v);
- $installedThemesList[$themes[0]] = $themes[1];
- }
- if (isset($installedThemesList[$name])) {
- $installedThemesList[$name] = $version;
- $installedThemesNew = '';
- foreach ($installedThemesList as $k => $v) {
- if ($installedThemesNew == '') {
- $installedThemesNew .= $k . ':' . $v;
- } else {
- $installedThemesNew .= '|' . $k . ':' . $v;
- }
- }
- } else {
- $installedThemesNew = $this->config['installedThemes'] . '|' . $name . ':' . $version;
- }
- } else {
- $installedThemesNew = $name . ':' . $version;
- }
- $this->updateConfig(array('installedThemes' => $installedThemesNew));
- $this->setAPIResponse('success', 'Theme installed', 200, $installedThemesNew);
- return true;
- }
-
- public function removePlugin($plugin)
- {
- $plugin = $this->reverseCleanClassName($plugin);
- $array = $this->getPluginsGithub();
- $arrayLower = array_change_key_case($array);
- if (!$array) {
- $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
- return false;
- }
- if (!$arrayLower[$plugin]) {
- $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
- return false;
- } else {
- $key = array_search($plugin, array_keys($arrayLower));
- $plugin = array_keys($array)[$key];
- }
- $array = $array[$plugin];
- $name = $plugin;
- $version = $array['version'];
- $installedPluginsNew = '';
- $pluginDir = $this->root . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $array['github_folder'] . DIRECTORY_SEPARATOR;
- $dirExists = file_exists($pluginDir);
- if ($dirExists) {
- if (!$this->rrmdir($pluginDir)) {
- $this->writeLog('error', 'Plugin Function - Remove File Failed for: ' . $array['github_folder'], $this->user['username']);
- return false;
- }
- } else {
- $this->setAPIResponse('error', 'Plugin is not installed', 404);
- return false;
- }
- if ($this->config['installedPlugins'] !== '') {
- $installedPlugins = explode('|', $this->config['installedPlugins']);
- foreach ($installedPlugins as $k => $v) {
- $plugins = explode(':', $v);
- $installedPluginsList[$plugins[0]] = $plugins[1];
- }
- if (isset($installedPluginsList[$name])) {
- foreach ($installedPluginsList as $k => $v) {
- if ($k !== $name) {
- if ($installedPluginsNew == '') {
- $installedPluginsNew .= $k . ':' . $v;
- } else {
- $installedPluginsNew .= '|' . $k . ':' . $v;
- }
- }
- }
- }
- }
- $this->updateConfig(array('installedPlugins' => $installedPluginsNew));
- $this->setAPIResponse('success', 'Plugin removed', 200, $installedPluginsNew);
- return true;
- }
-
- public function pluginFileListFormat($files, $folder)
- {
- $filesList = false;
- foreach ($files as $k => $v) {
- $filesList[] = array(
- 'fileName' => $v['name'],
- 'path' => DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR,
- 'githubPath' => $v['download_url']
- );
- }
- return $filesList;
- }
-
- public function getPluginFilesFromGithub($plugin = 'test')
- {
- $url = 'https://api.github.com/repos/causefx/organizr/contents/' . $plugin . '?ref=v2-plugins';
- $options = array('verify' => false);
- $response = Requests::get($url, array(), $options);
- if ($response->success) {
- return json_decode($response->body, true);
- }
- return false;
- }
-
- public function installPlugin($plugin)
- {
- $plugin = $this->reverseCleanClassName($plugin);
- $array = $this->getPluginsGithub();
- $arrayLower = array_change_key_case($array);
- if (!$array) {
- $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
- return false;
- }
- if (!$arrayLower[$plugin]) {
- $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
- return false;
- } else {
- $key = array_search($plugin, array_keys($arrayLower));
- $plugin = array_keys($array)[$key];
- }
- $array = $array[$plugin];
- // Check Version of Organizr against minimum version needed
- $compare = new Composer\Semver\Comparator;
- if (!$compare->lessThan($array['minimum_organizr_version'], $this->version)) {
- $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
- return true;
- }
- $files = $this->getPluginFilesFromGithub($array['github_folder']);
- if ($files) {
- $downloadList = $this->pluginFileListFormat($files, $array['github_folder']);
- } else {
- $this->writeLog('error', 'Plugin Function - Downloaded File Failed for: ' . $array['github_folder'], $this->user['username']);
- $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
- return false;
- }
- if (!$downloadList) {
- $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
- return false;
- }
- $name = $plugin;
- $version = $array['version'];
- foreach ($downloadList as $k => $v) {
- $file = array(
- 'from' => $v['githubPath'],
- 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->root . $v['path'] . $v['fileName']),
- 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->root . $v['path'])
- );
- if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
- $this->writeLog('error', 'Plugin Function - Downloaded File Failed for: ' . $v['githubPath'], $this->user['username']);
- $this->setAPIResponse('error', 'Plugin download failed', 500);
- return false;
- }
- }
- if ($this->config['installedPlugins'] !== '') {
- $installedPlugins = explode('|', $this->config['installedPlugins']);
- foreach ($installedPlugins as $k => $v) {
- $plugins = explode(':', $v);
- $installedPluginsList[$plugins[0]] = $plugins[1];
- }
- if (isset($installedPluginsList[$name])) {
- $installedPluginsList[$name] = $version;
- $installedPluginsNew = '';
- foreach ($installedPluginsList as $k => $v) {
- if ($installedPluginsNew == '') {
- $installedPluginsNew .= $k . ':' . $v;
- } else {
- $installedPluginsNew .= '|' . $k . ':' . $v;
- }
- }
- } else {
- $installedPluginsNew = $this->config['installedPlugins'] . '|' . $name . ':' . $version;
- }
- } else {
- $installedPluginsNew = $name . ':' . $version;
- }
- $this->updateConfig(array('installedPlugins' => $installedPluginsNew));
- $this->setAPIResponse('success', 'Plugin installed', 200, $installedPluginsNew);
- return true;
- }
-
- public function getThemesGithub()
- {
- $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-themes/themes.json';
- $options = ($this->localURL($url)) ? array('verify' => false) : array();
- $response = Requests::get($url, array(), $options);
- if ($response->success) {
- return json_decode($response->body, true);
- }
- return false;
- }
-
- public function getPluginsGithub()
- {
- $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-plugins/plugins.json';
- $options = ($this->localURL($url)) ? array('verify' => false) : array();
- try {
- $response = Requests::get($url, array(), $options);
- if ($response->success) {
- return json_decode($response->body, true);
- }
- } catch (Requests_Exception $e) {
- return false;
- }
- return false;
- }
-
- public function getOpenCollectiveBackers()
- {
- $url = 'https://opencollective.com/organizr/members/users.json?limit=100&offset=0';
- $options = ($this->localURL($url)) ? array('verify' => false) : array();
- try {
- $response = Requests::get($url, array(), $options);
- if ($response->success) {
- $api = json_decode($response->body, true);
- foreach ($api as $k => $backer) {
- $api[$k] = array_merge($api[$k], ['sortName' => strtolower($backer['name'])]);
- }
- $this->setAPIResponse('success', '', 200, $api);
- return $api;
- }
- } catch (Requests_Exception $e) {
- $this->setAPIResponse('error', $e->getMessage(), 500);
- return false;
- }
- $this->setAPIResponse('error', 'Error connecting to Open Collective', 409);
- return false;
- }
-
- public function getGithubSponsors()
- {
- $url = 'https://github.com/sponsors/causefx';
- $options = ($this->localURL($url)) ? array('verify' => false) : array();
- $response = Requests::get($url, array(), $options);
- if ($response->success) {
- $sponsors = [];
- $dom = new PHPHtmlParser\Dom;
- try {
- $dom->loadStr($response->body);
- $contents = $dom->find('#sponsors .clearfix div');
- foreach ($contents as $content) {
- $html = $content->innerHtml;
- preg_match('/(@[a-zA-Z])\w+/', $html, $username);
- preg_match('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»""\'\']))/', $html, $image);
- if (isset($image[0]) && isset($username[0])) {
- $sponsors[] = [
- 'name' => str_replace('@', '', $username[0]),
- 'sortName' => str_replace('@', '', strtolower($username[0])),
- 'image' => str_replace('s=60', 's=200', $image[0]),
- 'isActive' => true,
- 'type' => 'USER',
- 'role' => 'BACKER'
- ];
- }
- }
- $this->setAPIResponse('success', '', 200, $sponsors);
- return $sponsors;
- } catch (\PHPHtmlParser\Exceptions\ChildNotFoundException | \PHPHtmlParser\Exceptions\CircularException | \PHPHtmlParser\Exceptions\LogicalException | \PHPHtmlParser\Exceptions\StrictException | \PHPHtmlParser\Exceptions\ContentLengthException | \PHPHtmlParser\Exceptions\NotLoadedException $e) {
- $this->setAPIResponse('error', 'Error connecting to Github', 409);
- return false;
- }
- }
- $this->setAPIResponse('error', 'Error connecting to Github', 409);
- return false;
- }
-
- public function getAllSponsors()
- {
- $sponsors = [];
- $list = [
- 'openCollective' => $this->getOpenCollectiveBackers(),
- 'github' => $this->getGithubSponsors()
- ];
- foreach ($list as $k => $sponsor) {
- if ($sponsor) {
- $sponsors = array_merge($sponsor, $sponsors);
- }
- }
- if ($sponsors) {
- usort($sponsors, function ($a, $b) {
- return $a['sortName'] <=> $b['sortName'];
- });
- }
- $this->setAPIResponse('success', '', 200, $sponsors);
- return $sponsors;
- }
-
- public function getOrganizrSmtpFromAPI()
- {
- $url = 'https://api.organizr.app/?cmd=smtp';
- $options = ($this->localURL($url)) ? array('verify' => false) : array();
- try {
- $response = Requests::get($url, array(), $options);
- if ($response->success) {
- return json_decode($response->body, true);
- }
- } catch (Requests_Exception $e) {
- $this->setAPIResponse('error', $e->getMessage(), 500);
- return false;
- }
- return false;
- }
-
- public function saveOrganizrSmtpFromAPI()
- {
- $api = $this->getOrganizrSmtpFromAPI();
- if ($api) {
- $this->updateConfigItems($api['response']['data']);
- $this->setAPIResponse(null, 'SMTP activated with Organizr SMTP account');
- return true;
- } else {
- return false;
- }
- }
-
- public function guestHash($start, $end)
- {
- $ip = $this->userIP();
- $ip = md5($ip);
- return substr($ip, $start, $end);
- }
-
- public function rrmdir($dir)
- {
- ini_set('max_execution_time', 0);
- set_time_limit(0);
- if (is_dir($dir)) {
- $files = scandir($dir);
- foreach ($files as $file) {
- if ($file != "." && $file != "..") {
- $this->rrmdir("$dir/$file");
- }
- }
- rmdir($dir);
- } elseif (file_exists($dir)) {
- unlink($dir);
- }
- return true;
- }
-
- public function rcopy($src, $dst)
- {
- ini_set('max_execution_time', 0);
- set_time_limit(0);
- $src = $this->cleanPath($src);
- $dst = $this->cleanPath($dst);
- if (is_dir($src)) {
- if (!file_exists($dst)) : mkdir($dst);
- endif;
- $files = scandir($src);
- foreach ($files as $file) {
- if ($file != "." && $file != "..") {
- $this->rcopy("$src/$file", "$dst/$file");
- }
- }
- } elseif (file_exists($src)) {
- copy($src, $dst);
- }
- return true;
- }
-
- public function unzipFile($zipFile)
- {
- ini_set('max_execution_time', 0);
- set_time_limit(0);
- $zip = new ZipArchive;
- $extractPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade/";
- if ($zip->open($extractPath . $zipFile) != "true") {
- $this->writeLog("error", "organizr could not unzip upgrade.zip");
- } else {
- $this->writeLog("success", "organizr unzipped upgrade.zip");
- }
- /* Extract Zip File */
- $zip->extractTo($extractPath);
- $zip->close();
- return true;
- }
-
- public function downloadFile($url, $path)
- {
- ini_set('max_execution_time', 0);
- set_time_limit(0);
- $folderPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade" . DIRECTORY_SEPARATOR;
- if (!file_exists($folderPath)) {
- if (@!mkdir($folderPath)) {
- $this->writeLog('error', 'Update Function - Folder Creation failed', $this->user['username']);
- return false;
- }
- }
- $newfname = $folderPath . $path;
- $context = stream_context_create(
- array(
- 'ssl' => array(
- 'verify_peer' => true,
- 'cafile' => $this->getCert()
- )
- )
- );
- $file = fopen($url, 'rb', false, $context);
- if ($file) {
- $newf = fopen($newfname, 'wb');
- if ($newf) {
- while (!feof($file)) {
- fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
- }
- }
- } else {
- $this->writeLog("error", "organizr could not download $url");
- return false;
- }
- if ($file) {
- fclose($file);
- $this->writeLog("success", "organizr finished downloading the github zip file");
- } else {
- $this->writeLog("error", "organizr could not download the github zip file");
- return false;
- }
- if ($newf) {
- fclose($newf);
- $this->writeLog("success", "organizr created upgrade zip file from github zip file");
- } else {
- $this->writeLog("error", "organizr could not create upgrade zip file from github zip file");
- return false;
- }
- return true;
- }
-
- public function downloadFileToPath($from, $to, $path)
- {
- ini_set('max_execution_time', 0);
- set_time_limit(0);
- if (@!mkdir($path, 0777, true)) {
- $this->writeLog("error", "organizr could not create folder or folder already exists", 'SYSTEM');
- }
- $file = fopen($from, 'rb');
- if ($file) {
- $newf = fopen($to, 'wb');
- if ($newf) {
- while (!feof($file)) {
- fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
- }
- }
- } else {
- $this->writeLog("error", "organizr could not download file", 'SYSTEM');
- }
- if ($file) {
- fclose($file);
- $this->writeLog("success", "organizr finished downloading the file", 'SYSTEM');
- } else {
- $this->writeLog("error", "organizr could not download the file", 'SYSTEM');
- }
- if ($newf) {
- fclose($newf);
- $this->writeLog("success", "organizr saved/moved the file", 'SYSTEM');
- } else {
- $this->writeLog("error", "organizr could not saved/moved the file", 'SYSTEM');
- }
- return true;
- }
-
- public function getAllUsers($includeGroups = false)
- {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM users'
- ),
- 'key' => 'users'
- ),
- ];
- $groups = array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM groups ORDER BY group_id ASC'
- ),
- 'key' => 'groups'
- );
- $addGroups = (isset($_GET['includeGroups']) || $includeGroups) ?? false;
- if ($addGroups) {
- array_push($response, $groups);
- }
- return $this->processQueries($response);
- }
-
- public function getAllGroups()
- {
- $response = [
- array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM groups ORDER BY group_id ASC'
- ),
- 'key' => 'groups'
- ),
- ];
- $users = array(
- 'function' => 'fetchAll',
- 'query' => array(
- 'SELECT * FROM users'
- ),
- 'key' => 'users'
- );
- $addUsers = (isset($_GET['includeUsers'])) ?? false;
- if ($addUsers) {
- array_push($response, $users);
- }
- return $this->processQueries($response);
- }
-
- public function importUsers($array)
- {
- $imported = 0;
- foreach ($array as $user) {
- $password = $this->random_ascii_string(30);
- if ($user['username'] !== '' && $user['email'] !== '' && $password !== '') {
- $newUser = $this->createUser($user['username'], $password, $user['email']);
- if (!$newUser) {
- $this->writeLog('error', 'Import Function - Error', $user['username']);
- } else {
- $imported++;
- }
- }
- }
- $this->setAPIResponse('success', 'Imported ' . $imported . ' users', 200);
- return true;
- }
-
- public function importUsersType($type)
- {
- if ($type !== '') {
- switch ($type) {
- case 'plex':
- return $this->importUsers($this->allPlexUsers(true));
- case 'jellyfin':
- return $this->importUsers($this->allJellyfinUsers(true));
- case 'emby':
- return $this->importUsers($this->allEmbyUsers(true));
- default:
- return false;
- }
- }
- return false;
- }
-
- public function allPlexUsers($newOnly = false, $friendsOnly = false)
- {
- try {
- if (!empty($this->config['plexToken'])) {
- $url = 'https://plex.tv/api/users';
- $headers = array(
- 'X-Plex-Token' => $this->config['plexToken'],
- );
- $response = Requests::get($url, $headers);
- if ($response->success) {
- libxml_use_internal_errors(true);
- $userXML = simplexml_load_string($response->body);
- if (is_array($userXML) || is_object($userXML)) {
- $results = array();
- foreach ($userXML as $child) {
- if (((string)$child['restricted'] == '0')) {
- if ($newOnly) {
- $taken = $this->usernameTaken((string)$child['username'], (string)$child['email']);
- if (!$taken) {
- $results[] = array(
- 'username' => (string)$child['username'],
- 'email' => (string)$child['email'],
- 'id' => (string)$child['id'],
- );
- }
- } elseif ($friendsOnly) {
- $machineMatches = false;
- foreach ($child->Server as $server) {
- if ((string)$server['machineIdentifier'] == $this->config['plexID']) {
- $machineMatches = true;
- $shareId = $server['id'];
- }
- }
- if ($machineMatches) {
- $results[] = array(
- 'username' => (string)$child['username'],
- 'email' => (string)$child['email'],
- 'id' => (string)$child['id'],
- 'shareId' => (string)$shareId
- );
- }
- } else {
- $results[] = array(
- 'username' => (string)$child['username'],
- 'email' => (string)$child['email'],
- 'id' => (string)$child['id'],
- );
- }
-
- }
- }
- return $results;
- }
- }
- }
- return false;
- } catch (Requests_Exception $e) {
- $this->writeLog('success', 'Plex Import User Function - Error: ' . $e->getMessage(), 'SYSTEM');
- }
- return false;
- }
-
- public function allJellyfinUsers($newOnly = false)
- {
- try {
- if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
- $url = $this->qualifyURL($this->config['jellyfinURL']) . '/Users?api_key=' . $this->config['jellyfinToken'];
- $headers = array();
- $response = Requests::get($url, $headers);
- if ($response->success) {
- $users = json_decode($response->body, true);
- if (is_array($users) || is_object($users)) {
- $results = array();
- foreach ($users as $child) {
- // Jellyfin doesn't list emails for some reason
- $email = $this->random_ascii_string(10) . '@placeholder.eml';
- if ($newOnly) {
- $taken = $this->usernameTaken((string)$child['Name'], $email);
- if (!$taken) {
- $results[] = array(
- 'username' => (string)$child['Name'],
- 'email' => $email
- );
- }
- } else {
- $results[] = array(
- 'username' => (string)$child['Name'],
- 'email' => $email,
- );
- }
- }
- return $results;
- }
- }
- }
- return false;
- } catch (Requests_Exception $e) {
- $this->writeLog('success', 'Jellyfin Import User Function - Error: ' . $e->getMessage(), 'SYSTEM');
- }
- return false;
- }
-
- public function allEmbyUsers($newOnly = false)
- {
- try {
- if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
- $url = $this->qualifyURL($this->config['embyURL']) . '/Users?api_key=' . $this->config['embyToken'];
- $headers = array();
- $response = Requests::get($url, $headers);
- if ($response->success) {
- $users = json_decode($response->body, true);
- if (is_array($users) || is_object($users)) {
- $results = array();
- foreach ($users as $child) {
- // Emby doesn't list emails for some reason
- $email = $this->random_ascii_string(10) . '@placeholder.eml';
- if ($newOnly) {
- $taken = $this->usernameTaken((string)$child['Name'], $email);
- if (!$taken) {
- $results[] = array(
- 'username' => (string)$child['Name'],
- 'email' => $email
- );
- }
- } else {
- $results[] = array(
- 'username' => (string)$child['Name'],
- 'email' => $email,
- );
- }
- }
- return $results;
- }
- }
- }
- return false;
- } catch (Requests_Exception $e) {
- $this->writeLog('success', 'Emby Import User Function - Error: ' . $e->getMessage(), 'SYSTEM');
- }
- return false;
- }
-
- public function updateUser($id, $array)
- {
- if (!$id) {
- $this->setAPIResponse('error', 'Id was not supplied', 422);
- return false;
- }
- if ((int)$id !== $this->user['userID']) {
- if (!$this->qualifyRequest('1', true)) {
- return false;
- }
- }
- $user = $this->getUserById($id);
- if ($user) {
- $array = $this->checkKeys($user, $array);
- } else {
- $this->setAPIResponse('error', 'User was not found', 404);
- return false;
- }
- if ($user['group_id'] == 0 && $this->user['groupID'] !== 0) {
- $this->setAPIResponse('error', 'Cannot update admin unless you are admin', 401);
- return false;
- }
- if (array_key_exists('username', $array)) {
- if ($array['username'] == '') {
- $this->setAPIResponse('error', 'Username was set but empty', 409);
- return false;
- }
- if ($this->usernameTaken($array['username'], $array['username'], $id)) {
- $this->setAPIResponse('error', 'Username: ' . $array['username'] . ' is already taken', 409);
- return false;
- }
- }
- if (array_key_exists('email', $array)) {
- if ($array['email'] == '') {
- $this->setAPIResponse('error', 'Email was set but empty', 409);
- return false;
- }
- if ($this->usernameTaken($array['email'], $array['email'], $id)) {
- $this->setAPIResponse('error', 'Email: ' . $array['email'] . ' is already taken', 409);
- return false;
- }
- }
- if (array_key_exists('group_id', $array)) {
- if ($array['group_id'] == '') {
- $array['group_id'] = 0;
- //$this->setAPIResponse('error', 'group_id was set but empty', 409);
- //return false;
- }
- if (!$this->qualifyRequest('1', false)) {
- $this->setAPIResponse('error', 'Cannot change your own group_id', 401);
- return false;
- }
- if (($id == $this->user['userID']) && $this->user['groupID'] == 0) {
- $array['group_id'] = 0;
- }
- if (($id == $this->user['userID']) && ($array['group_id'] == 0 && $this->user['groupID'] !== 0)) {
- $this->setAPIResponse('error', 'Only admins can make others admins', 401);
- return false;
- }
- $array['group'] = $this->getGroupByGroupId($array['group_id'])['group'];
- if (!$array['group']) {
- $this->setAPIResponse('error', 'group_id does not exist', 404);
- return false;
- }
- }
- if (array_key_exists('locked', $array)) {
- //$this->setAPIResponse('error', 'Cannot use endpoint to unlock or lock user - please use /users/{id}/lock', 409);
- //return false;
- }
- if (array_key_exists('password', $array)) {
- if ($array['password'] == '') {
- $this->setAPIResponse('error', 'Password was set but empty', 409);
- return false;
- }
- $array['password'] = password_hash($array['password'], PASSWORD_BCRYPT);
- }
- if (array_key_exists('register_date', $array)) {
- $this->setAPIResponse('error', 'Cannot update register date', 409);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE users SET',
- $array,
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- $this->setAPIResponse(null, 'User info updated');
- $this->writeLog('success', 'User Editor Function - Updated User Info for [' . $user['username'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function deleteUser($id)
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM users WHERE id = ?',
- $id
- )
- ),
- ];
- $userInfo = $this->getUserById($id);
- if ($id == $this->user['userID']) {
- $this->setAPIResponse('error', 'Cannot delete your own user', 409);
- return false;
- }
- if ($userInfo) {
- $this->writeLog('success', 'User Delete Function - Deleted User [' . $userInfo['username'] . ']', $this->user['username']);
- $this->setAPIResponse('success', 'User deleted', 204);
- return $this->processQueries($response);
- } else {
- $this->setAPIResponse('error', 'id not found', 404);
- return false;
- }
- }
-
- public function addUser($array)
- {
- $username = $array['username'] ?? null;
- $password = $array['password'] ?? null;
- $email = $array['email'] ?? null;
- if (!$username) {
- $this->setAPIResponse('error', 'Username was not supplied', 409);
- return false;
- }
- if (!$password) {
- $this->setAPIResponse('error', 'Password was not supplied', 409);
- return false;
- }
- if ($this->createUser($username, $password, $email)) {
- $this->writeLog('success', 'Create User Function - Account created for [' . $username . ']', $this->user['username']);
- return true;
- } else {
- $this->writeLog('error', 'Create User Function - An error occurred', $this->user['username']);
- return false;
- }
- }
-
- public function createUser($username, $password, $email = null)
- {
- $username = $username ?? null;
- $password = $password ?? null;
- $email = ($email) ? $email : $this->random_ascii_string(10) . '@placeholder.eml';
- if (!$username) {
- $this->setAPIResponse('error', 'Username was set but empty', 409);
- return false;
- }
- if (!$password) {
- $this->setAPIResponse('error', 'Password was set but empty', 409);
- return false;
- }
- if ($this->usernameTaken($username, $email)) {
- $this->setAPIResponse('error', 'Username: ' . $username . ' or Email: ' . $email . ' is already taken', 409);
- return false;
- }
- $defaults = $this->getDefaultGroup();
- $userInfo = [
- 'username' => $username,
- 'password' => password_hash($password, PASSWORD_BCRYPT),
- 'email' => $email,
- 'group' => $defaults['group'],
- 'group_id' => $defaults['group_id'],
- 'image' => $this->gravatar($email),
- 'register_date' => $this->currentTime,
- ];
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [users]',
- $userInfo
- )
- ),
- ];
- $this->setAPIResponse('success', 'User created', 200);
- return $this->processQueries($response);
- }
-
- public function updateGroup($id, $array)
- {
- if (!$id || $id == '') {
- $this->setAPIResponse('error', 'id was not set', 422);
- return null;
- }
- if (!$array) {
- $this->setAPIResponse('error', 'no data was sent', 422);
- return null;
- }
- $groupInfo = $this->getGroupById($id);
- if ($groupInfo) {
- $array = $this->checkKeys($groupInfo, $array);
- } else {
- $this->setAPIResponse('error', 'No category info found', 404);
- return false;
- }
- if (array_key_exists('group_id', $array)) {
- $this->setAPIResponse('error', 'Cannot change group_id', 409);
- return false;
-
- }
- if (array_key_exists('group', $array)) {
- if ($array['group'] == '') {
- $this->setAPIResponse('error', 'Group was set but empty', 409);
- return false;
- }
- if ($this->isGroupNameTaken($array['group'], $id)) {
- $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
- return false;
- }
- }
- if (array_key_exists('image', $array)) {
- if ($array['image'] == '') {
- $this->setAPIResponse('error', 'Image was set but empty', 409);
- return false;
- }
- }
- if (array_key_exists('default', $array)) {
- if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
- $this->setAPIResponse('error', 'Setting ' . $groupInfo['group'] . ' as default group is not allowed', 409);
- return false;
- }
- if ($array['default']) {
- $this->clearGroupDefault();
- $array['default'] = 1;
- }
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE groups SET',
- $array,
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- $this->setAPIResponse(null, 'Group info updated');
- $this->writeLog('success', 'Group Editor Function - Edited Group Info for [' . $groupInfo['group'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function deleteGroup($id)
- {
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'DELETE FROM groups WHERE id = ?',
- $id
- )
- ),
- ];
- $groupInfo = $this->getGroupById($id);
- if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
- $this->setAPIResponse('error', 'Cannot delete group: ' . $groupInfo['group'] . ' as it is not allowed', 409);
- return false;
- }
- if ($this->getGroupUserCountById($id) >= 1) {
- $this->setAPIResponse('error', 'Cannot delete group as group still has users assigned to it', 409);
- return false;
- }
- if ($groupInfo) {
- $this->writeLog('success', 'Group Delete Function - Deleted Group [' . $groupInfo['group'] . ']', $this->user['username']);
- $this->setAPIResponse('success', 'Group deleted', 204);
- return $this->processQueries($response);
- } else {
- $this->setAPIResponse('error', 'id not found', 404);
- return false;
- }
- }
-
- public function addGroup($array)
- {
- if (!$array) {
- $this->setAPIResponse('error', 'no data was sent', 422);
- return null;
- }
- $array = $this->checkKeys($this->getTableColumnsFormatted('groups'), $array);
- $array['default'] = ($array['default']) ?? 0;
- $array['group_id'] = $this->getNextGroupOrder() + 1;
- if (array_key_exists('group', $array)) {
- if ($this->isGroupNameTaken($array['group'])) {
- $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
- return false;
- }
- } else {
- $this->setAPIResponse('error', 'Group name was not supplied', 422);
- return false;
- }
- if (array_key_exists('image', $array)) {
- if ($array['image'] == '') {
- $this->setAPIResponse('error', 'Group image cannot be empty', 422);
- return false;
- }
- } else {
- $this->setAPIResponse('error', 'Group image was not supplied', 422);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'INSERT INTO [groups]',
- $array
- )
- ),
- ];
- $this->setAPIResponse(null, 'Group added');
- $this->writeLog('success', 'Group Editor Function - Added Group for [' . $array['group'] . ']', $this->user['username']);
- return $this->processQueries($response);
- }
-
- public function userList($type = null)
- {
- switch ($type) {
- case 'plex':
- if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
- $url = 'https://plex.tv/api/servers/' . $this->config['plexID'] . '/shared_servers';
- try {
- $headers = array(
- "Accept" => "application/json",
- "X-Plex-Token" => $this->config['plexToken']
- );
- $response = Requests::get($url, $headers, array());
- libxml_use_internal_errors(true);
- if ($response->success) {
- $libraryList = array();
- $plex = simplexml_load_string($response->body);
- foreach ($plex->SharedServer as $child) {
- if (!empty($child['username'])) {
- $username = (string)strtolower($child['username']);
- $email = (string)strtolower($child['email']);
- $libraryList['users'][$username] = (string)$child['id'];
- $libraryList['emails'][$email] = (string)$child['id'];
- $libraryList['both'][$username] = $email;
- }
- }
- $libraryList = array_change_key_case($libraryList, CASE_LOWER);
- return $libraryList;
- }
- } catch (Requests_Exception $e) {
- $this->writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
- }
- }
- break;
- default:
- # code...
- break;
- }
- return false;
- }
-
-
- public function encrypt($password, $key = null)
- {
- $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
- return openssl_encrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
- }
-
- public function decrypt($password, $key = null)
- {
- if (empty($password)) {
- return '';
- }
- $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
- return openssl_decrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
- }
-
- public function checkValidCert($file)
- {
- if (file_exists($file)) {
- return filesize($file) > 0;
- } else {
- return false;
- }
- }
-
- public function getCert()
- {
- $url = 'http://curl.haxx.se/ca/cacert.pem';
- $file = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
- $file2 = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
- $useCert = ($this->checkValidCert($file)) ? $file : $file2;
- if ($this->config['selfSignedCert'] !== '') {
- if (file_exists($this->config['selfSignedCert'])) {
- return $this->config['selfSignedCert'];
- }
- }
- $context = stream_context_create(
- array(
- 'ssl' => array(
- 'verify_peer' => true,
- 'cafile' => $useCert
- )
- )
- );
- if (!$this->checkValidCert($file) || (file_exists($file) && time() - 2592000 > filemtime($file))) {
- file_put_contents($file, fopen($url, 'r', false, $context));
- }
- return ($this->checkValidCert($file)) ? $file : $file2;
- }
-
- public function hasCustomCert()
- {
- return file_exists(dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem');
- }
-
- public function getCustomCert()
- {
- return ($this->hasCustomCert()) ? dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem' : false;
- }
-
- public function uploadCert()
- {
- $filesCheck = array_filter($_FILES);
- if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'cert')) {
- ini_set('upload_max_filesize', '10M');
- ini_set('post_max_size', '10M');
- $tempFile = $_FILES['file']['tmp_name'];
- $targetPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR;
- $targetFile = $targetPath . 'custom.pem';
- $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
- return move_uploaded_file($tempFile, $targetFile);
- } else {
- $this->setAPIResponse('error', pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' is not approved to be uploaded', 403);
- return false;
- }
- }
-
- public function plexJoinAPI($array)
- {
- $username = ($array['username']) ?? null;
- $email = ($array['email']) ?? null;
- $password = ($array['password']) ?? null;
- if (!$username) {
- $this->setAPIResponse('error', 'Username not supplied', 409);
- return false;
- }
- if (!$email) {
- $this->setAPIResponse('error', 'Email not supplied', 409);
- return false;
- }
- if (!$password) {
- $this->setAPIResponse('error', 'Password not supplied', 409);
- return false;
- }
- return $this->plexJoin($username, $email, $password);
- }
-
- public function plexJoin($username, $email, $password)
- {
-
- try {
- $url = 'https://plex.tv/api/v2/users';
- $headers = array(
- 'Accept' => 'application/json',
- 'Content-Type' => 'application/x-www-form-urlencoded',
- 'X-Plex-Product' => 'Organizr',
- 'X-Plex-Version' => '2.0',
- 'X-Plex-Client-Identifier' => $this->config['uuid'],
- );
- $data = array(
- 'email' => $email,
- 'username' => $username,
- 'password' => $password,
- );
- $response = Requests::post($url, $headers, $data, array());
- $json = json_decode($response->body, true);
- $errors = !empty($json['errors']);
- $success = empty($json['errors']);
- //Use This for later
- $errorMessage = '';
- if ($errors) {
- foreach ($json['errors'] as $error) {
- if (isset($error['message']) && isset($error['field'])) {
- $errorMessage .= "[Plex.tv Error: " . $error['message'] . " for field: (" . $error['field'] . ")]";
- }
- }
- }
- $msg = (!empty($success) && empty($errors)) ? 'User has joined Plex' : $errorMessage;
- $status = (!empty($success) && empty($errors)) ? 'success' : 'error';
- $code = (!empty($success) && empty($errors)) ? 200 : 422;
- $this->setAPIResponse($status, $msg, $code);
- return (!empty($success) && empty($errors));
- } catch (Requests_Exception $e) {
- $this->writeLog('error', 'Plex.TV Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
- $this->setAPIResponse('error', 'An Error Occurred', 409);
- return false;
- }
- return false;
- }
-
- public function lockCurrentUser()
- {
- if ($this->user['userID'] == '999') {
- $this->setAPIResponse('error', 'Locking not allowed on Guest users', 409);
- return false;
- }
- return $this->lockUser($this->user['userID']);
- }
-
- public function lockUser($id)
- {
-
- $user = $this->getUserById($id);
- if (!$user) {
- $this->setAPIResponse('error', 'User not found', 404);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE users SET',
- ['locked' => '1'],
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- $this->writeLog('success', 'User Lockout Function - User: ' . $user['username'] . ' account locked', $this->user['username']);
- $this->setAPIResponse('success', 'User account locked', 200);
- return $this->processQueries($response);
- }
-
- public function unlockCurrentUser($array)
- {
- if ($array['password'] == '') {
- $this->setAPIResponse('error', 'Password Not Set', 422);
- return false;
- }
- $user = $this->getUserById($this->user['userID']);
- if (!password_verify($array['password'], $user['password'])) {
- $this->setAPIResponse('error', 'Password Incorrect', 401);
- return false;
- }
- return $this->unlockUser($this->user['userID']);
- }
-
- public function unlockUser($id)
- {
- $user = $this->getUserById($id);
- if (!$user) {
- $this->setAPIResponse('error', 'User not found', 404);
- return false;
- }
- $response = [
- array(
- 'function' => 'query',
- 'query' => array(
- 'UPDATE users SET',
- ['locked' => '0'],
- 'WHERE id = ?',
- $id
- )
- ),
- ];
- $this->writeLog('success', 'User Lockout Function - User: ' . $user['username'] . ' account unlocked', $this->user['username']);
- $this->setAPIResponse('success', 'User account unlocked', 200);
- return $this->processQueries($response);
- }
-
- public function youtubeSearch($query)
- {
- if (!$query) {
- $this->setAPIResponse('error', 'No query supplied', 422);
- return false;
- }
- $keys = array(
- 'AIzaSyBsdt8nLJRMTwOq5PY5A5GLZ2q7scgn01w',
- 'AIzaSyD-8SHutB60GCcSM8q_Fle38rJUV7ujd8k',
- 'AIzaSyBzOpVBT6VII-b-8gWD0MOEosGg4hyhCsQ',
- 'AIzaSyBKnRe1P8fpfBHgooJpmT0WOsrdUtZ4cpk'
- );
- $randomKeyIndex = array_rand($keys);
- $key = $keys[$randomKeyIndex];
- $apikey = ($this->config['youtubeAPI'] !== '') ? $this->config['youtubeAPI'] : $key;
- $results = false;
- $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=$query+official+trailer&part=snippet&maxResults=1&type=video&videoDuration=short&key=$apikey";
- $response = Requests::get($url);
- if ($response->success) {
- $results = json_decode($response->body, true);
- $this->setAPIResponse('success', null, 200, $results);
- return $results;
- } else {
- $this->setAPIResponse('error', 'Bad response from YouTube', 500);
- return false;
- }
- }
-
- public function scrapePage($array)
- {
- try {
- $url = $array['url'] ?? false;
- $type = $array['type'] ?? false;
- if (!$url) {
- $this->setAPIResponse('error', 'URL was not supplied', 422);
- return false;
- }
- $url = $this->qualifyURL($url);
- $data = array(
- 'full_url' => $url,
- 'drill_url' => $this->qualifyURL($url, true)
- );
- $options = array('verify' => false);
- $response = Requests::get($url, array(), $options);
- $data['response_code'] = $response->status_code;
- if ($response->success) {
- $data['result'] = 'Success';
- switch ($type) {
- case 'html':
- $data['data'] = html_entity_decode($response->body);
- break;
- case 'json':
- $data['data'] = json_decode($response->body);
- break;
- default:
- $data['data'] = $response->body;
- }
- $this->setAPIResponse('success', null, 200, $data);
- return $data;
- } else {
- $this->setAPIResponse('error', 'Error getting successful response', 500);
- return false;
- }
- } catch (Requests_Exception $e) {
- $this->setAPIResponse('error', $e->getMessage(), 500);
- return false;
- }
- }
-
- public function chooseInstance($url = null, $token = null, $instance = 0, $type = null)
- {
- if (!$url || !$token) {
- return false;
- }
- $list = $this->csvHomepageUrlToken($url, $token);
- if ($type) {
- $type = strtolower($type);
- switch ($type) {
- case 'url':
- case 'token':
- break;
- default:
- $type = 'url';
- break;
- }
- if (is_numeric($instance)) {
- return $list[$instance][$type];
- } else {
- return $list;
- }
- }
- if (is_numeric($instance)) {
- return $list[$instance];
- } else {
- return $list;
- }
- }
-
- public function CBPFWTabs()
- {
- return '
- <script>
- /**
- * cbpFWTabs.js v1.0.0
- * http://www.codrops.com
- *
- * Licensed under the MIT license.
- * http://www.opensource.org/licenses/mit-license.php
- *
- * Copyright 2014, Codrops
- * http://www.codrops.com
- */
- ;( function( window ) {
- \'use strict\';
-
- function extend( a, b ) {
- for( var key in b ) {
- if( b.hasOwnProperty( key ) ) {
- a[key] = b[key];
- }
- }
- return a;
- }
-
- function CBPFWTabs( el, options ) {
- this.el = el;
- this.options = extend( {}, this.options );
- extend( this.options, options );
- this._init();
- }
-
- CBPFWTabs.prototype.options = {
- start : 0
- };
-
- CBPFWTabs.prototype._init = function() {
- // tabs elems
- this.tabs = [].slice.call( this.el.querySelectorAll( \'nav > ul > li\' ) );
- // content items
- this.items = [].slice.call( this.el.querySelectorAll( \'.content-wrap > section\' ) );
- // current index
- this.current = -1;
- // show current content item
- try{
- if(this.tabs[0].innerHTML.indexOf(\'#settings\') >= 0){
- this._show(' . $this->config['defaultSettingsTab'] . ');
- let tabId = $(this.items[' . $this->config['defaultSettingsTab'] . ']).attr("id") + "-anchor";
- $("#" + tabId).click();
- $("#" + tabId + " a").click();
- }else{
- this._show();
- }
- }catch{
- this._show();
- }
- // init events
- this._initEvents();
- };
-
- CBPFWTabs.prototype._initEvents = function() {
- var self = this;
- this.tabs.forEach( function( tab, idx ) {
- tab.addEventListener( \'click\', function( ev ) {
- ev.preventDefault();
- self._show( idx );
- } );
- } );
- };
-
- CBPFWTabs.prototype._show = function( idx ) {
- if( this.current >= 0 ) {
- this.tabs[ this.current ].className = this.items[ this.current ].className = \'\';
- }
- // change current
- this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
- this.tabs[ this.current ].className = \'tab-current\';
- this.items[ this.current ].className = \'content-current\';
- };
-
- // add to global namespace
- window.CBPFWTabs = CBPFWTabs;
-
- })( window );
- </script>
- ';
- }
-
- public function socksHeadingHTML($app)
- {
- return '
- <h3 lang="en">' . ucwords($app) . ' SOCKS API Connection</h3>
- <p>Using this feature allows you to access the API without having to reverse proxy it. Just access it from: </p>
- <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/socks/' . $app . '/</code>
- <p>If you are using multiple URL\'s (using the csv method) you will have to use the url like these: </p>
- <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/1</code>
- <br/>
- <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/2</code>
- ';
- }
-
- public function socksListing($app = null)
- {
- switch ($app) {
- case 'sonarr':
- $appDetails = [
- 'url' => 'sonarrURL',
- 'enabled' => 'sonarrSocksEnabled',
- 'auth' => 'sonarrSocksAuth',
- 'header' => 'X-Api-Key'
- ];
- break;
- case 'radarr':
- $appDetails = [
- 'url' => 'radarrURL',
- 'enabled' => 'radarrSocksEnabled',
- 'auth' => 'radarrSocksAuth',
- 'header' => 'X-Api-Key'
- ];
- break;
- case 'lidarr':
- $appDetails = [
- 'url' => 'lidarrURL',
- 'enabled' => 'lidarrSocksEnabled',
- 'auth' => 'lidarrSocksAuth',
- 'header' => 'X-Api-Key'
- ];
- break;
- case 'sabnzbd':
- $appDetails = [
- 'url' => 'sabnzbdURL',
- 'enabled' => 'sabnzbdSocksEnabled',
- 'auth' => 'sabnzbdSocksAuth',
- 'header' => null
- ];
- break;
- case 'nzbget':
- $appDetails = [
- 'url' => 'nzbgetURL',
- 'enabled' => 'nzbgetSocksEnabled',
- 'auth' => 'nzbgetSocksAuth',
- 'header' => 'Authorization'
- ];
- break;
- case 'tautulli':
- $appDetails = [
- 'url' => 'tautulliURL',
- 'enabled' => 'tautulliSocksEnabled',
- 'auth' => 'tautulliSocksAuth',
- 'header' => null
- ];
- break;
- case 'qbittorrent':
- $appDetails = [
- 'url' => 'qBittorrentURL',
- 'enabled' => 'qBittorrentSocksEnabled',
- 'auth' => 'qBittorrentSocksAuth',
- 'header' => null
- ];
- break;
- default:
- $appDetails = null;
- }
- return $appDetails;
- }
-
- public function socks($appDetails, $requestObject, $multiple = null)
- {
- $url = $appDetails['url'];
- $enabled = $appDetails['enabled'];
- $auth = $appDetails['auth'];
- $header = $appDetails['header'];
- $error = false;
- if (!$this->config[$enabled]) {
- $error = true;
- $this->setAPIResponse('error', 'SOCKS module is not enabled', 409);
- }
- if (!$this->qualifyRequest($this->config[$auth], true)) {
- $error = true;
- }
- if (strpos($this->config[$url], ',') !== false) {
- if (!$multiple) {
- $error = true;
- $this->setAPIResponse('error', 'Multiple URLs found in field, please use /api/v2/multiple/socks endpoint', 409);
- }
- } else {
- if ($multiple) {
- $error = true;
- $this->setAPIResponse('error', 'Multiple endpoint accessed but multiple URLs not found in field, please use /api/v2/socks endpoint', 409);
- }
- }
- if (!$error) {
- if ($multiple) {
- $instance = $multiple - 1;
- $pre = explode('/api/v2/multiple/socks/', $requestObject->getUri()->getPath());
- $pre[1] = $this->replace_first('/' . $multiple . '/', '/', $pre[1]);
- // sent url twice since we arent using tokens
- $list = $this->csvHomepageUrlToken($this->config[$url], $this->config[$url]);
- $appURL = $list[$instance]['url'];
- } else {
- $pre = explode('/api/v2/socks/', $requestObject->getUri()->getPath());
- $appURL = $this->config[$url];
- }
- $endpoint = explode('/', $pre[1]);
- $new = urldecode(preg_replace('/' . $endpoint[0] . '/', '', $pre[1], 1));
- $getParams = ($_GET) ? '?' . http_build_query($_GET) : '';
- $url = $this->qualifyURL($appURL) . $new . $getParams;
- $url = $this->cleanPath($url);
- $options = ($this->localURL($appURL)) ? array('verify' => false, 'timeout' => 120) : array('timeout' => 120);
- $headers = [];
- $apiData = $this->json_validator($this->apiData($requestObject)) ? json_encode($this->apiData($requestObject)) : $this->apiData($requestObject);
- if ($header) {
- if ($requestObject->hasHeader($header)) {
- $headerKey = $requestObject->getHeaderLine($header);
- $headers[$header] = $headerKey;
- }
- }
- $debugInformation = [
- 'type' => $requestObject->getMethod(),
- 'headerType' => $requestObject->getHeaderLine('Content-Type'),
- 'header' => $header,
- 'headers' => $headers,
- 'url' => $url,
- 'options' => $options,
- 'data' => $apiData
- ];
- //$this->debug(json_encode($debugInformation));
- try {
- switch ($requestObject->getMethod()) {
- case 'GET':
- $call = Requests::get($url, $headers, $options);
- break;
- case 'POST':
- $call = Requests::post($url, $headers, $apiData, $options);
- break;
- case 'DELETE':
- $call = Requests::delete($url, $headers, $options);
- break;
- case 'PUT':
- $call = Requests::put($url, $headers, $apiData, $options);
- break;
- default:
- $call = Requests::get($url, $headers, $options);
- }
- return $call->body;
- } catch (Requests_Exception $e) {
- $this->setAPIResponse('error', $e->getMessage(), 500);
- return null;
- }
- } else {
- return null;
- }
- }
-
- public function getPlexServers()
- {
- if ($this->config['plexToken'] == '') {
- $this->setAPIResponse('error', 'Plex Token cannot be empty', 422);
- return false;
- }
- $ownedOnly = isset($_GET['owned']) ?? false;
- $url = $this->qualifyURL('https://plex.tv/pms/servers');
- $options = ($this->localURL($url)) ? array('verify' => false) : array();
- $headers = [
- 'X-Plex-Product' => 'Organizr',
- 'X-Plex-Version' => '2.0',
- 'X-Plex-Client-Identifier' => '01010101-10101010',
- 'X-Plex-Token' => $this->config['plexToken'],
- ];
- try {
- $response = Requests::get($url, $headers, $options);
- libxml_use_internal_errors(true);
- if ($response->success) {
- $items = array();
- $plex = simplexml_load_string($response->body);
- foreach ($plex as $server) {
- if ($ownedOnly) {
- if ($server['owned'] == 1) {
- $items[] = array(
- 'name' => (string)$server['name'],
- 'address' => (string)$server['address'],
- 'machineIdentifier' => (string)$server['machineIdentifier'],
- 'owned' => (float)$server['owned'],
- );
- }
- } else {
- $items[] = array(
- 'name' => (string)$server['name'],
- 'address' => (string)$server['address'],
- 'machineIdentifier' => (string)$server['machineIdentifier'],
- 'owned' => (float)$server['owned'],
- );
- }
- }
- $this->setAPIResponse('success', null, 200, $items);
- return $items;
- }
- } catch (Requests_Exception $e) {
- $this->writeLog('success', 'Plex Get Servers Function - Error: ' . $e->getMessage(), 'SYSTEM');
- $this->setAPIResponse('error', $e->getMessage(), 500);
- }
- }
-
- public function getIcons()
- {
- $term = $_GET['search'] ?? null;
- $page = $_GET['page'] ?? 1;
- $limit = $_GET['limit'] ?? 20;
- $offset = ($page * $limit) - $limit;
- $goodIcons['results'] = [];
- $goodIcons['limit'] = $limit;
- $goodIcons['page'] = $page;
- $goodIcons['term'] = $term;
- $allIcons = file_get_contents($this->root . '/js/icons.json');
- $iconListing = json_decode($allIcons, true);
- foreach ($iconListing as $setKey => $set) {
- foreach ($set['children'] as $k => $v) {
- if (stripos($v['text'], $term) !== false || !$term) {
- $goodIcons['results'][] = $v;
- }
- }
- }
- $total = count($goodIcons['results']);
- $goodIcons['total'] = $total;
- $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
- $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
- return $goodIcons;
- }
-
- public function getJournalMode()
- {
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => 'PRAGMA journal_mode',
- ),
- ];
- $query = $this->processQueries($response);
- if ($query) {
- if ($query['journal_mode']) {
- $this->setResponse(200, null, $query);
- } else {
- $this->setResponse(500, 'Error getting Journal Mode');
- }
- } else {
- $this->setResponse(404, 'Journal Mode not found');
- }
- return $query;
- }
-
- public function setJournalMode($option = 'WAL')
- {
- $option = strtoupper($option);
- switch ($option) {
- case 'WAL':
- case 'DELETE':
- break;
- default:
- return false;
- }
- $response = [
- array(
- 'function' => 'fetch',
- 'query' => 'PRAGMA journal_mode = \'' . $option . '\';',
- ),
- ];
- $query = $this->processQueries($response);
- if ($query) {
- if ($query['journal_mode']) {
- $this->setResponse(200, 'Journal Mode updated to: ' . $option, $query);
- } else {
- $this->setResponse(500, 'Error getting Journal Mode');
- }
- } else {
- $this->setResponse(404, 'Journal Mode not found');
- }
- return $query;
- }
-
- protected function processQueries(array $request, $migration = false)
- {
- $results = array();
- $firstKey = '';
- try {
- foreach ($request as $k => $v) {
-
- $query = ($migration) ? $this->otherDb->query($v['query']) : $this->db->query($v['query']);
- $keyName = (isset($v['key'])) ? $v['key'] : $k;
- $firstKey = (isset($v['key']) && $k == 0) ? $v['key'] : $k;
- switch ($v['function']) {
- case 'fetchAll':
- $results[$keyName] = $query->fetchAll();
- break;
- case 'fetch':
- // PHP 8 Fix?
- $query->setRowClass(null);
- $results[$keyName] = $query->fetch();
- break;
- case 'getAffectedRows':
- $results[$keyName] = $query->getAffectedRows();
- break;
- case 'getRowCount':
- $results[$keyName] = $query->getRowCount();
- break;
- case 'fetchSingle':
- // PHP 8 Fix?
- $query->setRowClass(null);
- $results[$keyName] = $query->fetchSingle();
- break;
- case 'query':
- $results[$keyName] = $query;
- break;
- default:
- return false;
- }
- }
-
- } catch (Exception $e) {
- $this->debug($e->getMessage());
- return false;
- }
- return count($request) > 1 ? $results : $results[$firstKey];
- }
-
- }
|